86>May 24 12:50:04 userdel[3469461]: delete user 'rooter' <86>May 24 12:50:04 userdel[3469461]: removed group 'rooter' owned by 'rooter' <86>May 24 12:50:04 userdel[3469461]: removed shadow group 'rooter' owned by 'rooter' <86>May 24 12:50:04 groupadd[3469477]: group added to /etc/group: name=rooter, GID=591 <86>May 24 12:50:04 groupadd[3469477]: group added to /etc/gshadow: name=rooter <86>May 24 12:50:04 groupadd[3469477]: new group: name=rooter, GID=591 <86>May 24 12:50:04 useradd[3469486]: new user: name=rooter, UID=591, GID=591, home=/root, shell=/bin/bash <86>May 24 12:50:04 userdel[3469504]: delete user 'builder' <86>May 24 12:50:04 userdel[3469504]: removed group 'builder' owned by 'builder' <86>May 24 12:50:04 userdel[3469504]: removed shadow group 'builder' owned by 'builder' <86>May 24 12:50:04 groupadd[3469517]: group added to /etc/group: name=builder, GID=592 <86>May 24 12:50:04 groupadd[3469517]: group added to /etc/gshadow: name=builder <86>May 24 12:50:04 groupadd[3469517]: new group: name=builder, GID=592 <86>May 24 12:50:04 useradd[3469530]: new user: name=builder, UID=592, GID=592, home=/usr/src, shell=/bin/bash <13>May 24 12:50:08 rpmi: libgdbm-1.8.3-alt10 1454943334 installed <13>May 24 12:50:08 rpmi: libexpat-2.2.4-alt1 1503305345 installed <13>May 24 12:50:08 rpmi: libp11-kit-0.23.15-alt1 sisyphus+226408.100.2.1 1554288204 installed <13>May 24 12:50:08 rpmi: libtasn1-4.14-alt1 p9+235792.100.2.1 1565425233 installed <13>May 24 12:50:08 rpmi: rpm-macros-alternatives-0.5.1-alt1 sisyphus+226946.100.1.1 1554830426 installed <13>May 24 12:50:08 rpmi: alternatives-0.5.1-alt1 sisyphus+226946.100.1.1 1554830426 installed <13>May 24 12:50:08 rpmi: ca-certificates-2020.01.23-alt1 p9+245253.100.3.1 1580749631 installed <13>May 24 12:50:08 rpmi: ca-trust-0.1.2-alt1 p9+233349.100.1.1 1561655062 installed <13>May 24 12:50:08 rpmi: p11-kit-trust-0.23.15-alt1 sisyphus+226408.100.2.1 1554288204 installed <13>May 24 12:50:08 rpmi: libcrypto1.1-1.1.1g-alt1 p9+250580.100.5.1 1588175266 installed <13>May 24 12:50:08 rpmi: libssl1.1-1.1.1g-alt1 p9+250580.100.5.1 1588175266 installed <13>May 24 12:50:08 rpmi: python3-3.7.4-alt3 p9+249932.100.2.1 1587127349 installed <13>May 24 12:50:08 rpmi: libpython3-3.7.4-alt3 p9+249932.100.2.1 1587127349 installed <13>May 24 12:50:09 rpmi: python3-base-3.7.4-alt3 p9+249932.100.2.1 1587127349 installed <13>May 24 12:50:09 rpmi: tests-for-installed-python3-pkgs-0.1.13.1-alt2 1535450458 installed <13>May 24 12:50:09 rpmi: rpm-build-python3-0.1.13.1-alt2 1535450458 installed <13>May 24 12:50:14 rpmi: python-modules-curses-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: libtinfo-devel-6.1.20180407-alt2 sisyphus+222164.200.1.1 1550686226 installed <13>May 24 12:50:14 rpmi: libncurses-devel-6.1.20180407-alt2 sisyphus+222164.200.1.1 1550686226 installed <13>May 24 12:50:14 rpmi: libverto-0.3.0-alt1_7 sisyphus+225932.100.1.1 1553994919 installed <13>May 24 12:50:14 rpmi: libkeyutils-1.6-alt2 sisyphus+226520.100.2.1 1554512089 installed <13>May 24 12:50:14 rpmi: libcom_err-1.44.6-alt1 sisyphus+224154.100.1.1 1552091678 installed <86>May 24 12:50:14 groupadd[3483205]: group added to /etc/group: name=_keytab, GID=499 <86>May 24 12:50:14 groupadd[3483205]: group added to /etc/gshadow: name=_keytab <86>May 24 12:50:14 groupadd[3483205]: new group: name=_keytab, GID=499 <13>May 24 12:50:14 rpmi: libkrb5-1.17.1-alt1 p9+242852.100.2.1 1576572639 installed <13>May 24 12:50:14 rpmi: libtirpc-1.0.3-alt1 1532008017 installed <13>May 24 12:50:14 rpmi: libnsl2-1.1.0-alt1_1 1511548749 installed <13>May 24 12:50:14 rpmi: python-modules-compiler-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-email-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-unittest-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-encodings-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-nis-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-xml-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-hotshot-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-bsddb-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-ctypes-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-multiprocessing-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-logging-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:14 rpmi: python-modules-distutils-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:15 rpmi: libnsl2-devel-1.1.0-alt1_1 1511548749 installed <13>May 24 12:50:15 rpmi: python-dev-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:15 rpmi: python-tools-2to3-2.7.16-alt1.M90P.1 p9+244933.100.1.1 1579867218 installed <13>May 24 12:50:15 rpmi: python3-dev-3.7.4-alt3 p9+249932.100.2.1 1587127349 installed Building target platforms: i586 Building for target i586 Wrote: /usr/src/in/nosrpm/python-module-openid-2.2.5-alt2.2.nosrc.rpm <13>May 24 12:50:18 rpmi: python3-module-pkg_resources-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed <13>May 24 12:50:18 rpmi: python-module-pkg_resources-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed <13>May 24 12:50:18 rpmi: python-module-setuptools-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed <13>May 24 12:50:19 rpmi: python3-module-setuptools-1:40.8.0-alt2 sisyphus+229158.200.2.1 1557735221 installed Installing python-module-openid-2.2.5-alt2.2.src.rpm Building target platforms: i586 Building for target i586 Executing(%prep): /bin/sh -e /usr/src/tmp/rpm-tmp.95180 + umask 022 + /bin/mkdir -p /usr/src/RPM/BUILD + cd /usr/src/RPM/BUILD + cd /usr/src/RPM/BUILD + rm -rf python-openid-2.2.5 + echo 'Source #0 (python-openid-2.2.5.tar.bz2):' Source #0 (python-openid-2.2.5.tar.bz2): + /bin/bzip2 -dc /usr/src/RPM/SOURCES/python-openid-2.2.5.tar.bz2 + /bin/tar -xf - + cd python-openid-2.2.5 + /bin/chmod -c -Rf u+rwX,go-w . + cp -fR . ../python3 + find ../python3 -type f -name '*.py' -exec 2to3 -w -n '{}' + RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: No changes to ../python3/setup.py RefactoringTool: Refactored ../python3/openid/yadis/xrires.py RefactoringTool: Refactored ../python3/openid/yadis/xri.py RefactoringTool: Refactored ../python3/openid/yadis/services.py RefactoringTool: Refactored ../python3/openid/yadis/parsehtml.py RefactoringTool: Refactored ../python3/openid/yadis/manager.py RefactoringTool: No changes to ../python3/openid/yadis/filters.py RefactoringTool: Refactored ../python3/openid/yadis/etxrd.py --- ../python3/openid/yadis/xrires.py (original) +++ ../python3/openid/yadis/xrires.py (refactored) @@ -2,7 +2,7 @@ """XRI resolution. """ -from urllib import urlencode +from urllib.parse import urlencode from openid import fetchers from openid.yadis import etxrd from openid.yadis.xri import toURINormal @@ -102,7 +102,7 @@ """ # to be merged with oidutil.appendArgs when we combine the projects. if hasattr(args, 'items'): - args = args.items() + args = list(args.items()) args.sort() if len(args) == 0: --- ../python3/openid/yadis/xri.py (original) +++ ../python3/openid/yadis/xri.py (refactored) @@ -5,11 +5,12 @@ """ import re +from functools import reduce XRI_AUTHORITIES = ['!', '=', '@', '+', '$', '('] try: - unichr(0x10000) + chr(0x10000) except ValueError: # narrow python build UCSCHAR = [ @@ -50,8 +51,7 @@ _escapeme_re = re.compile('[%s]' % (''.join( - map(lambda (m, n): u'%s-%s' % (unichr(m), unichr(n)), - UCSCHAR + IPRIVATE)),)) + ['%s-%s' % (chr(m_n[0]), chr(m_n[1])) for m_n in UCSCHAR + IPRIVATE]),)) def identifierScheme(identifier): @@ -147,7 +147,7 @@ # IRI reference. XXX: Can IRI authorities have segments? segments = authority.split('!') segments = reduce(list.__add__, - map(lambda s: s.split('*'), segments)) + [s.split('*') for s in segments]) root = segments[0] return XRI(root) --- ../python3/openid/yadis/services.py (original) +++ ../python3/openid/yadis/services.py (refactored) @@ -26,7 +26,7 @@ try: endpoints = applyFilter(result.normalized_uri, result.response_text, flt) - except XRDSError, err: + except XRDSError as err: raise DiscoveryFailure(str(err), None) return (result.normalized_uri, endpoints) --- ../python3/openid/yadis/parsehtml.py (original) +++ ../python3/openid/yadis/parsehtml.py (refactored) @@ -1,7 +1,7 @@ __all__ = ['findHTMLMeta', 'MetaNotFound'] -from HTMLParser import HTMLParser, HTMLParseError -import htmlentitydefs +from html.parser import HTMLParser, HTMLParseError +import html.entities import re from openid.yadis.constants import YADIS_HEADER_NAME @@ -39,12 +39,12 @@ codepoint = int(mo.group('dec')) else: assert mo.lastgroup == 'word' - codepoint = htmlentitydefs.name2codepoint.get(mo.group('word')) + codepoint = html.entities.name2codepoint.get(mo.group('word')) if codepoint is None: return mo.group() else: - return unichr(codepoint) + return chr(codepoint) def substituteEntities(s): return ent_re.sub(substituteMO, s) @@ -180,11 +180,11 @@ chunks.append(chunk) try: parser.feed(chunk) - except HTMLParseError, why: + except HTMLParseError as why: # HTML parse error, so bail chunks.append(stream.read()) break - except ParseDone, why: + except ParseDone as why: uri = why[0] if uri is None: # Parse finished, but we may need the rest of the file --- ../python3/openid/yadis/manager.py (original) +++ ../python3/openid/yadis/manager.py (refactored) @@ -24,7 +24,7 @@ def __iter__(self): return self - def next(self): + def __next__(self): """Return the next service self.current() will continue to return that service until the @@ -106,7 +106,7 @@ manager = self.createManager(services, yadis_url) if manager: - service = manager.next() + service = next(manager) manager.store(self.session) else: service = None --- ../python3/openid/yadis/etxrd.py (original) +++ ../python3/openid/yadis/etxrd.py (refactored) @@ -67,7 +67,7 @@ """ try: element = ElementTree.XML(text) - except XMLError, why: + except XMLError as why: exc = XRDSError('Error parsing document as XML') exc.reason = why RefactoringTool: Refactored ../python3/openid/yadis/discover.py RefactoringTool: No changes to ../python3/openid/yadis/constants.py RefactoringTool: No changes to ../python3/openid/yadis/accept.py RefactoringTool: Refactored ../python3/openid/yadis/__init__.py RefactoringTool: Refactored ../python3/openid/urinorm.py RefactoringTool: Refactored ../python3/openid/test/trustroot.py RefactoringTool: Refactored ../python3/openid/test/test_yadis_discover.py raise exc --- ../python3/openid/yadis/discover.py (original) +++ ../python3/openid/yadis/discover.py (refactored) @@ -1,7 +1,7 @@ # -*- test-case-name: openid.test.test_yadis_discover -*- __all__ = ['discover', 'DiscoveryResult', 'DiscoveryFailure'] -from cStringIO import StringIO +from io import StringIO from openid import fetchers --- ../python3/openid/yadis/__init__.py (original) +++ ../python3/openid/yadis/__init__.py (refactored) @@ -16,7 +16,7 @@ # Parse the version info try: - version_info = map(int, __version__.split('.')) + version_info = list(map(int, __version__.split('.'))) except ValueError: version_info = (None, None, None) else: --- ../python3/openid/urinorm.py (original) +++ ../python3/openid/urinorm.py (refactored) @@ -22,7 +22,7 @@ pct_encoded_re = re.compile(pct_encoded_pattern) try: - unichr(0x10000) + chr(0x10000) except ValueError: # narrow python build UCSCHAR = [ @@ -73,8 +73,7 @@ _escapeme_re = re.compile('[%s]' % (''.join( - map(lambda (m, n): u'%s-%s' % (unichr(m), unichr(n)), - UCSCHAR + IPRIVATE)),)) + ['%s-%s' % (chr(m_n[0]), chr(m_n[1])) for m_n in UCSCHAR + IPRIVATE]),)) def _pct_escape_unicode(char_match): @@ -137,7 +136,7 @@ def urinorm(uri): - if isinstance(uri, unicode): + if isinstance(uri, str): uri = _escapeme_re.sub(_pct_escape_unicode, uri).encode('ascii') illegal_mo = uri_illegal_char_re.search(uri) @@ -171,7 +170,7 @@ if '%' in host: host = host.lower() host = pct_encoded_re.sub(_pct_encoded_replace, host) - host = unicode(host, 'utf-8').encode('idna') + host = str(host, 'utf-8').encode('idna') else: host = host.lower() --- ../python3/openid/test/trustroot.py (original) +++ ../python3/openid/test/trustroot.py (refactored) @@ -35,7 +35,7 @@ def runTest(self): tr = TrustRoot.parse(self.tr) - self.failIf(tr is None, self.tr) + self.assertFalse(tr is None, self.tr) match = tr.validateURL(self.rt) if self.match: @@ -46,7 +46,7 @@ def getTests(t, grps, head, dat): tests = [] top = head.strip() - gdat = map(str.strip, dat.split('-' * 40 + '\n')) + gdat = list(map(str.strip, dat.split('-' * 40 + '\n'))) assert not gdat[0] assert len(gdat) == (len(grps) * 2 + 1), (gdat, grps) i = 1 @@ -60,7 +60,7 @@ return tests def parseTests(data): - parts = map(str.strip, data.split('=' * 40 + '\n')) + parts = list(map(str.strip, data.split('=' * 40 + '\n'))) assert not parts[0] _, ph, pdat, mh, mdat = parts --- ../python3/openid/test/test_yadis_discover.py (original) +++ ../python3/openid/test/test_yadis_discover.py (refactored) @@ -7,7 +7,7 @@ """ import unittest -import urlparse +import urllib.parse import re import types @@ -15,7 +15,7 @@ from openid import fetchers -import discoverdata +from . import discoverdata status_header_re = re.compile(r'Status: (\d+) .*?$', re.MULTILINE) @@ -48,7 +48,7 @@ def fetch(self, url, headers, body): current_url = url while True: - parsed = urlparse.urlparse(current_url) + parsed = urllib.parse.urlparse(current_url) path = parsed[2][1:] try: data = discoverdata.generateSample(path, self.base_url) @@ -88,7 +88,7 @@ def test_404(self): uri = "http://something.unittest/" - self.failUnlessRaises(DiscoveryFailure, discover, uri) + self.assertRaises(DiscoveryFailure, discover, uri) class _TestCase(unittest.TestCase): @@ -122,27 +122,27 @@ def runCustomTest(self): if self.expected is DiscoveryFailure: - self.failUnlessRaises(DiscoveryFailure, + self.assertRaises(DiscoveryFailure, discover, self.input_url) else: result = discover(self.input_url) - self.failUnlessEqual(self.input_url, result.request_uri) + self.assertEqual(self.input_url, result.request_uri)RefactoringTool: Refactored ../python3/openid/test/test_xrires.py RefactoringTool: Refactored ../python3/openid/test/test_xri.py msg = 'Identity URL mismatch: actual = %r, expected = %r' % ( result.normalized_uri, self.expected.normalized_uri) - self.failUnlessEqual( + self.assertEqual( 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.assertEqual( self.expected.response_text, result.response_text, msg) expected_keys = dir(self.expected) expected_keys.sort() actual_keys = dir(result) actual_keys.sort() - self.failUnlessEqual(actual_keys, expected_keys) + self.assertEqual(actual_keys, expected_keys) for k in dir(self.expected): if k.startswith('__') and k.endswith('__'): --- ../python3/openid/test/test_xrires.py (original) +++ ../python3/openid/test/test_xrires.py (refactored) @@ -16,17 +16,17 @@ args_esc = "_xrd_r=application%2Fxrds%2Bxml&_xrd_t=" + ste pqu = self.proxy.queryURL h = self.proxy_url - self.failUnlessEqual(h + '=foo?' + args_esc, pqu('=foo', st)) - self.failUnlessEqual(h + '=foo/bar?baz&' + args_esc, + self.assertEqual(h + '=foo?' + args_esc, pqu('=foo', st)) + self.assertEqual(h + '=foo/bar?baz&' + args_esc, pqu('=foo/bar?baz', st)) - self.failUnlessEqual(h + '=foo/bar?baz=quux&' + args_esc, + self.assertEqual(h + '=foo/bar?baz=quux&' + args_esc, pqu('=foo/bar?baz=quux', st)) - self.failUnlessEqual(h + '=foo/bar?mi=fa&so=la&' + args_esc, + self.assertEqual(h + '=foo/bar?mi=fa&so=la&' + args_esc, pqu('=foo/bar?mi=fa&so=la', st)) # With no service endpoint selection. args_esc = "_xrd_r=application%2Fxrds%2Bxml%3Bsep%3Dfalse" - self.failUnlessEqual(h + '=foo?' + args_esc, pqu('=foo', None)) + self.assertEqual(h + '=foo?' + args_esc, pqu('=foo', None)) def test_proxy_url_qmarks(self): @@ -35,6 +35,6 @@ args_esc = "_xrd_r=application%2Fxrds%2Bxml&_xrd_t=" + ste pqu = self.proxy.queryURL h = self.proxy_url - self.failUnlessEqual(h + '=foo/bar??' + args_esc, pqu('=foo/bar?', st)) - self.failUnlessEqual(h + '=foo/bar????' + args_esc, + self.assertEqual(h + '=foo/bar??' + args_esc, pqu('=foo/bar?', st)) + self.assertEqual(h + '=foo/bar????' + args_esc, pqu('=foo/bar???', st)) --- ../python3/openid/test/test_xri.py (original) +++ ../python3/openid/test/test_xri.py (refactored) @@ -4,51 +4,51 @@ class XriDiscoveryTestCase(TestCase): def test_isXRI(self): i = xri.identifierScheme - self.failUnlessEqual(i('=john.smith'), 'XRI') - self.failUnlessEqual(i('@smiths/john'), 'XRI') - self.failUnlessEqual(i('smoker.myopenid.com'), 'URI') - self.failUnlessEqual(i('xri://=john'), 'XRI') - self.failUnlessEqual(i(''), 'URI') + self.assertEqual(i('=john.smith'), 'XRI') + self.assertEqual(i('@smiths/john'), 'XRI') + self.assertEqual(i('smoker.myopenid.com'), 'URI') + self.assertEqual(i('xri://=john'), 'XRI') + self.assertEqual(i(''), 'URI') class XriEscapingTestCase(TestCase): def test_escaping_percents(self): - self.failUnlessEqual(xri.escapeForIRI('@example/abc%2Fd/ef'), + self.assertEqual(xri.escapeForIRI('@example/abc%2Fd/ef'), '@example/abc%252Fd/ef') def test_escaping_xref(self): # no escapes esc = xri.escapeForIRI - self.failUnlessEqual('@example/foo/(@bar)', esc('@example/foo/(@bar)')) + self.assertEqual('@example/foo/(@bar)', esc('@example/foo/(@bar)')) # escape slashes - self.failUnlessEqual('@example/foo/(@bar%2Fbaz)', + self.assertEqual('@example/foo/(@bar%2FbazRefactoringTool: Refactored ../python3/openid/test/test_verifydisco.py )', esc('@example/foo/(@bar/baz)')) - self.failUnlessEqual('@example/foo/(@bar%2Fbaz)/(+a%2Fb)', + self.assertEqual('@example/foo/(@bar%2Fbaz)/(+a%2Fb)', esc('@example/foo/(@bar/baz)/(+a/b)')) # escape query ? and fragment # - self.failUnlessEqual('@example/foo/(@baz%3Fp=q%23r)?i=j#k', + self.assertEqual('@example/foo/(@baz%3Fp=q%23r)?i=j#k', esc('@example/foo/(@baz?p=q#r)?i=j#k')) class XriTransformationTestCase(TestCase): def test_to_iri_normal(self): - self.failUnlessEqual(xri.toIRINormal('@example'), 'xri://@example') + self.assertEqual(xri.toIRINormal('@example'), 'xri://@example') try: - unichr(0x10000) + chr(0x10000) except ValueError: # bleh narrow python build def test_iri_to_url(self): - s = u'l\xa1m' + s = 'l\xa1m' expected = 'l%C2%A1m' - self.failUnlessEqual(xri.iriToURI(s), expected) + self.assertEqual(xri.iriToURI(s), expected) else: def test_iri_to_url(self): - s = u'l\xa1m\U00101010n' + s = 'l\xa1m\U00101010n' expected = 'l%C2%A1m%F4%81%80%90n' - self.failUnlessEqual(xri.iriToURI(s), expected) + self.assertEqual(xri.iriToURI(s), expected) @@ -58,7 +58,7 @@ result = xri.providerIsAuthoritative(providerID, canonicalID) format = "%s providing %s, expected %s" message = format % (providerID, canonicalID, isAuthoritative) - self.failUnlessEqual(isAuthoritative, result, message) + self.assertEqual(isAuthoritative, result, message) return test @@ -75,7 +75,7 @@ def mkTest(the_xri, expected_root): def test(self): actual_root = xri.rootAuthority(the_xri) - self.failUnlessEqual(actual_root, xri.XRI(expected_root)) + self.assertEqual(actual_root, xri.XRI(expected_root)) return test test_at = mkTest("@foo", "@") --- ../python3/openid/test/test_verifydisco.py (original) +++ ../python3/openid/test/test_verifydisco.py (refactored) @@ -17,8 +17,8 @@ def failUnlessProtocolError(self, prefix, callable, *args, **kwargs): try: result = callable(*args, **kwargs) - except consumer.ProtocolError, e: - self.failUnless( + except consumer.ProtocolError as e: + self.assertTrue( e[0].startswith(prefix), 'Expected message prefix %r, got message %r' % (prefix, e[0])) else: @@ -37,13 +37,13 @@ def test_openID1NoEndpoint(self): msg = message.Message.fromOpenIDArgs({'identity':'snakes on a plane'}) - self.failUnlessRaises(RuntimeError, + self.assertRaises(RuntimeError, self.consumer._verifyDiscoveryResults, msg) self.failUnlessLogEmpty() def test_openID2NoOPEndpointArg(self): msg = message.Message.fromOpenIDArgs({'ns':message.OPENID2_NS}) - self.failUnlessRaises(KeyError, + self.assertRaises(KeyError, self.consumer._verifyDiscoveryResults, msg) self.failUnlessLogEmpty() @@ -70,9 +70,9 @@ msg = message.Message.fromOpenIDArgs({'ns':message.OPENID2_NS, 'op_endpoint':op_endpoint}) result_endpoint = self.consumer._verifyDiscoveryResults(msg) - self.failUnless(result_endpoint.isOPIdentifier()) - self.failUnlessEqual(op_endpoint, result_endpoint.server_url) - self.failUnlessEqual(None, result_endpoint.claimed_id) + self.assertTrue(result_endpoint.isOPIdentifier()) + self.assertEqual(op_endpoint, result_endpoint.server_url) + self.assertEqual(None, result_endpoint.claimed_id) self.failUnlessLogEmpty() def test_openID2NoEndpointDoesDisco(self): @@ -86,7 +86,7 @@ 'claimed_id':'monkeysoft', 'op_eRefactoringTool: Refactored ../python3/openid/test/test_urinorm.py ndpoint':op_endpoint}) result = self.consumer._verifyDiscoveryResults(msg) - self.failUnlessEqual(sentinel, result) + self.assertEqual(sentinel, result) self.failUnlessLogMatches('No pre-discovered') def test_openID2MismatchedDoesDisco(self): @@ -104,7 +104,7 @@ 'claimed_id':'monkeysoft', 'op_endpoint':op_endpoint}) result = self.consumer._verifyDiscoveryResults(msg, mismatched) - self.failUnlessEqual(sentinel, result) + self.assertEqual(sentinel, result) self.failUnlessLogMatches('Error attempting to use stored', 'Attempting discovery') @@ -121,7 +121,7 @@ 'claimed_id':endpoint.claimed_id, 'op_endpoint':endpoint.server_url}) result = self.consumer._verifyDiscoveryResults(msg, endpoint) - self.failUnless(result is endpoint) + self.assertTrue(result is endpoint) self.failUnlessLogEmpty() def test_openid2UsePreDiscoveredWrongType(self): @@ -134,9 +134,9 @@ endpoint.type_uris = [discover.OPENID_1_1_TYPE] def discoverAndVerify(claimed_id, to_match_endpoints): - self.failUnlessEqual(claimed_id, endpoint.claimed_id) + self.assertEqual(claimed_id, endpoint.claimed_id) for to_match in to_match_endpoints: - self.failUnlessEqual(claimed_id, to_match.claimed_id) + self.assertEqual(claimed_id, to_match.claimed_id) raise consumer.ProtocolError(text) self.consumer._discoverAndVerify = discoverAndVerify @@ -149,9 +149,9 @@ try: r = self.consumer._verifyDiscoveryResults(msg, endpoint) - except consumer.ProtocolError, e: + except consumer.ProtocolError as e: # Should we make more ProtocolError subclasses? - self.failUnless(str(e), text) + self.assertTrue(str(e), text) else: self.fail("expected ProtocolError, %r returned." % (r,)) @@ -169,7 +169,7 @@ {'ns':message.OPENID1_NS, 'identity':endpoint.local_id}) result = self.consumer._verifyDiscoveryResults(msg, endpoint) - self.failUnless(result is endpoint) + self.assertTrue(result is endpoint) self.failUnlessLogEmpty() def test_openid1UsePreDiscoveredWrongType(self): @@ -190,7 +190,7 @@ {'ns':message.OPENID1_NS, 'identity':endpoint.local_id}) - self.failUnlessRaises( + self.assertRaises( VerifiedError, self.consumer._verifyDiscoveryResults, msg, endpoint) @@ -213,11 +213,11 @@ 'op_endpoint': endpoint.server_url}) result = self.consumer._verifyDiscoveryResults(msg, endpoint) - self.failUnlessEqual(result.local_id, endpoint.local_id) - self.failUnlessEqual(result.server_url, endpoint.server_url) - self.failUnlessEqual(result.type_uris, endpoint.type_uris) - - self.failUnlessEqual(result.claimed_id, claimed_id_frag) + self.assertEqual(result.local_id, endpoint.local_id) + self.assertEqual(result.server_url, endpoint.server_url) + self.assertEqual(result.type_uris, endpoint.type_uris) + + self.assertEqual(result.claimed_id, claimed_id_frag) self.failUnlessLogEmpty() @@ -244,7 +244,7 @@ actual_endpoint = self.consumer._verifyDiscoveryResults( resp_mesg, endpoint) - self.failUnless(actual_endpoint is expected_endpoint) + self.assertTrue(actual_endpoint is expected_endpoint) # XXX: test the implementation of _discoverAndVerify @@ -263,7 +263,7 @@ to_match.local_id = "http://localhost:8000/id/id-jo" result = self.consumer._verifyDiscoverySingle(endpoint, to_match) # result should always be None, raises exception on failure. - self.failUnlessEqual(result, None) + self.assertEqual(result, None) self.failUnlessLogEmpty() if __name__ == '__main__': --- ../python3/oRefactoringTool: Refactored ../python3/openid/test/test_symbol.py RefactoringTool: Refactored ../python3/openid/test/test_sreg.py penid/test/test_urinorm.py (original) +++ ../python3/openid/test/test_urinorm.py (refactored) @@ -15,14 +15,14 @@ def runTest(self): try: actual = openid.urinorm.urinorm(self.case) - except ValueError, why: + except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') - case = unicode(case, 'utf-8') + case = str(case, 'utf-8') return cls(desc, case, expected) --- ../python3/openid/test/test_symbol.py (original) +++ ../python3/openid/test/test_symbol.py (refactored) @@ -5,31 +5,31 @@ class SymbolTest(unittest.TestCase): def test_selfEquality(self): s = oidutil.Symbol('xxx') - self.failUnlessEqual(s, s) + self.assertEqual(s, s) def test_otherEquality(self): x = oidutil.Symbol('xxx') y = oidutil.Symbol('xxx') - self.failUnlessEqual(x, y) + self.assertEqual(x, y) def test_inequality(self): x = oidutil.Symbol('xxx') y = oidutil.Symbol('yyy') - self.failIfEqual(x, y) + self.assertNotEqual(x, y) def test_selfInequality(self): x = oidutil.Symbol('xxx') - self.failIf(x != x) + self.assertFalse(x != x) def test_otherInequality(self): x = oidutil.Symbol('xxx') y = oidutil.Symbol('xxx') - self.failIf(x != y) + self.assertFalse(x != y) def test_ne_inequality(self): x = oidutil.Symbol('xxx') y = oidutil.Symbol('yyy') - self.failUnless(x != y) + self.assertTrue(x != y) if __name__ == '__main__': unittest.main() --- ../python3/openid/test/test_sreg.py (original) +++ ../python3/openid/test/test_sreg.py (refactored) @@ -6,7 +6,7 @@ class SRegURITest(unittest.TestCase): def test_is11(self): - self.failUnlessEqual(sreg.ns_uri_1_1, sreg.ns_uri) + self.assertEqual(sreg.ns_uri_1_1, sreg.ns_uri) class CheckFieldNameTest(unittest.TestCase): def test_goodNamePasses(self): @@ -14,10 +14,10 @@ sreg.checkFieldName(field_name) def test_badNameFails(self): - self.failUnlessRaises(ValueError, sreg.checkFieldName, 'INVALID') + self.assertRaises(ValueError, sreg.checkFieldName, 'INVALID') def test_badTypeFails(self): - self.failUnlessRaises(ValueError, sreg.checkFieldName, None) + self.assertRaises(ValueError, sreg.checkFieldName, None) # For supportsSReg test class FakeEndpoint(object): @@ -32,19 +32,19 @@ class SupportsSRegTest(unittest.TestCase): def test_unsupported(self): endpoint = FakeEndpoint([]) - self.failIf(sreg.supportsSReg(endpoint)) - self.failUnlessEqual([sreg.ns_uri_1_1, sreg.ns_uri_1_0], + self.assertFalse(sreg.supportsSReg(endpoint)) + self.assertEqual([sreg.ns_uri_1_1, sreg.ns_uri_1_0], endpoint.checked_uris) def test_supported_1_1(self): endpoint = FakeEndpoint([sreg.ns_uri_1_1]) - self.failUnless(sreg.supportsSReg(endpoint)) - self.failUnlessEqual([sreg.ns_uri_1_1], endpoint.checked_uris) + self.assertTrue(sreg.supportsSReg(endpoint)) + self.assertEqual([sreg.ns_uri_1_1], endpoint.checked_uris) def test_supported_1_0(self): endpoint = FakeEndpoint([sreg.ns_uri_1_0]) - self.failUnless(sreg.supportsSReg(endpoint)) - self.failUnlessEqual([sreg.ns_uri_1_1, sreg.ns_uri_1_0], + self.assertTrue(sreg.supportsSReg(endpoint)) + self.assertEqual([sreg.ns_uri_1_1, sreg.ns_uri_1_0], endpoint.checked_uris) class FakeMessage(object): @@ -61,20 +61,20 @@ def test_openID2Empty(self): ns_uri = sreg.getSRegNS(self.msg) - self.failUnlessEqual(self.msg.namespaces.getAlias(ns_uri), 'sreg') - self.failUnlessEqual(sreg.ns_uri, ns_uri) + self.assertEqual(self.msg.namespaces.getAlias(ns_uri), 'sreg') + self.assertEqual(sreg.ns_uri, ns_uri) def test_openID1Empty(self): self.msg.openid1 = True ns_uri = sreg.getSRegNS(self.msg) - self.failUnlessEqual(self.msg.namespaces.getAlias(ns_uri), 'sreg') - self.failUnlessEqual(sreg.ns_uri, ns_uri) + self.assertEqual(self.msg.namespaces.getAlias(ns_uri), 'sreg') + self.assertEqual(sreg.ns_uri, ns_uri) def test_openID1Defined_1_0(self): self.msg.openid1 = True self.msg.namespaces.add(sreg.ns_uri_1_0) ns_uri = sreg.getSRegNS(self.msg) - self.failUnlessEqual(sreg.ns_uri_1_0, ns_uri) + self.assertEqual(sreg.ns_uri_1_0, ns_uri) def test_openID1Defined_1_0_overrideAlias(self): for openid_version in [True, False]: @@ -85,25 +85,25 @@ self.msg.openid1 = openid_version self.msg.namespaces.addAlias(sreg_version, alias) ns_uri = sreg.getSRegNS(self.msg) - self.failUnlessEqual(self.msg.namespaces.getAlias(ns_uri), alias) - self.failUnlessEqual(sreg_version, ns_uri) + self.assertEqual(self.msg.namespaces.getAlias(ns_uri), alias) + self.assertEqual(sreg_version, ns_uri) def test_openID1DefinedBadly(self): self.msg.openid1 = True self.msg.namespaces.addAlias('http://invalid/', 'sreg') - self.failUnlessRaises(sreg.SRegNamespaceError, + self.assertRaises(sreg.SRegNamespaceError, sreg.getSRegNS, self.msg) def test_openID2DefinedBadly(self): self.msg.openid1 = False self.msg.namespaces.addAlias('http://invalid/', 'sreg') - self.failUnlessRaises(sreg.SRegNamespaceError, + self.assertRaises(sreg.SRegNamespaceError, sreg.getSRegNS, self.msg) def test_openID2Defined_1_0(self): self.msg.namespaces.add(sreg.ns_uri_1_0) ns_uri = sreg.getSRegNS(self.msg) - self.failUnlessEqual(sreg.ns_uri_1_0, ns_uri) + self.assertEqual(sreg.ns_uri_1_0, ns_uri) def test_openID1_sregNSfromArgs(self): args = { @@ -113,16 +113,16 @@ m = Message.fromOpenIDArgs(args) - self.failUnless(m.getArg(sreg.ns_uri_1_1, 'optional') == 'nickname') - self.failUnless(m.getArg(sreg.ns_uri_1_1, 'required') == 'dob') + self.assertTrue(m.getArg(sreg.ns_uri_1_1, 'optional') == 'nickname') + self.assertTrue(m.getArg(sreg.ns_uri_1_1, 'required') == 'dob') class SRegRequestTest(unittest.TestCase): def test_constructEmpty(self): req = sreg.SRegRequest() - self.failUnlessEqual([], req.optional) - self.failUnlessEqual([], req.required) - self.failUnlessEqual(None, req.policy_url) - self.failUnlessEqual(sreg.ns_uri, req.ns_uri) + self.assertEqual([], req.optional) + self.assertEqual([], req.required) + self.assertEqual(None, req.policy_url) + self.assertEqual(sreg.ns_uri, req.ns_uri) def test_constructFields(self): req = sreg.SRegRequest( @@ -130,13 +130,13 @@ ['gender'], 'http://policy', 'http://sreg.ns_uri') - self.failUnlessEqual(['gender'], req.optional) - self.failUnlessEqual(['nickname'], req.required) - self.failUnlessEqual('http://policy', req.policy_url) - self.failUnlessEqual('http://sreg.ns_uri', req.ns_uri) + self.assertEqual(['gender'], req.optional) + self.assertEqual(['nickname'], req.required) + self.assertEqual('http://policy', req.policy_url) + self.assertEqual('http://sreg.ns_uri', req.ns_uri) def test_constructBadFields(self): - self.failUnlessRaises( + self.assertRaises( ValueError, sreg.SRegRequest, ['elvis']) @@ -152,7 +152,7 @@ self.message = Message() def getArgs(msg_self, ns_uri): - self.failUnlessEqual(ns_sentinel, ns_uri) + self.assertEqual(ns_sentinel, ns_uri) return args_sentinel def copy(msg_self): @@ -164,7 +164,7 @@ return ns_sentinel def parseExtensionArgs(req_self, args): - self.failUnlessEqual(args_sentinel, args) + self.assertEqual(args_sentinel, args) openid_req = OpenIDRequest() @@ -172,13 +172,13 @@ openid_req.message = msg req = TestingReq.fromOpenIDRequest(openid_req) - self.failUnless(type(req) is TestingReq) - self.failUnless(msg.copied) + self.assertTrue(type(req) is TestingReq) + self.assertTrue(msg.copied) def test_parseExtensionArgs_empty(self): req = sreg.SRegRequest() results = req.parseExtensionArgs({}) - self.failUnlessEqual(None, results) + self.assertEqual(None, results) def test_parseExtensionArgs_extraIgnored(self): req = sreg.SRegRequest() @@ -187,47 +187,47 @@ def test_parseExtensionArgs_nonStrict(self): req = sreg.SRegRequest() req.parseExtensionArgs({'required':'beans'}) - self.failUnlessEqual([], req.required) + self.assertEqual([], req.required) def test_parseExtensionArgs_strict(self): req = sreg.SRegRequest() - self.failUnlessRaises( + self.assertRaises( ValueError, req.parseExtensionArgs, {'required':'beans'}, strict=True) def test_parseExtensionArgs_policy(self): req = sreg.SRegRequest() req.parseExtensionArgs({'policy_url':'http://policy'}, strict=True) - self.failUnlessEqual('http://policy', req.policy_url) + self.assertEqual('http://policy', req.policy_url) def test_parseExtensionArgs_requiredEmpty(self): req = sreg.SRegRequest() req.parseExtensionArgs({'required':''}, strict=True) - self.failUnlessEqual([], req.required) + self.assertEqual([], req.required) def test_parseExtensionArgs_optionalEmpty(self): req = sreg.SRegRequest() req.parseExtensionArgs({'optional':''}, strict=True) - self.failUnlessEqual([], req.optional) + self.assertEqual([], req.optional) def test_parseExtensionArgs_optionalSingle(self): req = sreg.SRegRequest() req.parseExtensionArgs({'optional':'nickname'}, strict=True) - self.failUnlessEqual(['nickname'], req.optional) + self.assertEqual(['nickname'], req.optional) def test_parseExtensionArgs_optionalList(self): req = sreg.SRegRequest() req.parseExtensionArgs({'optional':'nickname,email'}, strict=True) - self.failUnlessEqual(['nickname','email'], req.optional) + self.assertEqual(['nickname','email'], req.optional) def test_parseExtensionArgs_optionalListBadNonStrict(self): req = sreg.SRegRequest() req.parseExtensionArgs({'optional':'nickname,email,beer'}) - self.failUnlessEqual(['nickname','email'], req.optional) + self.assertEqual(['nickname','email'], req.optional) def test_parseExtensionArgs_optionalListBadStrict(self): req = sreg.SRegRequest() - self.failUnlessRaises( + self.assertRaises( ValueError, req.parseExtensionArgs, {'optional':'nickname,email,beer'}, strict=True) @@ -236,12 +236,12 @@ req = sreg.SRegRequest() req.parseExtensionArgs({'optional':'nickname', 'required':'nickname'}) - self.failUnlessEqual([], req.optional) - self.failUnlessEqual(['nickname'], req.required) + self.assertEqual([], req.optional) + self.assertEqual(['nickname'], req.required) def test_parseExtensionArgs_bothStrict(self): req = sreg.SRegRequest() - self.failUnlessRaises( + self.assertRaises( ValueError, req.parseExtensionArgs, {'optional':'nickname', @@ -252,46 +252,46 @@ req = sreg.SRegRequest() req.parseExtensionArgs({'optional':'nickname,email', 'required':'country,postcode'}, strict=True) - self.failUnlessEqual(['nickname','email'], req.optional) - self.failUnlessEqual(['country','postcode'], req.required) + self.assertEqual(['nickname','email'], req.optional) + self.assertEqual(['country','postcode'], req.required) def test_allRequestedFields(self): req = sreg.SRegRequest() - self.failUnlessEqual([], req.allRequestedFields()) + self.assertEqual([], req.allRequestedFields()) req.requestField('nickname') - self.failUnlessEqual(['nickname'], req.allRequestedFields()) + self.assertEqual(['nickname'], req.allRequestedFields()) req.requestField('gender', required=True) requested = req.allRequestedFields() requested.sort() - self.failUnlessEqual(['gender', 'nickname'], requested) + self.assertEqual(['gender', 'nickname'], requested) def test_wereFieldsRequested(self): req = sreg.SRegRequest() - self.failIf(req.wereFieldsRequested()) + self.assertFalse(req.wereFieldsRequested()) req.requestField('gender') - self.failUnless(req.wereFieldsRequested()) + self.assertTrue(req.wereFieldsRequested()) def test_contains(self): req = sreg.SRegRequest() for field_name in sreg.data_fields: - self.failIf(field_name in req) - - self.failIf('something else' in req) + self.assertFalse(field_name in req) + + self.assertFalse('something else' in req) req.requestField('nickname') for field_name in sreg.data_fields: if field_name == 'nickname': - self.failUnless(field_name in req) + self.assertTrue(field_name in req) else: - self.failIf(field_name in req) + self.assertFalse(field_name in req) def test_requestField_bogus(self): req = sreg.SRegRequest() - self.failUnlessRaises( + self.assertRaises( ValueError, req.requestField, 'something else') - self.failUnlessRaises( + self.assertRaises( ValueError, req.requestField, 'something else', strict=True) @@ -302,40 +302,40 @@ for field_name in fields: req.requestField(field_name) - self.failUnlessEqual(fields, req.optional) - self.failUnlessEqual([], req.required) + self.assertEqual(fields, req.optional) + self.assertEqual([], req.required) # By default, adding the same fields over again has no effect for field_name in fields: req.requestField(field_name) - self.failUnlessEqual(fields, req.optional) - self.failUnlessEqual([], req.required) + self.assertEqual(fields, req.optional) + self.assertEqual([], req.required) # Requesting a field as required overrides requesting it as optional expected = list(fields) overridden = expected.pop(0) req.requestField(overridden, required=True) - self.failUnlessEqual(expected, req.optional) - self.failUnlessEqual([overridden], req.required) + self.assertEqual(expected, req.optional) + self.assertEqual([overridden], req.required) # Requesting a field as required overrides requesting it as optional for field_name in fields: req.requestField(field_name, required=True) - self.failUnlessEqual([], req.optional) - self.failUnlessEqual(fields, req.required) + self.assertEqual([], req.optional) + self.assertEqual(fields, req.required) # Requesting it as optional does not downgrade it to optional for field_name in fields: req.requestField(field_name) - self.failUnlessEqual([], req.optional) - self.failUnlessEqual(fields, req.required) + self.assertEqual([], req.optional) + self.assertEqual(fields, req.required) def test_requestFields_type(self): req = sreg.SRegRequest() - self.failUnlessRaises(TypeError, req.requestFields, 'nickname') + self.assertRaises(TypeError, req.requestFields, 'nickname') def test_requestFields(self): # Add all of the fields @@ -344,57 +344,57 @@ fields = list(sreg.data_fields) req.requestFields(fields) - self.failUnlessEqual(fields, req.optional) - self.failUnlessEqual([], req.required) + self.assertEqual(fields, req.optional) + self.assertEqual([], req.required) # By default, adding the same fields over again has no effect req.requestFields(fields) - self.failUnlessEqual(fields, req.optional) - self.failUnlessEqual([], req.required) + self.assertEqual(fields, req.optional) + self.assertEqual([], req.required) # Requesting a field as required overrides requesting it as optional expected = list(fields) overridden = expected.pop(0) req.requestFields([overridden], required=True) - self.failUnlessEqual(expected, req.optional) - self.failUnlessEqual([overridden], req.required) + self.assertEqual(expected, req.optional) + self.assertEqual([overridden], req.required) # Requesting a field as required overrides requesting it as optional req.requestFields(fields, required=True) - self.failUnlessEqual([], req.optional) - self.failUnlessEqual(fields, req.required) + self.assertEqual([], req.optional) + self.assertEqual(fields, req.required) # Requesting it as optional does not downgrade it to optional req.requestFields(fields) - self.failUnlessEqual([], req.optional) - self.failUnlessEqual(fields, req.required) + self.assertEqual([], req.optional) + self.assertEqual(fields, req.required) def test_getExtensionArgs(self): req = sreg.SRegRequest() - self.failUnlessEqual({}, req.getExtensionArgs()) + self.assertEqual({}, req.getExtensionArgs()) req.requestField('nickname') - self.failUnlessEqual({'optional':'nickname'}, req.getExtensionArgs()) + self.assertEqual({'optional':'nickname'}, req.getExtensionArgs()) req.requestField('email') - self.failUnlessEqual({'optional':'nickname,email'}, + self.assertEqual({'optional':'nickname,email'}, req.getExtensionArgs()) req.requestField('gender', required=True) - self.failUnlessEqual({'optional':'nickname,email', + self.assertEqual({'optional':'nickname,email', 'required':'gender'}, req.getExtensionArgs()) req.requestField('postcode', required=True) - self.failUnlessEqual({'optional':'nickname,email', + self.assertEqual({'optional':'nickname,email', 'required':'gender,postcode'}, req.getExtensionArgs()) req.policy_url = 'http://policy.invalid/' - self.failUnlessEqual({'optional':'nickname,email', + self.assertEqual({'optional':'nickname,email', 'required':'gender,postcode', 'policy_url':'http://policy.invalid/'}, req.getExtensionArgs()) @@ -422,10 +422,10 @@ def test_construct(self): resp = sreg.SRegResponse(data) - self.failUnless(resp) + self.assertTrue(resp) empty_resp = sreg.SRegResponse({}) - self.failIf(empty_resp) + self.assertFalse(empty_resp) # XXX: finish this test @@ -435,7 +435,7 @@ }) success_resp = DummySuccessResponse(message, {}) sreg_resp = sreg.SRegResponse.fromSuccessResponse(success_resp) - self.failIf(sreg_resp) + self.assertFalse(sreg_resp) def test_fromSuccessResponse_unsigned(self): message = Message.fromOpenIDArgs({ @@ -444,8 +444,8 @@ success_resp =RefactoringTool: Refactored ../python3/openid/test/test_services.py RefactoringTool: Refactored ../python3/openid/test/test_server.py DummySuccessResponse(message, {}) sreg_resp = sreg.SRegResponse.fromSuccessResponse(success_resp, signed_only=False) - self.failUnlessEqual([('nickname', 'The Mad Stork')], - sreg_resp.items()) + self.assertEqual([('nickname', 'The Mad Stork')], + list(sreg_resp.items())) class SendFieldsTest(unittest.TestCase): def test(self): @@ -474,7 +474,7 @@ # Extract the fields that were sent sreg_data_resp = resp_msg.getArgs(sreg.ns_uri) - self.failUnlessEqual( + self.assertEqual( {'nickname':'linusaur', 'email':'president@whitehouse.gov', 'fullname':'Leonhard Euler', --- ../python3/openid/test/test_services.py (original) +++ ../python3/openid/test/test_services.py (refactored) @@ -18,6 +18,6 @@ return result def test_catchXRDSError(self): - self.failUnlessRaises(DiscoveryFailure, + self.assertRaises(DiscoveryFailure, services.getServiceEndpoints, "http://example.invalid/sometest") --- ../python3/openid/test/test_server.py (original) +++ ../python3/openid/test/test_server.py (refactored) @@ -10,7 +10,7 @@ import unittest import warnings -from urlparse import urlparse +from urllib.parse import urlparse # In general, if you edit or add tests here, try to move in the direction # of testing smaller units. For testing the external interfaces, we'll be @@ -43,7 +43,7 @@ 'openid.return_to': return_to, }) e = server.ProtocolError(args, "plucky") - self.failUnless(e.hasReturnTo()) + self.assertTrue(e.hasReturnTo()) expected_args = { 'openid.mode': ['error'], 'openid.error': ['plucky'], @@ -51,7 +51,7 @@ rt_base, result_args = e.encodeToURL().split('?', 1) result_args = cgi.parse_qs(result_args) - self.failUnlessEqual(result_args, expected_args) + self.assertEqual(result_args, expected_args) def test_browserWithReturnTo_OpenID2_GET(self): return_to = "http://rp.unittest/consumer" @@ -64,7 +64,7 @@ 'openid.return_to': return_to, }) e = server.ProtocolError(args, "plucky") - self.failUnless(e.hasReturnTo()) + self.assertTrue(e.hasReturnTo()) expected_args = { 'openid.ns': [OPENID2_NS], 'openid.mode': ['error'], @@ -73,7 +73,7 @@ rt_base, result_args = e.encodeToURL().split('?', 1) result_args = cgi.parse_qs(result_args) - self.failUnlessEqual(result_args, expected_args) + self.assertEqual(result_args, expected_args) def test_browserWithReturnTo_OpenID2_POST(self): return_to = "http://rp.unittest/consumer" + ('x' * OPENID1_URL_LIMIT) @@ -86,15 +86,15 @@ 'openid.return_to': return_to, }) e = server.ProtocolError(args, "plucky") - self.failUnless(e.hasReturnTo()) + self.assertTrue(e.hasReturnTo()) expected_args = { 'openid.ns': [OPENID2_NS], 'openid.mode': ['error'], 'openid.error': ['plucky'], } - self.failUnless(e.whichEncoding() == server.ENCODE_HTML_FORM) - self.failUnless(e.toFormMarkup() == e.toMessage().toFormMarkup( + self.assertTrue(e.whichEncoding() == server.ENCODE_HTML_FORM) + self.assertTrue(e.toFormMarkup() == e.toMessage().toFormMarkup( args.getArg(OPENID_NS, 'return_to'))) def test_browserWithReturnTo_OpenID1_exceeds_limit(self): @@ -106,17 +106,17 @@ 'openid.return_to': return_to, }) e = server.ProtocolError(args, "plucky") - self.failUnless(e.hasReturnTo()) + self.assertTrue(e.hasReturnTo()) expected_args = { 'openid.mode': ['error'], 'openid.error': ['plucky'], } - self.failUnless(e.whichEncoding() == server.ENCODE_URL) + self.assertTrue(e.whichEncoding() == server.ENCODE_URL) rt_base, result_args = e.encodeToURL().split('?', 1) result_args = cgi.parse_qs(result_args) - self.failUnlessEqual(result_args, expected_args) + self.assertEqual(result_args, expected_args) def test_noReturnTo(self): # will be a ProtocolError raised by Decode or CheckIDRequest.answer @@ -125,17 +125,17 @@ 'openid.identity': 'http://wagu.unittest/', }) e = server.ProtocolError(args, "waffles") - self.failIf(e.hasReturnTo()) + self.assertFalse(e.hasReturnTo()) expected = """error:waffles mode:error """ - self.failUnlessEqual(e.encodeToKVForm(), expected) + self.assertEqual(e.encodeToKVForm(), expected) def test_noMessage(self): e = server.ProtocolError(None, "no moar pancakes") - self.failIf(e.hasReturnTo()) - self.failUnlessEqual(e.whichEncoding(), None) + self.assertFalse(e.hasReturnTo()) + self.assertEqual(e.whichEncoding(), None) class TestDecode(unittest.TestCase): @@ -154,21 +154,21 @@ def test_none(self): args = {} r = self.decode(args) - self.failUnlessEqual(r, None) + self.assertEqual(r, None) def test_irrelevant(self): args = { 'pony': 'spotted', 'sreg.mutant_power': 'decaffinator', } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_bad(self): args = { 'openid.mode': 'twos-compliment', 'openid.pants': 'zippered', } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_dictOfLists(self): args = { @@ -180,8 +180,8 @@ } try: result = self.decode(args) - except TypeError, err: - self.failUnless(str(err).find('values') != -1, err) + except TypeError as err: + self.assertTrue(str(err).find('values') != -1, err) else: self.fail("Expected TypeError, but got result %s" % (result,)) @@ -196,13 +196,13 @@ 'openid.some.extension': 'junk', } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckIDRequest)) - self.failUnlessEqual(r.mode, "checkid_immediate") - self.failUnlessEqual(r.immediate, True) - self.failUnlessEqual(r.identity, self.id_url) - self.failUnlessEqual(r.trust_root, self.tr_url) - self.failUnlessEqual(r.return_to, self.rt_url) - self.failUnlessEqual(r.assoc_handle, self.assoc_handle) + self.assertTrue(isinstance(r, server.CheckIDRequest)) + self.assertEqual(r.mode, "checkid_immediate") + self.assertEqual(r.immediate, True) + self.assertEqual(r.identity, self.id_url) + self.assertEqual(r.trust_root, self.tr_url) + self.assertEqual(r.return_to, self.rt_url) + self.assertEqual(r.assoc_handle, self.assoc_handle) def test_checkidSetup(self): args = { @@ -213,12 +213,12 @@ 'openid.trust_root': self.tr_url, } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckIDRequest)) - self.failUnlessEqual(r.mode, "checkid_setup") - self.failUnlessEqual(r.immediate, False) - self.failUnlessEqual(r.identity, self.id_url) - self.failUnlessEqual(r.trust_root, self.tr_url) - self.failUnlessEqual(r.return_to, self.rt_url) + self.assertTrue(isinstance(r, server.CheckIDRequest)) + self.assertEqual(r.mode, "checkid_setup") + self.assertEqual(r.immediate, False) + self.assertEqual(r.identity, self.id_url) + self.assertEqual(r.trust_root, self.tr_url) + self.assertEqual(r.return_to, self.rt_url) def test_checkidSetupOpenID2(self): args = { @@ -231,13 +231,13 @@ 'openid.realm': self.tr_url, } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckIDRequest)) - self.failUnlessEqual(r.mode, "checkid_setup") - self.failUnlessEqual(r.immediate, False) - self.failUnlessEqual(r.identity, self.id_url) - self.failUnlessEqual(r.claimed_id, self.claimed_id) - self.failUnlessEqual(r.trust_root, self.tr_url) - self.failUnlessEqual(r.return_to, self.rt_url) + self.assertTrue(isinstance(r, server.CheckIDRequest)) + self.assertEqual(r.mode, "checkid_setup") + self.assertEqual(r.immediate, False) + self.assertEqual(r.identity, self.id_url) + self.assertEqual(r.claimed_id, self.claimed_id) + self.assertEqual(r.trust_root, self.tr_url) + self.assertEqual(r.return_to, self.rt_url) def test_checkidSetupNoClaimedIDOpenID2(self): args = { @@ -248,7 +248,7 @@ 'openid.return_to': self.rt_url, 'openid.realm': self.tr_url, } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_checkidSetupNoIdentityOpenID2(self): args = { @@ -259,12 +259,12 @@ 'openid.realm': self.tr_url, } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckIDRequest)) - self.failUnlessEqual(r.mode, "checkid_setup") - self.failUnlessEqual(r.immediate, False) - self.failUnlessEqual(r.identity, None) - self.failUnlessEqual(r.trust_root, self.tr_url) - self.failUnlessEqual(r.return_to, self.rt_url) + self.assertTrue(isinstance(r, server.CheckIDRequest)) + self.assertEqual(r.mode, "checkid_setup") + self.assertEqual(r.immediate, False) + self.assertEqual(r.identity, None) + self.assertEqual(r.trust_root, self.tr_url) + self.assertEqual(r.return_to, self.rt_url) def test_checkidSetupNoReturnOpenID1(self): """Make sure an OpenID 1 request cannot be decoded if it lacks @@ -276,7 +276,7 @@ 'openid.assoc_handle': self.assoc_handle, 'openid.trust_root': self.tr_url, } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_checkidSetupNoReturnOpenID2(self): """Make sure an OpenID 2 request with no return_to can be @@ -291,7 +291,7 @@ 'openid.assoc_handle': self.assoc_handle, 'openid.realm': self.tr_url, } - self.failUnless(isinstance(self.decode(args), server.CheckIDRequest)) + self.assertTrue(isinstance(self.decode(args), server.CheckIDRequest)) req = self.decode(args) self.assertRaises(server.NoReturnToError, req.answer, False) @@ -309,7 +309,7 @@ 'openid.identity': self.id_url, 'openid.assoc_handle': self.assoc_handle, } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_checkidSetupBadReturn(self): args = { @@ -320,8 +320,8 @@ } try: result = self.decode(args) - except server.ProtocolError, err: - self.failUnless(err.openid_message) + except server.ProtocolError as err: + self.assertTrue(err.openid_message) else: self.fail("Expected ProtocolError, instead returned with %s" % (result,)) @@ -336,8 +336,8 @@ } try: result = self.decode(args) - except server.UntrustedReturnURL, err: - self.failUnless(err.openid_message) + except server.UntrustedReturnURL as err: + self.assertTrue(err.openid_message) else: self.fail("Expected UntrustedReturnURL, instead returned with %s" % (result,)) @@ -354,9 +354,9 @@ 'openid.baz': 'unsigned', } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckAuthRequest)) - self.failUnlessEqual(r.mode, 'check_authentication') - self.failUnlessEqual(r.sig, 'sigblob') + self.assertTrue(isinstance(r, server.CheckAuthRequest)) + self.assertEqual(r.mode, 'check_authentication') + self.assertEqual(r.sig, 'sigblob') def test_checkAuthMissingSignature(self): @@ -368,7 +368,7 @@ 'openid.bar': 'signedval2', 'openid.baz': 'unsigned', } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_checkAuthAndInvalidate(self): @@ -384,8 +384,8 @@ 'openid.baz': 'unsigned', } r = self.decode(args) - self.failUnless(isinstance(r, server.CheckAuthRequest)) - self.failUnlessEqual(r.invalidate_handle, '[[SMART_handle]]') + self.assertTrue(isinstance(r, server.CheckAuthRequest)) + self.assertEqual(r.invalidate_handle, '[[SMART_handle]]') def test_associateDH(self): @@ -395,11 +395,11 @@ 'openid.dh_consumer_public': "Rzup9265tw==", } r = self.decode(args) - self.failUnless(isinstance(r, server.AssociateRequest)) - self.failUnlessEqual(r.mode, "associate") - self.failUnlessEqual(r.session.session_type, "DH-SHA1") - self.failUnlessEqual(r.assoc_type, "HMAC-SHA1") - self.failUnless(r.session.consumer_pubkey) + self.assertTrue(isinstance(r, server.AssociateRequest)) + self.assertEqual(r.mode, "associate") + self.assertEqual(r.session.session_type, "DH-SHA1") + self.assertEqual(r.assoc_type, "HMAC-SHA1") + self.assertTrue(r.session.consumer_pubkey) def test_associateDHMissingKey(self): """Trying DH assoc w/o public key""" @@ -408,7 +408,7 @@ 'openid.session_type': 'DH-SHA1', } # Using DH-SHA1 without supplying dh_consumer_public is an error. - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_associateDHpubKeyNotB64(self): @@ -417,7 +417,7 @@ 'openid.session_type': 'DH-SHA1', 'openid.dh_consumer_public': "donkeydonkeydonkey", } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_associateDHModGen(self): @@ -430,13 +430,13 @@ 'openid.dh_gen': cryptutil.longToBase64(ALT_GEN) , } r = self.decode(args) - self.failUnless(isinstance(r, server.AssociateRequest)) - self.failUnlessEqual(r.mode, "associate") - self.failUnlessEqual(r.session.session_type, "DH-SHA1") - self.failUnlessEqual(r.assoc_type, "HMAC-SHA1") - self.failUnlessEqual(r.session.dh.modulus, ALT_MODULUS) - self.failUnlessEqual(r.session.dh.generator, ALT_GEN) - self.failUnless(r.session.consumer_pubkey) + self.assertTrue(isinstance(r, server.AssociateRequest)) + self.assertEqual(r.mode, "associate") + self.assertEqual(r.session.session_type, "DH-SHA1") + self.assertEqual(r.assoc_type, "HMAC-SHA1") + self.assertEqual(r.session.dh.modulus, ALT_MODULUS) + self.assertEqual(r.session.dh.generator, ALT_GEN) + self.assertTrue(r.session.consumer_pubkey) def test_associateDHCorruptModGen(self): @@ -448,7 +448,7 @@ 'openid.dh_modulus': 'pizza', 'openid.dh_gen': 'gnocchi', } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_associateDHMissingModGen(self): @@ -459,7 +459,7 @@ 'openid.dh_consumer_public': "Rzup9265tw==", 'openid.dh_modulus': 'pizza', } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) # def test_associateDHInvalidModGen(self): @@ -482,7 +482,7 @@ 'openid.session_type': 'FLCL6', 'openid.dh_consumer_public': "YQ==\n", } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_associatePlain(self): @@ -490,17 +490,17 @@ 'openid.mode': 'associate', } r = self.decode(args) - self.failUnless(isinstance(r, server.AssociateRequest)) - self.failUnlessEqual(r.mode, "associate") - self.failUnlessEqual(r.session.session_type, "no-encryption") - self.failUnlessEqual(r.assoc_type, "HMAC-SHA1") + self.assertTrue(isinstance(r, server.AssociateRequest)) + self.assertEqual(r.mode, "associate") + self.assertEqual(r.session.session_type, "no-encryption") + self.assertEqual(r.assoc_type, "HMAC-SHA1") def test_nomode(self): args = { 'openid.session_type': 'DH-SHA1', 'openid.dh_consumer_public': "my public keeey", } - self.failUnlessRaises(server.ProtocolError, self.decode, args) + self.assertRaises(server.ProtocolError, self.decode, args) def test_invalidns(self): args = {'openid.ns': 'Tuesday', @@ -508,12 +508,12 @@ try: r = self.decode(args) - except server.ProtocolError, err: + except server.ProtocolError as err: # Assert that the ProtocolError does have a Message attached # to it, even though the request wasn't a well-formed Message. - self.failUnless(err.openid_message) + self.assertTrue(err.openid_message) # The error message contains the bad openid.ns. - self.failUnless('Tuesday' in str(err), str(err)) + self.assertTrue('Tuesday' in str(err), str(err)) else: self.fail("Expected ProtocolError but returned with %r" % (r,)) @@ -549,10 +549,10 @@ 'return_to': request.return_to, }) - self.failIf(response.renderAsForm()) - self.failUnless(response.whichEncoding() == server.ENCODE_URL) + self.assertFalse(response.renderAsForm()) + self.assertTrue(response.whichEncoding() == server.ENCODE_URL) webresponse = self.encode(response) - self.failUnless(webresponse.headers.has_key('location')) + self.assertTrue('location' in webresponse.headers) def test_id_res_OpenID2_POST(self): """ @@ -577,11 +577,11 @@ 'return_to': 'x' * OPENID1_URL_LIMIT, }) - self.failUnless(response.renderAsForm()) - self.failUnless(len(response.encodeToURL()) > OPENID1_URL_LIMIT) - self.failUnless(response.whichEncoding() == server.ENCODE_HTML_FORM) + self.assertTrue(response.renderAsForm()) + self.assertTrue(len(response.encodeToURL()) > OPENID1_URL_LIMIT) + self.assertTrue(response.whichEncoding() == server.ENCODE_HTML_FORM) webresponse = self.encode(response) - self.failUnlessEqual(webresponse.body, response.toFormMarkup()) + self.assertEqual(webresponse.body, response.toFormMarkup()) def test_toFormMarkup(self): request = server.CheckIDRequest( @@ -602,7 +602,7 @@ }) form_markup = response.toFormMarkup({'foo':'bar'}) - self.failUnless(' foo="bar"' in form_markup) + self.assertTrue(' foo="bar"' in form_markup) def test_toHTML(self): request = server.CheckIDRequest( @@ -622,11 +622,11 @@ 'return_to': 'x' * OPENID1_URL_LIMIT, }) html = response.toHTML() - self.failUnless('' in html) - self.failUnless('' in html) - self.failUnless('
' in html) + self.assertTrue('' in html) + self.assertTrue(' OPENID1_URL_LIMIT) - self.failUnless(response.whichEncoding() == server.ENCODE_URL) + self.assertFalse(response.renderAsForm()) + self.assertTrue(len(response.encodeToURL()) > OPENID1_URL_LIMIT) + self.assertTrue(response.whichEncoding() == server.ENCODE_URL) webresponse = self.encode(response) - self.failUnlessEqual(webresponse.headers['location'], response.encodeToURL()) + self.assertEqual(webresponse.headers['location'], response.encodeToURL()) def test_id_res(self): request = server.CheckIDRequest( @@ -672,17 +672,17 @@ 'return_to': request.return_to, }) webresponse = self.encode(response) - self.failUnlessEqual(webresponse.code, server.HTTP_REDIRECT) - self.failUnless(webresponse.headers.has_key('location')) + self.assertEqual(webresponse.code, server.HTTP_REDIRECT) + self.assertTrue('location' in webresponse.headers) location = webresponse.headers['location'] - self.failUnless(location.startswith(request.return_to), + self.assertTrue(location.startswith(request.return_to), "%s does not start with %s" % (location, request.return_to)) # argh. q2 = dict(cgi.parse_qsl(urlparse(location)[4])) expected = response.fields.toPostArgs() - self.failUnlessEqual(q2, expected) + self.assertEqual(q2, expected) def test_cancel(self): request = server.CheckIDRequest( @@ -698,8 +698,8 @@ 'mode': 'cancel', }) webresponse = self.encode(response) - self.failUnlessEqual(webresponse.code, server.HTTP_REDIRECT) - self.failUnless(webresponse.headers.has_key('location')) + self.assertEqual(webresponse.code, server.HTTP_REDIRECT) + self.assertTrue('location' in webresponse.headers) def test_cancelToForm(self): request = server.CheckIDRequest( @@ -715,7 +715,7 @@ 'mode': 'cancel', }) form = response.toFormMarkup() - self.failUnless(form) + self.assertTrue(form) def test_assocReply(self): msg = Message(OPENID2_NS) @@ -727,9 +727,9 @@ webresponse = self.encode(response) body = """assoc_handle:every-zig """ - self.failUnlessEqual(webresponse.code, server.HTTP_OK) - self.failUnlessEqual(webresponse.headers, {}) - self.failUnlessEqual(webresponse.body, body) + self.assertEqual(webresponse.code, server.HTTP_OK) + self.assertEqual(webresponse.headers, {}) + self.assertEqual(webresponse.body, body) def test_checkauthReply(self): request = server.CheckAuthRequest('a_sock_monkey', @@ -744,16 +744,16 @@ is_valid:true """ webresponse = self.encode(response) - self.failUnlessEqual(webresponse.code, server.HTTP_OK) - self.failUnlessEqual(webresponse.headers, {}) - self.failUnlessEqual(webresponse.body, body) + self.assertEqual(webresponse.code, server.HTTP_OK) + self.assertEqual(webresponse.headers, {}) + self.assertEqual(webresponse.body, body) def test_unencodableError(self): args = Message.fromPostArgs({ 'openid.identity': 'http://limu.unittest/', }) e = server.ProtocolError(args, "wet paint") - self.failUnlessRaises(server.EncodingError, self.encode, e) + self.assertRaises(server.EncodingError, self.encode, e) def test_encodableError(self): args = Message.fromPostArgs({ @@ -762,9 +762,9 @@ }) body="error:snoot\nmode:error\n" webresponse = self.encode(server.ProtocolError(args, "snoot")) - self.failUnlessEqual(webresponse.code, server.HTTP_ERROR) - self.failUnlessEqual(webresponse.headers, {}) - self.failUnlessEqual(webresponse.body, body) + self.assertEqual(webresponse.code, server.HTTP_ERROR) + self.assertEqual(webresponse.headers, {}) + self.assertEqual(webresponse.body, body) @@ -800,29 +800,29 @@ 'sekrit', 'HMAC-SHA1')) self.request.assoc_handle = assoc_handle webresponse = self.encode(self.response) - self.failUnlessEqual(webresponse.code, server.HTTP_REDIRECT) - self.failUnless(webresponse.headers.has_key('location')) + self.assertEqual(webresponse.code, server.HTTP_REDIRECT) + self.assertTrue('location' in webresponse.headers) location = webresponse.headers['location'] query = cgi.parse_qs(urlparse(location)[4]) - self.failUnless('openid.sig' in query) - self.failUnless('openid.assoc_handle' in query) - self.failUnless('openid.signed' in query) + self.assertTrue('openid.sig' in query) + self.assertTrue('openid.assoc_handle' in query) + self.assertTrue('openid.signed' in query) def test_idresDumb(self): webresponse = self.encode(self.response) - self.failUnlessEqual(webresponse.code, server.HTTP_REDIRECT) - self.failUnless(webresponse.headers.has_key('location')) + self.assertEqual(webresponse.code, server.HTTP_REDIRECT) + self.assertTrue('location' in webresponse.headers) location = webresponse.headers['location'] query = cgi.parse_qs(urlparse(location)[4]) - self.failUnless('openid.sig' in query) - self.failUnless('openid.assoc_handle' in query) - self.failUnless('openid.signed' in query) + self.assertTrue('openid.sig' in query) + self.assertTrue('openid.assoc_handle' in query) + self.assertTrue('openid.signed' in query) def test_forgotStore(self): self.encoder.signatory = None - self.failUnlessRaises(ValueError, self.encode, self.response) + self.assertRaises(ValueError, self.encode, self.response) def test_cancel(self): request = server.CheckIDRequest( @@ -836,11 +836,11 @@ response = server.OpenIDResponse(request) response.fields.setArg(OPENID_NS, 'mode', 'cancel') webresponse = self.encode(response) - self.failUnlessEqual(webresponse.code, server.HTTP_REDIRECT) - self.failUnless(webresponse.headers.has_key('location')) + self.assertEqual(webresponse.code, server.HTTP_REDIRECT) + self.assertTrue('location' in webresponse.headers) location = webresponse.headers['location'] query = cgi.parse_qs(urlparse(location)[4]) - self.failIf('openid.sig' in query, response.fields.toPostArgs()) + self.assertFalse('openid.sig' in query, response.fields.toPostArgs()) def test_assocReply(self): msg = Message(OPENID2_NS) @@ -851,13 +851,13 @@ webresponse = self.encode(response) body = """assoc_handle:every-zig """ - self.failUnlessEqual(webresponse.code, server.HTTP_OK) - self.failUnlessEqual(webresponse.headers, {}) - self.failUnlessEqual(webresponse.body, body) + self.assertEqual(webresponse.code, server.HTTP_OK) + self.assertEqual(webresponse.headers, {}) + self.assertEqual(webresponse.body, body) def test_alreadySigned(self): self.response.fields.setArg(OPENID_NS, 'sig', 'priorSig==') - self.failUnlessRaises(server.AlreadySigned, self.encode, self.response) + self.assertRaises(server.AlreadySigned, self.encode, self.response) class TestCheckID(unittest.TestCase): def setUp(self): @@ -876,12 +876,12 @@ def test_trustRootInvalid(self): self.request.trust_root = "http://foo.unittest/17" self.request.return_to = "http://foo.unittest/39" - self.failIf(self.request.trustRootValid()) + self.assertFalse(self.request.trustRootValid()) def test_trustRootValid(self): self.request.trust_root = "http://foo.unittest/" self.request.return_to = "http://foo.unittest/39" - self.failUnless(self.request.trustRootValid()) + self.assertTrue(self.request.trustRootValid()) def test_malformedTrustRoot(self): self.request.trust_root = "invalid://trust*root/" @@ -890,8 +890,8 @@ self.request.message = sentinel try: result = self.request.trustRootValid() - except server.MalformedTrustRoot, why: - self.failUnless(sentinel is why.openid_message) + except server.MalformedTrustRoot as why: + self.assertTrue(sentinel is why.openid_message) else: self.fail('Expected MalformedTrustRoot exception. Got %r' % (result,)) @@ -905,7 +905,7 @@ op_endpoint = self.server.op_endpoint, ) - self.failUnless(request.trustRootValid()) + self.assertTrue(request.trustRootValid()) def test_returnToVerified_callsVerify(self): """Make sure that verifyReturnTo is calling the trustroot @@ -922,25 +922,25 @@ # Ensure that exceptions are passed through sentinel = Exception() def vrfyExc(trust_root, return_to): - self.failUnlessEqual(self.request.trust_root, trust_root) - self.failUnlessEqual(self.request.return_to, return_to) + self.assertEqual(self.request.trust_root, trust_root) + self.assertEqual(self.request.return_to, return_to) raise sentinel try: withVerifyReturnTo(vrfyExc, self.request.returnToVerified) - except Exception, e: - self.failUnless(e is sentinel, e) + except Exception as e: + self.assertTrue(e is sentinel, e) # Ensure that True and False are passed through unchanged def constVerify(val): def verify(trust_root, return_to): - self.failUnlessEqual(self.request.trust_root, trust_root) - self.failUnlessEqual(self.request.return_to, return_to) + self.assertEqual(self.request.trust_root, trust_root) + self.assertEqual(self.request.return_to, return_to) return val return verify for val in [True, False]: - self.failUnlessEqual( + self.assertEqual( val, withVerifyReturnTo(constVerify(val), self.request.returnToVerified)) @@ -960,13 +960,13 @@ for k, expected in expected_list: actual = answer.fields.getArg(OPENID_NS, k) - self.failUnlessEqual(actual, expected, "%s: expected %s, got %s" % (k, expected, actual)) - - self.failUnless(answer.fields.hasKey(OPENID_NS, 'response_nonce')) - self.failUnless(answer.fields.getOpenIDNamespace() == OPENID2_NS) + self.assertEqual(actual, expected, "%s: expected %s, got %s" % (k, expected, actual)) + + self.assertTrue(answer.fields.hasKey(OPENID_NS, 'response_nonce')) + self.assertTrue(answer.fields.getOpenIDNamespace() == OPENID2_NS) # One for nonce, one for ns - self.failUnlessEqual(len(answer.fields.toPostArgs()), + self.assertEqual(len(answer.fields.toPostArgs()), len(expected_list) + 2, answer.fields.toPostArgs()) @@ -976,7 +976,7 @@ including mode=id_res, identity, claimed_id, op_endpoint, return_to """ answer = self.request.answer(True) - self.failUnlessEqual(answer.request, self.request) + self.assertEqual(answer.request, self.request) self._expectAnswer(answer, self.request.identity) def test_answerAllowDelegatedIdentity(self): @@ -996,13 +996,13 @@ def test_answerAllowWithoutIdentityReally(self): self.request.identity = None answer = self.request.answer(True) - self.failUnlessEqual(answer.request, self.request) + self.assertEqual(answer.request, self.request) self._expectAnswer(answer) def test_answerAllowAnonymousFail(self): self.request.identity = None # XXX - Check on this, I think this behavior is legal in OpenID 2.0? - self.failUnlessRaises( + self.assertRaises( ValueError, self.request.answer, True, identity="=V") def test_answerAllowWithIdentity(self): @@ -1030,14 +1030,14 @@ self.request.identity = IDENTIFIER_SELECT selected_id = 'http://anon.unittest/9861' claimed_id = 'http://monkeyhat.unittest/' - self.failUnlessRaises(server.VersionError, + self.assertRaises(server.VersionError, self.request.answer, True, identity=selected_id, claimed_id=claimed_id) def test_answerAllowWithAnotherIdentity(self): # XXX - Check on this, I think this behavior is legal in OpenID 2.0? - self.failUnlessRaises(ValueError, self.request.answer, True, + self.assertRaises(ValueError, self.request.answer, True, identity="http://pebbles.unittest/") def test_answerAllowWithIdentityNormalization(self): @@ -1060,12 +1060,12 @@ def test_answerAllowNoIdentityOpenID1(self): self.request.message = Message(OPENID1_NS) self.request.identity = None - self.failUnlessRaises(ValueError, self.request.answer, True, + self.assertRaises(ValueError, self.request.answer, True, identity=None) def test_answerAllowForgotEndpoint(self): self.request.op_endpoint = None - self.failUnlessRaises(RuntimeError, self.request.answer, True) + self.assertRaises(RuntimeError, self.request.answer, True) def test_checkIDWithNoIdentityOpenID1(self): msg = Message(OPENID1_NS) @@ -1074,7 +1074,7 @@ msg.setArg(OPENID_NS, 'mode', 'checkid_setup') msg.setArg(OPENID_NS, 'assoc_handle', 'bogus') - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.CheckIDRequest.fromMessage, msg, self.server) @@ -1086,7 +1086,7 @@ msg.setArg(OPENID_NS, 'return_to', 'http://invalid:8000/rt') msg.setArg(OPENID_NS, 'claimed_id', name) - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.CheckIDRequest.fromMessage, msg, self.server) @@ -1098,7 +1098,7 @@ msg.setArg(OPENID_NS, 'return_to', 'http://invalid:8000/rt') msg.setArg(OPENID_NS, 'identity', name) - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.CheckIDRequest.fromMessage, msg, self.server) @@ -1114,7 +1114,7 @@ result = server.CheckIDRequest.fromMessage(msg, self.server.op_endpoint) - self.failUnless(result.trust_root == 'http://real_trust_root/') + self.assertTrue(result.trust_root == 'http://real_trust_root/') def test_trustRootOpenID2(self): """Ignore openid.trust_root in OpenID 2""" @@ -1129,12 +1129,12 @@ result = server.CheckIDRequest.fromMessage(msg, self.server.op_endpoint) - self.failUnless(result.trust_root == 'http://real_trust_root/') + self.assertTrue(result.trust_root == 'http://real_trust_root/') def test_answerAllowNoTrustRoot(self): self.request.trust_root = None answer = self.request.answer(True) - self.failUnlessEqual(answer.request, self.request) + self.assertEqual(answer.request, self.request) self._expectAnswer(answer, self.request.identity) def test_fromMessageWithoutTrustRoot(self): @@ -1147,22 +1147,22 @@ result = server.CheckIDRequest.fromMessage(msg, self.server.op_endpoint) - self.failUnlessEqual(result.trust_root, 'http://real_trust_root/foo') + self.assertEqual(result.trust_root, 'http://real_trust_root/foo') def test_fromMessageWithEmptyTrustRoot(self): - return_to = u'http://someplace.invalid/?go=thing' + return_to = 'http://someplace.invalid/?go=thing' msg = Message.fromPostArgs({ - u'openid.assoc_handle': u'{blah}{blah}{OZivdQ==}', - u'openid.claimed_id': u'http://delegated.invalid/', - u'openid.identity': u'http://op-local.example.com/', - u'openid.mode': u'checkid_setup', - u'openid.ns': u'http://openid.net/signon/1.0', - u'openid.return_to': return_to, - u'openid.trust_root': u''}) + 'openid.assoc_handle': '{blah}{blah}{OZivdQ==}', + 'openid.claimed_id': 'http://delegated.invalid/', + 'openid.identity': 'http://op-local.example.com/', + 'openid.mode': 'checkid_setup', + 'openid.ns': 'http://openid.net/signon/1.0', + 'openid.return_to': return_to, + 'openid.trust_root': ''}) result = server.CheckIDRequest.fromMessage(msg, self.server.op_endpoint) - self.failUnlessEqual(result.trust_root, return_to) + self.assertEqual(result.trust_root, return_to) def test_fromMessageWithoutTrustRootOrReturnTo(self): msg = Message(OPENID2_NS) @@ -1171,7 +1171,7 @@ msg.setArg(OPENID_NS, 'identity', 'george') msg.setArg(OPENID_NS, 'claimed_id', 'george') - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.CheckIDRequest.fromMessage, msg, self.server.op_endpoint) @@ -1196,16 +1196,16 @@ for k, expected in expected_list: actual = answer.fields.getArg(OPENID_NS, k) - self.failUnlessEqual( + self.assertEqual( expected, actual, "%s: expected %s, got %s" % (k, expected, actual)) - self.failUnless(answer.fields.hasKey(OPENID_NS, 'response_nonce')) - self.failUnlessEqual(answer.fields.getOpenIDNamespace(), OPENID1_NS) - self.failUnless(answer.fields.namespaces.isImplicit(OPENID1_NS)) + self.assertTrue(answer.fields.hasKey(OPENID_NS, 'response_nonce')) + self.assertEqual(answer.fields.getOpenIDNamespace(), OPENID1_NS) + self.assertTrue(answer.fields.namespaces.isImplicit(OPENID1_NS)) # One for nonce (OpenID v1 namespace is implicit) - self.failUnlessEqual(len(answer.fields.toPostArgs()), + self.assertEqual(len(answer.fields.toPostArgs()), len(expected_list) + 1, answer.fields.toPostArgs()) @@ -1222,15 +1222,15 @@ server_url = "http://setup-url.unittest/" # crappiting setup_url, you dirty my interface with your presence! answer = self.request.answer(False, server_url=server_url) - self.failUnlessEqual(answer.request, self.request) - self.failUnlessEqual(len(answer.fields.toPostArgs()), 3, answer.fields) - self.failUnlessEqual(answer.fields.getOpenIDNamespace(), OPENID2_NS) - self.failUnlessEqual(answer.fields.getArg(OPENID_NS, 'mode'), + self.assertEqual(answer.request, self.request) + self.assertEqual(len(answer.fields.toPostArgs()), 3, answer.fields) + self.assertEqual(answer.fields.getOpenIDNamespace(), OPENID2_NS) + self.assertEqual(answer.fields.getArg(OPENID_NS, 'mode'), 'setup_needed') usu = answer.fields.getArg(OPENID_NS, 'user_setup_url') expected_substr = 'openid.claimed_id=http%3A%2F%2Fclaimed-id.test%2F' - self.failUnless(expected_substr in usu, usu) + self.assertTrue(expected_substr in usu, usu) def test_answerImmediateDenyOpenID1(self): """Look for user_setup_url in checkid_immediate negative @@ -1241,17 +1241,17 @@ server_url = "http://setup-url.unittest/" # crappiting setup_url, you dirty my interface with your presence! answer = self.request.answer(False, server_url=server_url) - self.failUnlessEqual(answer.request, self.request) - self.failUnlessEqual(len(answer.fields.toPostArgs()), 2, answer.fields) - self.failUnlessEqual(answer.fields.getOpenIDNamespace(), OPENID1_NS) - self.failUnless(answer.fields.namespaces.isImplicit(OPENID1_NS)) - self.failUnlessEqual(answer.fields.getArg(OPENID_NS, 'mode'), 'id_res') - self.failUnless(answer.fields.getArg( + self.assertEqual(answer.request, self.request) + self.assertEqual(len(answer.fields.toPostArgs()), 2, answer.fields) + self.assertEqual(answer.fields.getOpenIDNamespace(), OPENID1_NS) + self.assertTrue(answer.fields.namespaces.isImplicit(OPENID1_NS)) + self.assertEqual(answer.fields.getArg(OPENID_NS, 'mode'), 'id_res') + self.assertTrue(answer.fields.getArg( OPENID_NS, 'user_setup_url', '').startswith(server_url)) def test_answerSetupDeny(self): answer = self.request.answer(False) - self.failUnlessEqual(answer.fields.getArgs(OPENID_NS), { + self.assertEqual(answer.fields.getArgs(OPENID_NS), { 'mode': 'cancel', }) @@ -1267,20 +1267,20 @@ self.server.op_endpoint) # argh, lousy hack self.request.message = message - self.failUnlessEqual(rebuilt_request.__dict__, self.request.__dict__) + self.assertEqual(rebuilt_request.__dict__, self.request.__dict__) def test_getCancelURL(self): url = self.request.getCancelURL() rt, query_string = url.split('?') - self.failUnlessEqual(self.request.return_to, rt) + self.assertEqual(self.request.return_to, rt) query = dict(cgi.parse_qsl(query_string)) - self.failUnlessEqual(query, {'openid.mode':'cancel', + self.assertEqual(query, {'openid.mode':'cancel', 'openid.ns':OPENID2_NS}) def test_getCancelURLimmed(self): self.request.mode = 'checkid_immediate' self.request.immediate = True - self.failUnlessRaises(ValueError, self.request.getCancelURL) + self.assertRaises(ValueError, self.request.getCancelURL) @@ -1306,12 +1306,12 @@ def test_addField(self): namespace = 'something:' self.response.fields.setArg(namespace, 'bright', 'potato') - self.failUnlessEqual(self.response.fields.getArgs(OPENID_NS), + self.assertEqual(self.response.fields.getArgs(OPENID_NS), {'blue': 'star', 'mode': 'id_res', }) - self.failUnlessEqual(self.response.fields.getArgs(namespace), + self.assertEqual(self.response.fields.getArgs(namespace), {'bright':'potato'}) @@ -1320,11 +1320,11 @@ args = {'tangy': 'suspenders', 'bravo': 'inclusion'} self.response.fields.updateArgs(namespace, args) - self.failUnlessEqual(self.response.fields.getArgs(OPENID_NS), + self.assertEqual(self.response.fields.getArgs(OPENID_NS), {'blue': 'star', 'mode': 'id_res', }) - self.failUnlessEqual(self.response.fields.getArgs(namespace), args) + self.assertEqual(self.response.fields.getArgs(namespace), args) @@ -1369,13 +1369,13 @@ def test_valid(self): r = self.request.answer(self.signatory) - self.failUnlessEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'true'}) - self.failUnlessEqual(r.request, self.request) + self.assertEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'true'}) + self.assertEqual(r.request, self.request) def test_invalid(self): self.signatory.isValid = False r = self.request.answer(self.signatory) - self.failUnlessEqual(r.fields.getArgs(OPENID_NS), + self.assertEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'false'}) def test_replay(self): @@ -1393,23 +1393,23 @@ """ r = self.request.answer(self.signatory) r = self.request.answer(self.signatory) - self.failUnlessEqual(r.fields.getArgs(OPENID_NS), + self.assertEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'false'}) def test_invalidatehandle(self): self.request.invalidate_handle = "bogusHandle" r = self.request.answer(self.signatory) - self.failUnlessEqual(r.fields.getArgs(OPENID_NS), + self.assertEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'true', 'invalidate_handle': "bogusHandle"}) - self.failUnlessEqual(r.request, self.request) + self.assertEqual(r.request, self.request) def test_invalidatehandleNo(self): assoc_handle = 'goodhandle' self.signatory.assocs.append((False, 'goodhandle')) self.request.invalidate_handle = assoc_handle r = self.request.answer(self.signatory) - self.failUnlessEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'true'}) + self.assertEqual(r.fields.getArgs(OPENID_NS), {'is_valid': 'true'}) class TestAssociate(unittest.TestCase): @@ -1433,17 +1433,17 @@ self.request = server.AssociateRequest(session, 'HMAC-SHA1') response = self.request.answer(self.assoc) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg("assoc_type"), "HMAC-SHA1") - self.failUnlessEqual(rfg("assoc_handle"), self.assoc.handle) - self.failIf(rfg("mac_key")) - self.failUnlessEqual(rfg("session_type"), "DH-SHA1") - self.failUnless(rfg("enc_mac_key")) - self.failUnless(rfg("dh_server_public")) + self.assertEqual(rfg("assoc_type"), "HMAC-SHA1") + self.assertEqual(rfg("assoc_handle"), self.assoc.handle) + self.assertFalse(rfg("mac_key")) + self.assertEqual(rfg("session_type"), "DH-SHA1") + self.assertTrue(rfg("enc_mac_key")) + self.assertTrue(rfg("dh_server_public")) enc_key = rfg("enc_mac_key").decode('base64') spub = cryptutil.base64ToLong(rfg("dh_server_public")) secret = consumer_dh.xorSecret(spub, enc_key, cryptutil.sha1) - self.failUnlessEqual(secret, self.assoc.secret) + self.assertEqual(secret, self.assoc.secret) if not cryptutil.SHA256_AVAILABLE: @@ -1461,17 +1461,17 @@ self.request = server.AssociateRequest(session, 'HMAC-SHA256') response = self.request.answer(self.assoc) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg("assoc_type"), "HMAC-SHA256") - self.failUnlessEqual(rfg("assoc_handle"), self.assoc.handle) - self.failIf(rfg("mac_key")) - self.failUnlessEqual(rfg("session_type"), "DH-SHA256") - self.failUnless(rfg("enc_mac_key")) - self.failUnless(rfg("dh_server_public")) + self.assertEqual(rfg("assoc_type"), "HMAC-SHA256") + self.assertEqual(rfg("assoc_handle"), self.assoc.handle) + self.assertFalse(rfg("mac_key")) + self.assertEqual(rfg("session_type"), "DH-SHA256") + self.assertTrue(rfg("enc_mac_key")) + self.assertTrue(rfg("dh_server_public")) enc_key = rfg("enc_mac_key").decode('base64') spub = cryptutil.base64ToLong(rfg("dh_server_public")) secret = consumer_dh.xorSecret(spub, enc_key, cryptutil.sha256) - self.failUnlessEqual(secret, self.assoc.secret) + self.assertEqual(secret, self.assoc.secret) def test_protoError256(self): from openid.consumer.consumer import \ @@ -1494,7 +1494,7 @@ for request_args in bad_request_argss: message = Message.fromPostArgs(request_args) - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.AssociateRequest.fromMessage, message) @@ -1519,7 +1519,7 @@ for request_args in bad_request_argss: message = Message.fromPostArgs(request_args) - self.failUnlessRaises(server.ProtocolError, + self.assertRaises(server.ProtocolError, server.AssociateRequest.fromMessage, message) @@ -1544,16 +1544,16 @@ contact=contact, reference=reference) reply = p.toMessage() - self.failUnlessEqual(reply.getArg(OPENID_NS, 'reference'), reference) - self.failUnlessEqual(reply.getArg(OPENID_NS, 'contact'), contact) + self.assertEqual(reply.getArg(OPENID_NS, 'reference'), reference) + self.assertEqual(reply.getArg(OPENID_NS, 'contact'), contact) openid2_msg = Message.fromPostArgs(openid2_args) p = server.ProtocolError(openid2_msg, error, contact=contact, reference=reference) reply = p.toMessage() - self.failUnlessEqual(reply.getArg(OPENID_NS, 'reference'), reference) - self.failUnlessEqual(reply.getArg(OPENID_NS, 'contact'), contact) + self.assertEqual(reply.getArg(OPENID_NS, 'reference'), reference) + self.assertEqual(reply.getArg(OPENID_NS, 'contact'), contact) def failUnlessExpiresInMatches(self, msg, expected_expires_in): expires_in_str = msg.getArg(OPENID_NS, 'expires_in', no_default) @@ -1567,24 +1567,24 @@ error_message = ('"expires_in" value not within %s of expected: ' 'expected=%s, actual=%s' % (slop, expected_expires_in, expires_in)) - self.failUnless(0 <= difference <= slop, error_message) + self.assertTrue(0 <= difference <= slop, error_message) def test_plaintext(self): self.assoc = self.signatory.createAssociation(dumb=False, assoc_type='HMAC-SHA1') response = self.request.answer(self.assoc) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg("assoc_type"), "HMAC-SHA1") - self.failUnlessEqual(rfg("assoc_handle"), self.assoc.handle) + self.assertEqual(rfg("assoc_type"), "HMAC-SHA1") + self.assertEqual(rfg("assoc_handle"), self.assoc.handle) self.failUnlessExpiresInMatches( response.fields, self.signatory.SECRET_LIFETIME) - self.failUnlessEqual( + self.assertEqual( rfg("mac_key"), oidutil.toBase64(self.assoc.secret)) - self.failIf(rfg("session_type")) - self.failIf(rfg("enc_mac_key")) - self.failIf(rfg("dh_server_public")) + self.assertFalse(rfg("session_type")) + self.assertFalse(rfg("enc_mac_key")) + self.assertFalse(rfg("dh_server_public")) def test_plaintext_v2(self): # The main difference between this and the v1 test is that @@ -1598,42 +1598,42 @@ self.request = server.AssociateRequest.fromMessage( Message.fromPostArgs(args)) - self.failIf(self.request.message.isOpenID1()) + self.assertFalse(self.request.message.isOpenID1()) self.assoc = self.signatory.createAssociation( dumb=False, assoc_type='HMAC-SHA1') response = self.request.answer(self.assoc) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg("assoc_type"), "HMAC-SHA1") - self.failUnlessEqual(rfg("assoc_handle"), self.assoc.handle) + self.assertEqual(rfg("assoc_type"), "HMAC-SHA1") + self.assertEqual(rfg("assoc_handle"), self.assoc.handle) self.failUnlessExpiresInMatches( response.fields, self.signatory.SECRET_LIFETIME) - self.failUnlessEqual( + self.assertEqual( rfg("mac_key"), oidutil.toBase64(self.assoc.secret)) - self.failUnlessEqual(rfg("session_type"), "no-encryption") - self.failIf(rfg("enc_mac_key")) - self.failIf(rfg("dh_server_public")) + self.assertEqual(rfg("session_type"), "no-encryption") + self.assertFalse(rfg("enc_mac_key")) + self.assertFalse(rfg("dh_server_public")) def test_plaintext256(self): self.assoc = self.signatory.createAssociation(dumb=False, assoc_type='HMAC-SHA256') response = self.request.answer(self.assoc) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg("assoc_type"), "HMAC-SHA1") - self.failUnlessEqual(rfg("assoc_handle"), self.assoc.handle) + self.assertEqual(rfg("assoc_type"), "HMAC-SHA1") + self.assertEqual(rfg("assoc_handle"), self.assoc.handle) self.failUnlessExpiresInMatches( response.fields, self.signatory.SECRET_LIFETIME) - self.failUnlessEqual( + self.assertEqual( rfg("mac_key"), oidutil.toBase64(self.assoc.secret)) - self.failIf(rfg("session_type")) - self.failIf(rfg("enc_mac_key")) - self.failIf(rfg("dh_server_public")) + self.assertFalse(rfg("session_type")) + self.assertFalse(rfg("enc_mac_key")) + self.assertFalse(rfg("dh_server_public")) def test_unsupportedPrefer(self): allowed_assoc = 'COLD-PET-RAT' @@ -1650,10 +1650,10 @@ preferred_association_type=allowed_assoc, ) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg('error_code'), 'unsupported-type') - self.failUnlessEqual(rfg('assoc_type'), allowed_assoc) - self.failUnlessEqual(rfg('error'), message) - self.failUnlessEqual(rfg('session_type'), allowed_sess) + self.assertEqual(rfg('error_code'), 'unsupported-type') + self.assertEqual(rfg('assoc_type'), allowed_assoc) + self.assertEqual(rfg('error'), message) + self.assertEqual(rfg('session_type'), allowed_sess) def test_unsupported(self): message = 'This is a unit test' @@ -1664,10 +1664,10 @@ response = self.request.answerUnsupported(message) rfg = lambda f: response.fields.getArg(OPENID_NS, f) - self.failUnlessEqual(rfg('error_code'), 'unsupported-type') - self.failUnlessEqual(rfg('assoc_type'), None) - self.failUnlessEqual(rfg('error'), message) - self.failUnlessEqual(rfg('session_type'), None) + self.assertEqual(rfg('error_code'), 'unsupported-type') + self.assertEqual(rfg('assoc_type'), None) + self.assertEqual(rfg('error'), message) + self.assertEqual(rfg('session_type'), None) class Counter(object): def __init__(self): @@ -1693,12 +1693,12 @@ request.mode = "monkeymode" request.namespace = OPENID1_NS webresult = self.server.handleRequest(request) - self.failUnlessEqual(monkeycalled.count, 1) + self.assertEqual(monkeycalled.count, 1) def test_associate(self): request = server.AssociateRequest.fromMessage(Message.fromPostArgs({})) response = self.server.openid_associate(request) - self.failUnless(response.fields.hasKey(OPENID_NS, "assoc_handle"), + self.assertTrue(response.fields.hasKey(OPENID_NS, "assoc_handle"), "No assoc_handle here: %s" % (response.fields,)) def test_associate2(self): @@ -1718,11 +1718,11 @@ request = server.AssociateRequest.fromMessage(msg) response = self.server.openid_associate(request) - self.failUnless(response.fields.hasKey(OPENID_NS, "error")) - self.failUnless(response.fields.hasKey(OPENID_NS, "error_code")) - self.failIf(response.fields.hasKey(OPENID_NS, "assoc_handle")) - self.failIf(response.fields.hasKey(OPENID_NS, "assoc_type")) - self.failIf(response.fields.hasKey(OPENID_NS, "session_type")) + self.assertTrue(response.fields.hasKey(OPENID_NS, "error")) + self.assertTrue(response.fields.hasKey(OPENID_NS, "error_code")) + self.assertFalse(response.fields.hasKey(OPENID_NS, "assoc_handle")) + self.assertFalse(response.fields.hasKey(OPENID_NS, "assoc_type")) + self.assertFalse(response.fields.hasKey(OPENID_NS, "session_type")) def test_associate3(self): """Request an assoc type that is not supported when there are @@ -1740,12 +1740,12 @@ request = server.AssociateRequest.fromMessage(msg) response = self.server.openid_associate(request) - self.failUnless(response.fields.hasKey(OPENID_NS, "error")) - self.failUnless(response.fields.hasKey(OPENID_NS, "error_code")) - self.failIf(response.fields.hasKey(OPENID_NS, "assoc_handle")) - self.failUnlessEqual(response.fields.getArg(OPENID_NS, "assoc_type"), + self.assertTrue(response.fields.hasKey(OPENID_NS, "error")) + self.assertTrue(response.fields.hasKey(OPENID_NS, "error_code")) + self.assertFalse(response.fields.hasKey(OPENID_NS, "assoc_handle")) + self.assertEqual(response.fields.getArg(OPENID_NS, "assoc_type"), 'HMAC-SHA256') - self.failUnlessEqual(response.fields.getArg(OPENID_NS, "session_type"), + self.assertEqual(response.fields.getArg(OPENID_NS, "session_type"), 'DH-SHA256') if not cryptutil.SHA256_AVAILABLE: @@ -1766,7 +1766,7 @@ message = Message.fromPostArgs(query) request = server.AssociateRequest.fromMessage(message) response = self.server.openid_associate(request) - self.failUnless(response.fields.hasKey(OPENID_NS, "assoc_handle")) + self.assertTrue(response.fields.hasKey(OPENID_NS, "assoc_handle")) def test_missingSessionTypeOpenID2(self): """Make sure session_type is required in OpenID 2""" @@ -1780,7 +1780,7 @@ def test_checkAuth(self): request = server.CheckAuthRequest('arrrrrf', '0x3999', []) response = self.server.openid_check_authentication(request) - self.failUnless(response.fields.hasKey(OPENID_NS, "is_valid")) + self.assertTrue(response.fields.hasKey(OPENID_NS, "is_valid")) class TestSignatory(unittest.TestCase, CatchLogs): def setUp(self): @@ -1806,13 +1806,13 @@ 'azu': 'alsosigned', }) sresponse = self.signatory.sign(response) - self.failUnlessEqual( + self.assertEqual( sresponse.fields.getArg(OPENID_NS, 'assoc_handle'), assoc_handle) - self.failUnlessEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), + self.assertEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), 'assoc_handle,azu,bar,foo,signed') - self.failUnless(sresponse.fields.getArg(OPENID_NS, 'sig')) - self.failIf(self.messages, self.messages) + self.assertTrue(sresponse.fields.getArg(OPENID_NS, 'sig')) + self.assertFalse(self.messages, self.messages) def test_signDumb(self): request = server.OpenIDRequest() @@ -1827,13 +1827,13 @@ }) sresponse = self.signatory.sign(response) assoc_handle = sresponse.fields.getArg(OPENID_NS, 'assoc_handle') - self.failUnless(assoc_handle) + self.assertTrue(assoc_handle) assoc = self.signatory.getAssociation(assoc_handle, dumb=True) - self.failUnless(assoc) - self.failUnlessEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), + self.assertTrue(assoc) + self.assertEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), 'assoc_handle,azu,bar,foo,ns,signed') - self.failUnless(sresponse.fields.getArg(OPENID_NS, 'sig')) - self.failIf(self.messages, self.messages) + self.assertTrue(sresponse.fields.getArg(OPENID_NS, 'sig')) + self.assertFalse(self.messages, self.messages) def test_signExpired(self): """Sign a response to a message with an expired handle (using invalidate_handle). @@ -1856,7 +1856,7 @@ self._normal_key, association.Association.fromExpiresIn(-10, assoc_handle, 'sekrit', 'HMAC-SHA1')) - self.failUnless(self.store.getAssociation(self._normal_key, assoc_handle)) + self.assertTrue(self.store.getAssociation(self._normal_key, assoc_handle)) request.assoc_handle = assoc_handle response = server.OpenIDResponse(request) @@ -1868,25 +1868,25 @@ sresponse = self.signatory.sign(response) new_assoc_handle = sresponse.fields.getArg(OPENID_NS, 'assoc_handle') - self.failUnless(new_assoc_handle) - self.failIfEqual(new_assoc_handle, assoc_handle) - - self.failUnlessEqual( + self.assertTrue(new_assoc_handle) + self.assertNotEqual(new_assoc_handle, assoc_handle) + + self.assertEqual( sresponse.fields.getArg(OPENID_NS, 'invalidate_handle'), assoc_handle) - self.failUnlessEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), + self.assertEqual(sresponse.fields.getArg(OPENID_NS, 'signed'), 'assoc_handle,azu,bar,foo,invalidate_handle,signed') - self.failUnless(sresponse.fields.getArg(OPENID_NS, 'sig')) + self.assertTrue(sresponse.fields.getArg(OPENID_NS, 'sig')) # make sure the expired association is gone - self.failIf(self.store.getAssociation(self._normal_key, assoc_handle), + self.assertFalse(self.store.getAssociation(self._normal_key, assoc_handle), "expired association is still retrievable.") # make sure the new key is a dumb mode association - self.failUnless(self.store.getAssociation(self._dumb_key, new_assoc_handle)) - self.failIf(self.store.getAssociation(self._normal_key, new_assoc_handle)) - self.failUnless(self.messages) + self.assertTrue(self.store.getAssociation(self._dumb_key, new_assoc_handle)) + self.assertFalse(self.store.getAssociation(self._normal_key, new_assoc_handle)) + self.assertTrue(self.messages) def test_signInvalidHandle(self): @@ -1904,21 +1904,21 @@ sresponse = self.signatory.sign(response) new_assoc_handle = sresponse.fields.getArg(OPENID_NS, 'assoc_handle') - self.failUnless(new_assoc_handle) - self.failIfEqual(new_assoc_handle, assoc_handle) - - self.failUnlessEqual( + self.assertTrue(new_assoc_handle) + self.assertNotEqual(new_assoc_handle, assoc_handle) + + self.assertEqual( sresponse.fields.getArg(OPENID_NS, 'invalidate_handle'), assoc_handle) - self.failUnlessEqual( + self.assertEqual( sresponse.fields.getArg(OPENID_NS, 'signed'), 'assoc_handle,azu,bar,foo,invalidate_handle,signed') - self.failUnless(sresponse.fields.getArg(OPENID_NS, 'sig')) + self.assertTrue(sresponse.fields.getArg(OPENID_NS, 'sig')) # make sure the new key is a dumb mode association - self.failUnless(self.store.getAssociation(self._dumb_key, new_assoc_handle)) - self.failIf(self.store.getAssociation(self._normal_key, new_assoc_handle)) - self.failIf(self.messages, self.messages) + self.assertTrue(self.store.getAssociation(self._dumb_key, new_assoc_handle)) + self.assertFalse(self.store.getAssociation(self._normal_key, new_assoc_handle)) + self.assertFalse(self.messages, self.messages) def test_verify(self): @@ -1937,8 +1937,8 @@ }) verified = self.signatory.verify(assoc_handle, signed) - self.failIf(self.messages, self.messages) - self.failUnless(verified) + self.assertFalse(self.messages, self.messages) + self.assertTrue(verified) def test_verifyBadSig(self): @@ -1957,8 +1957,8 @@ RefactoringTool: Refactored ../python3/openid/test/test_rpverify.py }) verified = self.signatory.verify(assoc_handle, signed) - self.failIf(self.messages, self.messages) - self.failIf(verified) + self.assertFalse(self.messages, self.messages) + self.assertFalse(verified) def test_verifyBadHandle(self): assoc_handle = '{vroom}{zoom}' @@ -1969,8 +1969,8 @@ }) verified = self.signatory.verify(assoc_handle, signed) - self.failIf(verified) - self.failUnless(self.messages) + self.assertFalse(verified) + self.assertTrue(self.messages) def test_verifyAssocMismatch(self): @@ -1988,34 +1988,34 @@ }) verified = self.signatory.verify(assoc_handle, signed) - self.failIf(verified) - self.failUnless(self.messages) + self.assertFalse(verified) + self.assertTrue(self.messages) def test_getAssoc(self): assoc_handle = self.makeAssoc(dumb=True) assoc = self.signatory.getAssociation(assoc_handle, True) - self.failUnless(assoc) - self.failUnlessEqual(assoc.handle, assoc_handle) - self.failIf(self.messages, self.messages) + self.assertTrue(assoc) + self.assertEqual(assoc.handle, assoc_handle) + self.assertFalse(self.messages, self.messages) def test_getAssocExpired(self): assoc_handle = self.makeAssoc(dumb=True, lifetime=-10) assoc = self.signatory.getAssociation(assoc_handle, True) - self.failIf(assoc, assoc) - self.failUnless(self.messages) + self.assertFalse(assoc, assoc) + self.assertTrue(self.messages) def test_getAssocInvalid(self): ah = 'no-such-handle' - self.failUnlessEqual( + self.assertEqual( self.signatory.getAssociation(ah, dumb=False), None) - self.failIf(self.messages, self.messages) + self.assertFalse(self.messages, self.messages) def test_getAssocDumbVsNormal(self): """getAssociation(dumb=False) cannot get a dumb assoc""" assoc_handle = self.makeAssoc(dumb=True) - self.failUnlessEqual( + self.assertEqual( self.signatory.getAssociation(assoc_handle, dumb=False), None) - self.failIf(self.messages, self.messages) + self.assertFalse(self.messages, self.messages) def test_getAssocNormalVsDumb(self): """getAssociation(dumb=True) cannot get a shared assoc @@ -2026,14 +2026,14 @@ MAC keys. """ assoc_handle = self.makeAssoc(dumb=False) - self.failUnlessEqual( + self.assertEqual( self.signatory.getAssociation(assoc_handle, dumb=True), None) - self.failIf(self.messages, self.messages) + self.assertFalse(self.messages, self.messages) def test_createAssociation(self): assoc = self.signatory.createAssociation(dumb=False) - self.failUnless(self.signatory.getAssociation(assoc.handle, dumb=False)) - self.failIf(self.messages, self.messages) + self.assertTrue(self.signatory.getAssociation(assoc.handle, dumb=False)) + self.assertFalse(self.messages, self.messages) def makeAssoc(self, dumb, lifetime=60): assoc_handle = '{bling}' @@ -2050,13 +2050,13 @@ self.store.storeAssociation(self._dumb_key, assoc) assoc = self.signatory.getAssociation(assoc_handle, dumb=True) - self.failUnless(assoc) + self.assertTrue(assoc) assoc = self.signatory.getAssociation(assoc_handle, dumb=True) - self.failUnless(assoc) + self.assertTrue(assoc) self.signatory.invalidate(assoc_handle, dumb=True) assoc = self.signatory.getAssociation(assoc_handle, dumb=True) - self.failIf(assoc) - self.failIf(self.messages, self.messages) + self.assertFalse(assoc) + self.assertFalse(self.messages, self.messages) --- ../python3/openid/test/test_rpverify.py (original) +++ ../python3/openid/test/test_rpverify.py (refactored) @@ -22,7 +22,7 @@ """ realm_obj = trustroot.TrustRRefactoringTool: Refactored ../python3/openid/test/test_parsehtml.py oot.parse(realm) actual_discovery_url = realm_obj.buildDiscoveryURL() - self.failUnlessEqual(expected_discovery_url, actual_discovery_url) + self.assertEqual(expected_discovery_url, actual_discovery_url) def test_trivial(self): """There is no wildcard and the realm is the same as the return_to URL @@ -62,11 +62,11 @@ actual_return_urls = list(trustroot.getAllowedReturnURLs( self.disco_url)) - self.failUnlessEqual(expected_return_urls, actual_return_urls) + self.assertEqual(expected_return_urls, actual_return_urls) def failUnlessDiscoveryFailure(self, text): self.data = text - self.failUnlessRaises( + self.assertRaises( DiscoveryFailure, trustroot.getAllowedReturnURLs, self.disco_url) def test_empty(self): @@ -164,15 +164,15 @@ class TestReturnToMatches(unittest.TestCase): def test_noEntries(self): - self.failIf(trustroot.returnToMatches([], 'anything')) + self.assertFalse(trustroot.returnToMatches([], 'anything')) def test_exactMatch(self): r = 'http://example.com/return.to' - self.failUnless(trustroot.returnToMatches([r], r)) + self.assertTrue(trustroot.returnToMatches([r], r)) def test_garbageMatch(self): r = 'http://example.com/return.to' - self.failUnless(trustroot.returnToMatches( + self.assertTrue(trustroot.returnToMatches( ['This is not a URL at all. In fact, it has characters, ' 'like "<" that are not allowed in URLs', r], @@ -180,18 +180,18 @@ def test_descendant(self): r = 'http://example.com/return.to' - self.failUnless(trustroot.returnToMatches( + self.assertTrue(trustroot.returnToMatches( [r], 'http://example.com/return.to/user:joe')) def test_wildcard(self): - self.failIf(trustroot.returnToMatches( + self.assertFalse(trustroot.returnToMatches( ['http://*.example.com/return.to'], 'http://example.com/return.to')) def test_noMatch(self): r = 'http://example.com/return.to' - self.failIf(trustroot.returnToMatches( + self.assertFalse(trustroot.returnToMatches( [r], 'http://example.com/xss_exploit')) @@ -204,17 +204,17 @@ CatchLogs.tearDown(self) def test_bogusRealm(self): - self.failIf(trustroot.verifyReturnTo('', 'http://example.com/')) + self.assertFalse(trustroot.verifyReturnTo('', 'http://example.com/')) def test_verifyWithDiscoveryCalled(self): realm = 'http://*.example.com/' return_to = 'http://www.example.com/foo' def vrfy(disco_url): - self.failUnlessEqual('http://www.example.com/', disco_url) + self.assertEqual('http://www.example.com/', disco_url) return [return_to] - self.failUnless( + self.assertTrue( trustroot.verifyReturnTo(realm, return_to, _vrfy=vrfy)) self.failUnlessLogEmpty() @@ -223,10 +223,10 @@ return_to = 'http://www.example.com/foo' def vrfy(disco_url): - self.failUnlessEqual('http://www.example.com/', disco_url) + self.assertEqual('http://www.example.com/', disco_url) return ['http://something-else.invalid/'] - self.failIf( + self.assertFalse( trustroot.verifyReturnTo(realm, return_to, _vrfy=vrfy)) self.failUnlessLogMatches("Failed to validate return_to") @@ -238,7 +238,7 @@ raise trustroot.RealmVerificationRedirected( disco_url, "http://redirected.invalid") - self.failIf( + self.assertFalse( trustroot.verifyReturnTo(realm, return_to, _vrfy=vrfy)) self.failUnlessLogMatches("Attempting to verify") --- ../python3/openid/test/test_parsehtml.py (original) +++ ../python3/openid/test/test_parsehtml.py (refactored) @@ -1,5 +1,5 @@ from openid.yadis.parsehtml import YadisHTMLParser, ParseDRefactoringTool: Refactored ../python3/openid/test/test_pape_draft5.py one -from HTMLParser import HTMLParseError +from html.parser import HTMLParseError import os.path, unittest, sys @@ -17,7 +17,7 @@ p = YadisHTMLParser() try: p.feed(self.case) - except ParseDone, why: + except ParseDone as why: found = why[0] # make sure we protect outselves against accidental bogus @@ -29,11 +29,11 @@ found = 'None' msg = "%r != %r for case %s" % (found, self.expected, self.case) - self.failUnlessEqual(found, self.expected, msg) + self.assertEqual(found, self.expected, msg) except HTMLParseError: - self.failUnless(self.expected == 'None', (self.case, self.expected)) + self.assertTrue(self.expected == 'None', (self.case, self.expected)) else: - self.failUnless(self.expected == 'EOF', (self.case, self.expected)) + self.assertTrue(self.expected == 'EOF', (self.case, self.expected)) def shortDescription(self): return "%s (%s<%s>)" % ( --- ../python3/openid/test/test_pape_draft5.py (original) +++ ../python3/openid/test/test_pape_draft5.py (refactored) @@ -14,84 +14,84 @@ self.req = pape.Request() def test_construct(self): - self.failUnlessEqual([], self.req.preferred_auth_policies) - self.failUnlessEqual(None, self.req.max_auth_age) - self.failUnlessEqual('pape', self.req.ns_alias) - self.failIf(self.req.preferred_auth_level_types) + self.assertEqual([], self.req.preferred_auth_policies) + self.assertEqual(None, self.req.max_auth_age) + self.assertEqual('pape', self.req.ns_alias) + self.assertFalse(self.req.preferred_auth_level_types) bogus_levels = ['http://janrain.com/our_levels'] req2 = pape.Request( [pape.AUTH_MULTI_FACTOR], 1000, bogus_levels) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], + self.assertEqual([pape.AUTH_MULTI_FACTOR], req2.preferred_auth_policies) - self.failUnlessEqual(1000, req2.max_auth_age) - self.failUnlessEqual(bogus_levels, req2.preferred_auth_level_types) + self.assertEqual(1000, req2.max_auth_age) + self.assertEqual(bogus_levels, req2.preferred_auth_level_types) def test_addAuthLevel(self): self.req.addAuthLevel('http://example.com/', 'example') - self.failUnlessEqual(['http://example.com/'], + self.assertEqual(['http://example.com/'], self.req.preferred_auth_level_types) - self.failUnlessEqual('http://example.com/', + self.assertEqual('http://example.com/', self.req.auth_level_aliases['example']) self.req.addAuthLevel('http://example.com/1', 'example1') - self.failUnlessEqual(['http://example.com/', 'http://example.com/1'], + self.assertEqual(['http://example.com/', 'http://example.com/1'], self.req.preferred_auth_level_types) self.req.addAuthLevel('http://example.com/', 'exmpl') - self.failUnlessEqual(['http://example.com/', 'http://example.com/1'], + self.assertEqual(['http://example.com/', 'http://example.com/1'], self.req.preferred_auth_level_types) self.req.addAuthLevel('http://example.com/', 'example') - self.failUnlessEqual(['http://example.com/', 'http://example.com/1'], + self.assertEqual(['http://example.com/', 'http://example.com/1'], self.req.preferred_auth_level_types) - self.failUnlessRaises(KeyError, + self.assertRaises(KeyError, self.req.addAuthLevel, 'http://example.com/2', 'example') # alias is None; we expect a new one to be generated. uri = 'http://another.example.com/' self.req.addAuthLevel(uri) - self.assert_(uri in self.req.auth_level_aliases.values()) + self.assertTrue(uri in list(self.req.auth_level_aliases.values())) # We don't expect a new alias to be generated if one already # exists. - before_aliases = self.req.auth_level_aliases.keys() + before_aliases = list(self.req.auth_level_aliases.keys()) self.req.addAuthLevel(uri) - after_aliases = self.req.auth_level_aliases.keys() + after_aliases = list(self.req.auth_level_aliases.keys()) self.assertEqual(before_aliases, after_aliases) def test_add_policy_uri(self): - self.failUnlessEqual([], self.req.preferred_auth_policies) + self.assertEqual([], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_PHISHING_RESISTANT) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.preferred_auth_policies) def test_getExtensionArgs(self): - self.failUnlessEqual({'preferred_auth_policies': ''}, + self.assertEqual({'preferred_auth_policies': ''}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://uri') - self.failUnlessEqual( + self.assertEqual( {'preferred_auth_policies': 'http://uri'}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://zig') - self.failUnlessEqual( + self.assertEqual( {'preferred_auth_policies': 'http://uri http://zig'}, self.req.getExtensionArgs()) self.req.max_auth_age = 789 - self.failUnlessEqual( + self.assertEqual( {'preferred_auth_policies': 'http://uri http://zig', 'max_auth_age': '789'}, self.req.getExtensionArgs()) @@ -112,7 +112,7 @@ 'preferred_auth_policies': '', } - self.failUnlessEqual(expected_args, self.req.getExtensionArgs()) + self.assertEqual(expected_args, self.req.getExtensionArgs()) def test_parseExtensionArgsWithAuthLevels(self): uri = 'http://example.com/auth_level' @@ -153,7 +153,7 @@ self.req.preferred_auth_level_types) self.req = pape.Request() - self.failUnlessRaises(ValueError, + self.assertRaises(ValueError, self.req.parseExtensionArgs, request_args, is_openid1=False, strict=True) @@ -164,17 +164,17 @@ def test_parseExtensionArgs_strictBadAuthLevels(self): request_args = {'preferred_auth_level_types':'monkeys'} - self.failUnlessRaises(ValueError, self.req.parseExtensionArgs, + self.assertRaises(ValueError, self.req.parseExtensionArgs, request_args, is_openid1=False, strict=True) def test_parseExtensionArgs(self): args = {'preferred_auth_policies': 'http://foo http://bar', 'max_auth_age': '9'} self.req.parseExtensionArgs(args, False) - self.failUnlessEqual(9, self.req.max_auth_age) - self.failUnlessEqual(['http://foo','http://bar'], + self.assertEqual(9, self.req.max_auth_age) + self.assertEqual(['http://foo','http://bar'], self.req.preferred_auth_policies) - self.failUnlessEqual([], self.req.preferred_auth_level_types) + self.assertEqual([], self.req.preferred_auth_level_types) def test_parseExtensionArgs_strict_bad_auth_age(self): args = {'max_auth_age': 'not an int'} @@ -183,9 +183,9 @@ def test_parseExtensionArgs_empty(self): self.req.parseExtensionArgs({}, False) - self.failUnlessEqual(None, self.req.max_auth_age) - self.failUnlessEqual([], self.req.preferred_auth_policies) - self.failUnlessEqual([], self.req.preferred_auth_level_types) + self.assertEqual(None, self.req.max_auth_age) + self.assertEqual([], self.req.preferred_auth_policies) + self.assertEqual([], self.req.preferred_auth_level_types) def test_fromOpenIDRequest(self): policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT] @@ -199,8 +199,8 @@ oid_req = server.OpenIDRequest() oid_req.message = openid_req_msg req = pape.Request.fromOpenIDRequest(oid_req) - self.failUnlessEqual(policy_uris, req.preferred_auth_policies) - self.failUnlessEqual(5476, req.max_auth_age) + self.assertEqual(policy_uris, req.preferred_auth_policies) + self.assertEqual(5476, req.max_auth_age) def test_fromOpenIDRequest_no_pape(self): message = Message() @@ -214,7 +214,7 @@ self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) pt = self.req.preferredTypes([pape.AUTH_MULTI_FACTOR, pape.AUTH_MULTI_FACTOR_PHYSICAL]) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], pt) + self.assertEqual([pape.AUTH_MULTI_FACTOR], pt) class DummySuccessResponse: def __init__(self, message, signed_stuff): @@ -232,51 +232,51 @@ self.resp = pape.Response() def test_construct(self): - self.failUnlessEqual([], self.resp.auth_policies) - self.failUnlessEqual(None, self.resp.auth_time) - self.failUnlessEqual('pape', self.resp.ns_alias) - self.failUnlessEqual(None, self.resp.nist_auth_level) + self.assertEqual([], self.resp.auth_policies) + self.assertEqual(None, self.resp.auth_time) + self.assertEqual('pape', self.resp.ns_alias) + self.assertEqual(None, self.resp.nist_auth_level) req2 = pape.Response([pape.AUTH_MULTI_FACTOR], "2004-12-11T10:30:44Z", {pape.LEVELS_NIST: 3}) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], req2.auth_policies) - self.failUnlessEqual("2004-12-11T10:30:44Z", req2.auth_time) - self.failUnlessEqual(3, req2.nist_auth_level) + self.assertEqual([pape.AUTH_MULTI_FACTOR], req2.auth_policies) + self.assertEqual("2004-12-11T10:30:44Z", req2.auth_time) + self.assertEqual(3, req2.nist_auth_level) def test_add_policy_uri(self): - self.failUnlessEqual([], self.resp.auth_policies) + self.assertEqual([], self.resp.auth_policies) self.resp.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.resp.auth_policies) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.resp.auth_policies) self.resp.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.resp.auth_policies) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.resp.auth_policies) self.resp.addPolicyURI(pape.AUTH_PHISHING_RESISTANT) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.resp.auth_policies) self.resp.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.resp.auth_policies) - self.failUnlessRaises(RuntimeError, self.resp.addPolicyURI, + self.assertRaises(RuntimeError, self.resp.addPolicyURI, pape.AUTH_NONE) def test_getExtensionArgs(self): - self.failUnlessEqual({'auth_policies': pape.AUTH_NONE}, + self.assertEqual({'auth_policies': pape.AUTH_NONE}, self.resp.getExtensionArgs()) self.resp.addPolicyURI('http://uri') - self.failUnlessEqual({'auth_policies': 'http://uri'}, + self.assertEqual({'auth_policies': 'http://uri'}, self.resp.getExtensionArgs()) self.resp.addPolicyURI('http://zig') - self.failUnlessEqual({'auth_policies': 'http://uri http://zig'}, + self.assertEqual({'auth_policies': 'http://uri http://zig'}, self.resp.getExtensionArgs()) self.resp.auth_time = "1776-07-04T14:43:12Z" - self.failUnlessEqual( + self.assertEqual( {'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z"}, self.resp.getExtensionArgs()) self.resp.setAuthLevel(pape.LEVELS_NIST, '3') - self.failUnlessEqual( + self.assertEqual( {'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z", 'auth_level.nist': '3', @@ -285,39 +285,39 @@ def test_getExtensionArgs_error_auth_age(self): self.resp.auth_time = "long ago" - self.failUnlessRaises(ValueError, self.resp.getExtensionArgs) + self.assertRaises(ValueError, self.resp.getExtensionArgs) def test_parseExtensionArgs(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': '1970-01-01T00:00:00Z'} self.resp.parseExtensionArgs(args, is_openid1=False) - self.failUnlessEqual('1970-01-01T00:00:00Z', self.resp.auth_time) - self.failUnlessEqual(['http://foo','http://bar'], + self.assertEqual('1970-01-01T00:00:00Z', self.resp.auth_time) + self.assertEqual(['http://foo','http://bar'], self.resp.auth_policies) def test_parseExtensionArgs_valid_none(self): args = {'auth_policies': pape.AUTH_NONE} self.resp.parseExtensionArgs(args, is_openid1=False) - self.failUnlessEqual([], self.resp.auth_policies) + self.assertEqual([], self.resp.auth_policies) def test_parseExtensionArgs_old_none(self): args = {'auth_policies': 'none'} self.resp.parseExtensionArgs(args, is_openid1=False) - self.failUnlessEqual([], self.resp.auth_policies) + self.assertEqual([], self.resp.auth_policies) def test_parseExtensionArgs_old_none_strict(self): args = {'auth_policies': 'none'} - self.failUnlessRaises( + self.assertRaises( ValueError, self.resp.parseExtensionArgs, args, is_openid1=False, strict=True) def test_parseExtensionArgs_empty(self): self.resp.parseExtensionArgs({}, is_openid1=False) - self.failUnlessEqual(None, self.resp.auth_time) - self.failUnlessEqual([], self.resp.auth_policies) + self.assertEqual(None, self.resp.auth_time) + self.assertEqual([], self.resp.auth_policies) def test_parseExtensionArgs_empty_strict(self): - self.failUnlessRaises( + self.assertRaises( ValueError, self.resp.parseExtensionArgs, {}, is_openid1=False, strict=True) @@ -340,13 +340,13 @@ 'auth_policies': ' '.join(policies), } - self.failUnlessRaises(ValueError, self.resp.parseExtensionArgs, + self.assertRaises(ValueError, self.resp.parseExtensionArgs, args, is_openid1=False, strict=True) def test_parseExtensionArgs_strict_bogus1(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': 'yesterday'} - self.failUnlessRaises(ValueError, self.resp.parseExtensionArgs, + self.assertRaises(ValueError, self.resp.parseExtensionArgs, args, is_openid1=False, strict=True) def test_parseERefactoringTool: Refactored ../python3/openid/test/test_pape_draft2.py xtensionArgs_openid1_strict(self): @@ -354,8 +354,8 @@ 'auth_policies': pape.AUTH_NONE, } self.resp.parseExtensionArgs(args, strict=True, is_openid1=True) - self.failUnlessEqual('0', self.resp.getAuthLevel(pape.LEVELS_NIST)) - self.failUnlessEqual([], self.resp.auth_policies) + self.assertEqual('0', self.resp.getAuthLevel(pape.LEVELS_NIST)) + self.assertEqual([], self.resp.auth_policies) def test_parseExtensionArgs_strict_no_namespace_decl_openid2(self): # Test the case where the namespace is not declared for an @@ -363,7 +363,7 @@ args = {'auth_policies': pape.AUTH_NONE, 'auth_level.nist': '0', } - self.failUnlessRaises(ValueError, self.resp.parseExtensionArgs, + self.assertRaises(ValueError, self.resp.parseExtensionArgs, args, is_openid1=False, strict=True) def test_parseExtensionArgs_nostrict_no_namespace_decl_openid2(self): @@ -375,7 +375,7 @@ self.resp.parseExtensionArgs(args, is_openid1=False, strict=False) # There is no namespace declaration for this auth level. - self.failUnlessRaises(KeyError, self.resp.getAuthLevel, + self.assertRaises(KeyError, self.resp.getAuthLevel, pape.LEVELS_NIST) def test_parseExtensionArgs_strict_good(self): @@ -384,20 +384,20 @@ 'auth_level.nist': '0', 'auth_level.ns.nist': pape.LEVELS_NIST} self.resp.parseExtensionArgs(args, is_openid1=False, strict=True) - self.failUnlessEqual(['http://foo','http://bar'], + self.assertEqual(['http://foo','http://bar'], self.resp.auth_policies) - self.failUnlessEqual('1970-01-01T00:00:00Z', self.resp.auth_time) - self.failUnlessEqual(0, self.resp.nist_auth_level) + self.assertEqual('1970-01-01T00:00:00Z', self.resp.auth_time) + self.assertEqual(0, self.resp.nist_auth_level) def test_parseExtensionArgs_nostrict_bogus(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': 'when the cows come home', 'nist_auth_level': 'some'} self.resp.parseExtensionArgs(args, is_openid1=False) - self.failUnlessEqual(['http://foo','http://bar'], + self.assertEqual(['http://foo','http://bar'], self.resp.auth_policies) - self.failUnlessEqual(None, self.resp.auth_time) - self.failUnlessEqual(None, self.resp.nist_auth_level) + self.assertEqual(None, self.resp.auth_time) + self.assertEqual(None, self.resp.nist_auth_level) def test_fromSuccessResponse(self): policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT] @@ -414,8 +414,8 @@ } oid_req = DummySuccessResponse(openid_req_msg, signed_stuff) req = pape.Response.fromSuccessResponse(oid_req) - self.failUnlessEqual(policy_uris, req.auth_policies) - self.failUnlessEqual('1970-01-01T00:00:00Z', req.auth_time) + self.assertEqual(policy_uris, req.auth_policies) + self.assertEqual('1970-01-01T00:00:00Z', req.auth_time) def test_fromSuccessResponseNoSignedArgs(self): policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT] @@ -435,7 +435,7 @@ oid_req = NoSigningDummyResponse(openid_req_msg, signed_stuff) resp = pape.Response.fromSuccessResponse(oid_req) - self.failUnless(resp is None) + self.assertTrue(resp is None) if __name__ == '__main__': unittest.main() --- ../python3/openid/test/test_pape_draft2.py (original) +++ ../python3/openid/test/test_pape_draft2.py (refactored) @@ -10,47 +10,47 @@ self.req = pape.Request() def test_construct(self): - self.failUnlessEqual([], self.req.preferred_auth_policies) - self.failUnlessEqual(None, self.req.max_auth_age) - self.failUnlessEqual('pape', self.req.ns_alias) + self.assertEqual([], self.req.preferred_auth_policies) + self.assertEqual(None, self.req.max_auth_age) + self.assertEqual('pape', self.req.ns_alias) req2 = pape.Request([pape.AUTH_MULTI_FACTOR], 1000) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], req2.preferred_auth_policies) - self.failUnlessEqual(1000, req2.max_auth_age) + self.assertEqual([pape.AUTH_MULTI_FACTOR], req2.preferred_auth_policies) + self.assertEqual(1000, req2.max_auth_age) def test_add_policy_uri(self): - self.failUnlessEqual([], self.req.preferred_auth_policies) - self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) - self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) + self.assertEqual([], self.req.preferred_auth_policies) + self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) + self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_PHISHING_RESISTANT) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.preferred_auth_policies) self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.preferred_auth_policies) def test_getExtensionArgs(self): - self.failUnlessEqual({'preferred_auth_policies': ''}, self.req.getExtensionArgs()) + self.assertEqual({'preferred_auth_policies': ''}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://uri') - self.failUnlessEqual({'preferred_auth_policies': 'http://uri'}, self.req.getExtensionArgs()) + self.assertEqual({'preferred_auth_policies': 'http://uri'}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://zig') - self.failUnlessEqual({'preferred_auth_policies': 'http://uri http://zig'}, self.req.getExtensionArgs()) + self.assertEqual({'preferred_auth_policies': 'http://uri http://zig'}, self.req.getExtensionArgs()) self.req.max_auth_age = 789 - self.failUnlessEqual({'preferred_auth_policies': 'http://uri http://zig', 'max_auth_age': '789'}, self.req.getExtensionArgs()) + self.assertEqual({'preferred_auth_policies': 'http://uri http://zig', 'max_auth_age': '789'}, self.req.getExtensionArgs()) def test_parseExtensionArgs(self): args = {'preferred_auth_policies': 'http://foo http://bar', 'max_auth_age': '9'} self.req.parseExtensionArgs(args) - self.failUnlessEqual(9, self.req.max_auth_age) - self.failUnlessEqual(['http://foo','http://bar'], self.req.preferred_auth_policies) + self.assertEqual(9, self.req.max_auth_age) + self.assertEqual(['http://foo','http://bar'], self.req.preferred_auth_policies) def test_parseExtensionArgs_empty(self): self.req.parseExtensionArgs({}) - self.failUnlessEqual(None, self.req.max_auth_age) - self.failUnlessEqual([], self.req.preferred_auth_policies) + self.assertEqual(None, self.req.max_auth_age) + self.assertEqual([], self.req.preferred_auth_policies) def test_fromOpenIDRequest(self): openid_req_msg = Message.fromOpenIDArgs({ @@ -63,8 +63,8 @@ oid_req = server.OpenIDRequest() oid_req.message = openid_req_msg req = pape.Request.fromOpenIDRequest(oid_req) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], req.preferred_auth_policies) - self.failUnlessEqual(5476, req.max_auth_age) + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], req.preferred_auth_policies) + self.assertEqual(5476, req.max_auth_age) def test_fromOpenIDRequest_no_pape(self): message = Message() @@ -78,7 +78,7 @@ self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) pt = self.req.preferredTypes([pape.AUTH_MULTI_FACTOR, pape.AUTH_MULTI_FACTOR_PHYSICAL]) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], pt) + self.assertEqual([pape.AUTH_MULTI_FACTOR], pt) class DummySuccessResponse: def __init__(self, message, signed_stuff): @@ -93,73 +93,73 @@ self.req = pape.Response() def test_construct(self): - self.failUnlessEqual([], self.req.auth_policies) - self.failUnlessEqual(None, self.req.auth_time) - self.failUnlessEqual('pape', self.req.ns_alias) - self.failUnlessEqual(None, self.req.nist_auth_level) + self.assertEqual([], self.req.auth_policies) + self.assertEqual(None, self.req.auth_time) + self.assertEqual('pape', self.req.ns_alias) + self.assertEqual(None, self.req.nist_auth_level) req2 = pape.Response([pape.AUTH_MULTI_FACTOR], "2004-12-11T10:30:44Z", 3) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], req2.auth_policies) - self.failUnlessEqual("2004-12-11T10:30:44Z", req2.auth_time) - self.failUnlessEqual(3, req2.nist_auth_level) + self.assertEqual([pape.AUTH_MULTI_FACTOR], req2.auth_policies) + self.assertEqual("2004-12-11T10:30:44Z", req2.auth_time) + self.assertEqual(3, req2.nist_auth_level) def test_add_policy_uri(self): - self.failUnlessEqual([], self.req.auth_policies) - self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.req.auth_policies) - self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR], self.req.auth_policies) + self.assertEqual([], self.req.auth_policies) + self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.auth_policies) + self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) + self.assertEqual([pape.AUTH_MULTI_FACTOR], self.req.auth_policies) self.req.addPolicyURI(pape.AUTH_PHISHING_RESISTANT) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.auth_policies) - self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.auth_policies) + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.auth_policies) + self.req.addPolicyURI(pape.AUTH_MULTI_FACTOR) + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], self.req.auth_policies) def test_getExtensionArgs(self): - self.failUnlessEqual({'auth_policies': 'none'}, self.req.getExtensionArgs()) + self.assertEqual({'auth_policies': 'none'}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://uri') - self.failUnlessEqual({'auth_policies': 'http://uri'}, self.req.getExtensionArgs()) + self.assertEqual({'auth_policies': 'http://uri'}, self.req.getExtensionArgs()) self.req.addPolicyURI('http://zig') - self.failUnlessEqual({'auth_policies': 'http://uri http://zig'}, self.req.getExtensionArgs()) + self.assertEqual({'auth_policies': 'http://uri http://zig'}, self.req.getExtensionArgs()) self.req.auth_time = "1776-07-04T14:43:12Z" - self.failUnlessEqual({'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z"}, self.req.getExtensionArgs()) + self.assertEqual({'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z"}, self.req.getExtensionArgs()) self.req.nist_auth_level = 3 - self.failUnlessEqual({'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z", 'nist_auth_level': '3'}, self.req.getExtensionArgs()) + self.assertEqual({'auth_policies': 'http://uri http://zig', 'auth_time': "1776-07-04T14:43:12Z", 'nist_auth_level': '3'}, self.req.getExtensionArgs()) def test_getExtensionArgs_error_auth_age(self): self.req.auth_time = "long ago" - self.failUnlessRaises(ValueError, self.req.getExtensionArgs) + self.assertRaises(ValueError, self.req.getExtensionArgs) def test_getExtensionArgs_error_nist_auth_level(self): self.req.nist_auth_level = "high as a kite" - self.failUnlessRaises(ValueError, self.req.getExtensionArgs) + self.assertRaises(ValueError, self.req.getExtensionArgs) self.req.nist_auth_level = 5 - self.failUnlessRaises(ValueError, self.req.getExtensionArgs) + self.assertRaises(ValueError, self.req.getExtensionArgs) self.req.nist_auth_level = -1 - self.failUnlessRaises(ValueError, self.req.getExtensionArgs) + self.assertRaises(ValueError, self.req.getExtensionArgs) def test_parseExtensionArgs(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': '1970-01-01T00:00:00Z'} self.req.parseExtensionArgs(args) - self.failUnlessEqual('1970-01-01T00:00:00Z', self.req.auth_time) - self.failUnlessEqual(['http://foo','http://bar'], self.req.auth_policies) + self.assertEqual('1970-01-01T00:00:00Z', self.req.auth_time) + self.assertEqual(['http://foo','http://bar'], self.req.auth_policies) def test_parseExtensionArgs_empty(self): self.req.parseExtensionArgs({}) - self.failUnlessEqual(None, self.req.auth_time) - self.failUnlessEqual([], self.req.auth_policies) + self.assertEqual(None, self.req.auth_time) + self.assertEqual([], self.req.auth_policies) def test_parseExtensionArgs_strict_bogus1(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': 'yesterday'} - self.failUnlessRaises(ValueError, self.req.parseExtensionArgs, + self.assertRaises(ValueError, self.req.parseExtensionArgs, args, True) def test_parseExtensionArgs_strict_bogus2(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': '1970-01-01T00:00:00Z', 'nist_auth_level': 'some'} - self.failUnlessRaises(ValueError, self.req.parseExtensionArgs, + self.assertRaises(ValueError, self.req.parseExtensionArgs, args, True) def test_parseExtensionArgs_strict_good(self): @@ -167,18 +167,18 @@ 'auth_time': '1970-01-01T00:00:00Z', 'nist_auth_level': '0'} self.req.parseExtensionArgs(args, True) - self.failUnlessEqual(['http://foo','http://bar'], self.req.auth_policies) - self.failUnlessEqual('1970-01-01T00:00:00Z', self.req.auth_time) - self.failUnlessEqual(0, self.req.nist_auth_level) + self.assertEqual(['http://foo','http://bar'], self.req.auth_policies) + self.assertEqual('1970-01-01T00:00:00Z', self.req.auth_time) + self.assertEqual(0, self.req.nist_auth_level) def test_parseExtensionArgs_nostrict_bogus(self): args = {'auth_policies': 'http://foo http://bar', 'auth_time': 'when the cows come home', 'nist_auth_level': 'some'} self.req.parseExtensionArgs(args) - self.failUnlessEqual(['http://foo','http://bar'], self.req.auth_policies) - self.failUnlessEqual(None, self.req.auth_time) - self.failUnlessEqual(None, self.req.nist_auth_level) + self.assertEqual(['http://foo','http://bar'], self.req.auth_policies) + self.assertEqual(None, self.req.auth_time) + self.assertEqual(None, self.req.nist_auth_level) def test_fromSuccessResponse(self): openid_req_msg = Message.fromOpenIDArgs({ @@ -194,8 +194,8 @@ } oid_req = DummySuccessResponse(openid_req_msg, signed_stuff) req = pape.Response.RefactoringTool: Refactored ../python3/openid/test/test_pape.py RefactoringTool: Refactored ../python3/openid/test/test_openidyadis.py RefactoringTool: Refactored ../python3/openid/test/test_nonce.py fromSuccessResponse(oid_req) - self.failUnlessEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], req.auth_policies) - self.failUnlessEqual('1970-01-01T00:00:00Z', req.auth_time) + self.assertEqual([pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT], req.auth_policies) + self.assertEqual('1970-01-01T00:00:00Z', req.auth_time) def test_fromSuccessResponseNoSignedArgs(self): openid_req_msg = Message.fromOpenIDArgs({ @@ -214,4 +214,4 @@ oid_req = NoSigningDummyResponse(openid_req_msg, signed_stuff) resp = pape.Response.fromSuccessResponse(oid_req) - self.failUnless(resp is None) + self.assertTrue(resp is None) --- ../python3/openid/test/test_pape.py (original) +++ ../python3/openid/test/test_pape.py (refactored) @@ -6,4 +6,4 @@ class PapeImportTestCase(unittest.TestCase): def test_version(self): from openid.extensions.draft import pape5 - self.assert_(pape is pape5) + self.assertTrue(pape is pape5) --- ../python3/openid/test/test_openidyadis.py (original) +++ ../python3/openid/test/test_openidyadis.py (refactored) @@ -127,7 +127,7 @@ # make sure there are the same number of endpoints as # URIs. This assumes that the type_uris contains at least one # OpenID type. - self.failUnlessEqual(len(self.uris), len(endpoints)) + self.assertEqual(len(self.uris), len(endpoints)) # So that we can check equality on the endpoint types type_uris = list(self.type_uris) @@ -138,15 +138,15 @@ seen_uris.append(endpoint.server_url) # All endpoints will have same yadis_url - self.failUnlessEqual(self.yadis_url, endpoint.claimed_id) + self.assertEqual(self.yadis_url, endpoint.claimed_id) # and local_id - self.failUnlessEqual(self.local_id, endpoint.local_id) + self.assertEqual(self.local_id, endpoint.local_id) # and types actual_types = list(endpoint.type_uris) actual_types.sort() - self.failUnlessEqual(actual_types, type_uris) + self.assertEqual(actual_types, type_uris) # So that they will compare equal, because we don't care what # order they are in @@ -155,7 +155,7 @@ uris.sort() # Make sure we saw all URIs, and saw each one once - self.failUnlessEqual(uris, seen_uris) + self.assertEqual(uris, seen_uris) def pyUnitTests(): cases = [] --- ../python3/openid/test/test_nonce.py (original) +++ ../python3/openid/test/test_nonce.py (refactored) @@ -13,30 +13,30 @@ class NonceTest(unittest.TestCase): def test_mkNonce(self): nonce = mkNonce() - self.failUnless(nonce_re.match(nonce)) - self.failUnless(len(nonce) == 26) + self.assertTrue(nonce_re.match(nonce)) + self.assertTrue(len(nonce) == 26) def test_mkNonce_when(self): nonce = mkNonce(0) - self.failUnless(nonce_re.match(nonce)) - self.failUnless(nonce.startswith('1970-01-01T00:00:00Z')) - self.failUnless(len(nonce) == 26) + self.assertTrue(nonce_re.match(nonce)) + self.assertTrue(nonce.startswith('1970-01-01T00:00:00Z')) + self.assertTrue(len(nonce) == 26) def test_splitNonce(self): s = '1970-01-01T00:00:00Z' expected_t = 0 expected_salt = '' actual_t, actual_salt = splitNonce(s) - self.failUnlessEqual(expected_t, actual_t) - self.failUnlessEqual(expected_salt, actual_salt) + self.assertEqual(expected_t, actual_t) + self.assertEqual(expected_salt, actual_salt) def test_mkSplit(self): t = 42 nonce_str = mkNonce(t) - self.failUnless(nonce_re.match(nonce_str)) + self.assertTrue(nonce_re.match(nonce_str)) et, salt = splitNonce(nonce_str) - self.failUnlessEqual(len(salt), 6) - self.failUnlessEqual(et, t) + self.assertEqual(len(salt), 6) + self.assertEqual(et, t) class BadSpRefactoringTool: Refactored ../python3/openid/test/test_negotiation.py RefactoringTool: Refactored ../python3/openid/test/test_message.py litTest(datadriven.DataDrivenTestCase): cases = [ @@ -54,7 +54,7 @@ self.nonce_str = nonce_str def runOneTest(self): - self.failUnlessRaises(ValueError, splitNonce, self.nonce_str) + self.assertRaises(ValueError, splitNonce, self.nonce_str) class CheckTimestampTest(datadriven.DataDrivenTestCase): cases = [ @@ -93,7 +93,7 @@ def runOneTest(self): actual = checkTimestamp(self.nonce_string, self.allowed_skew, self.now) - self.failUnlessEqual(bool(self.expected), bool(actual)) + self.assertEqual(bool(self.expected), bool(actual)) def pyUnitTests(): return datadriven.loadTests(__name__) --- ../python3/openid/test/test_negotiation.py (original) +++ ../python3/openid/test/test_negotiation.py (refactored) @@ -1,6 +1,6 @@ import unittest -from support import CatchLogs +from .support import CatchLogs from openid.message import Message, OPENID2_NS, OPENID1_NS, OPENID_NS from openid import association @@ -123,7 +123,7 @@ 'handle', 'secret', 'issued', 10000, 'HMAC-SHA1') self.consumer.return_messages = [msg, assoc] - self.failUnless(self.consumer._negotiateAssociation(self.endpoint) is assoc) + self.assertTrue(self.consumer._negotiateAssociation(self.endpoint) is assoc) self.failUnlessLogMatches('Unsupported association type') @@ -141,7 +141,7 @@ self.consumer.return_messages = [msg, Message(self.endpoint.preferredNamespace())] - self.failUnlessEqual(self.consumer._negotiateAssociation(self.endpoint), None) + self.assertEqual(self.consumer._negotiateAssociation(self.endpoint), None) self.failUnlessLogMatches('Unsupported association type', 'Server %s refused' % (self.endpoint.server_url)) @@ -155,7 +155,7 @@ 'handle', 'secret', 'issued', 10000, 'HMAC-SHA1') self.consumer.return_messages = [assoc] - self.failUnless(self.consumer._negotiateAssociation(self.endpoint) is assoc) + self.assertTrue(self.consumer._negotiateAssociation(self.endpoint) is assoc) self.failUnlessLogEmpty() class TestOpenID1SessionNegotiation(unittest.TestCase, CatchLogs): @@ -233,7 +233,7 @@ 'handle', 'secret', 'issued', 10000, 'HMAC-SHA1') self.consumer.return_messages = [msg, assoc] - self.failUnless(self.consumer._negotiateAssociation(self.endpoint) is None) + self.assertTrue(self.consumer._negotiateAssociation(self.endpoint) is None) self.failUnlessLogMatches('Server error when requesting an association') @@ -242,7 +242,7 @@ 'handle', 'secret', 'issued', 10000, 'HMAC-SHA1') self.consumer.return_messages = [assoc] - self.failUnless(self.consumer._negotiateAssociation(self.endpoint) is assoc) + self.assertTrue(self.consumer._negotiateAssociation(self.endpoint) is assoc) self.failUnlessLogEmpty() class TestNegotiatorBehaviors(unittest.TestCase, CatchLogs): @@ -262,10 +262,10 @@ def testAddAllowedTypeContents(self): assoc_type = 'HMAC-SHA1' - self.failUnless(self.n.addAllowedType(assoc_type) is None) + self.assertTrue(self.n.addAllowedType(assoc_type) is None) for typ in association.getSessionTypes(assoc_type): - self.failUnless((assoc_type, typ) in self.n.allowed_types) + self.assertTrue((assoc_type, typ) in self.n.allowed_types) if __name__ == '__main__': unittest.main() --- ../python3/openid/test/test_message.py (original) +++ ../python3/openid/test/test_message.py (refactored) @@ -2,23 +2,23 @@ from openid import oidutil from openid.extensions import sreg -import urllib +import urllib.request, urllib.parse, urllib.error import cgi import unittest def mkGetArgTest(ns, key, expected=None): def test(self): a_default = object() - self.failUnlessEqual(self.msg.getArg(ns, key), expected) + self.assertEqual(self.msg.getArg(ns, key), expected) if expected is None: - self.failUnlessEqual( + self.assertEqual( self.msg.getArg(ns, key, a_default), a_default) - self.failUnlessRaises( + self.assertRaises( KeyError, self.msg.getArg, ns, key, message.no_default) else: - self.failUnlessEqual( + self.assertEqual( self.msg.getArg(ns, key, a_default), expected) - self.failUnlessEqual( + self.assertEqual( self.msg.getArg(ns, key, message.no_default), expected) return test @@ -28,43 +28,43 @@ self.msg = message.Message() def test_toPostArgs(self): - self.failUnlessEqual(self.msg.toPostArgs(), {}) + self.assertEqual(self.msg.toPostArgs(), {}) def test_toArgs(self): - self.failUnlessEqual(self.msg.toArgs(), {}) + self.assertEqual(self.msg.toArgs(), {}) def test_toKVForm(self): - self.failUnlessEqual(self.msg.toKVForm(), '') + self.assertEqual(self.msg.toKVForm(), '') def test_toURLEncoded(self): - self.failUnlessEqual(self.msg.toURLEncoded(), '') + self.assertEqual(self.msg.toURLEncoded(), '') def test_toURL(self): base_url = 'http://base.url/' - self.failUnlessEqual(self.msg.toURL(base_url), base_url) + self.assertEqual(self.msg.toURL(base_url), base_url) def test_getOpenID(self): - self.failUnlessEqual(self.msg.getOpenIDNamespace(), None) + self.assertEqual(self.msg.getOpenIDNamespace(), None) def test_getKeyOpenID(self): # Could reasonably return None instead of raising an # exception. I'm not sure which one is more right, since this # case should only happen when you're building a message from # scratch and so have no default namespace. - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.getKey, message.OPENID_NS, 'foo') def test_getKeyBARE(self): - self.failUnlessEqual(self.msg.getKey(message.BARE_NS, 'foo'), 'foo') + self.assertEqual(self.msg.getKey(message.BARE_NS, 'foo'), 'foo') def test_getKeyNS1(self): - self.failUnlessEqual(self.msg.getKey(message.OPENID1_NS, 'foo'), None) + self.assertEqual(self.msg.getKey(message.OPENID1_NS, 'foo'), None) def test_getKeyNS2(self): - self.failUnlessEqual(self.msg.getKey(message.OPENID2_NS, 'foo'), None) + self.assertEqual(self.msg.getKey(message.OPENID2_NS, 'foo'), None) def test_getKeyNS3(self): - self.failUnlessEqual(self.msg.getKey('urn:nothing-significant', 'foo'), + self.assertEqual(self.msg.getKey('urn:nothing-significant', 'foo'), None) def test_hasKey(self): @@ -72,27 +72,27 @@ # exception. I'm not sure which one is more right, since this # case should only happen when you're building a message from # scratch and so have no default namespace. - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.hasKey, message.OPENID_NS, 'foo') def test_hasKeyBARE(self): - self.failUnlessEqual(self.msg.hasKey(message.BARE_NS, 'foo'), False) + self.assertEqual(self.msg.hasKey(message.BARE_NS, 'foo'), False) def test_hasKeyNS1(self): - self.failUnlessEqual(self.msg.hasKey(message.OPENID1_NS, 'foo'), False) + self.assertEqual(self.msg.hasKey(message.OPENID1_NS, 'foo'), False) def test_hasKeyNS2(self): - self.failUnlessEqual(self.msg.hasKey(message.OPENID2_NS, 'foo'), False) + self.assertEqual(self.msg.hasKey(message.OPENID2_NS, 'foo'), False) def test_hasKeyNS3(self): - self.failUnlessEqual(self.msg.hasKey('urn:nothing-significant', 'foo'), + self.assertEqual(self.msg.hasKey('urn:nothing-significant', 'foo'), False) def test_getAliasedArgSuccess(self): msg = message.Message.fromPostArgs({'openid.ns.test': 'urn://foo', 'openid.test.flub': 'bogus'}) actual_uri = msg.getAliasedArg('ns.test', message.no_default) - self.assertEquals("urn://foo", actual_uri) + self.assertEqual("urn://foo", actual_uri) def test_getAliasedArgFailure(self): msg = message.Message.fromPostArgs({'openid.test.flub': 'bogus'}) @@ -104,7 +104,7 @@ # exception. I'm not sure which one is more right, since this # case should only happen when you're building a message from # scratch and so have no default namespace. - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.getArg, message.OPENID_NS, 'foo') test_getArgBARE = mkGetArgTest(message.BARE_NS, 'foo') @@ -117,23 +117,23 @@ # exception. I'm not sure which one is more right, since this # case should only happen when you're building a message from # scratch and so have no default namespace. - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.getArgs, message.OPENID_NS) def test_getArgsBARE(self): - self.failUnlessEqual(self.msg.getArgs(message.BARE_NS), {}) + self.assertEqual(self.msg.getArgs(message.BARE_NS), {}) def test_getArgsNS1(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID1_NS), {}) + self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {}) def test_getArgsNS2(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID2_NS), {}) + self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {}) def test_getArgsNS3(self): - self.failUnlessEqual(self.msg.getArgs('urn:nothing-significant'), {}) + self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {}) def test_updateArgs(self): - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.updateArgs, message.OPENID_NS, {'does not':'matter'}) @@ -143,9 +143,9 @@ 'Magnolia Electric Co.':'Jason Molina', } - self.failUnlessEqual(self.msg.getArgs(ns), {}) + self.assertEqual(self.msg.getArgs(ns), {}) self.msg.updateArgs(ns, update_args) - self.failUnlessEqual(self.msg.getArgs(ns), update_args) + self.assertEqual(self.msg.getArgs(ns), update_args) def test_updateArgsBARE(self): self._test_updateArgsNS(message.BARE_NS) @@ -160,16 +160,16 @@ self._test_updateArgsNS('urn:nothing-significant') def test_setArg(self): - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.setArg, message.OPENID_NS, 'does not', 'matter') def _test_setArgNS(self, ns): key = 'Camper van Beethoven' value = 'David Lowery' - self.failUnlessEqual(self.msg.getArg(ns, key), None) + self.assertEqual(self.msg.getArg(ns, key), None) self.msg.setArg(ns, key, value) - self.failUnlessEqual(self.msg.getArg(ns, key), value) + self.assertEqual(self.msg.getArg(ns, key), value) def test_setArgBARE(self): self._test_setArgNS(message.BARE_NS) @@ -184,7 +184,7 @@ self._test_setArgNS('urn:nothing-significant') def test_setArgToNone(self): - self.failUnlessRaises(AssertionError, self.msg.setArg, + self.assertRaises(AssertionError, self.msg.setArg, message.OPENID1_NS, 'op_endpoint', None) def test_delArg(self): @@ -193,12 +193,12 @@ # right, since this case should only happen when you're # building a message from scratch and so have no default # namespace. - self.failUnlessRaises(message.UndefinedOpenIDNamespace, + self.assertRaises(message.UndefinedOpenIDNamespace, self.msg.delArg, message.OPENID_NS, 'key') def _test_delArgNS(self, ns): key = 'Camper van Beethoven' - self.failUnlessRaises(KeyError, self.msg.delArg, ns, key) + self.assertRaises(KeyError, self.msg.delArg, ns, key) def test_delArgBARE(self): self._test_delArgNS(message.BARE_NS) @@ -213,10 +213,10 @@ self._test_delArgNS('urn:nothing-significant') def test_isOpenID1(self): - self.failIf(self.msg.isOpenID1()) + self.assertFalse(self.msg.isOpenID1()) def test_isOpenID2(self): - self.failIf(self.msg.isOpenID2()) + self.assertFalse(self.msg.isOpenID2()) class OpenID1MessageTest(unittest.TestCase): def setUp(self): @@ -224,69 +224,69 @@ 'openid.error':'unit test'}) def test_toPostArgs(self): - self.failUnlessEqual(self.msg.toPostArgs(), + self.assertEqual(self.msg.toPostArgs(), {'openid.mode':'error', 'openid.error':'unit test'}) def test_toArgs(self): - self.failUnlessEqual(self.msg.toArgs(), {'mode':'error', + self.assertEqual(self.msg.toArgs(), {'mode':'error', 'error':'unit test'}) def test_toKVForm(self): - self.failUnlessEqual(self.msg.toKVForm(), + self.assertEqual(self.msg.toKVForm(), 'error:unit test\nmode:error\n') def test_toURLEncoded(self): - self.failUnlessEqual(self.msg.toURLEncoded(), + self.assertEqual(self.msg.toURLEncoded(), 'openid.error=unit+test&openid.mode=error') def test_toURL(self): base_url = 'http://base.url/' actual = self.msg.toURL(base_url) actual_base = actual[:len(base_url)] - self.failUnlessEqual(actual_base, base_url) - self.failUnlessEqual(actual[len(base_url)], '?') + self.assertEqual(actual_base, base_url) + self.assertEqual(actual[len(base_url)], '?') query = actual[len(base_url) + 1:] parsed = cgi.parse_qs(query) - self.failUnlessEqual(parsed, {'openid.mode':['error'], + self.assertEqual(parsed, {'openid.mode':['error'], 'openid.error':['unit test']}) def test_getOpenID(self): - self.failUnlessEqual(self.msg.getOpenIDNamespace(), message.OPENID1_NS) + self.assertEqual(self.msg.getOpenIDNamespace(), message.OPENID1_NS) def test_getKeyOpenID(self): - self.failUnlessEqual(self.msg.getKey(message.OPENID_NS, 'mode'), + self.assertEqual(self.msg.getKey(message.OPENID_NS, 'mode'), 'openid.mode') def test_getKeyBARE(self): - self.failUnlessEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode') + self.assertEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode') def test_getKeyNS1(self): - self.failUnlessEqual( + self.assertEqual( self.msg.getKey(message.OPENID1_NS, 'mode'), 'openid.mode') def test_getKeyNS2(self): - self.failUnlessEqual(self.msg.getKey(message.OPENID2_NS, 'mode'), None) + self.assertEqual(self.msg.getKey(message.OPENID2_NS, 'mode'), None) def test_getKeyNS3(self): - self.failUnlessEqual( + self.assertEqual( self.msg.getKey('urn:nothing-significant', 'mode'), None) def test_hasKey(self): - self.failUnlessEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True) + self.assertEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True) def test_hasKeyBARE(self): - self.failUnlessEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False) + self.assertEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False) def test_hasKeyNS1(self): - self.failUnlessEqual(self.msg.hasKey(message.OPENID1_NS, 'mode'), True) + self.assertEqual(self.msg.hasKey(message.OPENID1_NS, 'mode'), True) def test_hasKeyNS2(self): - self.failUnlessEqual( + self.assertEqual( self.msg.hasKey(message.OPENID2_NS, 'mode'), False) def test_hasKeyNS3(self): - self.failUnlessEqual( + self.assertEqual( self.msg.hasKey('urn:nothing-significant', 'mode'), False) test_getArgBARE = mkGetArgTest(message.BARE_NS, 'mode') @@ -296,25 +296,25 @@ test_getArgNS3 = mkGetArgTest('urn:nothing-significant', 'mode') def test_getArgs(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID_NS), + self.assertEqual(self.msg.getArgs(message.OPENID_NS), {'mode':'error', 'error':'unit test', }) def test_getArgsBARE(self): - self.failUnlessEqual(self.msg.getArgs(message.BARE_NS), {}) + self.assertEqual(self.msg.getArgs(message.BARE_NS), {}) def test_getArgsNS1(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID1_NS), + self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {'mode':'error', 'error':'unit test', }) def test_getArgsNS2(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID2_NS), {}) + self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {}) def test_getArgsNS3(self): - self.failUnlessEqual(self.msg.getArgs('urn:nothing-significant'), {}) + self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {}) def _test_updateArgsNS(self, ns, before=None): if before is None: @@ -324,11 +324,11 @@ 'Magnolia Electric Co.':'Jason Molina', } - self.failUnlessEqual(self.msg.getArgs(ns), before) + self.assertEqual(self.msg.getArgs(ns), before) self.msg.updateArgs(ns, update_args) after = dict(before) after.update(update_args) - self.failUnlessEqual(self.msg.getArgs(ns), after) + self.assertEqual(self.msg.getArgs(ns), after) def test_updateArgs(self): self._test_updateArgsNS(message.OPENID_NS, @@ -350,9 +350,9 @@ def _test_setArgNS(self, ns): key = 'Camper van Beethoven' value = 'David Lowery' - self.failUnlessEqual(self.msg.getArg(ns, key), None) + self.assertEqual(self.msg.getArg(ns, key), None) self.msg.setArg(ns, key, value) - self.failUnlessEqual(self.msg.getArg(ns, key), value) + self.assertEqual(self.msg.getArg(ns, key), value) def test_setArg(self): self._test_setArgNS(message.OPENID_NS) @@ -373,11 +373,11 @@ key = 'Camper van Beethoven' value = 'David Lowery' - self.failUnlessRaises(KeyError, self.msg.delArg, ns, key) + self.assertRaises(KeyError, self.msg.delArg, ns, key) self.msg.setArg(ns, key, value) - self.failUnlessEqual(self.msg.getArg(ns, key), value) + self.assertEqual(self.msg.getArg(ns, key), value) self.msg.delArg(ns, key) - self.failUnlessEqual(self.msg.getArg(ns, key), None) + self.assertEqual(self.msg.getArg(ns, key), None) def test_delArg(self): self._test_delArgNS(message.OPENID_NS) @@ -396,10 +396,10 @@ def test_isOpenID1(self): - self.failUnless(self.msg.isOpenID1()) + self.assertTrue(self.msg.isOpenID1()) def test_isOpenID2(self): - self.failIf(self.msg.isOpenID2()) + self.assertFalse(self.msg.isOpenID2()) class OpenID1ExplicitMessageTest(unittest.TestCase): def setUp(self): @@ -409,41 +409,41 @@ }) def test_toPostArgs(self): - self.failUnlessEqual(self.msg.toPostArgs(), + self.assertEqual(self.msg.toPostArgs(), {'openid.mode':'error', 'openid.error':'unit test', 'openid.ns':message.OPENID1_NS }) def test_toArgs(self): - self.failUnlessEqual(self.msg.toArgs(), {'mode':'error', + self.assertEqual(self.msg.toArgs(), {'mode':'error', 'error':'unit test', 'ns':message.OPENID1_NS}) def test_toKVForm(self): - self.failUnlessEqual(self.msg.toKVForm(), + self.assertEqual(self.msg.toKVForm(), 'error:unit test\nmode:error\nns:%s\n' %message.OPENID1_NS) def test_toURLEncoded(self): - self.failUnlessEqual(self.msg.toURLEncoded(), + self.assertEqual(self.msg.toURLEncoded(), 'openid.error=unit+test&openid.mode=error&openid.ns=http%3A%2F%2Fopenid.net%2Fsignon%2F1.0') def test_toURL(self): base_url = 'http://base.url/' actual = self.msg.toURL(base_url) actual_base = actual[:len(base_url)] - self.failUnlessEqual(actual_base, base_url) - self.failUnlessEqual(actual[len(base_url)], '?') + self.assertEqual(actual_base, base_url) + self.assertEqual(actual[len(base_url)], '?') query = actual[len(base_url) + 1:] parsed = cgi.parse_qs(query) - self.failUnlessEqual(parsed, {'openid.mode':['error'], + self.assertEqual(parsed, {'openid.mode':['error'], 'openid.error':['unit test'], 'openid.ns':[message.OPENID1_NS] }) def test_isOpenID1(self): - self.failUnless(self.msg.isOpenID1()) + self.assertTrue(self.msg.isOpenID1()) class OpenID2MessageTest(unittest.TestCase): @@ -455,7 +455,7 @@ self.msg.setArg(message.BARE_NS, "xey", "value") def test_toPostArgs(self): - self.failUnlessEqual(self.msg.toPostArgs(), + self.assertEqual(self.msg.toPostArgs(), {'openid.mode':'error', 'openid.error':'unit test', 'openid.ns':message.OPENID2_NS, @@ -465,7 +465,7 @@ def test_toArgs(self): # This method can't tolerate BARE_NS. self.msg.delArg(message.BARE_NS, "xey") - self.failUnlessEqual(self.msg.toArgs(), {'mode':'error', + self.assertEqual(self.msg.toArgs(), {'mode':'error', 'error':'unit test', 'ns':message.OPENID2_NS, }) @@ -473,15 +473,15 @@ def test_toKVForm(self): # Can't tolerate BARE_NS in kvform self.msg.delArg(message.BARE_NS, "xey") - self.failUnlessEqual(self.msg.toKVForm(), + self.assertEqual(self.msg.toKVForm(), 'error:unit test\nmode:error\nns:%s\n' % (message.OPENID2_NS,)) def _test_urlencoded(self, s): expected = ('openid.error=unit+test&openid.mode=error&' 'openid.ns=%s&xey=value' % ( - urllib.quote(message.OPENID2_NS, ''),)) - self.failUnlessEqual(s, expected) + urllib.parse.quote(message.OPENID2_NS, ''),)) + self.assertEqual(s, expected) def test_toURLEncoded(self): @@ -491,49 +491,49 @@ base_url = 'http://base.url/' actual = self.msg.toURL(base_url) actual_base = actual[:len(base_url)] - self.failUnlessEqual(actual_base, base_url) - self.failUnlessEqual(actual[len(base_url)], '?') + self.assertEqual(actual_base, base_url) + self.assertEqual(actual[len(base_url)], '?') query = actual[len(base_url) + 1:] self._test_urlencoded(query) def test_getOpenID(self): - self.failUnlessEqual(self.msg.getOpenIDNamespace(), message.OPENID2_NS) + self.assertEqual(self.msg.getOpenIDNamespace(), message.OPENID2_NS) def test_getKeyOpenID(self): - self.failUnlessEqual(self.msg.getKey(message.OPENID_NS, 'mode'), + self.assertEqual(self.msg.getKey(message.OPENID_NS, 'mode'), 'openid.mode') def test_getKeyBARE(self): - self.failUnlessEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode') + self.assertEqual(self.msg.getKey(message.BARE_NS, 'mode'), 'mode') def test_getKeyNS1(self): - self.failUnlessEqual( + self.assertEqual( self.msg.getKey(message.OPENID1_NS, 'mode'), None) def test_getKeyNS2(self): - self.failUnlessEqual( + self.assertEqual( self.msg.getKey(message.OPENID2_NS, 'mode'), 'openid.mode') def test_getKeyNS3(self): - self.failUnlessEqual( + self.assertEqual( self.msg.getKey('urn:nothing-significant', 'mode'), None) def test_hasKeyOpenID(self): - self.failUnlessEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True) + self.assertEqual(self.msg.hasKey(message.OPENID_NS, 'mode'), True) def test_hasKeyBARE(self): - self.failUnlessEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False) + self.assertEqual(self.msg.hasKey(message.BARE_NS, 'mode'), False) def test_hasKeyNS1(self): - self.failUnlessEqual( + self.assertEqual( self.msg.hasKey(message.OPENID1_NS, 'mode'), False) def test_hasKeyNS2(self): - self.failUnlessEqual( + self.assertEqual( self.msg.hasKey(message.OPENID2_NS, 'mode'), True) def test_hasKeyNS3(self): - self.failUnlessEqual( + self.assertEqual( self.msg.hasKey('urn:nothing-significant', 'mode'), False) test_getArgBARE = mkGetArgTest(message.BARE_NS, 'mode') @@ -543,26 +543,26 @@ test_getArgNS3 = mkGetArgTest('urn:nothing-significant', 'mode') def test_getArgsOpenID(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID_NS), + self.assertEqual(self.msg.getArgs(message.OPENID_NS), {'mode':'error', 'error':'unit test', }) def test_getArgsBARE(self): - self.failUnlessEqual(self.msg.getArgs(message.BARE_NS), + self.assertEqual(self.msg.getArgs(message.BARE_NS), {'xey': 'value'}) def test_getArgsNS1(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID1_NS), {}) + self.assertEqual(self.msg.getArgs(message.OPENID1_NS), {}) def test_getArgsNS2(self): - self.failUnlessEqual(self.msg.getArgs(message.OPENID2_NS), + self.assertEqual(self.msg.getArgs(message.OPENID2_NS), {'mode':'error', 'error':'unit test', }) def test_getArgsNS3(self): - self.failUnlessEqual(self.msg.getArgs('urn:nothing-significant'), {}) + self.assertEqual(self.msg.getArgs('urn:nothing-significant'), {}) def _test_updateArgsNS(self, ns, before=None): if before is None: @@ -572,11 +572,11 @@ 'Magnolia Electric Co.':'Jason Molina', } - self.failUnlessEqual(self.msg.getArgs(ns), before) + self.assertEqual(self.msg.getArgs(ns), before) self.msg.updateArgs(ns, update_args) after = dict(before) after.update(update_args) - self.failUnlessEqual(self.msg.getArgs(ns), after) + self.assertEqual(self.msg.getArgs(ns), after) def test_updateArgsOpenID(self): self._test_updateArgsNS(message.OPENID_NS, @@ -599,9 +599,9 @@ def _test_setArgNS(self, ns): key = 'Camper van Beethoven' value = 'David Lowery' - self.failUnlessEqual(self.msg.getArg(ns, key), None) + self.assertEqual(self.msg.getArg(ns, key), None) self.msg.setArg(ns, key, value) - self.failUnlessEqual(self.msg.getArg(ns, key), value) + self.assertEqual(self.msg.getArg(ns, key), value) def test_setArgOpenID(self): self._test_setArgNS(message.OPENID_NS) @@ -629,7 +629,7 @@ # .fromPostArgs covers .fromPostArgs, .fromOpenIDArgs, # ._fromOpenIDArgs, and .fromOpenIDArgs (since it calls # .fromPostArgs). - self.failUnlessRaises(AssertionError, self.msg.fromPostArgs, + self.assertRaises(AssertionError, self.msg.fromPostArgs, args) def test_mysterious_missing_namespace_bug(self): @@ -651,15 +651,15 @@ } m = message.Message.fromOpenIDArgs(openid_args) - self.failUnless(('http://openid.net/extensions/sreg/1.1', 'sreg') in - list(m.namespaces.iteritems())) + self.assertTrue(('http://openid.net/extensions/sreg/1.1', 'sreg') in + list(m.namespaces.items())) missing = [] for k in openid_args['signed'].split(','): - if not ("openid."+k) in m.toPostArgs().keys(): + if not ("openid."+k) in list(m.toPostArgs().keys()): missing.append(k) self.assertEqual([], missing, missing) self.assertEqual(openid_args, m.toArgs()) - self.failUnless(m.isOpenID1()) + self.assertTrue(m.isOpenID1()) def test_112B(self): args = {'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8', @@ -680,32 +680,32 @@ m = message.Message.fromPostArgs(args) missing = [] for k in args['openid.signed'].split(','): - if not ("openid."+k) in m.toPostArgs().keys(): + if not ("openid."+k) in list(m.toPostArgs().keys()): missing.append(k) self.assertEqual([], missing, missing) self.assertEqual(args, m.toPostArgs()) - self.failUnless(m.isOpenID2()) + self.assertTrue(m.isOpenID2()) def test_implicit_sreg_ns(self): openid_args = { 'sreg.email': 'a@b.com' } m = message.Message.fromOpenIDArgs(openid_args) - self.failUnless((sreg.ns_uri, 'sreg') in - list(m.namespaces.iteritems())) + self.assertTrue((sreg.ns_uri, 'sreg') in + list(m.namespaces.items())) self.assertEqual('a@b.com', m.getArg(sreg.ns_uri, 'email')) self.assertEqual(openid_args, m.toArgs()) - self.failUnless(m.isOpenID1()) + self.assertTrue(m.isOpenID1()) def _test_delArgNS(self, ns): key = 'Camper van Beethoven' value = 'David Lowery' - self.failUnlessRaises(KeyError, self.msg.delArg, ns, key) + self.assertRaises(KeyError, self.msg.delArg, ns, key) self.msg.setArg(ns, key, value) - self.failUnlessEqual(self.msg.getArg(ns, key), value) + self.assertEqual(self.msg.getArg(ns, key), value) self.msg.delArg(ns, key) - self.failUnlessEqual(self.msg.getArg(ns, key), None) + self.assertEqual(self.msg.getArg(ns, key), None) def test_delArgOpenID(self): self._test_delArgNS(message.OPENID_NS) @@ -729,19 +729,19 @@ value_2 = 'value_2' self.msg.setArg(ns, key, value_1) - self.failUnless(self.msg.getArg(ns, key) == value_1) + self.assertTrue(self.msg.getArg(ns, key) == value_1) self.msg.setArg(ns, key, value_2) - self.failUnless(self.msg.getArg(ns, key) == value_2) + self.assertTrue(self.msg.getArg(ns, key) == value_2) def test_argList(self): - self.failUnlessRaises(TypeError, self.msg.fromPostArgs, + self.assertRaises(TypeError, self.msg.fromPostArgs, {'arg': [1, 2, 3]}) def test_isOpenID1(self): - self.failIf(self.msg.isOpenID1()) + self.assertFalse(self.msg.isOpenID1()) def test_isOpenID2(self): - self.failUnless(self.msg.isOpenID2()) + self.assertTrue(self.msg.isOpenID2()) class MessageTest(unittest.TestCase): def setUp(self): @@ -781,13 +781,13 @@ form = input_tree.getroot() # Check required form attributes - for k, v in self.required_form_attrs.iteritems(): + for k, v in self.required_form_attrs.items(): assert form.attrib[k] == v, \ "Expected '%s' for required form attribute '%s', got '%s'" % \ (v, k, form.attrib[k]) # Check extra form attributes - for k, v in form_tag_attrs.iteritems(): + for k, v in form_tag_attrs.items(): # Skip attributes that already passed the required # attribute check, since they should be ignored by the @@ -806,7 +806,7 @@ # For each post arg, make sure there is a hidden with that # value. Make sure there are no other hiddens. - for name, value in message_.toPostArgs().iteritems(): + for name, value in message_.toPostArgs().items(): for e in hiddens: if e.attrib['name'] == name: assert e.attrib['value'] == value, \ @@ -817,7 +817,7 @@ self.fail("Post arg '%s' not found in form" % (name,)) for e in hiddens: - assert e.attrib['name'] in message_.toPostArgs().keys(), \ + assert e.attrib['name'] in list(message_.toPostArgs().keys()), \ "Form element for '%s' not in " + \ "original message" % (e.attrib['name']) @@ -881,7 +881,7 @@ # Good guess! But wrong. 'http://openid.net/signon/2.0', # What? - u'http://specs%\\\r2Eopenid.net/auth/2.0', + 'http://specs%\\\r2Eopenid.net/auth/2.0', # Too much escapings! 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0', # This is a Type URI, not a openid.ns value. @@ -889,7 +889,7 @@ ] for x in invalid_things: - self.failUnlessRaises(message.InvalidOpenIDNamespace, + self.assertRaises(message.InvalidOpenIDNamespace, m.setOpenIDNamespace, x, False) @@ -902,28 +902,28 @@ for ns in v1_namespaces: m = message.Message(ns) - self.failUnless(m.isOpenID1(), "%r not recognized as OpenID 1" % + self.assertTrue(m.isOpenID1(), "%r not recognized as OpenID 1" % (ns,)) - self.failUnlessEqual(ns, m.getOpenIDNamespace()) - self.failUnless(m.namespaces.isImplicit(ns), + self.assertEqual(ns, m.getOpenIDNamespace()) + self.assertTrue(m.namespaces.isImplicit(ns), m.namespaces.getNamespaceURI(message.NULL_NAMESPACE)) def test_isOpenID2(self): ns = 'http://specs.openid.net/auth/2.0' m = message.Message(ns) - self.failUnless(m.isOpenID2()) - self.failIf(m.namespaces.isImplicit(message.NULL_NAMESPACE)) - self.failUnlessEqual(ns, m.getOpenIDNamespace()) + self.assertTrue(m.isOpenID2()) + self.assertFalse(m.namespaces.isImplicit(message.NULL_NAMESPACE)) + self.assertEqual(ns, m.getOpenIDNamespace()) def test_setOpenIDNamespace_explicit(self): m = message.Message() m.setOpenIDNamespace(message.THE_OTHER_OPENID1_NS, False) - self.failIf(m.namespaces.isImplicit(message.THE_OTHER_OPENID1_NS)) + self.assertFalse(m.namespaces.isImplicit(message.THE_OTHER_OPENID1_NS)) def test_setOpenIDNamespace_implicit(self): m = message.Message() m.setOpenIDNamespace(message.THE_OTHER_OPENID1_NS, True) - self.failUnless(m.namespaces.isImplicit(message.THE_OTHER_OPENID1_NS)) + self.assertTrue(m.namespaces.isImplicit(message.THE_OTHER_OPENID1_NS)) def test_explicitOpenID11NSSerialzation(self): @@ -931,25 +931,25 @@ m.setOpenIDNamespace(message.THE_OTHER_OPENID1_NS, implicit=False) post_args = m.toPostArgs() - self.failUnlessEqual(post_args, + self.assertEqual(post_args, {'openid.ns':message.THE_OTHER_OPENID1_NS}) def test_fromPostArRefactoringTool: Refactored ../python3/openid/test/test_htmldiscover.py RefactoringTool: Refactored ../python3/openid/test/test_fetchers.py gs_ns11(self): # An example of the stuff that some Drupal installations send us, # which includes openid.ns but is 1.1. query = { - u'openid.assoc_handle': u'', - u'openid.claimed_id': u'http://foobar.invalid/', - u'openid.identity': u'http://foobar.myopenid.com', - u'openid.mode': u'checkid_setup', - u'openid.ns': u'http://openid.net/signon/1.1', - u'openid.ns.sreg': u'http://openid.net/extensions/sreg/1.1', - u'openid.return_to': u'http://drupal.invalid/return_to', - u'openid.sreg.required': u'nickname,email', - u'openid.trust_root': u'http://drupal.invalid', + 'openid.assoc_handle': '', + 'openid.claimed_id': 'http://foobar.invalid/', + 'openid.identity': 'http://foobar.myopenid.com', + 'openid.mode': 'checkid_setup', + 'openid.ns': 'http://openid.net/signon/1.1', + 'openid.ns.sreg': 'http://openid.net/extensions/sreg/1.1', + 'openid.return_to': 'http://drupal.invalid/return_to', + 'openid.sreg.required': 'nickname,email', + 'openid.trust_root': 'http://drupal.invalid', } m = message.Message.fromPostArgs(query) - self.failUnless(m.isOpenID1()) + self.assertTrue(m.isOpenID1()) @@ -959,8 +959,8 @@ uri = 'http://example.com/foo' alias = "foo" nsm.addAlias(uri, alias) - self.failUnless(nsm.getNamespaceURI(alias) == uri) - self.failUnless(nsm.getAlias(uri) == alias) + self.assertTrue(nsm.getNamespaceURI(alias) == uri) + self.assertTrue(nsm.getAlias(uri) == alias) def test_iteration(self): nsm = message.NamespaceMap() @@ -968,30 +968,30 @@ nsm.add(uripat%0) for n in range(1,23): - self.failUnless(uripat%(n-1) in nsm) - self.failUnless(nsm.isDefined(uripat%(n-1))) + self.assertTrue(uripat%(n-1) in nsm) + self.assertTrue(nsm.isDefined(uripat%(n-1))) nsm.add(uripat%n) - for (uri, alias) in nsm.iteritems(): - self.failUnless(uri[22:]==alias[3:]) + for (uri, alias) in nsm.items(): + self.assertTrue(uri[22:]==alias[3:]) i=0 it = nsm.iterAliases() try: while True: - it.next() + next(it) i += 1 except StopIteration: - self.failUnless(i == 23) + self.assertTrue(i == 23) i=0 it = nsm.iterNamespaceURIs() try: while True: - it.next() + next(it) i += 1 except StopIteration: - self.failUnless(i == 23) + self.assertTrue(i == 23) if __name__ == '__main__': --- ../python3/openid/test/test_htmldiscover.py (original) +++ ../python3/openid/test/test_htmldiscover.py (refactored) @@ -1,5 +1,5 @@ from openid.consumer.discover import OpenIDServiceEndpoint -import datadriven +from . import datadriven class BadLinksTestCase(datadriven.DataDrivenTestCase): cases = [ @@ -15,7 +15,7 @@ def runOneTest(self): actual = OpenIDServiceEndpoint.fromHTML('http://unused.url/', self.data) expected = [] - self.failUnlessEqual(expected, actual) + self.assertEqual(expected, actual) def pyUnitTests(): return datadriven.loadTests(__name__) --- ../python3/openid/test/test_fetchers.py (original) +++ ../python3/openid/test/test_fetchers.py (refactored) @@ -1,7 +1,7 @@ import warnings import unittest import sys -import urllib2 +import urllib.request, urllib.error, urllib.parse import socket from openid import fetchers @@ -16,7 +16,7 @@ got_headers = dict(actual.headers) del got_headers['date'] del got_headers['server'] - for k, v in expected.headers.iteritems(): + for k, v in expected.headers.items(): assert got_headers[k] == v, (k, v, got_headers[k]) def test_fetcher(fetcher, exc, server): @@ RefactoringTool: Refactored ../python3/openid/test/test_extension.py -55,7 +55,7 @@ except (SystemExit, KeyboardInterrupt): pass except: - print fetcher, fetch_url + print(fetcher, fetch_url) raise else: failUnlessResponseExpected(expected, actual) @@ -68,12 +68,12 @@ result = fetcher.fetch(err_url) except (KeyboardInterrupt, SystemExit): raise - except fetchers.HTTPError, why: + except fetchers.HTTPError as why: # This is raised by the Curl fetcher for bad cases # detected by the fetchers module, but it's a subclass of # HTTPFetchingError, so we have to catch it explicitly. assert exc - except fetchers.HTTPFetchingError, why: + except fetchers.HTTPFetchingError as why: assert not exc, (fetcher, exc, server) except: assert exc @@ -89,7 +89,7 @@ ]: try: exc_fetchers.append(klass()) - except RuntimeError, why: + except RuntimeError as why: if why[0].startswith('Cannot find %s library' % (library_name,)): try: __import__(library_name) @@ -113,7 +113,7 @@ for f in non_exc_fetchers: test_fetcher(f, False, server) -from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from http.server import BaseHTTPRequestHandler, HTTPServer class FetcherTestHandler(BaseHTTPRequestHandler): cases = { @@ -227,33 +227,33 @@ def test_getDefaultNotNone(self): """Make sure that None is never returned as a default fetcher""" - self.failUnless(fetchers.getDefaultFetcher() is not None) + self.assertTrue(fetchers.getDefaultFetcher() is not None) fetchers.setDefaultFetcher(None) - self.failUnless(fetchers.getDefaultFetcher() is not None) + self.assertTrue(fetchers.getDefaultFetcher() is not None) def test_setDefault(self): """Make sure the getDefaultFetcher returns the object set for setDefaultFetcher""" sentinel = object() fetchers.setDefaultFetcher(sentinel, wrap_exceptions=False) - self.failUnless(fetchers.getDefaultFetcher() is sentinel) + self.assertTrue(fetchers.getDefaultFetcher() is sentinel) def test_callFetch(self): """Make sure that fetchers.fetch() uses the default fetcher instance that was set.""" fetchers.setDefaultFetcher(FakeFetcher()) actual = fetchers.fetch('bad://url') - self.failUnless(actual is FakeFetcher.sentinel) + self.assertTrue(actual is FakeFetcher.sentinel) def test_wrappedByDefault(self): """Make sure that the default fetcher instance wraps exceptions by default""" default_fetcher = fetchers.getDefaultFetcher() - self.failUnless(isinstance(default_fetcher, + self.assertTrue(isinstance(default_fetcher, fetchers.ExceptionWrappingFetcher), default_fetcher) - self.failUnlessRaises(fetchers.HTTPFetchingError, + self.assertRaises(fetchers.HTTPFetchingError, fetchers.fetch, 'http://invalid.janrain.com/') def test_notWrapped(self): @@ -264,7 +264,7 @@ fetcher = fetchers.Urllib2Fetcher() fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False) - self.failIf(isinstance(fetchers.getDefaultFetcher(), + self.assertFalse(isinstance(fetchers.getDefaultFetcher(), fetchers.ExceptionWrappingFetcher)) try: @@ -273,7 +273,7 @@ self.fail('Should not be wrapping exception') except: exc = sys.exc_info()[1] - self.failUnless(isinstance(exc, urllib2.URLError), exc) + self.assertTrue(isinstance(exc, urllib.error.URLError), exc) pass else: self.fail('Should have raised an exception') --- ../python3/openid/test/test_extension.py (original) +++ ../python3/openid/test/RefactoringTool: Refactored ../python3/openid/test/test_examples.py RefactoringTool: Refactored ../python3/openid/test/test_etxrd.py test_extension.py (refactored) @@ -16,11 +16,11 @@ ext = DummyExtension() ext.toMessage(oid1_msg) namespaces = oid1_msg.namespaces - self.failUnless(namespaces.isImplicit(DummyExtension.ns_uri)) - self.failUnlessEqual( + self.assertTrue(namespaces.isImplicit(DummyExtension.ns_uri)) + self.assertEqual( DummyExtension.ns_uri, namespaces.getNamespaceURI(DummyExtension.ns_alias)) - self.failUnlessEqual(DummyExtension.ns_alias, + self.assertEqual(DummyExtension.ns_alias, namespaces.getAlias(DummyExtension.ns_uri)) def test_OpenID2(self): @@ -28,9 +28,9 @@ ext = DummyExtension() ext.toMessage(oid2_msg) namespaces = oid2_msg.namespaces - self.failIf(namespaces.isImplicit(DummyExtension.ns_uri)) - self.failUnlessEqual( + self.assertFalse(namespaces.isImplicit(DummyExtension.ns_uri)) + self.assertEqual( DummyExtension.ns_uri, namespaces.getNamespaceURI(DummyExtension.ns_alias)) - self.failUnlessEqual(DummyExtension.ns_alias, + self.assertEqual(DummyExtension.ns_alias, namespaces.getAlias(DummyExtension.ns_uri)) --- ../python3/openid/test/test_examples.py (original) +++ ../python3/openid/test/test_examples.py (refactored) @@ -2,7 +2,7 @@ import socket import os.path, unittest, sys, time -from cStringIO import StringIO +from io import StringIO import twill.commands, twill.parse, twill.unit @@ -43,7 +43,7 @@ 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): + for i in range(count): d = os.path.dirname(d) return d @@ -53,7 +53,7 @@ exampleDir = os.path.join(topDir, 'examples') serverExample = os.path.join(exampleDir, 'server.py') serverModule = {} - execfile(serverExample, serverModule) + exec(compile(open(serverExample, "rb").read(), serverExample, 'exec'), serverModule) serverMain = serverModule['main'] serverMain(host, port, data_path) @@ -136,9 +136,9 @@ c.code(302) headers = c.get_browser()._browser.response().info() finalURL = headers['Location'] - self.failUnless('openid.mode=id_res' in finalURL, finalURL) - self.failUnless('openid.identity=' in finalURL, finalURL) - except twill.commands.TwillAssertionError, e: + self.assertTrue('openid.mode=id_res' in finalURL, finalURL) + self.assertTrue('openid.identity=' in finalURL, finalURL) + except twill.commands.TwillAssertionError as e: msg = '%s\nFinal page:\n%s' % ( str(e), c.get_browser().get_html()) self.fail(msg) @@ -165,8 +165,8 @@ c.code(302) headers = c.get_browser()._browser.response().info() finalURL = headers['Location'] - self.failUnless(finalURL.startswith(self.return_to)) - except twill.commands.TwillAssertionError, e: + self.assertTrue(finalURL.startswith(self.return_to)) + except twill.commands.TwillAssertionError as e: from traceback import format_exc msg = '%s\nTwill output:%s\nTwill errors:%s\nFinal page:\n%s' % ( format_exc(), --- ../python3/openid/test/test_etxrd.py (original) +++ ../python3/openid/test/test_etxrd.py (refactored) @@ -53,8 +53,8 @@ it = iter(services) for (server_url, delegate) in expectedServices: for (actual_url, actual_delegate) in it: - self.failUnlessEqual(server_url, actual_url) - self.failUnlessEqual(delegate, actual_delegate) + self.assertEqual(server_url, actual_url) + self.assertEqual(delegate, actual_delegate) break else: self.fail('Not enough services found') @@ -66,7 +66,7 @@ for (type_uri, uri) in expectedServices: foRefactoringTool: Refactored ../python3/openid/test/test_discover.py r service in it: if type_uri in service.type_uris: - self.failUnlessEqual(service.uri, uri) + self.assertEqual(service.uri, uri) break else: self.fail('Did not find %r service' % (type_uri,)) @@ -101,7 +101,7 @@ """Make sure that we get an exception when an XRDS element is not present""" self.xmldoc = file(NOXRDS_FILE).read() - self.failUnlessRaises( + self.assertRaises( etxrd.XRDSError, services.applyFilter, self.yadis_url, self.xmldoc, None) @@ -109,7 +109,7 @@ """Make sure that we get an exception when an XRDS element is not present""" self.xmldoc = '' - self.failUnlessRaises( + self.assertRaises( etxrd.XRDSError, services.applyFilter, self.yadis_url, self.xmldoc, None) @@ -117,7 +117,7 @@ """Make sure that we get an exception when there is no XRD element present.""" self.xmldoc = file(NOXRD_FILE).read() - self.failUnlessRaises( + self.assertRaises( etxrd.XRDSError, services.applyFilter, self.yadis_url, self.xmldoc, None) @@ -179,11 +179,11 @@ # somewhere in the resolution chain. def _getCanonicalID(self, iname, xrds, expectedID): - if isinstance(expectedID, (str, unicode, type(None))): + if isinstance(expectedID, (str, type(None))): cid = etxrd.getCanonicalID(iname, xrds) - self.failUnlessEqual(cid, expectedID and xri.XRI(expectedID)) + self.assertEqual(cid, expectedID and xri.XRI(expectedID)) elif issubclass(expectedID, etxrd.XRDSError): - self.failUnlessRaises(expectedID, etxrd.getCanonicalID, + self.assertRaises(expectedID, etxrd.getCanonicalID, iname, xrds) else: self.fail("Don't know how to test for expected value %r" --- ../python3/openid/test/test_discover.py (original) +++ ../python3/openid/test/test_discover.py (refactored) @@ -1,6 +1,6 @@ import sys import unittest -import datadriven +from . import datadriven import os.path from openid import fetchers from openid.fetchers import HTTPResponse @@ -8,7 +8,7 @@ from openid.consumer import discover from openid.yadis import xrires from openid.yadis.xri import XRI -from urlparse import urlsplit +from urllib.parse import urlsplit from openid import message ### Tests for conditions that trigger DiscoveryFailure @@ -50,8 +50,8 @@ expected_status = self.responses[-1].status try: discover.discover(self.url) - except DiscoveryFailure, why: - self.failUnlessEqual(why.http_response.status, expected_status) + except DiscoveryFailure as why: + self.assertEqual(why.http_response.status, expected_status) else: self.fail('Did not raise DiscoveryFailure') @@ -112,9 +112,9 @@ exc = sys.exc_info()[1] if exc is None: # str exception - self.failUnless(self.exc is sys.exc_info()[0]) + self.assertTrue(self.exc is sys.exc_info()[0]) else: - self.failUnless(self.exc is exc, exc) + self.assertTrue(self.exc is exc, exc) else: self.fail('Expected %r', self.exc) @@ -128,7 +128,7 @@ try: discover.discover('users.stompy.janrain.com:8000/x') - except DiscoveryFailure, why: + except DiscoveryFailure as why: self.fail('failed to parse url with port correctly') except RuntimeError: pass #expected @@ -178,25 +178,25 @@ used_yadis=False, display_identifier=None ): - self.failUnlessEqual(server_url, s.server_url) + self.assertEqual(server_url, s.server_url) if types == ['2.0 OP']: - self.failIf(claimed_id) - self.failIf(local_id) - self.failIf(s.claimed_id) - self.failIf(s.local_id) - self.failIf(s.getLocalID()) - self.failIf(s.compatibilityMode()) - self.failUnless(s.isOPIdentifier()) - self.failUnlessEqual(s.preferredNamespace(), + self.assertFalse(claimed_id) + self.assertFalse(local_id) + self.assertFalse(s.claimed_id) + self.assertFalse(s.local_id) + self.assertFalse(s.getLocalID()) + self.assertFalse(s.compatibilityMode()) + self.assertTrue(s.isOPIdentifier()) + self.assertEqual(s.preferredNamespace(), discover.OPENID_2_0_MESSAGE_NS) else: - self.failUnlessEqual(claimed_id, s.claimed_id) - self.failUnlessEqual(local_id, s.getLocalID()) + self.assertEqual(claimed_id, s.claimed_id) + self.assertEqual(local_id, s.getLocalID()) if used_yadis: - self.failUnless(s.used_yadis, "Expected to use Yadis") + self.assertTrue(s.used_yadis, "Expected to use Yadis") else: - self.failIf(s.used_yadis, + self.assertFalse(s.used_yadis, "Expected to use old-style discovery") openid_types = { @@ -207,16 +207,16 @@ } type_uris = [openid_types[t] for t in types] - self.failUnlessEqual(type_uris, s.type_uris) - self.failUnlessEqual(canonical_id, s.canonicalID) + self.assertEqual(type_uris, s.type_uris) + self.assertEqual(canonical_id, s.canonicalID) if s.canonicalID: - self.failUnless(s.getDisplayIdentifier() != claimed_id) - self.failUnless(s.getDisplayIdentifier() is not None) - self.failUnlessEqual(display_identifier, s.getDisplayIdentifier()) - self.failUnlessEqual(s.claimed_id, s.canonicalID) - - self.failUnlessEqual(s.display_identifier or s.claimed_id, s.getDisplayIdentifier()) + self.assertTrue(s.getDisplayIdentifier() != claimed_id) + self.assertTrue(s.getDisplayIdentifier() is not None) + self.assertEqual(display_identifier, s.getDisplayIdentifier()) + self.assertEqual(s.claimed_id, s.canonicalID) + + self.assertEqual(s.display_identifier or s.claimed_id, s.getDisplayIdentifier()) def setUp(self): self.documents = self.documents.copy() @@ -240,12 +240,12 @@ self.documents[self.id_url] = (content_type, data) id_url, services = discover.discover(self.id_url) - self.failUnlessEqual(expected_services, len(services)) - self.failUnlessEqual(expected_id, id_url) + self.assertEqual(expected_services, len(services)) + self.assertEqual(expected_id, id_url) return services def test_404(self): - self.failUnlessRaises(DiscoveryFailure, + self.assertRaises(DiscoveryFailure, discover.discover, self.id_url + '/404') def test_noOpenID(self): @@ -296,8 +296,8 @@ expected_id = self.id_url self.id_url = self.id_url + '#fragment' id_url, services = discover.discover(self.id_url) - self.failUnlessEqual(expected_services, len(services)) - self.failUnlessEqual(expected_id, id_url) + self.assertEqual(expected_services, len(services)) + self.assertEqual(expected_id, id_url) self._checkService( services[0], @@ -451,7 +451,7 @@ ) def test_yadis2BadLocalID(self): - self.failUnlessRaises(DiscoveryFailure, self._discover, + self.assertRaises(DiscoveryFailure, self._discover, content_type='application/xrds+xml', data=readDataFile('yadis_2_bad_local_id.xml'), expected_services=1, @@ -475,7 +475,7 @@ ) def test_yadis1And2BadLocalID(self): - self.failUnlessRaises(DiscoveryFailure, self._discover, + self.assertRaises(DiscoveryFailure, self._discover, content_type='application/xrds+xml', data=readDataFile('openid_1_and_2_xrds_bad_delegate.xml'), expected_services=1, @@ -576,7 +576,7 @@ def test_xriNoCanonicalID(self): user_xri, services = discover.discoverXRI('=smoker*bad') - self.failIf(services) + self.assertFalse(services) def test_useCanonicalID(self): """When there is no delegate, the CanonicalID should be used with XRI. @@ -584,7 +584,7 @@ endpoint = discover.OpenIDServiceEndpoint() endpoint.claimed_id = XRI("=!1000") endpoint.canonicalID = XRI("=!1000") - self.failUnlessEqual(endpoint.getLocalID(), XRI("=!1000")) + self.assertEqual(endpoint.getLocalID(), XRI("=!1000")) class TestXRIDiscoveryIDP(BaseTestDiscovery): @@ -595,8 +595,8 @@ def test_xri(self): user_xri, services = discover.discoverXRI('=smoker') - self.failUnless(services, "Expected services, got zero") - self.failUnlessEqual(services[0].server_url, + self.assertTrue(services, "Expected services, got zero") + self.assertEqual(services[0].server_url, "http://www.livejournal.com/openid/server.bml") @@ -611,7 +611,7 @@ endpoint = discover.OpenIDServiceEndpoint() endpoint.type_uris = self.type_uris actual_ns = endpoint.preferredNamespace() - self.failUnlessEqual(actual_ns, self.expected_ns) + self.assertEqual(actual_ns, self.expected_ns) cases = [ (message.OPENID1_NS, []), @@ -631,34 +631,34 @@ self.endpoint = discover.OpenIDServiceEndpoint() def test_none(self): - self.failIf(self.endpoint.isOPIdentifier()) + self.assertFalse(self.endpoint.isOPIdentifier()) def test_openid1_0(self): self.endpoint.type_uris = [discover.OPENID_1_0_TYPE] - self.failIf(self.endpoint.isOPIdentifier()) + self.assertFalse(self.endpoint.isOPIdentifier()) def test_openid1_1(self): self.endpoint.type_uris = [discover.OPENID_1_1_TYPE] - self.failIf(self.endpoint.isOPIdentifier()) + self.assertFalse(self.endpoint.isOPIdentifier()) def test_openid2(self): self.endpoint.type_uris = [discover.OPENID_2_0_TYPE] - self.failIf(self.endpoint.isOPIdentifier()) + self.assertFalse(self.endpoint.isOPIdentifier()) def test_openid2OP(self): self.endpoint.type_uris = [discover.OPENID_IDP_2_0_TYPE] - self.failUnless(self.endpoint.isOPIdentifier()) + self.assertTrue(self.endpoint.isOPIdentifier()) def test_multipleMissing(self): self.endpoint.type_uris = [discover.OPENID_2_0_TYPE, discover.OPENID_1_0_TYPE] - self.failIf(self.endpoint.isOPIdentifier()) + self.assertFalse(self.endpoint.isOPIdentifier()) def test_multiplePresent(self): self.endpoint.type_uris = [discover.OPENID_2_0_TYPE, discover.OPENID_1_0_TYPE, discover.OPENID_IDP_2_0_TYPE] - self.failUnless(self.endpoint.isOPIdentifier()) + self.assertTrue(self.endpoint.isOPIdentifier()) class TestFromOPEndpointURL(unittest.TestCase): def setUp(self): @@ -667,20 +667,20 @@ self.op_endpoint_url) def test_isOPEndpoint(self): - self.failUnless(self.endpoint.isOPIdentifier()) + self.assertTrue(self.endpoint.isOPIdentifier()) def test_noIdentifiers(self): - self.failUnlessEqual(self.endpoint.getLocalID(), None) - self.failUnlessEqual(self.endpoint.claimed_id, None) + self.assertEqual(self.endpoint.getLocalID(), None) + self.assertEqual(self.endpoint.claimed_id, None) def test_compatibility(self): - self.failIf(self.endpoint.compatibilityMode()) + self.assertFalse(self.endpoint.compatibilityMode()) def test_canonicalID(self): - self.failUnlessEqual(self.endpoint.canonicalID, None) + self.assertEqual(self.endpoint.canonicalID, None) RefactoringTool: Refactored ../python3/openid/test/test_consumer.py def test_serverURL(self): - self.failUnlessEqual(self.endpoint.server_url, self.op_endpoint_url) + self.assertEqual(self.endpoint.server_url, self.op_endpoint_url) class TestDiscoverFunction(unittest.TestCase): def setUp(self): @@ -701,16 +701,16 @@ return 'URI' def test_uri(self): - self.failUnlessEqual('URI', discover.discover('http://woo!')) + self.assertEqual('URI', discover.discover('http://woo!')) def test_uriForBogus(self): - self.failUnlessEqual('URI', discover.discover('not a URL or XRI')) + self.assertEqual('URI', discover.discover('not a URL or XRI')) def test_xri(self): - self.failUnlessEqual('XRI', discover.discover('xri://=something')) + self.assertEqual('XRI', discover.discover('xri://=something')) def test_xriChar(self): - self.failUnlessEqual('XRI', discover.discover('=something')) + self.assertEqual('XRI', discover.discover('=something')) class TestEndpointSupportsType(unittest.TestCase): def setUp(self): @@ -725,10 +725,10 @@ discover.OPENID_IDP_2_0_TYPE, ]: if t in types: - self.failUnless(self.endpoint.supportsType(t), + self.assertTrue(self.endpoint.supportsType(t), "Must support %r" % (t,)) else: - self.failIf(self.endpoint.supportsType(t), + self.assertFalse(self.endpoint.supportsType(t), "Shouldn't support %r" % (t,)) def test_supportsNothing(self): @@ -771,7 +771,7 @@ def test_strip_fragment(self): endpoint = discover.OpenIDServiceEndpoint() endpoint.claimed_id = 'http://recycled.invalid/#123' - self.failUnlessEqual('http://recycled.invalid/', endpoint.getDisplayIdentifier()) + self.assertEqual('http://recycled.invalid/', endpoint.getDisplayIdentifier()) def pyUnitTests(): --- ../python3/openid/test/test_consumer.py (original) +++ ../python3/openid/test/test_consumer.py (refactored) @@ -1,4 +1,4 @@ -import urlparse +import urllib.parse import cgi import time import warnings @@ -26,7 +26,7 @@ from openid import fetchers from openid.store import memstore -from support import CatchLogs +from .support import CatchLogs assocs = [ ('another 20-byte key.', 'Snarky'), @@ -36,13 +36,13 @@ def mkSuccess(endpoint, q): """Convenience function to create a SuccessResponse with the given arguments, all signed.""" - signed_list = ['openid.' + k for k in q.keys()] + signed_list = ['openid.' + k for k in list(q.keys())] return SuccessResponse(endpoint, Message.fromOpenIDArgs(q), signed_list) def parseQuery(qs): q = {} for (k, v) in cgi.parse_qsl(qs): - assert not q.has_key(k) + assert k not in q q[k] = v return q @@ -91,7 +91,8 @@ class TestFetcher(object): - def __init__(self, user_url, user_page, (assoc_secret, assoc_handle)): + def __init__(self, user_url, user_page, xxx_todo_changeme): + (assoc_secret, assoc_handle) = xxx_todo_changeme self.get_responses = {user_url:self.response(user_url, 200, user_page)} self.assoc_secret = assoc_secret self.assoc_handle = assoc_handle @@ -158,7 +159,7 @@ redirect_url = request.redirectURL(trust_root, return_to, immediate) - parsed = urlparse.urlparse(redirect_url) + parsed = urllib.parse.urlparse(redirect_url) qs = parsed[4] q = parseQuery(qs) new_return_to = q['openid.return_to'] @@ -173,7 +174,7 @@ assert new_return_to.startswith(return_to) assert redirect_url.startswith(server_url) - parsed = urlparse.urlparse(new_return_to) + parsed = urllib.parse.urlparse(new_return_to) query = parseQuery(parsed[4]) query.update({ 'openid.mode':'id_res', @@ -257,10 +258,10 @@ def test_construct(self): oidc = GenericConsumer(self.store_sentinel) - self.failUnless(oidc.store is self.store_sentinel) + self.assertTrue(oidc.store is self.store_sentinel) def test_nostore(self): - self.failUnlessRaises(TypeError, GenericConsumer) + self.assertRaises(TypeError, GenericConsumer) class TestIdRes(unittest.TestCase, CatchLogs): @@ -319,7 +320,7 @@ def test_signFailsWithBadSig(self): self.message.setArg(OPENID_NS, 'sig', 'BAD SIGNATURE') - self.failUnlessRaises( + self.assertRaises( ProtocolError, self.consumer._idResCheckSignature, self.message, self.endpoint.server_url) @@ -337,7 +338,7 @@ # assoc_handle missing assoc, consumer._checkAuth returns goodthings self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle") self.consumer._checkAuth = lambda unused1, unused2: False - self.failUnlessRaises( + self.assertRaises( ProtocolError, self.consumer._idResCheckSignature, self.message, self.endpoint.server_url) @@ -356,7 +357,7 @@ self.message.setArg(OPENID_NS, "assoc_handle", "dumbHandle") self.consumer._checkAuth = lambda unused1, unused2: False self.consumer.store = None - self.failUnlessRaises( + self.assertRaises( ProtocolError, self.consumer._idResCheckSignature, self.message, self.endpoint.server_url) @@ -370,8 +371,8 @@ query = {'openid.mode': ['cancel']} try: r = Message.fromPostArgs(query) - except TypeError, err: - self.failUnless(str(err).find('values') != -1, err) + except TypeError as err: + self.assertTrue(str(err).find('values') != -1, err) else: self.fail("expected TypeError, got this instead: %s" % (r,)) @@ -386,27 +387,27 @@ setup_url_sentinel = object() def raiseSetupNeeded(msg): - self.failUnless(msg is message) + self.assertTrue(msg is message) raise SetupNeededError(setup_url_sentinel) self.consumer._checkSetupNeeded = raiseSetupNeeded response = self.consumer.complete(message, None, None) - self.failUnlessEqual(SETUP_NEEDED, response.status) - self.failUnless(setup_url_sentinel is response.setup_url) + self.assertEqual(SETUP_NEEDED, response.status) + self.assertTrue(setup_url_sentinel is response.setup_url) def test_cancel(self): message = Message.fromPostArgs({'openid.mode': 'cancel'}) self.disableReturnToChecking() r = self.consumer.complete(message, self.endpoint) - self.failUnlessEqual(r.status, CANCEL) - self.failUnless(r.identity_url == self.endpoint.claimed_id) + self.assertEqual(r.status, CANCEL) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) def test_cancel_with_return_to(self): message = Message.fromPostArgs({'openid.mode': 'cancel'}) r = self.consumer.complete(message, self.endpoint, self.return_to) - self.failUnlessEqual(r.status, CANCEL) - self.failUnless(r.identity_url == self.endpoint.claimed_id) + self.assertEqual(r.status, CANCEL) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) def test_error(self): msg = 'an error message' @@ -415,9 +416,9 @@ }) self.disableReturnToChecking() r = self.consumer.complete(message, self.endpoint) - self.failUnlessEqual(r.status, FAILURE) - self.failUnless(r.identity_url == self.endpoint.claimed_id) - self.failUnlessEqual(r.message, msg) + self.assertEqual(r.status, FAILURE) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) + self.assertEqual(r.message, msg) def test_errorWithNoOptionalKeys(self): msg = 'an error message' @@ -428,11 +429,11 @@ }) self.disableReturnToChecking() r = self.consumer.complete(message, self.endpoint) - self.failUnlessEqual(r.status, FAILURE) - self.failUnless(r.identity_url == self.endpoint.claimed_id) - self.failUnless(r.contact == contact) - self.failUnless(r.reference is None) - self.failUnlessEqual(r.message, msg) + self.assertEqual(r.status, FAILURE) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) + self.assertTrue(r.contact == contact) + self.assertTrue(r.reference is None) + self.assertEqual(r.message, msg) def test_errorWithOptionalKeys(self): msg = 'an error message' @@ -443,24 +444,24 @@ 'openid.contact': contact, 'openid.ns': OPENID2_NS, }) r = self.consumer.complete(message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) - self.failUnless(r.identity_url == self.endpoint.claimed_id) - self.failUnless(r.contact == contact) - self.failUnless(r.reference == reference) - self.failUnlessEqual(r.message, msg) + self.assertEqual(r.status, FAILURE) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) + self.assertTrue(r.contact == contact) + self.assertTrue(r.reference == reference) + self.assertEqual(r.message, msg) def test_noMode(self): message = Message.fromPostArgs({}) r = self.consumer.complete(message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) - self.failUnless(r.identity_url == self.endpoint.claimed_id) + self.assertEqual(r.status, FAILURE) + self.assertTrue(r.identity_url == self.endpoint.claimed_id) def test_idResMissingField(self): # XXX - this test is passing, but not necessarily by what it # is supposed to test for. status in FAILURE, but it's because # *check_auth* failed, not because it's missing an arg, exactly. message = Message.fromPostArgs({'openid.mode': 'id_res'}) - self.failUnlessRaises(ProtocolError, self.consumer._doIdRes, + self.assertRaises(ProtocolError, self.consumer._doIdRes, message, self.endpoint, None) def test_idResURLMismatch(self): @@ -482,7 +483,7 @@ }) self.consumer.store = GoodAssocStore() - self.failUnlessRaises(VerifiedError, + self.assertRaises(VerifiedError, self.consumer.complete, message, self.endpoint) @@ -542,25 +543,25 @@ def test_idResMissingIdentitySig(self): self.message.setArg(OPENID_NS, 'signed', 'return_to,response_nonce,assoc_handle,claimed_id') r = self.consumer.complete(self.message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) + self.assertEqual(r.status, FAILURE) def test_idResMissingReturnToSig(self): self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,assoc_handle,claimed_id') r = self.consumer.complete(self.message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) + self.assertEqual(r.status, FAILURE) def test_idResMissingAssocHandleSig(self): self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,return_to,claimed_id') r = self.consumer.complete(self.message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) + self.assertEqual(r.status, FAILURE) def test_idResMissingClaimedIDSig(self): self.message.setArg(OPENID_NS, 'signed', 'identity,response_nonce,return_to,assoc_handle') r = self.consumer.complete(self.message, self.endpoint, None) - self.failUnlessEqual(r.status, FAILURE) + self.assertEqual(r.status, FAILURE) def failUnlessSuccess(self, response): @@ -585,25 +586,25 @@ store = self.consumer.store store.storeAssociation(self.server_url, assoc) assoc2 = store.getAssociation(self.server_url) - self.failUnlessEqual(assoc, assoc2) + self.assertEqual(assoc, assoc2) def test_goodResponse(self): """successful response to check_authentication""" response = Message.fromOpenIDArgs({'is_valid':'true',}) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failUnless(r) + self.assertTrue(r) def test_missingAnswer(self): """check_authentication returns false when the server sends no answer""" response = Message.fromOpenIDArgs({}) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failIf(r) + self.assertFalse(r) def test_badResponse(self): """check_authentication returns false when is_valid is false""" response = Message.fromOpenIDArgs({'is_valid':'false',}) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failIf(r) + self.assertFalse(r) def test_badResponseInvalidate(self): """Make sure that the handle is invalidated when is_valid is false @@ -620,8 +621,8 @@ 'invalidate_handle':'handle', }) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failIf(r) - self.failUnless( + self.assertFalse(r) + self.assertTrue( self.consumer.store.getAssociation(self.server_url) is None) def test_invalidateMissing(self): @@ -631,7 +632,7 @@ 'invalidate_handle':'missing', }) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failUnless(r) + self.assertTrue(r) self.failUnlessLogMatches( 'Received "invalidate_handle"' ) @@ -644,7 +645,7 @@ }) self.consumer.store = None r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failUnless(r) + self.assertTrue(r) self.failUnlessLogMatches( 'Received "invalidate_handle"', 'Unexpectedly got invalidate_handle without a store') @@ -664,16 +665,16 @@ 'invalidate_handle':'handle', }) r = self.consumer._processCheckAuthResponse(response, self.server_url) - self.failUnless(r) - self.failUnless( + self.assertTrue(r) + self.assertTrue( self.consumer.store.getAssociation(self.server_url) is None) class TestSetupNeeded(TestIdRes): def failUnlessSetupNeeded(self, expected_setup_url, message): try: self.consumer._checkSetupNeeded(message) - except SetupNeededError, why: - self.failUnlessEqual(expected_setup_url, why.user_setup_url) + except SetupNeededError as why: + self.assertEqual(expected_setup_url, why.user_setup_url) else: self.fail("Expected to find an immediate-mode response") @@ -684,7 +685,7 @@ 'openid.mode': 'id_res', 'openid.user_setup_url': setup_url, }) - self.failUnless(message.isOpenID1()) + self.assertTrue(message.isOpenID1()) self.failUnlessSetupNeeded(setup_url, message) def test_setupNeededOpenID1_extra(self): @@ -695,14 +696,14 @@ 'openid.user_setup_url': setup_url, 'openid.identity': 'bogus', }) - self.failUnless(message.isOpenID1()) + self.assertTrue(message.isOpenID1()) self.failUnlessSetupNeeded(setup_url, message) def test_noSetupNeededOpenID1(self): """When the user_setup_url is missing on an OpenID 1 message, we assume that it's not a cancel response to checkid_immediate""" message = Message.fromOpenIDArgs({'mode': 'id_res'}) - self.failUnless(message.isOpenID1()) + self.assertTrue(message.isOpenID1()) # No SetupNeededError raised self.consumer._checkSetupNeeded(message) @@ -712,10 +713,10 @@ 'mode':'setup_needed', 'ns':OPENID2_NS, }) - self.failUnless(message.isOpenID2()) + self.assertTrue(message.isOpenID2()) response = self.consumer.complete(message, None, None) - self.failUnlessEqual('setup_needed', response.status) - self.failUnlessEqual(None, response.setup_url) + self.assertEqual('setup_needed', response.status) + self.assertEqual(None, response.setup_url) def test_setupNeededDoesntWorkForOpenID1(self): message = Message.fromOpenIDArgs({ @@ -726,8 +727,8 @@ self.consumer._checkSetupNeeded(message) response = self.consumer.complete(message, None, None) - self.failUnlessEqual('failure', response.status) - self.failUnless(response.message.startswith('Invalid openid.mode')) + self.assertEqual('failure', response.status) + self.assertTrue(response.message.startswith('Invalid openid.mode')) def test_noSetupNeededOpenID2(self): message = Message.fromOpenIDArgs({ @@ -735,7 +736,7 @@ 'game':'puerto_rico', 'ns':OPENID2_NS, }) - self.failUnless(message.isOpenID2()) + self.assertTrue(message.isOpenID2()) # No SetupNeededError raised self.consumer._checkSetupNeeded(message) @@ -787,8 +788,8 @@ message = Message.fromOpenIDArgs(openid_args) try: self.consumer._idResCheckForFields(message) - except ProtocolError, why: - self.failUnless(why[0].startswith('Missing required')) + except ProtocolError as why: + self.assertTrue(why[0].startswith('Missing required')) else: self.fail('Expected an error, but none occurred') return test @@ -798,8 +799,8 @@ message = Message.fromOpenIDArgs(openid_args) try: self.consumer._idResCheckForFields(message) - except ProtocolError, why: - self.failUnless(why[0].endswith('not signed')) + except ProtocolError as why: + self.assertTrue(why[0].endswith('not signed')) else: self.fail('Expected an error, but none occurred') return test @@ -868,7 +869,7 @@ """use consumer-generated nonce""" self.response = Message.fromOpenIDArgs({}) n = self.consumer._idResGetNonceOpenID1(self.response, self.endpoint) - self.failUnless(n is None, n) + self.assertTrue(n is None, n) self.failUnlessLogEmpty() def test_consumerNonceOpenID2(self): @@ -876,7 +877,7 @@ self.return_to = 'http://rt.unittest/?nonce=%s' % (mkNonce(),) self.response = Message.fromOpenIDArgs( {'return_to': self.return_to, 'ns':OPENID2_NS}) - self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce, + self.assertRaises(ProtocolError, self.consumer._idResCheckNonce, self.response, self.endpoint) self.failUnlessLogEmpty() @@ -893,7 +894,7 @@ {'ns':OPENID1_NS, 'return_to': 'http://return.to/', 'response_nonce': mkNonce(),}) - self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce, + self.assertRaises(ProtocolError, self.consumer._idResCheckNonce, self.response, self.endpoint) self.failUnlessLogEmpty() @@ -915,7 +916,7 @@ {'response_nonce': nonce, 'ns':OPENID2_NS, }) - self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce, + self.assertRaises(ProtocolError, self.consumer._idResCheckNonce, self.response, self.endpoint) def test_successWithNoStore(self): @@ -933,14 +934,14 @@ self.response = Message.fromOpenIDArgs( {'ns':OPENID2_NS, 'response_nonce':'malformed'}) - self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce, + self.assertRaises(ProtocolError, self.consumer._idResCheckNonce, self.response, self.endpoint) def test_missingNonce(self): """no nonce parameter on the return_to""" self.response = Message.fromOpenIDArgs( {'return_to': self.return_to}) - self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce, + self.assertRaises(ProtocolError, self.consumer._idResCheckNonce, self.response, self.endpoint) class CheckAuthDetectingConsumer(GenericConsumer): @@ -1008,7 +1009,7 @@ handle = 'handle' assoc = association.Association( handle, 'secret', issued, lifetime, 'HMAC-SHA1') - self.failUnless(assoc.expiresIn <= 0) + self.assertTrue(assoc.expiresIn <= 0) self.store.storeAssociation(self.server_url, assoc) message = Message.fromPostArgs({ @@ -1019,7 +1020,7 @@ 'openid.signed': 'identity,return_to', }) self.disableReturnToChecking() - self.failUnlessRaises(ProtocolError, self.consumer._doIdRes, + self.assertRaises(ProtocolError, self.consumer._doIdRes, message, self.endpoint, None) def test_newerAssoc(self): @@ -1047,8 +1048,8 @@ message = good_assoc.signMessage(message) self.disableReturnToChecking() info = self.consumer._doIdRes(message, self.endpoint, None) - self.failUnlessEqual(info.status, SUCCESS, info.message) - self.failUnlessEqual(self.consumer_id, info.identity_url) + self.assertEqual(info.status, SUCCESS, info.message) + self.assertEqual(self.consumer_id, info.identity_url) @@ -1090,7 +1091,7 @@ 'foo': 'bar', } # no return value, success is assumed if there are no exceptions. - self.failUnlessRaises(ProtocolError, + self.assertRaises(ProtocolError, self.consumer._verifyReturnToArgs, query) def test_returnToMismatch(self): @@ -1099,18 +1100,18 @@ 'openid.return_to': 'http://example.com/?foo=bar', } # fail, query has no key 'foo'. - self.failUnlessRaises(ValueError, + self.assertRaises(ValueError, self.consumer._verifyReturnToArgs, query) query['foo'] = 'baz' # fail, values for 'foo' do not match. - self.failUnlessRaises(ValueError, + self.assertRaises(ValueError, self.consumer._verifyReturnToArgs, query) def test_noReturnTo(self): query = {'openid.mode': 'id_res'} - self.failUnlessRaises(ValueError, + self.assertRaises(ValueError, self.consumer._verifyReturnToArgs, query) def test_completeBadReturnTo(self): @@ -1141,7 +1142,7 @@ for bad in bad_return_tos: m.setArg(OPENID_NS, 'return_to', bad) - self.failIf(self.consumer._checkReturnTo(m, return_to)) + self.assertFalse(self.consumer._checkReturnTo(m, return_to)) def test_completeGoodReturnTo(self): """Test GenericConsumer.complete()'s handling of good @@ -1171,7 +1172,7 @@ m.setArg(OPENID_NS, 'return_to', good) result = self.consumer.complete(m, endpoint, return_to) - self.failUnless(isinstance(result, CancelResponse), \ + self.assertTrue(isinstance(result, CancelResponse), \ "Expected CancelResponse, got %r for %s" % (result, good,)) class MockFetcher(object): @@ -1223,8 +1224,8 @@ 'openid.stuff':'a value'} r = self.consumer._checkAuth(Message.fromPostArgs(query), http_server_url) - self.failIf(r) - self.failUnless(self.messages) + self.assertFalse(r) + self.assertTrue(self.messages) def test_bad_args(self): query = { @@ -1247,9 +1248,9 @@ 'foo': 'bar', }) args = self.consumer._createCheckAuthRequest(query) - self.failUnless(args.isOpenID1()) + self.assertTrue(args.isOpenID1()) for signed_arg in query.getArg(OPENID_NS, 'signed').split(','): - self.failUnless(args.getAliasedArg(signed_arg), signed_arg) + self.assertTrue(args.getAliasedArg(signed_arg), signed_arg) def test_112(self): args = {'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8', @@ -1267,16 +1268,16 @@ 'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=', 'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,ns.pape,pape.nist_auth_level,pape.auth_policies' } - self.failUnlessEqual(OPENID2_NS, args['openid.ns']) + self.assertEqual(OPENID2_NS, args['openid.ns']) incoming = Message.fromPostArgs(args) - self.failUnless(incoming.isOpenID2()) + self.assertTrue(incoming.isOpenID2()) car = self.consumer._createCheckAuthRequest(incoming) expected_args = args.copy() expected_args['openid.mode'] = 'check_authentication' expected =Message.fromPostArgs(expected_args) - self.failUnless(expected.isOpenID2()) - self.failUnlessEqual(expected, car) - self.failUnlessEqual(expected_args, car.toPostArgs()) + self.assertTrue(expected.isOpenID2()) + self.assertEqual(expected, car) + self.assertEqual(expected_args, car.toPostArgs()) @@ -1294,7 +1295,7 @@ """404 from a kv post raises HTTPFetchingError""" self.fetcher.response = HTTPResponse( "http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n') - self.failUnlessRaises( + self.assertRaises( fetchers.HTTPFetchingError, self.consumer._makeKVPost, Message.fromPostArgs({'mode':'associate'}), @@ -1306,7 +1307,7 @@ """ self.fetcher = ExceptionRaisingMockFetcher() fetchers.setDefaultFetcher(self.fetcher, wrap_exceptions=False) - self.failUnlessRaises(self.fetcher.MyException, + self.assertRaises(self.fetcher.MyException, self.consumer._makeKVPost, Message.fromPostArgs({'mode':'associate'}), "http://server_url") @@ -1314,10 +1315,10 @@ # exception fetching returns no association e = OpenIDServiceEndpoint() e.server_url = 'some://url' - self.failUnlessRaises(self.fetcher.MyException, + self.assertRaises(self.fetcher.MyException, self.consumer._getAssociation, e) - self.failUnlessRaises(self.fetcher.MyException, + self.assertRaises(self.fetcher.MyException, self.consumer._checkAuth, Message.fromPostArgs({'openid.signed':''}), 'some://url') @@ -1329,7 +1330,7 @@ self.fetcher = ExceptionRaisingMockFetcher() # This will wrap exceptions! fetchers.setDefaultFetcher(self.fetcher) - self.failUnlessRaises(fetchers.HTTPFetchingError, + self.assertRaises(fetchers.HTTPFetchingError, self.consumer._makeKVPost, Message.fromOpenIDArgs({'mode':'associate'}), "http://server_url") @@ -1337,10 +1338,10 @@ # exception fetching returns no association e = OpenIDServiceEndpoint() e.server_url = 'some://url' - self.failUnless(self.consumer._getAssociation(e) is None) + self.assertTrue(self.consumer._getAssociation(e) is None) msg = Message.fromPostArgs({'openid.signed':''}) - self.failIf(self.consumer._checkAuth(msg, 'some://url')) + self.assertFalse(self.consumer._checkAuth(msg, 'some://url')) class TestSuccessResponse(unittest.TestCase): @@ -1358,9 +1359,9 @@ 'return_to':'return_to', }) utargs = resp.extensionResponse('urn:unittest', False) - self.failUnlessEqual(utargs, {'one':'1', 'two':'2'}) + self.assertEqual(utargs, {'one':'1', 'two':'2'}) sregargs = resp.extensionResponse('urn:sreg', False) - self.failUnlessEqual(sregargs, {'nickname':'j3h'}) + self.assertEqual(sregargs, {'nickname':'j3h'}) def test_extensionResponseSigned(self): args = { @@ -1385,30 +1386,30 @@ # All args in this NS are signed, so expect all. sregargs = resp.extensionResponse('urn:sreg', True) - self.failUnlessEqual(sregargs, {'nickname':'j3h', 'dob': 'yesterday'}) + self.assertEqual(sregargs, {'nickname':'j3h', 'dob': 'yesterday'}) # Not all args in this NS are signed, so expect None when # asking for them. utargs = resp.extensionResponse('urn:unittest', True) - self.failUnlessEqual(utargs, None) + self.assertEqual(utargs, None) def test_noReturnTo(self): resp = mkSuccess(self.endpoint, {}) - self.failUnless(resp.getReturnTo() is None) + self.assertTrue(resp.getReturnTo() is None) def test_returnTo(self): resp = mkSuccess(self.endpoint, {'return_to':'return_to'}) - self.failUnlessEqual(resp.getReturnTo(), 'return_to') + self.assertEqual(resp.getReturnTo(), 'return_to') def test_displayIdentifierClaimedId(self): resp = mkSuccess(self.endpoint, {}) - self.failUnlessEqual(resp.getDisplayIdentifier(), + self.assertEqual(resp.getDisplayIdentifier(), resp.endpoint.claimed_id) def test_displayIdentifierOverride(self): self.endpoint.display_identifier = "http://input.url/" resp = mkSuccess(self.endpoint, {}) - self.failUnlessEqual(resp.getDisplayIdentifier(), + self.assertEqual(resp.getDisplayIdentifier(), "http://input.url/") class StubConsumer(object): @@ -1444,12 +1445,12 @@ def test_setAssociationPreference(self): self.consumer.setAssociationPreference([]) - self.failUnless(isinstance(self.consumer.consumer.negotiator, + self.assertTrue(isinstance(self.consumer.consumer.negotiator, association.SessionNegotiator)) - self.failUnlessEqual([], + self.assertEqual([], self.consumer.consumer.negotiator.allowed_types) self.consumer.setAssociationPreference([('HMAC-SHA1', 'DH-SHA1')]) - self.failUnlessEqual([('HMAC-SHA1', 'DH-SHA1')], + self.assertEqual([('HMAC-SHA1', 'DH-SHA1')], self.consumer.consumer.negotiator.allowed_types) def withDummyDiscovery(self, callable, dummy_getNextService): @@ -1476,9 +1477,9 @@ def test(): try: self.consumer.begin('unused in this test') - except DiscoveryFailure, why: - self.failUnless(why[0].startswith('Error fetching')) - self.failIf(why[0].find('Unit test') == -1) + except DiscoveryFailure as why: + self.assertTrue(why[0].startswith('Error fetching')) + self.assertFalse(why[0].find('Unit test') == -1) else: self.fail('Expected DiscoveryFailure') @@ -1492,9 +1493,9 @@ def test(): try: self.consumer.begin(url) - except DiscoveryFailure, why: - self.failUnless(why[0].startswith('No usable OpenID')) - self.failIf(why[0].find(url) == -1) + except DiscoveryFailure as why: + self.assertTrue(why[0].startswith('No usable OpenID')) + self.assertFalse(why[0].find(url) == -1) else: self.fail('Expected DiscoveryFailure') @@ -1506,28 +1507,28 @@ result = self.consumer.beginWithoutDiscovery(self.endpoint) # The result is an auth request - self.failUnless(isinstance(result, AuthRequest)) + self.assertTrue(isinstance(result, AuthRequest)) # Side-effect of calling beginWithoutDiscovery is setting the # session value to the endpoint attribute of the result - self.failUnless(self.session[self.consumer._token_key] is result.endpoint) + self.assertTrue(self.session[self.consumer._token_key] is result.endpoint) # The endpoint that we passed in is the endpoint on the auth_request - self.failUnless(result.endpoint is self.endpoint) + self.assertTrue(result.endpoint is self.endpoint) def test_completeEmptySession(self): text = "failed complete" def checkEndpoint(message, endpoint, return_to): - self.failUnless(endpoint is None) + self.assertTrue(endpoint is None) return FailureResponse(endpoint, text) self.consumer.consumer.complete = checkEndpoint response = self.consumer.complete({}, None) - self.failUnlessEqual(response.status, FAILURE) - self.failUnlessEqual(response.message, text) - self.failUnless(response.identity_url is None) + self.assertEqual(response.status, FAILURE) + self.assertEqual(response.message, text) + self.assertTrue(response.identity_url is None) def _doResp(self, auth_req, exp_resp): """complete a transaction, using the expected response from @@ -1537,18 +1538,18 @@ self.consumer.consumer.response = exp_resp # endpoint is stored in the session - self.failUnless(self.session) + self.assertTrue(self.session) resp = self.consumer.complete({}, None) # All responses should have the same identity URL, and the # session should be cleaned out if self.endpoint.claimed_id != IDENTIFIER_SELECT: - self.failUnless(resp.identity_url is self.identity_url) - - self.failIf(self.consumer._token_key in self.session) + self.assertTrue(resp.identity_url is self.identity_url) + + self.assertFalse(self.consumer._token_key in self.session) # Expected status response - self.failUnlessEqual(resp.status, exp_resp.status) + self.assertEqual(resp.status, exp_resp.status) return resp @@ -1557,7 +1558,7 @@ auth_req = self.consumer.beginWithoutDiscovery(self.endpoint) resp = self._doResp(auth_req, exp_resp) # There should be nothing left in the session once we have completed. - self.failIf(self.session) + self.assertFalse(self.session) return resp def test_noDiscoCompleteSuccessWithToken(self): @@ -1569,13 +1570,13 @@ def test_noDiscoCompleteFailure(self): msg = 'failed!' resp = self._doRespNoDisco(FailureResponse(self.endpoint, msg)) - self.failUnless(resp.message is msg) + self.assertTrue(resp.message is msg) def test_noDiscoCompleteSetupNeeded(self): setup_url = 'http://setup.url/' resp = self._doRespNoDisco( SetupNeededResponse(self.endpoint, setup_url)) - self.failUnless(resp.setup_url is setup_url) + self.assertTrue(resp.setup_url is setup_url) # To test that discovery is cleaned up, we need to initialize a # Yadis manager, and have it put its values in the session. @@ -1587,9 +1588,9 @@ manager = self.discovery.getManager() if is_clean: - self.failUnless(self.discovery.getManager() is None, manager) + self.assertTrue(self.discovery.getManager() is None, manager) else: - self.failIf(self.discovery.getManager() is None, manager) + self.assertFalse(self.discovery.getManager() is None, manager) return resp @@ -1604,14 +1605,14 @@ def test_completeFailure(self): msg = 'failed!' resp = self._doRespDisco(False, FailureResponse(self.endpoint, msg)) - self.failUnless(resp.message is msg) + self.assertTrue(resp.message is msg) def test_completeSetupNeeded(self): setup_url = 'http://setup.url/' resp = self._doRespDisco( False, SetupNeededResponse(self.endpoint, setup_url)) - self.failUnless(resp.setup_url is setup_url) + self.assertTrue(resp.setup_url is setup_url) def test_successDifferentURL(self): """ @@ -1631,16 +1632,16 @@ resp = self._doRespDisco( True, mkSuccess(resp_endpoint, {})) - self.failUnless(self.discovery.getManager(force=True) is None) + self.assertTrue(self.discovery.getManager(force=True) is None) def test_begin(self): self.discovery.createManager([self.endpoint], self.identity_url) # Should not raise an exception auth_req = self.consumer.begin(self.identity_url) - self.failUnless(isinstance(auth_req, AuthRequest)) - self.failUnless(auth_req.endpoint is self.endpoint) - self.failUnless(auth_req.endpoint is self.consumer.consumer.endpoint) - self.failUnless(auth_req.assoc is self.consumer.consumer.assoc) + self.assertTrue(isinstance(auth_req, AuthRequest)) + self.assertTrue(auth_req.endpoint is self.endpoint) + self.assertTrue(auth_req.endpoint is self.consumer.consumer.endpoint) + self.assertTrue(auth_req.assoc is self.consumer.consumer.assoc) @@ -1674,7 +1675,7 @@ discovered_endpoint.local_id = identifier iverified = [] def verifyDiscoveryResults(identifier, endpoint): - self.failUnless(endpoint is self.endpoint) + self.assertTrue(endpoint is self.endpoint) iverified.append(discovered_endpoint) return discovered_endpoint self.consumer._verifyDiscoveryResults = verifyDiscoveryResults @@ -1683,10 +1684,10 @@ response = self.consumer._doIdRes(message, self.endpoint, None) self.failUnlessSuccess(response) - self.failUnlessEqual(response.identity_url, "=directed_identifier") + self.assertEqual(response.identity_url, "=directed_identifier") # assert that discovery attempt happens and returns good - self.failUnlessEqual(iverified, [discovered_endpoint]) + self.assertEqual(iverified, [discovered_endpoint]) def test_idpDrivenCompleteFraud(self): @@ -1702,7 +1703,7 @@ raise DiscoveryFailure("PHREAK!", None) self.consumer._verifyDiscoveryResults = verifyDiscoveryResults self.consumer._checkReturnTo = lambda unused1, unused2 : True - self.failUnlessRaises(DiscoveryFailure, self.consumer._doIdRes, + self.assertRaises(DiscoveryFailure, self.consumer._doIdRes, message, self.endpoint, None) @@ -1743,16 +1744,16 @@ self.services = [endpoint] r = self.consumer._verifyDiscoveryResults(self.message, endpoint) - self.failUnlessEqual(r, endpoint) + self.assertEqual(r, endpoint) def test_otherServer(self): text = "verify failed" def discoverAndVerify(claimed_id, to_match_endpoints): - self.failUnlessEqual(claimed_id, self.identifier) + self.assertEqual(claimed_id, self.identifier) for to_match in to_match_endpoints: - self.failUnlessEqual(claimed_id, to_match.claimed_id) + self.assertEqual(claimed_id, to_match.claimed_id) raise ProtocolError(text) self.consumer._discoverAndVerify = discoverAndVerify @@ -1766,9 +1767,9 @@ self.services = [endpoint] try: r = self.consumer._verifyDiscoveryResults(self.message, endpoint) - except ProtocolError, e: + except ProtocolError as e: # Should we make more ProtocolError subclasses? - self.failUnless(str(e), text) + self.assertTrue(str(e), text) else: self.fail("expected ProtocolError, %r returned." % (r,)) @@ -1777,9 +1778,9 @@ text = "verify failed" def discoverAndVerify(claimed_id, to_match_endpoints): - self.failUnlessEqual(claimed_id, self.identifier) + self.assertEqual(claimed_id, self.identifier) for to_match in to_match_endpoints: - self.failUnlessEqual(claimed_id, to_match.claimed_id) + self.assertEqual(claimed_id, to_match.claimed_id) raise ProtocolError(text) self.consumer._discoverAndVerify = discoverAndVerify @@ -1793,15 +1794,15 @@ try: r = self.consumer._verifyDiscoveryResults(self.message, endpoint) - except ProtocolError, e: - self.failUnlessEqual(str(e), text) + except ProtocolError as e: + self.assertEqual(str(e), text) else: self.fail("Exepected ProtocolError, %r returned" % (r,)) def test_nothingDiscovered(self): # a set of no things. self.services = [] - self.failUnlessRaises(DiscoveryFailure, + self.assertRaises(DiscoveryFailure, self.consumer._verifyDiscoveryResults, self.message, self.endpoint) @@ -1827,7 +1828,7 @@ session, args = self.consumer._createAssociateRequest( self.endpoint, self.assoc_type, session_type) - self.failUnless(isinstance(session, PlainTextConsumerSession)) + self.assertTrue(isinstance(session, PlainTextConsumerSession)) expected = Message.fromOpenIDArgs( {'ns':OPENID2_NS, 'session_type':session_type, @@ -1835,7 +1836,7 @@ 'assoc_type':self.assoc_type, }) - self.failUnlessEqual(expected, args) + self.assertEqual(expected, args) def test_noEncryptionCompatibility(self): self.endpoint.use_compatibility = True @@ -1843,8 +1844,8 @@ session, args = self.consumer._createAssociateRequest( self.endpoint, self.assoc_type, session_type) - self.failUnless(isinstance(session, PlainTextConsumerSession)) - self.failUnlessEqual(Message.fromOpenIDArgs({'mode':'associate', + self.assertTrue(isinstance(session, PlainTextConsumerSession)) + self.assertEqual(Message.fromOpenIDArgs({'mode':'associate', 'assoc_type':self.assoc_type, }), args) @@ -1858,11 +1859,11 @@ session, args = self.consumer._createAssociateRequest( self.endpoint, self.assoc_type, session_type) - self.failUnless(isinstance(session, DiffieHellmanSHA1ConsumerSession)) + self.assertTrue(isinstance(session, DiffieHellmanSHA1ConsumerSession)) # This is a random base-64 value, so just check that it's # present. - self.failUnless(args.getArg(OPENID1_NS, 'dh_consumer_public')) + self.assertTrue(args.getArg(OPENID1_NS, 'dh_consumer_public')) args.delArg(OPENID1_NS, 'dh_consumer_public') # OK, session_type is set here and not for no-encryption @@ -1874,7 +1875,7 @@ 'dh_gen': 'Ag==', }) - self.failUnlessEqual(expected, args) + self.assertEqual(expected, args) # XXX: test the other types @@ -1906,29 +1907,29 @@ self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key) extracted = self.consumer_session.extractSecret(self.msg) - self.failUnlessEqual(extracted, self.secret) + self.assertEqual(extracted, self.secret) def testAbsentServerPublic(self): self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key) - self.failUnlessRaises(KeyError, self.consumer_session.extractSecret, self.msg) + self.assertRaises(KeyError, self.consumer_session.extractSecret, self.msg) def testAbsentMacKey(self): self.msg.setArg(OPENID_NS, 'dh_server_public', self.dh_server_public) - self.failUnlessRaises(KeyError, self.consumer_session.extractSecret, self.msg) + self.assertRaises(KeyError, self.consumer_session.extractSecret, self.msg) def testInvalidBase64Public(self): self.msg.setArg(OPENID_NS, 'dh_server_public', 'n o t b a s e 6 4.') self.msg.setArg(OPENID_NS, 'enc_mac_key', self.enc_mac_key) - self.failUnlessRaises(ValueError, self.consumer_RefactoringTool: Refactored ../python3/openid/test/test_ax.py session.extractSecret, self.msg) + self.assertRaises(ValueError, self.consumer_session.extractSecret, self.msg) def testInvalidBase64MacKey(self): self.msg.setArg(OPENID_NS, 'dh_server_public', self.dh_server_public) self.msg.setArg(OPENID_NS, 'enc_mac_key', 'n o t base 64') - self.failUnlessRaises(ValueError, self.consumer_session.extractSecret, self.msg) + self.assertRaises(ValueError, self.consumer_session.extractSecret, self.msg) class TestOpenID1SHA1(TestDiffieHellmanResponseParameters, unittest.TestCase): session_cls = DiffieHellmanSHA1ConsumerSession @@ -1980,7 +1981,7 @@ def bogusBegin(unused): return NonAnonymousAuthRequest() consumer.consumer.begin = bogusBegin - self.failUnlessRaises( + self.assertRaises( ProtocolError, consumer.beginWithoutDiscovery, None) @@ -1995,7 +1996,7 @@ self.to_match = OpenIDServiceEndpoint() def failUnlessDiscoveryFailure(self): - self.failUnlessRaises( + self.assertRaises( DiscoveryFailure, self.consumer._discoverAndVerify, 'http://claimed-id.com/', @@ -2033,7 +2034,7 @@ # first endpoint that we passed in as a result. result = self.consumer._discoverAndVerify( 'http://claimed.id/', [self.to_match]) - self.failUnlessEqual(matching_endpoint, result) + self.assertEqual(matching_endpoint, result) from openid.extension import Extension class SillyExtension(Extension): @@ -2050,7 +2051,7 @@ ar = AuthRequest(OpenIDServiceEndpoint(), None) ar.addExtension(ext) ext_args = ar.message.getArgs(ext.ns_uri) - self.failUnlessEqual(ext.getExtensionArgs(), ext_args) + self.assertEqual(ext.getExtensionArgs(), ext_args) @@ -2065,7 +2066,7 @@ response.body = "foo:bar\nbaz:quux\n" r = _httpResponseToMessage(response, self.server_url) expected_msg = Message.fromOpenIDArgs({'foo':'bar','baz':'quux'}) - self.failUnlessEqual(expected_msg, r) + self.assertEqual(expected_msg, r) def test_400(self): @@ -2074,9 +2075,9 @@ response.body = "error:bonk\nerror_code:7\n" try: r = _httpResponseToMessage(response, self.server_url) - except ServerError, e: - self.failUnlessEqual(e.error_text, 'bonk') - self.failUnlessEqual(e.error_code, '7') + except ServerError as e: + self.assertEqual(e.error_text, 'bonk') + self.assertEqual(e.error_code, '7') else: self.fail("Expected ServerError, got return %r" % (r,)) @@ -2086,7 +2087,7 @@ response = HTTPResponse() response.status = 500 response.body = "foo:bar\nbaz:quux\n" - self.failUnlessRaises(fetchers.HTTPFetchingError, + self.assertRaises(fetchers.HTTPFetchingError, _httpResponseToMessage, response, self.server_url) --- ../python3/openid/test/test_ax.py (original) +++ ../python3/openid/test/test_ax.py (refactored) @@ -21,8 +21,8 @@ def test_checkMode(self): check = self.bax._checkMode - self.failUnlessRaises(ax.NotAXMessage, check, {}) - self.failUnlessRaises(ax.AXError, check, {'mode':'fetch_request'}) + self.assertRaises(ax.NotAXMessage, check, {}) + self.assertRaises(ax.AXError, check, {'mode':'fetch_request'}) # does not raise an exception when the mode is right check({'mode':self.bax.mode}) @@ -35,14 +35,14 @@ class AttrInfoTest(unittest.TestCase): def test_construct(self): - self.failUnlessRaises(TypeError, ax.AttrInfo) + self.assertRaises(TypeError, ax.AttrInfo) type_uri = 'a uri' ainfo = ax.AttrInfo(type_uri) - self.failUnlessEqual(type_uri, ainfo.type_uri) - self.failUnlessEqual(1, ainfo.count) - self.failIf(ainfo.required) - self.failUnless(ainfo.alias is None) + self.assertEqual(type_uri, ainfo.type_uri) + self.assertEqual(1, ainfo.count) + self.assertFalse(ainfo.required) + self.assertTrue(ainfo.alias is None) class ToTypeURIsTest(unittest.TestCase): @@ -52,10 +52,10 @@ def test_empty(self): for empty in [None, '']: uris = ax.toTypeURIs(self.aliases, empty) - self.failUnlessEqual([], uris) + self.assertEqual([], uris) def test_undefined(self): - self.failUnlessRaises( + self.assertRaises( KeyError, ax.toTypeURIs, self.aliases, 'http://janrain.com/') @@ -64,7 +64,7 @@ alias = 'openid_hackers' self.aliases.addAlias(uri, alias) uris = ax.toTypeURIs(self.aliases, alias) - self.failUnlessEqual([uri], uris) + self.assertEqual([uri], uris) def test_two(self): uri1 = 'http://janrain.com/' @@ -76,20 +76,20 @@ self.aliases.addAlias(uri2, alias2) uris = ax.toTypeURIs(self.aliases, ','.join([alias1, alias2])) - self.failUnlessEqual([uri1, uri2], uris) + self.assertEqual([uri1, uri2], uris) class ParseAXValuesTest(unittest.TestCase): """Testing AXKeyValueMessage.parseExtensionArgs.""" def failUnlessAXKeyError(self, ax_args): msg = ax.AXKeyValueMessage() - self.failUnlessRaises(KeyError, msg.parseExtensionArgs, ax_args) + self.assertRaises(KeyError, msg.parseExtensionArgs, ax_args) def failUnlessAXValues(self, ax_args, expected_args): """Fail unless parseExtensionArgs(ax_args) == expected_args.""" msg = ax.AXKeyValueMessage() msg.parseExtensionArgs(ax_args) - self.failUnlessEqual(expected_args, msg.data) + self.assertEqual(expected_args, msg.data) def test_emptyIsValid(self): self.failUnlessAXValues({}, {}) @@ -103,7 +103,7 @@ def test_invalidCountValue(self): msg = ax.FetchRequest() - self.failUnlessRaises(ax.AXError, + self.assertRaises(ax.AXError, msg.parseExtensionArgs, {'type.foo':'urn:foo', 'count.foo':'bogus'}) @@ -120,8 +120,8 @@ attrs = list(msg.iterAttrs()) foo = attrs[0] - self.failUnless(foo.count == ax.UNLIMITED_VALUES) - self.failUnless(foo.wantsUnlimitedValues()) + self.assertTrue(foo.count == ax.UNLIMITED_VALUES) + self.assertTrue(foo.wantsUnlimitedValues()) def test_longAlias(self): # Spec minimum length is 32 characters. This is a silly test @@ -151,7 +151,7 @@ for typ in types: for input in inputs: msg = typ() - self.failUnlessRaises(ax.AXError, msg.parseExtensionArgs, + self.assertRaises(ax.AXError, msg.parseExtensionArgs, input) def test_countPresentAndIsZero(self): @@ -197,40 +197,40 @@ def test_mode(self): - self.failUnlessEqual(self.msg.mode, 'fetch_request') + self.assertEqual(self.msg.mode, 'fetch_request') def test_construct(self): - self.failUnlessEqual({}, self.msg.requested_attributes) - self.failUnlessEqual(None, self.msg.update_url) + self.assertEqual({}, self.msg.requested_attributes) + self.assertEqual(None, self.msg.update_url) msg = ax.FetchRequest('hailstorm') - self.failUnlessEqual({}, msg.requested_attributes) - self.failUnlessEqual('hailstorm', msg.update_url) + self.assertEqual({}, msg.requested_attributes) + self.assertEqual('hailstorm', msg.update_url) def test_add(self): uri = 'mud://puddle' # Not yet added: - self.failIf(uri in self.msg) + self.assertFalse(uri in self.msg) attr = ax.AttrInfo(uri) self.msg.add(attr) # Present after adding - self.failUnless(uri in self.msg) + self.assertTrue(uri in self.msg) def test_addTwice(self): uri = 'lightning://storm' attr = ax.AttrInfo(uri) self.msg.add(attr) - self.failUnlessRaises(KeyError, self.msg.add, attr) + self.assertRaises(KeyError, self.msg.add, attr) def test_getExtensionArgs_empty(self): expected_args = { 'mode':'fetch_request', } - self.failUnlessEqual(expected_args, self.msg.getExtensionArgs()) + self.assertEqual(expected_args, self.msg.getExtensionArgs()) def test_getExtensionArgs_noAlias(self): attr = ax.AttrInfo( @@ -238,7 +238,7 @@ ) self.msg.add(attr) ax_args = self.msg.getExtensionArgs() - for k, v in ax_args.iteritems(): + for k, v in ax_args.items(): if v == attr.type_uri and k.startswith('type.'): alias = k[5:] break @@ -280,21 +280,21 @@ """ expected_args = dict(expected_args) expected_args['mode'] = self.msg.mode - self.failUnlessEqual(expected_args, self.msg.getExtensionArgs()) + self.assertEqual(expected_args, self.msg.getExtensionArgs()) def test_isIterable(self): - self.failUnlessEqual([], list(self.msg)) - self.failUnlessEqual([], list(self.msg.iterAttrs())) + self.assertEqual([], list(self.msg)) + self.assertEqual([], list(self.msg.iterAttrs())) def test_getRequiredAttrs_empty(self): - self.failUnlessEqual([], self.msg.getRequiredAttrs()) + self.assertEqual([], self.msg.getRequiredAttrs()) def test_parseExtensionArgs_extraType(self): extension_args = { 'mode':'fetch_request', 'type.' + self.alias_a:self.type_a, } - self.failUnlessRaises(ValueError, + self.assertRaises(ValueError, self.msg.parseExtensionArgs, extension_args) def test_parseExtensionArgs(self): @@ -304,14 +304,14 @@ 'if_available':self.alias_a } self.msg.parseExtensionArgs(extension_args) - self.failUnless(self.type_a in self.msg) - self.failUnlessEqual([self.type_a], list(self.msg)) + self.assertTrue(self.type_a in self.msg) + self.assertEqual([self.type_a], list(self.msg)) attr_info = self.msg.requested_attributes.get(self.type_a) - self.failUnless(attr_info) - self.failIf(attr_info.required) - self.failUnlessEqual(self.type_a, attr_info.type_uri) - self.failUnlessEqual(self.alias_a, attr_info.alias) - self.failUnlessEqual([attr_info], list(self.msg.iterAttrs())) + self.assertTrue(attr_info) + self.assertFalse(attr_info.required) + self.assertEqual(self.type_a, attr_info.type_uri) + self.assertEqual(self.alias_a, attr_info.alias) + self.assertEqual([attr_info], list(self.msg.iterAttrs())) def test_extensionArgs_idempotent(self): extension_args = { @@ -320,8 +320,8 @@ 'if_available':self.alias_a } self.msg.parseExtensionArgs(extension_args) - self.failUnlessEqual(extension_args, self.msg.getExtensionArgs()) - self.failIf(self.msg.requested_attributes[self.type_a].required) + self.assertEqual(extension_args, self.msg.getExtensionArgs()) + self.assertFalse(self.msg.requested_attributes[self.type_a].required) def test_extensionArgs_idempotent_count_required(self): extension_args = { @@ -331,8 +331,8 @@ 'required':self.alias_a } self.msg.parseExtensionArgs(extension_args) - self.failUnlessEqual(extension_args, self.msg.getExtensionArgs()) - self.failUnless(self.msg.requested_attributes[self.type_a].required) + self.assertEqual(extension_args, self.msg.getExtensionArgs()) + self.assertTrue(self.msg.requested_attributes[self.type_a].required) def test_extensionArgs_count1(self): extension_args = { @@ -347,7 +347,7 @@ 'if_available':self.alias_a, } self.msg.parseExtensionArgs(extension_args) - self.failUnlessEqual(extension_args_norm, self.msg.getExtensionArgs()) + self.assertEqual(extension_args_norm, self.msg.getExtensionArgs()) def test_openidNoRealm(self): openid_req_msg = Message.fromOpenIDArgs({ @@ -357,7 +357,7 @@ 'ax.update_url': 'http://different.site/path', 'ax.mode': 'fetch_request', }) - self.failUnlessRaises(ax.AXError, + self.assertRaises(ax.AXError, ax.FetchRequest.fromOpenIDRequest, DummyRequest(openid_req_msg)) @@ -371,7 +371,7 @@ 'ax.mode': 'fetch_request', }) - self.failUnlessRaises(ax.AXError, + self.assertRaises(ax.AXError, ax.FetchRequest.fromOpenIDRequest, DummyRequest(openid_req_msg)) @@ -407,7 +407,7 @@ }) oreq = DummyRequest(openid_req_msg) r = ax.FetchRequest.fromOpenIDRequest(oreq) - self.failUnless(r is None, "%s is not None" % (r,)) + self.assertTrue(r is None, "%s is not None" % (r,)) def test_fromOpenIDRequestWithoutData(self): """return something for SuccessResponse with AX paramaters, @@ -421,7 +421,7 @@ }) oreq = DummyRequest(openid_req_msg) r = ax.FetchRequest.fromOpenIDRequest(oreq) - self.failUnless(r is not None) + self.assertTrue(r is not None) class FetchResponseTest(unittest.TestCase): @@ -433,14 +433,14 @@ self.request_update_url = 'http://update.bogus/' def test_construct(self): - self.failUnless(self.msg.update_url is None) - self.failUnlessEqual({}, self.msg.data) + self.assertTrue(self.msg.update_url is None) + self.assertEqual({}, self.msg.data) def test_getExtensionArgs_empty(self): expected_args = { 'mode':'fetch_response', } - self.failUnlessEqual(expected_args, self.msg.getExtensionArgs()) + self.assertEqual(expected_args, self.msg.getExtensionArgs()) def test_getExtensionArgs_empty_request(self): expected_args = { @@ -448,7 +448,7 @@ } req = ax.FetchRequest() msg = ax.FetchResponse(request=req) - self.failUnlessEqual(expected_args, msg.getExtensionArgs()) + self.assertEqual(expected_args, msg.getExtensionArgs()) def test_getExtensionArgs_empty_request_some(self): uri = 'http://not.found/' @@ -462,7 +462,7 @@ req = ax.FetchRequest() req.add(ax.AttrInfo(uri)) msg = ax.FetchResponse(request=req) - self.failUnlessEqual(expected_args, msg.getExtensionArgs()) + self.assertEqual(expected_args, msg.getExtensionArgs()) def test_updateUrlInResponse(self): uri = 'http://not.found/' @@ -477,7 +477,7 @@ req = ax.FetchRequest(update_url=self.request_update_url) req.add(ax.AttrInfo(uri)) msg = ax.FetchResponse(request=req) - self.failUnlessEqual(expected_args, msg.getExtensionArgs()) + self.assertEqual(expected_args, msg.getExtensionArgs()) def test_getExtensionArgs_some_request(self): expected_args = { @@ -490,28 +490,28 @@ req.add(ax.AttrInfo(self.type_a, alias=self.alias_a)) msg = ax.FetchResponse(request=req) msg.addValue(self.type_a, self.value_a) - self.failUnlessEqual(expected_args, msg.getExtensionArgs()) + self.assertEqual(expected_args, msg.getExtensionArgs()) def test_getExtensionArgs_some_not_request(self): req = ax.FetchRequest() msg = ax.FetchResponse(request=req) msg.addValue(self.type_a, self.value_a) - self.failUnlessRaises(KeyError, msg.getExtensionArgs) + self.assertRaises(KeyError, msg.getExtensionArgs) def test_getSingle_success(self): req = ax.FetchRequest() self.msg.addValue(self.type_a, self.value_a) - self.failUnlessEqual(self.value_a, self.msg.getSingle(self.type_a)) + self.assertEqual(self.value_a, self.msg.getSingle(self.type_a)) def test_getSingle_none(self): - self.failUnlessEqual(None, self.msg.getSingle(self.type_a)) + self.assertEqual(None, self.msg.getSingle(self.type_a)) def test_getSingle_extra(self): self.msg.setValues(self.type_a, ['x', 'y']) - self.failUnlessRaises(ax.AXError, self.msg.getSingle, self.type_a) + self.assertRaises(ax.AXError, self.msg.getSingle, self.type_a) def test_get(self): - self.failUnlessRaises(KeyError, self.msg.get, self.type_a) + self.assertRaises(KeyError, self.msg.get, self.type_a) def test_fromSuccessResponseWithoutExtension(self): """return None for SuccessResponse with no AX paramaters.""" @@ -519,14 +519,14 @@ 'mode': 'id_res', 'ns': OPENID2_NS, } - sf = ['openid.' + i for i in args.keys()] + sf = ['openid.' + i for i in list(args.keys())] msg = Message.fromOpenIDArgs(args) class Endpoint: claimed_id = 'http://invalid.' oreq = SuccessResponse(Endpoint(), msg, signed_fields=sf) r = ax.FetchResponse.fromSuccessResponse(oreq) - self.failUnless(r is None, "%s is not None" % (r,)) + self.assertTrue(r is None, "%s is not None" % (r,)) def test_fromSuccessResponseWithoutData(self): """return something for SuccessResponse with AX paramaters, @@ -537,14 +537,14 @@ 'ns.ax': ax.AXMessage.ns_uri, 'ax.mode': 'fetch_response', } - sf = ['openid.' + i for i in args.keys()] + sf = ['openid.' + i for i in list(args.keys())] msg = Message.fromOpenIDArgs(args) class Endpoint: claimed_id = 'http://invalid.' oreq = SuccessResponse(Endpoint(), msg, signed_fields=sf) r = ax.FetchResponse.fromSuccessResponse(oreq) - self.failUnless(r is not None) + self.assertTrue(r is not None) def test_fromSuccessResponseWithData(self): name = 'ext0' @@ -560,7 +560,7 @@ 'ax.count.'+name: '1', 'ax.value.%s.1'%name: value, } - sf = ['openid.' + i for i in args.keys()] + sf = ['openid.' + i for i in list(args.keys())] msg = Message.fromOpenIDArgs(args) class Endpoint: claimed_id = 'http://invalid.' @@ -568,7 +568,7 @@ resp = SuccessResponse(Endpoint(), msg, signed_fields=sf) ax_resp = ax.FetchResponse.fromSuccessResponse(resp) values = ax_resp.get(uri) - self.failUnlessEqual([value], values) + self.assertEqual([value], values) class StoreRequestTest(unittest.TestCase): @@ -578,14 +578,14 @@ self.alias_a = 'juggling' def test_construct(self): - self.failUnlessEqual({}, self.msg.data) + self.assertEqual({}, self.msg.data) def test_getExtensionArgs_empty(self): args = self.msg.getExtensionArgs() expected_args = { 'mode':'store_request', } - self.failUnlessEqual(expected_args, args) + self.assertEqual(expected_args, args) def test_getExtensionArgs_nonempty(self): aliases = NamespaceMap() @@ -600,27 +600,27 @@ 'value.%s.1' % (self.alias_a,):'foo', 'value.%s.2' % (self.alias_a,):'bar', } - self.failUnlessEqual(expected_args, args) + self.assertEqual(expected_args, args) class StoreResponseTest(unittest.TestCase): def test_success(self): msg = ax.StoreResponse() - self.failUnless(msg.succeeded()) - self.failIf(msg.error_message) - self.failUnlessEqual({'mode':'store_response_success'}, + self.assertTrue(msg.succeeded()) + self.assertFalse(msg.error_message) + self.assertEqual({'mode':'store_response_success'}, msg.getExtensionArgs()) def test_fail_nomsg(self): msg = ax.StoreResponse(False) - self.failIf(msg.succeeded()) - self.failIf(msg.error_message) - RefactoringTool: Refactored ../python3/openid/test/test_auth_request.py self.failUnlessEqual({'mode':'store_response_failure'}, + self.assertFalse(msg.succeeded()) + self.assertFalse(msg.error_message) + self.assertEqual({'mode':'store_response_failure'}, msg.getExtensionArgs()) def test_fail_msg(self): reason = 'no reason, really' msg = ax.StoreResponse(False, reason) - self.failIf(msg.succeeded()) - self.failUnlessEqual(reason, msg.error_message) - self.failUnlessEqual({'mode':'store_response_failure', + self.assertFalse(msg.succeeded()) + self.assertEqual(reason, msg.error_message) + self.assertEqual({'mode':'store_response_failure', 'error':reason}, msg.getExtensionArgs()) --- ../python3/openid/test/test_auth_request.py (original) +++ ../python3/openid/test/test_auth_request.py (refactored) @@ -47,10 +47,10 @@ self.failIfOpenIDKeyExists(msg, key) def failUnlessHasRequiredFields(self, msg): - self.failUnlessEqual(self.preferred_namespace, + self.assertEqual(self.preferred_namespace, self.authreq.message.getOpenIDNamespace()) - self.failUnlessEqual(self.preferred_namespace, + self.assertEqual(self.preferred_namespace, msg.getOpenIDNamespace()) self.failUnlessOpenIDValueEquals(msg, 'mode', @@ -80,8 +80,8 @@ def test_addExtensionArg(self): self.authreq.addExtensionArg('bag:', 'color', 'brown') self.authreq.addExtensionArg('bag:', 'material', 'paper') - self.failUnless('bag:' in self.authreq.message.namespaces) - self.failUnlessEqual(self.authreq.message.getArgs('bag:'), + self.assertTrue('bag:' in self.authreq.message.namespaces) + self.assertEqual(self.authreq.message.getArgs('bag:'), {'color': 'brown', 'material': 'paper'}) msg = self.authreq.getMessage(self.realm, self.return_to, @@ -91,8 +91,8 @@ # namespaces. Really it doesn't care that it has alias "0", # but that is tested anyway post_args = msg.toPostArgs() - self.failUnlessEqual('brown', post_args['openid.ext0.color']) - self.failUnlessEqual('paper', post_args['openid.ext0.material']) + self.assertEqual('brown', post_args['openid.ext0.color']) + self.assertEqual('paper', post_args['openid.ext0.material']) def test_standard(self): msg = self.authreq.getMessage(self.realm, self.return_to, @@ -114,7 +114,7 @@ identity_present = msg.hasKey(message.OPENID_NS, 'identity') claimed_present = msg.hasKey(message.OPENID_NS, 'claimed_id') - self.failUnlessEqual(claimed_present, identity_present) + self.assertEqual(claimed_present, identity_present) def failUnlessHasIdentifiers(self, msg, op_specific_id, claimed_id): self.failUnlessOpenIDValueEquals(msg, 'identity', op_specific_id) @@ -124,7 +124,7 @@ def test_setAnonymousWorksForOpenID2(self): """OpenID AuthRequests should be able to set 'anonymous' to true.""" - self.failUnless(self.authreq.message.isOpenID2()) + self.assertTrue(self.authreq.message.isOpenID2()) self.authreq.setAnonymous(True) self.authreq.setAnonymous(False) @@ -165,7 +165,7 @@ def failUnlessIdentifiersPresent(self, msg): self.failIfOpenIDKeyExists(msg, 'claimed_id') - self.failUnless(msg.hasKey(message.OPENID_NS, 'identity')) + self.assertTrue(msg.hasKey(message.OPENID_NS, 'identity')) def failUnlessHasRealm(self, msg): # check presence of proper realm key and absence of the wrong @@ -177,8 +177,8 @@ def test_setAnonymousFailsForOpenID1(self): """OpenID 1 requests MUST NOT be able to set anonymous to True""" - self.failUnless(self.authreq.message.isOpenID1()) - self.failUnlessRaises(ValueError, self.authreq.setAnonymous, True) + self.assertTrue(self.authreq.message.isOpenID1()) + RefactoringTool: Refactored ../python3/openid/test/test_association_response.py self.assertRaises(ValueError, self.authreq.setAnonymous, True) self.authreq.setAnonymous(False) def test_identifierSelect(self): @@ -191,7 +191,7 @@ msg = self.authreq.getMessage(self.realm, self.return_to, self.immediate) self.failUnlessHasRequiredFields(msg) - self.failUnlessEqual(message.IDENTIFIER_SELECT, + self.assertEqual(message.IDENTIFIER_SELECT, msg.getArg(message.OPENID1_NS, 'identity')) class TestAuthRequestOpenID1Immediate(TestAuthRequestOpenID1): --- ../python3/openid/test/test_association_response.py (original) +++ ../python3/openid/test/test_association_response.py (refactored) @@ -42,9 +42,9 @@ def failUnlessProtocolError(self, str_prefix, func, *args, **kwargs): try: result = func(*args, **kwargs) - except ProtocolError, e: + except ProtocolError as e: message = 'Expected prefix %r, got %r' % (str_prefix, e[0]) - self.failUnless(e[0].startswith(str_prefix), message) + self.assertTrue(e[0].startswith(str_prefix), message) else: self.fail('Expected ProtocolError, got %r' % (result,)) @@ -72,7 +72,7 @@ def test(self): msg = mkAssocResponse(*keys) - self.failUnlessRaises(KeyError, + self.assertRaises(KeyError, self.consumer._extractAssociation, msg, None) return test @@ -119,7 +119,7 @@ def mkTest(requested_session_type, response_session_type, openid1=False): def test(self): assoc_session = DummyAssocationSession(requested_session_type) - keys = association_response_values.keys() + keys = list(association_response_values.keys()) if openid1: keys.remove('ns') msg = mkAssocResponse(*keys) @@ -176,7 +176,7 @@ """ def test(self): self._doTest(expected_session_type, session_type_value) - self.failUnlessEqual(0, len(self.messages)) + self.assertEqual(0, len(self.messages)) return test @@ -188,14 +188,14 @@ if session_type_value is not None: args['session_type'] = session_type_value message = Message.fromOpenIDArgs(args) - self.failUnless(message.isOpenID1()) + self.assertTrue(message.isOpenID1()) actual_session_type = self.consumer._getOpenID1SessionType(message) error_message = ('Returned sesion type parameter %r was expected ' 'to yield session type %r, but yielded %r' % (session_type_value, expected_session_type, actual_session_type)) - self.failUnlessEqual( + self.assertEqual( expected_session_type, actual_session_type, error_message) test_none = mkTest( @@ -214,8 +214,8 @@ session_type_value='no-encryption', expected_session_type='no-encryption', ) - self.failUnlessEqual(1, len(self.messages)) - self.failUnless(self.messages[0].startswith( + self.assertEqual(1, len(self.messages)) + self.assertTrue(self.messages[0].startswith( 'WARNING: OpenID server sent "no-encryption"')) test_dhSHA1 = mkTest( @@ -274,11 +274,11 @@ """Handle a full successful association response""" assoc = self.consumer._extractAssociation( self.assoc_response, self.assoc_session) - self.failUnless(self.assoc_session.extract_secret_called) - self.failUnlessEqual(self.assoc_session.secret, assoc.secret) - self.failUnlessEqual(1000, assoc.lifetime) - self.failUnlessEqual(self.assoc_handle, assoc.handle) - self.failUnlessEqual(self.assoc_type, assoc.assoc_type) + self.assertTrue(self.assoc_session.extract_secret_called) + self.assertEqual(self.assoc_session.secret, assoc.secret) + self.assertEqual(1000, assoc.lifetime) + self.assertEqual(self.assoc_handRefactoringTool: Refactored ../python3/openid/test/test_association.py le, assoc.handle) + self.assertEqual(self.assoc_type, assoc.assoc_type) def test_badAssocType(self): # Make sure that the assoc type in the response is not valid @@ -307,7 +307,7 @@ self.endpoint, 'HMAC-SHA1', 'DH-SHA1') # XXX: this is testing _createAssociateRequest - self.failUnlessEqual(self.endpoint.compatibilityMode(), + self.assertEqual(self.endpoint.compatibilityMode(), message.isOpenID1()) server_sess = DiffieHellmanSHA1ServerSession.fromMessage(message) @@ -321,11 +321,11 @@ def test_success(self): sess, server_resp = self._setUpDH() ret = self.consumer._extractAssociation(server_resp, sess) - self.failIf(ret is None) - self.failUnlessEqual(ret.assoc_type, 'HMAC-SHA1') - self.failUnlessEqual(ret.secret, self.secret) - self.failUnlessEqual(ret.handle, 'handle') - self.failUnlessEqual(ret.lifetime, 1000) + self.assertFalse(ret is None) + self.assertEqual(ret.assoc_type, 'HMAC-SHA1') + self.assertEqual(ret.secret, self.secret) + self.assertEqual(ret.handle, 'handle') + self.assertEqual(ret.lifetime, 1000) def test_openid2success(self): # Use openid 2 type in endpoint so _setUpDH checks --- ../python3/openid/test/test_association.py (original) +++ ../python3/openid/test/test_association.py (refactored) @@ -16,11 +16,11 @@ 'handle', 'secret', issued, lifetime, 'HMAC-SHA1') s = assoc.serialize() assoc2 = association.Association.deserialize(s) - self.failUnlessEqual(assoc.handle, assoc2.handle) - self.failUnlessEqual(assoc.issued, assoc2.issued) - self.failUnlessEqual(assoc.secret, assoc2.secret) - self.failUnlessEqual(assoc.lifetime, assoc2.lifetime) - self.failUnlessEqual(assoc.assoc_type, assoc2.assoc_type) + self.assertEqual(assoc.handle, assoc2.handle) + self.assertEqual(assoc.issued, assoc2.issued) + self.assertEqual(assoc.secret, assoc2.secret) + self.assertEqual(assoc.lifetime, assoc2.lifetime) + self.assertEqual(assoc.assoc_type, assoc2.assoc_type) from openid.server.server import \ DiffieHellmanSHA1ServerSession, \ @@ -71,7 +71,7 @@ ssess = self.ssess_fact.fromMessage(msg) check_secret = csess.extractSecret( Message.fromOpenIDArgs(ssess.answer(self.secret))) - self.failUnlessEqual(self.secret, check_secret) + self.assertEqual(self.secret, check_secret) @@ -99,7 +99,7 @@ ('identifier', '=example'), ('mode', 'id_res'), ] - self.failUnlessEqual(pairs, expected) + self.assertEqual(pairs, expected) @@ -115,7 +115,7 @@ expected = ('\xe0\x1bv\x04\xf1G\xc0\xbb\x7f\x9a\x8b' '\xe9\xbc\xee}\\\xe5\xbb7*') sig = assoc.sign(self.pairs) - self.failUnlessEqual(sig, expected) + self.assertEqual(sig, expected) if cryptutil.SHA256_AVAILABLE: def test_sha256(self): @@ -124,7 +124,7 @@ expected = ('\xfd\xaa\xfe;\xac\xfc*\x988\xad\x05d6-\xeaVy' '\xd5\xa5Z.<\xa9\xed\x18\x82\\$\x95x\x1c&') sig = assoc.sign(self.pairs) - self.failUnlessEqual(sig, expected) + self.assertEqual(sig, expected) @@ -143,10 +143,10 @@ assoc = association.Association.fromExpiresIn( 3600, '{sha1}', 'very_secret', "HMAC-SHA1") signed = assoc.signMessage(self.message) - self.failUnless(signed.getArg(OPENID_NS, "sig")) - self.failUnlessEqual(signed.getArg(OPENID_NS, "signed"), + self.assertTrue(signed.getArg(OPENID_NS, "sig")) + self.assertEqual(signed.getArg(OPENID_NS, "signed"), "assoc_handle,identifier,mode,ns,signed") - self.failUnlessEqual(signed.getArg(BARE_NS, "xey"), "value", + self.assertEqual(signed.getArg(BARE_NS, "xey"), "value", signed) if crypRefactoringTool: Refactored ../python3/openid/test/test_accept.py RefactoringTool: Refactored ../python3/openid/test/support.py RefactoringTool: Refactored ../python3/openid/test/storetest.py RefactoringTool: Refactored ../python3/openid/test/oidutil.py tutil.SHA256_AVAILABLE: @@ -154,10 +154,10 @@ assoc = association.Association.fromExpiresIn( 3600, '{sha1}', 'very_secret', "HMAC-SHA256") signed = assoc.signMessage(self.message) - self.failUnless(signed.getArg(OPENID_NS, "sig")) - self.failUnlessEqual(signed.getArg(OPENID_NS, "signed"), + self.assertTrue(signed.getArg(OPENID_NS, "sig")) + self.assertEqual(signed.getArg(OPENID_NS, "signed"), "assoc_handle,identifier,mode,ns,signed") - self.failUnlessEqual(signed.getArg(BARE_NS, "xey"), "value", + self.assertEqual(signed.getArg(BARE_NS, "xey"), "value", signed) @@ -171,7 +171,7 @@ m.updateArgs(BARE_NS, {'xey': 'value'}) assoc = association.Association.fromExpiresIn( 3600, '{sha1}', 'very_secret', "HMAC-SHA1") - self.failUnlessRaises(ValueError, assoc.checkMessageSignature, m) + self.assertRaises(ValueError, assoc.checkMessageSignature, m) def pyUnitTests(): --- ../python3/openid/test/test_accept.py (original) +++ ../python3/openid/test/test_accept.py (refactored) @@ -90,12 +90,12 @@ def runTest(self): accepted = accept.parseAcceptHeader(self.accept_header) actual = accept.matchTypes(accepted, self.available) - self.failUnlessEqual(self.expected, actual) + self.assertEqual(self.expected, actual) def pyUnitTests(): lines = getTestData() chunks = chunk(lines) - data_sets = map(parseLines, chunks) + data_sets = list(map(parseLines, chunks)) cases = [] for data in data_sets: lnos = [] @@ -106,7 +106,7 @@ try: available = parseAvailable(avail_data) except: - print 'On line', lno + print('On line', lno) raise lno, exp_data = data['expected'] @@ -114,7 +114,7 @@ try: expected = parseExpected(exp_data) except: - print 'On line', lno + print('On line', lno) raise descr = 'MatchAcceptTest for lines %r' % (lnos,) --- ../python3/openid/test/support.py (original) +++ ../python3/openid/test/support.py (refactored) @@ -9,7 +9,7 @@ actual = msg.getArg(ns, key) error_format = 'Wrong value for openid.%s: expected=%s, actual=%s' error_message = error_format % (key, expected, actual) - self.failUnlessEqual(expected, actual, error_message) + self.assertEqual(expected, actual, error_message) def failIfOpenIDKeyExists(self, msg, key, ns=None): if ns is None: @@ -17,7 +17,7 @@ actual = msg.getArg(ns, key) error_message = 'openid.%s unexpectedly present: %s' % (key, actual) - self.failIf(actual is not None, error_message) + self.assertFalse(actual is not None, error_message) class CatchLogs(object): def setUp(self): --- ../python3/openid/test/storetest.py (original) +++ ../python3/openid/test/storetest.py (refactored) @@ -268,10 +268,10 @@ # 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, why: + except MySQLdb.OperationalError as why: if why[0] == 2005: - print ('Skipping MySQL store test (cannot connect ' - 'to test server on host %r)' % (db_host,)) + print(('Skipping MySQL store test (cannot connect ' + 'to test server on host %r)' % (db_host,))) return else: raise @@ -382,7 +382,7 @@ ] def pyUnitTests(): - tests = map(unittest.FunctionTestCase, test_functions) + tests = list(map(unittest.FunctionTestCase, test_functions)) load = unittest.defaultTestLoader.loadTestsFromTestCase return unittest.TestSuite(tests) --- ../python3/openid/test/oidutil.py (original) +++ ../python3/oRefactoringTool: Refactored ../python3/openid/test/linkparse.py RefactoringTool: Refactored ../python3/openid/test/kvform.py penid/test/oidutil.py (refactored) @@ -21,7 +21,7 @@ '\x00', '\x01', '\x00' * 100, - ''.join(map(chr, range(256))), + ''.join(map(chr, list(range(256)))), ] for s in cases: @@ -31,9 +31,9 @@ assert s_prime == s, (s, b64, s_prime) # Randomized test - for _ in xrange(50): + for _ in range(50): n = random.randrange(2048) - s = ''.join(map(chr, map(lambda _: random.randrange(256), range(n)))) + s = ''.join(map(chr, [random.randrange(256) for _ in range(n)])) b64 = oidutil.toBase64(s) checkEncoded(b64) s_prime = oidutil.fromBase64(b64) @@ -61,10 +61,10 @@ s = oidutil.Symbol("Foo") d = {s: 1} d_prime = copy.deepcopy(d) - self.failUnless(s in d_prime, "%r isn't in %r" % (s, d_prime)) + self.assertTrue(s in d_prime, "%r isn't in %r" % (s, d_prime)) t = oidutil.Symbol("Bar") - self.failIfEqual(hash(s), hash(t)) + self.assertNotEqual(hash(s), hash(t)) def buildAppendTests(): --- ../python3/openid/test/linkparse.py (original) +++ ../python3/openid/test/linkparse.py (refactored) @@ -27,7 +27,7 @@ name = lines.pop(0) assert name.startswith('Name: ') desc = name[6:] - return desc, markup, map(parseLink, lines) + return desc, markup, list(map(parseLink, lines)) def parseTests(s): tests = [] @@ -65,7 +65,7 @@ continue act_link = actual[i] - for k, (o, v) in exp_link.items(): + for k, (o, v) in list(exp_link.items()): if o: act_v = act_link.get(k) if act_v is None: --- ../python3/openid/test/kvform.py (original) +++ ../python3/openid/test/kvform.py (refactored) @@ -10,13 +10,13 @@ self.warnings.append(message) def checkWarnings(self, num_warnings): - self.failUnlessEqual(num_warnings, len(self.warnings), repr(self.warnings)) + self.assertEqual(num_warnings, len(self.warnings), repr(self.warnings)) def setUp(self): self.warnings = [] self.old_log = oidutil.log self.log_func = oidutil.log = self.log - self.failUnless(self.log_func is oidutil.log, + self.assertTrue(self.log_func is oidutil.log, (oidutil.log, self.log_func)) def tearDown(self): @@ -34,7 +34,7 @@ d = kvform.kvToDict(self.kvform) # make sure it parses to expected dict - self.failUnlessEqual(self.dict, d) + self.assertEqual(self.dict, d) # Check to make sure we got the expected number of warnings self.checkWarnings(self.expected_warnings) @@ -43,7 +43,7 @@ # sure that *** dict -> kv -> dict is identity. *** kv = kvform.dictToKV(d) d2 = kvform.kvToDict(kv) - self.failUnlessEqual(d, d2) + self.assertEqual(d, d2) class KVSeqTest(KVBaseTest): def __init__(self, seq, kv, expected_warnings): @@ -67,8 +67,8 @@ def runTest(self): # seq serializes to expected kvform actual = kvform.seqToKV(self.seq) - self.failUnlessEqual(self.kvform, actual) - self.failUnless(type(actual) is str) + self.assertEqual(self.kvform, actual) + self.assertTrue(type(actual) is str) # Parse back to sequence. Expected to be unchanged, except # stripping whitespace from start and end of values @@ -76,7 +76,7 @@ seq = kvform.kvToSeq(actual) clean_seq = self.cleanSeq(seq) - self.failUnlessEqual(seq, clean_seq) + self.assertEqual(seq, clean_seq) self.checkWarnings(self.expected_warnings) kvdict_cases = [ @@ -115,7 +115,7 @@ ([], '', 0), # Make sure that we handle non-ascii characters (also wider than 8 bits) - ([(u'\u03bbx', u'x')], '\xce\xbbx:x\n', 0), + ([('\u03bbx', 'x')], '\xce\xbbx:x\n', 0), # If it's a UTF-8 str, make sure that it's equivalent to the same # string, decoded. @@ -135,7 +135,7 @@ ([(' open id ', ' uRefactoringTool: Refactored ../python3/openid/test/discoverdata.py RefactoringTool: Refactored ../python3/openid/test/dh.py RefactoringTool: Refactored ../python3/openid/test/datadriven.py RefactoringTool: Refactored ../python3/openid/test/cryptutil.py se ful '), (' a ', ' b ')], ' open id : use ful \n a : b \n', 8), - ([(u'foo', 'bar')], 'foo:bar\n', 0), + ([('foo', 'bar')], 'foo:bar\n', 0), ] kvexc_cases = [ @@ -156,14 +156,14 @@ return 'KVExcTest for %r' % (self.seq,) def runTest(self): - self.failUnlessRaises(ValueError, kvform.seqToKV, self.seq) + self.assertRaises(ValueError, kvform.seqToKV, self.seq) class GeneralTest(KVBaseTest): kvform = '%s' % cgi.escape(text)) return self.send_response(webresponse.code) - for header, value in webresponse.headers.iteritems(): + for header, value in webresponse.headers.items(): self.send_header(header, value) self.writeUserHeader() self.end_headers() @@ -436,7 +436,7 @@ ident = self.server.base_url + path[1:] approved_trust_roots = [] - for (aident, trust_root) in self.server.approved.keys(): + for (aident, trust_root) in list(self.server.approved.keys()): if aident == ident: trs = '