view wibble/tests.py @ 4:ad5a8748afcf

Add test framework
author Ben Croston <ben@croston.org>
date Wed, 31 Aug 2011 21:35:14 +0100
parents
children f5e3ba8cfcd0
line wrap: on
line source

#!/usr/bin/env python
import unittest
import hashlib
from threading import Thread
import time
from wsgiref import simple_server
import platform

##### server vvv #####
class api(object):
  def mymethod(self):
      #raise Exception("This is a test error")
      return 'wibbler woz ere'

def myauth(username, password, useragent=None):
  #raise Exception("This is a test error in auth")
  return username == 'testuser' and hashlib.md5('s3cr3t').hexdigest() == password and useragent == 'wibble_unittest'

def make_server():
    from wibble.server import JsonRpcApp
    class myhandler(simple_server.WSGIRequestHandler):
        def log_request(self, *a, **b):
            pass # do not output log messages
    application = JsonRpcApp(api(), auth=myauth)
    return simple_server.make_server('localhost', 1337, application, handler_class=myhandler)
##### server ^^^ #####

##### client vvv #####
class WibbleTests(unittest.TestCase):
    def setUp(self):
        from wibble.client.ServerProxy import ServerProxy
        self.client = ServerProxy('http://localhost:1337/',
                                  username='testuser',
                                  password='s3cr3t',
                                  user_agent='wibble_unittest')

class IgnoreModuleNameTest(WibbleTests):
    def runTest(self):
        self.assertEqual(self.client.api.mymethod(),self.client.mymethod())

#def client_tests():
#    try:
#        print(jsonrpc_client.wibble('this should fail'))
#    except BadRequestException:
#        pass # test passed
#    else:
#       raise Exception('Test failed (calling unknown method)')
#
#    print 'All tests passed'

##### client ^^^ #####

def suite():
    if platform.python_version().startswith('3'):
        # no tests for python 3 because server not ported yet
        return unittest.TestSuite()
    def test_wrapper():
        server = make_server()
        server.log_request = None
        server.serve_forever()
    thread = Thread(target=test_wrapper)
    thread.start()
    time.sleep(0.1) # wait for server thread to start
    suite = unittest.TestSuite()
    suite.addTest(IgnoreModuleNameTest())
    return suite

if __name__ == '__main__':
#    unittest.main()
    main()