diff options
author | Vlastimil Zíma <vlastimil.zima@nic.cz> | 2017-12-12 16:46:35 +0100 |
---|---|---|
committer | Vlastimil Zíma <vlastimil.zima@nic.cz> | 2018-01-22 08:21:57 +0100 |
commit | a14a20576f1d5e21806886a0af1b89203c8ca31a (patch) | |
tree | d793ceb268edc8c6230d809de75f95d508add048 | |
parent | a3dd223cd78bafcedc2714090cb264ccef9948b3 (diff) | |
download | openid-a14a20576f1d5e21806886a0af1b89203c8ca31a.tar.gz |
Drop custom test runner
-rw-r--r-- | .travis.yml | 2 | ||||
-rwxr-xr-x | admin/fixperms | 3 | ||||
-rwxr-xr-x | admin/runtests | 207 | ||||
-rw-r--r-- | openid/test/test_accept.py | 37 | ||||
-rw-r--r-- | openid/test/test_cryptutil.py | 171 | ||||
-rw-r--r-- | openid/test/test_dh.py | 135 | ||||
-rw-r--r-- | openid/test/test_fetchers.py | 36 | ||||
-rw-r--r-- | openid/test/test_kvform.py | 31 | ||||
-rw-r--r-- | openid/test/test_linkparse.py | 86 | ||||
-rw-r--r-- | openid/test/test_oidutil.py | 271 | ||||
-rw-r--r-- | openid/test/test_openidyadis.py | 7 | ||||
-rw-r--r-- | openid/test/test_parsehtml.py | 22 | ||||
-rw-r--r-- | openid/test/test_storetest.py | 307 | ||||
-rw-r--r-- | openid/test/test_trustroot.py | 87 | ||||
-rw-r--r-- | openid/test/test_urinorm.py | 25 | ||||
-rw-r--r-- | openid/test/test_yadis_discover.py | 117 |
16 files changed, 537 insertions, 1007 deletions
diff --git a/.travis.yml b/.travis.yml index fe11957..7d67a57 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ language: python python: - 2.7 -before_install: pip install Django pycrypto lxml isort flake8 +before_install: pip install 'Django<=1.11.99' pycrypto lxml isort flake8 install: python setup.py install script: - make check-isort diff --git a/admin/fixperms b/admin/fixperms index d0303e1..8bcf8ec 100755 --- a/admin/fixperms +++ b/admin/fixperms @@ -4,7 +4,6 @@ admin/builddiscover.py admin/fixperms admin/makechangelog admin/pythonsource -admin/runtests admin/setversion admin/tagrelease -EOF
\ No newline at end of file +EOF diff --git a/admin/runtests b/admin/runtests deleted file mode 100755 index db7a647..0000000 --- a/admin/runtests +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env python -import os.path -import sys -import warnings - -test_modules = [ - 'cryptutil', - 'oidutil', - 'dh', -] - - -def fixpath(): - try: - d = os.path.dirname(__file__) - except NameError: - d = os.path.dirname(sys.argv[0]) - parent = os.path.normpath(os.path.join(d, '..')) - if parent not in sys.path: - print "putting %s in sys.path" % (parent,) - sys.path.insert(0, parent) - - -def otherTests(): - failed = [] - for module_name in test_modules: - print 'Testing %s...' % (module_name,), - sys.stdout.flush() - module_name = 'openid.test.' + module_name - try: - test_mod = __import__(module_name, {}, {}, [None]) - except ImportError: - print 'Failed to import test %r' % (module_name,) - failed.append(module_name) - else: - try: - test_mod.test() - except Exception: - sys.excepthook(*sys.exc_info()) - failed.append(module_name) - else: - print 'Succeeded.' - - return failed - - -def pyunitTests(): - import unittest - pyunit_module_names = [ - 'server', - 'consumer', - 'message', - 'symbol', - 'etxrd', - 'xri', - 'xrires', - 'association_response', - 'auth_request', - 'negotiation', - 'verifydisco', - 'sreg', - 'ax', - 'pape', - 'pape_draft2', - 'pape_draft5', - 'rpverify', - 'extension', - ] - - pyunit_modules = [ - __import__('openid.test.test_%s' % (name,), {}, {}, ['unused']) - for name in pyunit_module_names - ] - - try: - from openid.test import test_examples - except ImportError as e: - if 'twill' in str(e): - warnings.warn("Could not import twill; skipping test_examples.") - else: - raise - else: - pyunit_modules.append(test_examples) - - # Some modules have data-driven tests, and they use custom methods - # to build the test suite: - custom_module_names = [ - 'kvform', - 'linkparse', - 'oidutil', - 'storetest', - 'test_accept', - 'test_association', - 'test_discover', - 'test_fetchers', - 'test_htmldiscover', - 'test_nonce', - 'test_openidyadis', - 'test_parsehtml', - 'test_urinorm', - 'test_yadis_discover', - 'trustroot', - ] - - loader = unittest.TestLoader() - s = unittest.TestSuite() - - for m in pyunit_modules: - s.addTest(loader.loadTestsFromModule(m)) - - for name in custom_module_names: - m = __import__('openid.test.%s' % (name,), {}, {}, ['unused']) - try: - s.addTest(m.pyUnitTests()) - except AttributeError as ex: - # because the AttributeError doesn't actually say which - # object it was. - print "Error loading tests from %s:" % (name,) - raise - - runner = unittest.TextTestRunner() # verbosity=2) - - return runner.run(s) - - -def splitDir(d, count): - # in python2.4 and above, it's easier to spell this as - # d.rsplit(os.sep, count) - for i in xrange(count): - d = os.path.dirname(d) - return d - - -def _import_djopenid(): - """Import djopenid from examples/ - - It's not in sys.path, and I don't really want to put it in sys.path. - """ - import types - thisfile = os.path.abspath(sys.modules[__name__].__file__) - topDir = splitDir(thisfile, 2) - djdir = os.path.join(topDir, 'examples', 'djopenid') - - djinit = os.path.join(djdir, '__init__.py') - - djopenid = types.ModuleType('djopenid') - execfile(djinit, djopenid.__dict__) - djopenid.__file__ = djinit - - # __path__ is the magic that makes child modules of the djopenid package - # importable. New feature in python 2.3, see PEP 302. - djopenid.__path__ = [djdir] - sys.modules['djopenid'] = djopenid - - -def django_tests(): - """Runs tests from examples/djopenid. - - @returns: number of failed tests. - """ - import os - # Django uses this to find out where its settings are. - os.environ['DJANGO_SETTINGS_MODULE'] = 'djopenid.settings' - - _import_djopenid() - - try: - import django.test.simple - except ImportError as e: - warnings.warn("django.test.simple not found; " - "django examples not tested.") - return 0 - import djopenid.server.models - import djopenid.consumer.models - print "Testing Django examples:" - - # These tests do get put in to a pyunit test suite, so we could run them - # with the other pyunit tests, but django also establishes a test database - # for them, so we let it do that thing instead. - return django.test.simple.run_tests([djopenid.server.models, - djopenid.consumer.models]) - - -try: - bool -except NameError: - def bool(x): - return not not x - - -def main(): - fixpath() - other_failed = otherTests() - pyunit_result = pyunitTests() - django_failures = django_tests() - - if other_failed: - print 'Failures:', ', '.join(other_failed) - - failed = (bool(other_failed) or - bool(not pyunit_result.wasSuccessful()) or - (django_failures > 0)) - return failed - - -if __name__ == '__main__': - sys.exit(main() and 1 or 0) diff --git a/openid/test/test_accept.py b/openid/test/test_accept.py index c180f8c..55e7ede 100644 --- a/openid/test/test_accept.py +++ b/openid/test/test_accept.py @@ -1,3 +1,4 @@ +"""Test `openid.yadis.accept` module.""" import os.path import unittest @@ -112,39 +113,3 @@ class MatchAcceptTest(unittest.TestCase): accepted = accept.parseAcceptHeader(accept_header) actual = accept.matchTypes(accepted, available) self.failUnlessEqual(expected, actual) - - -def pyUnitTests(): - lines = getTestData() - chunks = chunk(lines) - data_sets = map(parseLines, chunks) - cases = [] - for data in data_sets: - lnos = [] - lno, header = data['accept'] - lnos.append(lno) - lno, avail_data = data['available'] - lnos.append(lno) - try: - available = parseAvailable(avail_data) - except Exception: - print 'On line', lno - raise - - lno, exp_data = data['expected'] - lnos.append(lno) - try: - expected = parseExpected(exp_data) - except Exception: - print 'On line', lno - raise - - descr = 'MatchAcceptTest for lines %r' % (lnos,) - case = MatchAcceptTest(descr, header, available, expected) - cases.append(case) - return unittest.TestSuite(cases) - - -if __name__ == '__main__': - runner = unittest.TextTestRunner() - runner.run(pyUnitTests()) diff --git a/openid/test/test_cryptutil.py b/openid/test/test_cryptutil.py index cf6074c..4cf57b0 100644 --- a/openid/test/test_cryptutil.py +++ b/openid/test/test_cryptutil.py @@ -1,6 +1,8 @@ +"""Test `openid.cryptutil` module.""" import os.path import random import sys +import unittest from openid import cryptutil @@ -8,107 +10,84 @@ from openid import cryptutil # find a good source of randomness on this machine. -def test_cryptrand(): - # It's possible, but HIGHLY unlikely that a correct implementation - # will fail by returning the same number twice +class TestRandRange(unittest.TestCase): + """Test `randrange` function.""" - s = cryptutil.getBytes(32) - t = cryptutil.getBytes(32) - assert len(s) == 32 - assert len(t) == 32 - assert s != t + def test_cryptrand(self): + # It's possible, but HIGHLY unlikely that a correct implementation + # will fail by returning the same number twice - a = cryptutil.randrange(2 ** 128) - b = cryptutil.randrange(2 ** 128) - assert isinstance(a, long) - assert isinstance(b, long) - assert b != a + s = cryptutil.getBytes(32) + t = cryptutil.getBytes(32) + assert len(s) == 32 + assert len(t) == 32 + assert s != t - # Make sure that we can generate random numbers that are larger - # than platform int size - cryptutil.randrange(long(sys.maxsize) + 1) + a = cryptutil.randrange(2 ** 128) + b = cryptutil.randrange(2 ** 128) + assert isinstance(a, long) + assert isinstance(b, long) + assert b != a + # Make sure that we can generate random numbers that are larger + # than platform int size + cryptutil.randrange(long(sys.maxsize) + 1) + + +class TestLongBinary(unittest.TestCase): + """Test `longToBinary` and `binaryToLong` functions.""" + + def test_binaryLongConvert(self): + MAX = sys.maxsize + for iteration in xrange(500): + n = 0 + for i in range(10): + n += long(random.randrange(MAX)) + + s = cryptutil.longToBinary(n) + assert isinstance(s, str) + n_prime = cryptutil.binaryToLong(s) + assert n == n_prime, (n, n_prime) -def test_reversed(): - if hasattr(cryptutil, 'reversed'): cases = [ - ('', ''), - ('a', 'a'), - ('ab', 'ba'), - ('abc', 'cba'), - ('abcdefg', 'gfedcba'), - ([], []), - ([1], [1]), - ([1, 2], [2, 1]), - ([1, 2, 3], [3, 2, 1]), - (range(1000), range(999, -1, -1)), + ('\x00', 0), + ('\x01', 1), + ('\x7F', 127), + ('\x00\xFF', 255), + ('\x00\x80', 128), + ('\x00\x81', 129), + ('\x00\x80\x00', 32768), + ('OpenID is cool', 1611215304203901150134421257416556) ] - for case, expected in cases: - expected = list(expected) - actual = list(cryptutil.reversed(case)) - assert actual == expected, (case, expected, actual) - twice = list(cryptutil.reversed(actual)) - assert twice == list(case), (actual, case, twice) - - -def test_binaryLongConvert(): - MAX = sys.maxsize - for iteration in xrange(500): - n = 0 - for i in range(10): - n += long(random.randrange(MAX)) - - s = cryptutil.longToBinary(n) - assert isinstance(s, str) - n_prime = cryptutil.binaryToLong(s) - assert n == n_prime, (n, n_prime) - - cases = [ - ('\x00', 0), - ('\x01', 1), - ('\x7F', 127), - ('\x00\xFF', 255), - ('\x00\x80', 128), - ('\x00\x81', 129), - ('\x00\x80\x00', 32768), - ('OpenID is cool', 1611215304203901150134421257416556) - ] - - for s, n in cases: - n_prime = cryptutil.binaryToLong(s) - s_prime = cryptutil.longToBinary(n) - assert n == n_prime, (s, n, n_prime) - assert s == s_prime, (n, s, s_prime) - - -def test_longToBase64(): - f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) - try: - for line in f: - parts = line.strip().split(' ') - assert parts[0] == cryptutil.longToBase64(long(parts[1])) - finally: - f.close() - - -def test_base64ToLong(): - f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) - try: - for line in f: - parts = line.strip().split(' ') - assert long(parts[1]) == cryptutil.base64ToLong(parts[0]) - finally: - f.close() - - -def test(): - test_reversed() - test_binaryLongConvert() - test_cryptrand() - test_longToBase64() - test_base64ToLong() - - -if __name__ == '__main__': - test() + for s, n in cases: + n_prime = cryptutil.binaryToLong(s) + s_prime = cryptutil.longToBinary(n) + assert n == n_prime, (s, n, n_prime) + assert s == s_prime, (n, s, s_prime) + + +class TestLongToBase64(unittest.TestCase): + """Test `longToBase64` function.""" + + def test_longToBase64(self): + f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) + try: + for line in f: + parts = line.strip().split(' ') + assert parts[0] == cryptutil.longToBase64(long(parts[1])) + finally: + f.close() + + +class TestBase64ToLong(unittest.TestCase): + """Test `Base64ToLong` function.""" + + def test_base64ToLong(self): + f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) + try: + for line in f: + parts = line.strip().split(' ') + assert long(parts[1]) == cryptutil.base64ToLong(parts[0]) + finally: + f.close() diff --git a/openid/test/test_dh.py b/openid/test/test_dh.py index 01a6ab5..6c78a0b 100644 --- a/openid/test/test_dh.py +++ b/openid/test/test_dh.py @@ -1,77 +1,72 @@ +"""Test `openid.dh` module.""" import os.path +import unittest from openid.dh import DiffieHellman, strxor -def test_strxor(): - NUL = '\x00' - - cases = [ - (NUL, NUL, NUL), - ('\x01', NUL, '\x01'), - ('a', 'a', NUL), - ('a', NUL, 'a'), - ('abc', NUL * 3, 'abc'), - ('x' * 10, NUL * 10, 'x' * 10), - ('\x01', '\x02', '\x03'), - ('\xf0', '\x0f', '\xff'), - ('\xff', '\x0f', '\xf0'), - ] - - for aa, bb, expected in cases: - actual = strxor(aa, bb) - assert actual == expected, (aa, bb, expected, actual) - - exc_cases = [ - ('', 'a'), - ('foo', 'ba'), - (NUL * 3, NUL * 4), - (''.join(map(chr, xrange(256))), - ''.join(map(chr, xrange(128)))), - ] - - for aa, bb in exc_cases: +class TestStrXor(unittest.TestCase): + """Test `strxor` function.""" + + def test_strxor(self): + NUL = '\x00' + + cases = [ + (NUL, NUL, NUL), + ('\x01', NUL, '\x01'), + ('a', 'a', NUL), + ('a', NUL, 'a'), + ('abc', NUL * 3, 'abc'), + ('x' * 10, NUL * 10, 'x' * 10), + ('\x01', '\x02', '\x03'), + ('\xf0', '\x0f', '\xff'), + ('\xff', '\x0f', '\xf0'), + ] + + for aa, bb, expected in cases: + actual = strxor(aa, bb) + assert actual == expected, (aa, bb, expected, actual) + + exc_cases = [ + ('', 'a'), + ('foo', 'ba'), + (NUL * 3, NUL * 4), + (''.join(map(chr, xrange(256))), + ''.join(map(chr, xrange(128)))), + ] + + for aa, bb in exc_cases: + try: + unexpected = strxor(aa, bb) + except ValueError: + pass + else: + assert False, 'Expected ValueError, got %r' % (unexpected,) + + +class TestDiffieHellman(unittest.TestCase): + + def _test_dh(self): + dh1 = DiffieHellman.fromDefaults() + dh2 = DiffieHellman.fromDefaults() + secret1 = dh1.getSharedSecret(dh2.public) + secret2 = dh2.getSharedSecret(dh1.public) + assert secret1 == secret2 + return secret1 + + def test_exchange(self): + s1 = self._test_dh() + s2 = self._test_dh() + assert s1 != s2 + + def test_public(self): + f = file(os.path.join(os.path.dirname(__file__), 'dhpriv')) + dh = DiffieHellman.fromDefaults() try: - unexpected = strxor(aa, bb) - except ValueError: - pass - else: - assert False, 'Expected ValueError, got %r' % (unexpected,) - - -def test1(): - dh1 = DiffieHellman.fromDefaults() - dh2 = DiffieHellman.fromDefaults() - secret1 = dh1.getSharedSecret(dh2.public) - secret2 = dh2.getSharedSecret(dh1.public) - assert secret1 == secret2 - return secret1 - - -def test_exchange(): - s1 = test1() - s2 = test1() - assert s1 != s2 - - -def test_public(): - f = file(os.path.join(os.path.dirname(__file__), 'dhpriv')) - dh = DiffieHellman.fromDefaults() - try: - for line in f: - parts = line.strip().split(' ') - dh._setPrivate(long(parts[0])) - - assert dh.public == long(parts[1]) - finally: - f.close() - - -def test(): - test_exchange() - test_public() - test_strxor() - + for line in f: + parts = line.strip().split(' ') + dh._setPrivate(long(parts[0])) -if __name__ == '__main__': - test() + assert dh.public == long(parts[1]) + finally: + f.close() diff --git a/openid/test/test_fetchers.py b/openid/test/test_fetchers.py index 4cf5a22..d7a4e6c 100644 --- a/openid/test/test_fetchers.py +++ b/openid/test/test_fetchers.py @@ -196,23 +196,24 @@ class FetcherTestHandler(BaseHTTPRequestHandler): self.rfile.close() -def test(): - import socket - host = socket.getfqdn('127.0.0.1') - # When I use port 0 here, it works for the first fetch and the - # next one gets connection refused. Bummer. So instead, pick a - # port that's *probably* not in use. - import os - port = (os.getpid() % 31000) + 1024 +class TestFetchers(unittest.TestCase): + def test(self): + import socket + host = socket.getfqdn('127.0.0.1') + # When I use port 0 here, it works for the first fetch and the + # next one gets connection refused. Bummer. So instead, pick a + # port that's *probably* not in use. + import os + port = (os.getpid() % 31000) + 1024 - server = HTTPServer((host, port), FetcherTestHandler) + server = HTTPServer((host, port), FetcherTestHandler) - import threading - server_thread = threading.Thread(target=server.serve_forever) - server_thread.setDaemon(True) - server_thread.start() + import threading + server_thread = threading.Thread(target=server.serve_forever) + server_thread.setDaemon(True) + server_thread.start() - run_fetcher_tests(server) + run_fetcher_tests(server) class FakeFetcher(object): @@ -356,10 +357,3 @@ class TestSilencedUrllib2Fetcher(TestUrllib2Fetcher): fetcher = fetchers.ExceptionWrappingFetcher(fetchers.Urllib2Fetcher()) invalid_url_error = fetchers.HTTPFetchingError - - -def pyUnitTests(): - case1 = unittest.FunctionTestCase(test) - loadTests = unittest.defaultTestLoader.loadTestsFromTestCase - case2 = loadTests(DefaultFetcherTest) - return unittest.TestSuite([case1, case2, loadTests(TestUrllib2Fetcher), loadTests(TestSilencedUrllib2Fetcher)]) diff --git a/openid/test/test_kvform.py b/openid/test/test_kvform.py index a2ebd7d..1992927 100644 --- a/openid/test/test_kvform.py +++ b/openid/test/test_kvform.py @@ -6,8 +6,11 @@ from openid.test.support import CatchLogs class KVBaseTest(unittest.TestCase, CatchLogs): - def checkWarnings(self, num_warnings): - self.failUnlessEqual(num_warnings, len(self.messages), repr(self.messages)) + def checkWarnings(self, num_warnings, msg=None): + full_msg = 'Invalid number of warnings {} != {}'.format(num_warnings, len(self.messages)) + if msg is not None: + full_msg = full_msg + ' ' + msg + self.failUnlessEqual(num_warnings, len(self.messages), full_msg) def setUp(self): CatchLogs.setUp(self) @@ -20,6 +23,9 @@ class KVDictTest(KVBaseTest): def runTest(self): for kv_data, result, expected_warnings in kvdict_cases: + # Clean captrured messages + del self.messages[:] + # Convert KVForm to dict d = kvform.kvToDict(kv_data) @@ -27,7 +33,7 @@ class KVDictTest(KVBaseTest): self.failUnlessEqual(d, result) # Check to make sure we got the expected number of warnings - self.checkWarnings(expected_warnings) + self.checkWarnings(expected_warnings, msg='kvToDict({!r})'.format(kv_data)) # Convert back to KVForm and round-trip back to dict to make # sure that *** dict -> kv -> dict is identity. *** @@ -42,7 +48,7 @@ class KVSeqTest(KVBaseTest): """Create a new sequence by stripping whitespace from start and end of each value of each pair""" clean = [] - for k, v in self.seq: + for k, v in seq: if isinstance(k, str): k = k.decode('utf8') if isinstance(v, str): @@ -52,6 +58,9 @@ class KVSeqTest(KVBaseTest): def runTest(self): for kv_data, result, expected_warnings in kvseq_cases: + # Clean captrured messages + del self.messages[:] + # seq serializes to expected kvform actual = kvform.seqToKV(kv_data) self.failUnlessEqual(actual, result) @@ -148,17 +157,3 @@ class GeneralTest(KVBaseTest): result = kvform.seqToKV([(1, 1)]) self.failUnlessEqual(result, '1:1\n') self.checkWarnings(2) - - -def pyUnitTests(): - tests = [KVDictTest(*case) for case in kvdict_cases] - tests.extend([KVSeqTest(*case) for case in kvseq_cases]) - tests.extend([KVExcTest(case) for case in kvexc_cases]) - tests.append(unittest.defaultTestLoader.loadTestsFromTestCase(GeneralTest)) - return unittest.TestSuite(tests) - - -if __name__ == '__main__': - suite = pyUnitTests() - runner = unittest.TextTestRunner() - runner.run(suite) diff --git a/openid/test/test_linkparse.py b/openid/test/test_linkparse.py index f31f9ef..230bd05 100644 --- a/openid/test/test_linkparse.py +++ b/openid/test/test_linkparse.py @@ -1,4 +1,4 @@ -import codecs +"""Test `openid.consumer.html_parse` module.""" import os.path import unittest @@ -47,70 +47,42 @@ def parseTests(s): desc, markup, links = parseCase(case) tests.append((desc, markup, links, case)) + assert len(tests) == num_tests, (len(tests), num_tests) return num_tests, tests -class _LinkTest(unittest.TestCase): - def __init__(self, desc, case, expected, raw): - unittest.TestCase.__init__(self) - self.desc = desc - self.case = case - self.expected = expected - self.raw = raw +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'linkparse.txt')) as link_test_data_file: + link_test_data = link_test_data_file.read().decode('utf-8') - def shortDescription(self): - return self.desc + +class LinkTest(unittest.TestCase): + """Test `parseLinkAttrs` function.""" def runTest(self): - actual = parseLinkAttrs(self.case) - i = 0 - for optional, exp_link in self.expected: - if optional: - if i >= len(actual): - continue - - act_link = actual[i] - for k, (o, v) in exp_link.items(): - if o: - act_v = act_link.get(k) - if act_v is None: + num_tests, test_cases = parseTests(link_test_data) + + for desc, case, expected, raw in test_cases: + actual = parseLinkAttrs(case) + i = 0 + for optional, exp_link in expected: + if optional: + if i >= len(actual): continue - else: - act_v = act_link[k] - - if optional and v != act_v: - break - - self.assertEqual(v, act_v) - else: - i += 1 - - assert i == len(actual) - -def pyUnitTests(): - here = os.path.dirname(os.path.abspath(__file__)) - test_data_file_name = os.path.join(here, 'linkparse.txt') - test_data_file = codecs.open(test_data_file_name, 'r', 'utf-8') - test_data = test_data_file.read() - test_data_file.close() + act_link = actual[i] + for k, (o, v) in exp_link.items(): + if o: + act_v = act_link.get(k) + if act_v is None: + continue + else: + act_v = act_link[k] - num_tests, test_cases = parseTests(test_data) - - tests = [_LinkTest(*case) for case in test_cases] - - def test_parseSucceeded(): - assert len(test_cases) == num_tests, (len(test_cases), num_tests) - - check_desc = 'Check that we parsed the correct number of test cases' - check = unittest.FunctionTestCase( - test_parseSucceeded, description=check_desc) - tests.insert(0, check) - - return unittest.TestSuite(tests) + if optional and v != act_v: + break + self.assertEqual(v, act_v) + else: + i += 1 -if __name__ == '__main__': - suite = pyUnitTests() - runner = unittest.TextTestRunner() - runner.run(suite) + assert i == len(actual) diff --git a/openid/test/test_oidutil.py b/openid/test/test_oidutil.py index c7a002f..7eed886 100644 --- a/openid/test/test_oidutil.py +++ b/openid/test/test_oidutil.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +"""Test `openid.oidutil` module.""" import random import string import unittest @@ -6,55 +7,128 @@ import unittest from openid import oidutil -def test_base64(): - allowed_s = string.ascii_letters + string.digits + '+/=' - allowed_d = {} - for c in allowed_s: - allowed_d[c] = None - isAllowed = allowed_d.has_key - - def checkEncoded(s): - for c in s: - assert isAllowed(c), s - - cases = [ - '', - 'x', - '\x00', - '\x01', - '\x00' * 100, - ''.join(map(chr, range(256))), - ] - - for s in cases: - b64 = oidutil.toBase64(s) - checkEncoded(b64) - s_prime = oidutil.fromBase64(b64) - assert s_prime == s, (s, b64, s_prime) - - # Randomized test - for _ in xrange(50): - n = random.randrange(2048) - s = ''.join(map(chr, map(lambda _: random.randrange(256), range(n)))) - b64 = oidutil.toBase64(s) - checkEncoded(b64) - s_prime = oidutil.fromBase64(b64) - assert s_prime == s, (s, b64, s_prime) +class TestBase64(unittest.TestCase): + """Test `toBase64` and `fromBase64` functions.""" + + def test_base64(self): + allowed_s = string.ascii_letters + string.digits + '+/=' + allowed_d = {} + for c in allowed_s: + allowed_d[c] = None + isAllowed = allowed_d.has_key + + def checkEncoded(s): + for c in s: + assert isAllowed(c), s + + cases = [ + '', + 'x', + '\x00', + '\x01', + '\x00' * 100, + ''.join(map(chr, range(256))), + ] + + for s in cases: + b64 = oidutil.toBase64(s) + checkEncoded(b64) + s_prime = oidutil.fromBase64(b64) + assert s_prime == s, (s, b64, s_prime) + + # Randomized test + for _ in xrange(50): + n = random.randrange(2048) + s = ''.join(map(chr, map(lambda _: random.randrange(256), range(n)))) + b64 = oidutil.toBase64(s) + checkEncoded(b64) + s_prime = oidutil.fromBase64(b64) + assert s_prime == s, (s, b64, s_prime) + + +simple = 'http://www.example.com/' +append_args_cases = [ + ('empty list', + (simple, []), + simple), + + ('empty dict', + (simple, {}), + simple), + + ('one list', + (simple, [('a', 'b')]), + simple + '?a=b'), + + ('one dict', + (simple, {'a': 'b'}), + simple + '?a=b'), + + ('two list (same)', + (simple, [('a', 'b'), ('a', 'c')]), + simple + '?a=b&a=c'), + + ('two list', + (simple, [('a', 'b'), ('b', 'c')]), + simple + '?a=b&b=c'), + + ('two list (order)', + (simple, [('b', 'c'), ('a', 'b')]), + simple + '?b=c&a=b'), + + ('two dict (order)', + (simple, {'b': 'c', 'a': 'b'}), + simple + '?a=b&b=c'), + + ('escape', + (simple, [('=', '=')]), + simple + '?%3D=%3D'), + + ('escape (URL)', + (simple, [('this_url', simple)]), + simple + '?this_url=http%3A%2F%2Fwww.example.com%2F'), + + ('use dots', + (simple, [('openid.stuff', 'bother')]), + simple + '?openid.stuff=bother'), + + ('args exist (empty)', + (simple + '?stuff=bother', []), + simple + '?stuff=bother'), + + ('args exist', + (simple + '?stuff=bother', [('ack', 'ack')]), + simple + '?stuff=bother&ack=ack'), + + ('args exist', + (simple + '?stuff=bother', [('ack', 'ack')]), + simple + '?stuff=bother&ack=ack'), + + ('args exist (dict)', + (simple + '?stuff=bother', {'ack': 'ack'}), + simple + '?stuff=bother&ack=ack'), + + ('args exist (dict 2)', + (simple + '?stuff=bother', {'ack': 'ack', 'zebra': 'lion'}), + simple + '?stuff=bother&ack=ack&zebra=lion'), + + ('three args (dict)', + (simple, {'stuff': 'bother', 'ack': 'ack', 'zebra': 'lion'}), + simple + '?ack=ack&stuff=bother&zebra=lion'), + + ('three args (list)', + (simple, [('stuff', 'bother'), ('ack', 'ack'), ('zebra', 'lion')]), + simple + '?stuff=bother&ack=ack&zebra=lion'), +] class AppendArgsTest(unittest.TestCase): - def __init__(self, desc, args, expected): - unittest.TestCase.__init__(self) - self.desc = desc - self.args = args - self.expected = expected + """Test `appendArgs` function.""" def runTest(self): - result = oidutil.appendArgs(*self.args) - self.assertEqual(self.expected, result, self.args) - - def shortDescription(self): - return self.desc + for name, args, expected in append_args_cases: + result = oidutil.appendArgs(*args) + self.assertEqual(expected, result, '{} {}'.format(name, args)) class TestUnicodeConversion(unittest.TestCase): @@ -82,115 +156,6 @@ class TestSymbol(unittest.TestCase): self.failIfEqual(hash(s), hash(t)) -def buildAppendTests(): - simple = 'http://www.example.com/' - cases = [ - ('empty list', - (simple, []), - simple), - - ('empty dict', - (simple, {}), - simple), - - ('one list', - (simple, [('a', 'b')]), - simple + '?a=b'), - - ('one dict', - (simple, {'a': 'b'}), - simple + '?a=b'), - - ('two list (same)', - (simple, [('a', 'b'), ('a', 'c')]), - simple + '?a=b&a=c'), - - ('two list', - (simple, [('a', 'b'), ('b', 'c')]), - simple + '?a=b&b=c'), - - ('two list (order)', - (simple, [('b', 'c'), ('a', 'b')]), - simple + '?b=c&a=b'), - - ('two dict (order)', - (simple, {'b': 'c', 'a': 'b'}), - simple + '?a=b&b=c'), - - ('escape', - (simple, [('=', '=')]), - simple + '?%3D=%3D'), - - ('escape (URL)', - (simple, [('this_url', simple)]), - simple + '?this_url=http%3A%2F%2Fwww.example.com%2F'), - - ('use dots', - (simple, [('openid.stuff', 'bother')]), - simple + '?openid.stuff=bother'), - - ('args exist (empty)', - (simple + '?stuff=bother', []), - simple + '?stuff=bother'), - - ('args exist', - (simple + '?stuff=bother', [('ack', 'ack')]), - simple + '?stuff=bother&ack=ack'), - - ('args exist', - (simple + '?stuff=bother', [('ack', 'ack')]), - simple + '?stuff=bother&ack=ack'), - - ('args exist (dict)', - (simple + '?stuff=bother', {'ack': 'ack'}), - simple + '?stuff=bother&ack=ack'), - - ('args exist (dict 2)', - (simple + '?stuff=bother', {'ack': 'ack', 'zebra': 'lion'}), - simple + '?stuff=bother&ack=ack&zebra=lion'), - - ('three args (dict)', - (simple, {'stuff': 'bother', 'ack': 'ack', 'zebra': 'lion'}), - simple + '?ack=ack&stuff=bother&zebra=lion'), - - ('three args (list)', - (simple, [('stuff', 'bother'), ('ack', 'ack'), ('zebra', 'lion')]), - simple + '?stuff=bother&ack=ack&zebra=lion'), - ] - - tests = [] - - for name, args, expected in cases: - test = AppendArgsTest(name, args, expected) - tests.append(test) - - return unittest.TestSuite(tests) - - -def pyUnitTests(): - some = buildAppendTests() - some.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(TestSymbol)) - some.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(TestUnicodeConversion)) - return some - - -def test_appendArgs(): - suite = buildAppendTests() - suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(TestSymbol)) - runner = unittest.TextTestRunner() - result = runner.run(suite) - assert result.wasSuccessful() - # XXX: there are more functions that could benefit from being better # specified and tested in oidutil.py These include, but are not # limited to appendArgs - - -def test(skipPyUnit=True): - test_base64() - if not skipPyUnit: - test_appendArgs() - - -if __name__ == '__main__': - test(skipPyUnit=False) diff --git a/openid/test/test_openidyadis.py b/openid/test/test_openidyadis.py index 3f730b5..4a76749 100644 --- a/openid/test/test_openidyadis.py +++ b/openid/test/test_openidyadis.py @@ -154,10 +154,3 @@ class OpenIDYadisTest(unittest.TestCase): # Make sure we saw all URIs, and saw each one once self.failUnlessEqual(uris, seen_uris) - - -def pyUnitTests(): - cases = [] - for args in data: - cases.append(OpenIDYadisTest(*args)) - return unittest.TestSuite(cases) diff --git a/openid/test/test_parsehtml.py b/openid/test/test_parsehtml.py index 4ee1b61..bd5a626 100644 --- a/openid/test/test_parsehtml.py +++ b/openid/test/test_parsehtml.py @@ -1,15 +1,14 @@ import os.path -import sys import unittest from HTMLParser import HTMLParseError from openid.yadis.parsehtml import ParseDone, YadisHTMLParser -class _TestCase(unittest.TestCase): +class TestParseHTML(unittest.TestCase): reserved_values = ['None', 'EOF'] - def runTest(self): + def test(self): for expected, case in getCases(): p = YadisHTMLParser() try: @@ -41,19 +40,6 @@ def parseCases(data): return cases -def pyUnitTests(): - """Make a pyunit TestSuite from a file defining test cases.""" - s = unittest.TestSuite() - for (filename, test_num, expected, case) in getCases(): - s.addTest(_TestCase(filename, str(test_num), expected, case)) - return s - - -def test(): - runner = unittest.TextTestRunner() - return runner.run(pyUnitTests()) - - filenames = ['data/test1-parsehtml.txt'] default_test_files = [] @@ -70,7 +56,3 @@ def getCases(test_files=default_test_files): for expected, case in parseCases(data): cases.append((expected, case)) return cases - - -if __name__ == '__main__': - sys.exit(not test().wasSuccessful()) diff --git a/openid/test/test_storetest.py b/openid/test/test_storetest.py index a3885b5..6937f04 100644 --- a/openid/test/test_storetest.py +++ b/openid/test/test_storetest.py @@ -1,3 +1,4 @@ +"""Test `openid.store` module.""" import os import random import socket @@ -222,179 +223,169 @@ def testStore(store): nonceModule.SKEW = orig_skew -def test_filestore(): - from openid.store import filestore - import tempfile - import shutil - try: - temp_dir = tempfile.mkdtemp() - except AttributeError: - import os - temp_dir = os.tmpnam() - os.mkdir(temp_dir) +class TestFileOpenIDStore(unittest.TestCase): + """Test `FileOpenIDStore` class.""" - store = filestore.FileOpenIDStore(temp_dir) - try: - testStore(store) - store.cleanup() - except Exception: - raise - else: - shutil.rmtree(temp_dir) + def test_filestore(self): + from openid.store import filestore + import tempfile + import shutil + try: + temp_dir = tempfile.mkdtemp() + except AttributeError: + import os + temp_dir = os.tmpnam() + os.mkdir(temp_dir) + store = filestore.FileOpenIDStore(temp_dir) + try: + testStore(store) + store.cleanup() + except Exception: + raise + else: + shutil.rmtree(temp_dir) -def test_sqlite(): - from openid.store import sqlstore - try: - from pysqlite2 import dbapi2 as sqlite - except ImportError: - pass - else: - conn = sqlite.connect(':memory:') - store = sqlstore.SQLiteStore(conn) - store.createTables() - testStore(store) - - -def test_mysql(): - from openid.store import sqlstore - try: - import MySQLdb - except ImportError: - pass - else: - db_user = 'openid_test' - db_passwd = '' - db_name = getTmpDbName() - - # Change this connect line to use the right user and password + +class TestSQLiteStore(unittest.TestCase): + """Test `SQLiteStore` class.""" + + def test_sqlite(self): + from openid.store import sqlstore try: - conn = MySQLdb.connect(user=db_user, passwd=db_passwd, host=db_host) - except MySQLdb.OperationalError as why: - if why[0] == 2005: - print ('Skipping MySQL store test (cannot connect ' - 'to test server on host %r)' % (db_host,)) - return - else: - raise - - conn.query('CREATE DATABASE %s;' % db_name) + from pysqlite2 import dbapi2 as sqlite + except ImportError: + pass + else: + conn = sqlite.connect(':memory:') + store = sqlstore.SQLiteStore(conn) + store.createTables() + testStore(store) + + +class TestMySQLStore(unittest.TestCase): + """Test `MySQLStore` class.""" + + def test_mysql(self): + from openid.store import sqlstore try: - conn.query('USE %s;' % db_name) + import MySQLdb + except ImportError: + pass + else: + db_user = 'openid_test' + db_passwd = '' + db_name = getTmpDbName() - # OK, we're in the right environment. Create store and - # create the tables. - store = sqlstore.MySQLStore(conn) - store.createTables() + # Change this connect line to use the right user and password + try: + conn = MySQLdb.connect(user=db_user, passwd=db_passwd, host=db_host) + except MySQLdb.OperationalError as why: + if why[0] == 2005: + print ('Skipping MySQL store test (cannot connect ' + 'to test server on host %r)' % (db_host,)) + return + else: + raise - # At last, we get to run the test. - testStore(store) - finally: - # Remove the database. If you want to do post-mortem on a - # failing test, comment out this line. - conn.query('DROP DATABASE %s;' % db_name) + conn.query('CREATE DATABASE %s;' % db_name) + try: + conn.query('USE %s;' % db_name) + # OK, we're in the right environment. Create store and + # create the tables. + store = sqlstore.MySQLStore(conn) + store.createTables() -def test_postgresql(): - """ - Tests the PostgreSQLStore on a locally-hosted PostgreSQL database - cluster, version 7.4 or later. To run this test, you must have: + # At last, we get to run the test. + testStore(store) + finally: + # Remove the database. If you want to do post-mortem on a + # failing test, comment out this line. + conn.query('DROP DATABASE %s;' % db_name) - - The 'psycopg' python module (version 1.1) installed - - PostgreSQL running locally +class TestPostgreSQLStore(unittest.TestCase): + """Test `PostgreSQLStore` class.""" - - An 'openid_test' user account in your database cluster, which - you can create by running 'createuser -Ad openid_test' as the - 'postgres' user + def test_postgresql(self): + """ + Tests the PostgreSQLStore on a locally-hosted PostgreSQL database + cluster, version 7.4 or later. To run this test, you must have: - - Trust auth for the 'openid_test' account, which you can activate - by adding the following line to your pg_hba.conf file: + - The 'psycopg' python module (version 1.1) installed - local all openid_test trust + - PostgreSQL running locally - This test connects to the database cluster three times: + - An 'openid_test' user account in your database cluster, which + you can create by running 'createuser -Ad openid_test' as the + 'postgres' user - - To the 'template1' database, to create the test database + - Trust auth for the 'openid_test' account, which you can activate + by adding the following line to your pg_hba.conf file: - - To the test database, to run the store tests + local all openid_test trust - - To the 'template1' database once more, to drop the test database - """ - from openid.store import sqlstore - try: - import psycopg - except ImportError: - pass - else: - db_name = getTmpDbName() - db_user = 'openid_test' - - # Connect once to create the database; reconnect to access the - # new database. - conn_create = psycopg.connect(database='template1', user=db_user, host=db_host) - conn_create.autocommit() - - # Create the test database. - cursor = conn_create.cursor() - cursor.execute('CREATE DATABASE %s;' % (db_name,)) - conn_create.close() - - # Connect to the test database. - conn_test = psycopg.connect(database=db_name, user=db_user, host=db_host) - - # OK, we're in the right environment. Create the store - # instance and create the tables. - store = sqlstore.PostgreSQLStore(conn_test) - store.createTables() - - # At last, we get to run the test. - testStore(store) - - # Disconnect. - conn_test.close() - - # It takes a little time for the close() call above to take - # effect, so we'll wait for a second before trying to remove - # the database. (Maybe this is because we're using a UNIX - # socket to connect to postgres rather than TCP?) - import time - time.sleep(1) - - # Remove the database now that the test is over. - conn_remove = psycopg.connect(database='template1', user=db_user, host=db_host) - conn_remove.autocommit() - - cursor = conn_remove.cursor() - cursor.execute('DROP DATABASE %s;' % (db_name,)) - conn_remove.close() - - -def test_memstore(): - from openid.store import memstore - testStore(memstore.MemoryStore()) - - -test_functions = [ - test_filestore, - test_sqlite, - test_mysql, - test_postgresql, - test_memstore, -] - - -def pyUnitTests(): - tests = map(unittest.FunctionTestCase, test_functions) - return unittest.TestSuite(tests) - - -if __name__ == '__main__': - import sys - suite = pyUnitTests() - runner = unittest.TextTestRunner() - result = runner.run(suite) - if result.wasSuccessful(): - sys.exit(0) - else: - sys.exit(1) + This test connects to the database cluster three times: + + - To the 'template1' database, to create the test database + + - To the test database, to run the store tests + + - To the 'template1' database once more, to drop the test database + """ + from openid.store import sqlstore + try: + import psycopg + except ImportError: + pass + else: + db_name = getTmpDbName() + db_user = 'openid_test' + + # Connect once to create the database; reconnect to access the + # new database. + conn_create = psycopg.connect(database='template1', user=db_user, host=db_host) + conn_create.autocommit() + + # Create the test database. + cursor = conn_create.cursor() + cursor.execute('CREATE DATABASE %s;' % (db_name,)) + conn_create.close() + + # Connect to the test database. + conn_test = psycopg.connect(database=db_name, user=db_user, host=db_host) + + # OK, we're in the right environment. Create the store + # instance and create the tables. + store = sqlstore.PostgreSQLStore(conn_test) + store.createTables() + + # At last, we get to run the test. + testStore(store) + + # Disconnect. + conn_test.close() + + # It takes a little time for the close() call above to take + # effect, so we'll wait for a second before trying to remove + # the database. (Maybe this is because we're using a UNIX + # socket to connect to postgres rather than TCP?) + import time + time.sleep(1) + + # Remove the database now that the test is over. + conn_remove = psycopg.connect(database='template1', user=db_user, host=db_host) + conn_remove.autocommit() + + cursor = conn_remove.cursor() + cursor.execute('DROP DATABASE %s;' % (db_name,)) + conn_remove.close() + + +class TestMemoryStore(unittest.TestCase): + """Test `MemoryStore` class.""" + + def test_memstore(self): + from openid.store import memstore + testStore(memstore.MemoryStore()) diff --git a/openid/test/test_trustroot.py b/openid/test/test_trustroot.py index c9a0f72..7905e4a 100644 --- a/openid/test/test_trustroot.py +++ b/openid/test/test_trustroot.py @@ -3,51 +3,43 @@ import unittest from openid.server.trustroot import TrustRoot +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'trustroot.txt')) as test_data_file: + trustroot_test_data = test_data_file.read() -class _ParseTest(unittest.TestCase): - def __init__(self, sanity, desc, case): - unittest.TestCase.__init__(self) - self.desc = desc + ': ' + repr(case) - self.case = case - self.sanity = sanity - def shortDescription(self): - return self.desc +class ParseTest(unittest.TestCase): - def runTest(self): - tr = TrustRoot.parse(self.case) - if self.sanity == 'sane': - assert tr.isSane(), self.case - elif self.sanity == 'insane': - assert not tr.isSane(), self.case - else: - assert tr is None, tr + def test(self): + ph, pdat, mh, mdat = parseTests(trustroot_test_data) + for sanity, desc, case in getTests(['bad', 'insane', 'sane'], ph, pdat): + tr = TrustRoot.parse(case) + if sanity == 'sane': + assert tr.isSane(), case + elif sanity == 'insane': + assert not tr.isSane(), case + else: + assert tr is None, tr -class _MatchTest(unittest.TestCase): - def __init__(self, match, desc, line): - unittest.TestCase.__init__(self) - tr, rt = line.split() - self.desc = desc + ': ' + repr(tr) + ' ' + repr(rt) - self.tr = tr - self.rt = rt - self.match = match - def shortDescription(self): - return self.desc +class MatchTest(unittest.TestCase): - def runTest(self): - tr = TrustRoot.parse(self.tr) - self.failIf(tr is None, self.tr) + def test(self): + ph, pdat, mh, mdat = parseTests(trustroot_test_data) - match = tr.validateURL(self.rt) - if self.match: - assert match - else: - assert not match + for expected_match, desc, line in getTests([1, 0], mh, mdat): + tr, rt = line.split() + tr = TrustRoot.parse(tr) + self.failIf(tr is None, tr) + match = tr.validateURL(rt) + if expected_match: + assert match + else: + assert not match -def getTests(t, grps, head, dat): + +def getTests(grps, head, dat): tests = [] top = head.strip() gdat = map(str.strip, dat.split('-' * 40 + '\n')) @@ -59,7 +51,7 @@ def getTests(t, grps, head, dat): cases = gdat[i + 1].split('\n') assert len(cases) == int(n) for case in cases: - tests.append(t(x, top + ' - ' + desc, case)) + tests.append((x, top + ' - ' + desc, case)) i += 2 return tests @@ -68,25 +60,4 @@ def parseTests(data): parts = map(str.strip, data.split('=' * 40 + '\n')) assert not parts[0] _, ph, pdat, mh, mdat = parts - - tests = [] - tests.extend(getTests(_ParseTest, ['bad', 'insane', 'sane'], ph, pdat)) - tests.extend(getTests(_MatchTest, [1, 0], mh, mdat)) - return tests - - -def pyUnitTests(): - here = os.path.dirname(os.path.abspath(__file__)) - test_data_file_name = os.path.join(here, 'data', 'trustroot.txt') - test_data_file = file(test_data_file_name) - test_data = test_data_file.read() - test_data_file.close() - - tests = parseTests(test_data) - return unittest.TestSuite(tests) - - -if __name__ == '__main__': - suite = pyUnitTests() - runner = unittest.TextTestRunner() - runner.run(suite) + return ph, pdat, mh, mdat diff --git a/openid/test/test_urinorm.py b/openid/test/test_urinorm.py index 49f18fc..0db74eb 100644 --- a/openid/test/test_urinorm.py +++ b/openid/test/test_urinorm.py @@ -3,7 +3,6 @@ import unittest import openid.urinorm - with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'urinorm.txt')) as test_data_file: test_data = test_data_file.read() @@ -29,27 +28,3 @@ class UrinormTest(unittest.TestCase): case = unicode(case, 'utf-8') return (desc, case, expected) - - -def parseTests(test_data): - result = [] - - cases = test_data.split('\n\n') - for case in cases: - case = case.strip() - - if case: - result.append(UrinormTest.parse(case)) - - return result - - -def pyUnitTests(): - here = os.path.dirname(os.path.abspath(__file__)) - test_data_file_name = os.path.join(here, 'urinorm.txt') - test_data_file = file(test_data_file_name) - test_data = test_data_file.read() - test_data_file.close() - - tests = parseTests(test_data) - return unittest.TestSuite(tests) diff --git a/openid/test/test_yadis_discover.py b/openid/test/test_yadis_discover.py index c7ba05c..e00f0e8 100644 --- a/openid/test/test_yadis_discover.py +++ b/openid/test/test_yadis_discover.py @@ -96,90 +96,51 @@ class TestSecondGet(unittest.TestCase): self.failUnlessRaises(DiscoveryFailure, discover, uri) -class _TestCase(unittest.TestCase): +class TestDiscover(unittest.TestCase): base_url = 'http://invalid.unittest/' - def __init__(self, input_name, id_name, result_name, success): - self.input_name = input_name - self.id_name = id_name - self.result_name = result_name - self.success = success - # Still not quite sure how to best construct these custom tests. - # Between python2.3 and python2.4, a patch attached to pyunit.sf.net - # bug #469444 got applied which breaks loadTestsFromModule on this - # class if it has test_ or runTest methods. So, kludge to change - # the method name. - unittest.TestCase.__init__(self, methodName='runCustomTest') - def setUp(self): fetchers.setDefaultFetcher(TestFetcher(self.base_url), wrap_exceptions=False) - self.input_url, self.expected = discoverdata.generateResult( - self.base_url, - self.input_name, - self.id_name, - self.result_name, - self.success) - def tearDown(self): fetchers.setDefaultFetcher(None) - def runCustomTest(self): - if self.expected is DiscoveryFailure: - self.failUnlessRaises(DiscoveryFailure, - discover, self.input_url) - else: - result = discover(self.input_url) - self.failUnlessEqual(self.input_url, result.request_uri) - - msg = 'Identity URL mismatch: actual = %r, expected = %r' % ( - result.normalized_uri, self.expected.normalized_uri) - self.failUnlessEqual( - self.expected.normalized_uri, result.normalized_uri, msg) - - msg = 'Content mismatch: actual = %r, expected = %r' % ( - result.response_text, self.expected.response_text) - self.failUnlessEqual( - self.expected.response_text, result.response_text, msg) - - expected_keys = sorted(dir(self.expected)) - actual_keys = sorted(dir(result)) - self.failUnlessEqual(actual_keys, expected_keys) - - for k in dir(self.expected): - if k.startswith('__') and k.endswith('__'): - continue - exp_v = getattr(self.expected, k) - if isinstance(exp_v, types.MethodType): - continue - act_v = getattr(result, k) - assert act_v == exp_v, (k, exp_v, act_v) - - def shortDescription(self): - try: - n = self.input_url - except AttributeError: - # run before setUp, or if setUp did not complete successfully. - n = self.input_name - return "%s (%s)" % ( - n, - self.__class__.__module__) - - -def pyUnitTests(): - s = unittest.TestSuite() - for success, input_name, id_name, result_name in discoverdata.testlist: - test = _TestCase(input_name, id_name, result_name, success) - s.addTest(test) - - return s - - -def test(): - runner = unittest.TextTestRunner() - return runner.run(pyUnitTests()) - - -if __name__ == '__main__': - test() + def test(self): + for success, input_name, id_name, result_name in discoverdata.testlist: + input_url, expected = discoverdata.generateResult( + self.base_url, + input_name, + id_name, + result_name, + success) + + if expected is DiscoveryFailure: + self.failUnlessRaises(DiscoveryFailure, + discover, input_url) + else: + result = discover(input_url) + self.failUnlessEqual(input_url, result.request_uri) + + msg = 'Identity URL mismatch: actual = %r, expected = %r' % ( + result.normalized_uri, expected.normalized_uri) + self.failUnlessEqual( + expected.normalized_uri, result.normalized_uri, msg) + + msg = 'Content mismatch: actual = %r, expected = %r' % ( + result.response_text, expected.response_text) + self.failUnlessEqual( + expected.response_text, result.response_text, msg) + + expected_keys = sorted(dir(expected)) + actual_keys = sorted(dir(result)) + self.failUnlessEqual(actual_keys, expected_keys) + + for k in dir(expected): + if k.startswith('__') and k.endswith('__'): + continue + exp_v = getattr(expected, k) + if isinstance(exp_v, types.MethodType): + continue + act_v = getattr(result, k) + assert act_v == exp_v, (k, exp_v, act_v) |