diff options
Diffstat (limited to 'Lib/test')
48 files changed, 1224 insertions, 254 deletions
diff --git a/Lib/test/exception_hierarchy.txt b/Lib/test/exception_hierarchy.txt index a03f7bbd71..079ce2963c 100644 --- a/Lib/test/exception_hierarchy.txt +++ b/Lib/test/exception_hierarchy.txt @@ -4,39 +4,38 @@ BaseException +-- Exception +-- GeneratorExit +-- StopIteration - +-- StandardError - | +-- ArithmeticError - | | +-- FloatingPointError - | | +-- OverflowError - | | +-- ZeroDivisionError - | +-- AssertionError - | +-- AttributeError - | +-- EnvironmentError - | | +-- IOError - | | +-- OSError - | | +-- WindowsError (Windows) - | | +-- VMSError (VMS) - | +-- EOFError - | +-- ImportError - | +-- LookupError - | | +-- IndexError - | | +-- KeyError - | +-- MemoryError - | +-- NameError - | | +-- UnboundLocalError - | +-- ReferenceError - | +-- RuntimeError - | | +-- NotImplementedError - | +-- SyntaxError - | | +-- IndentationError - | | +-- TabError - | +-- SystemError - | +-- TypeError - | +-- ValueError - | | +-- UnicodeError - | | +-- UnicodeDecodeError - | | +-- UnicodeEncodeError - | | +-- UnicodeTranslateError + +-- ArithmeticError + | +-- FloatingPointError + | +-- OverflowError + | +-- ZeroDivisionError + +-- AssertionError + +-- AttributeError + +-- EnvironmentError + | +-- IOError + | +-- OSError + | +-- WindowsError (Windows) + | +-- VMSError (VMS) + +-- EOFError + +-- ImportError + +-- LookupError + | +-- IndexError + | +-- KeyError + +-- MemoryError + +-- NameError + | +-- UnboundLocalError + +-- ReferenceError + +-- RuntimeError + | +-- NotImplementedError + +-- SyntaxError + | +-- IndentationError + | +-- TabError + +-- SystemError + +-- TypeError + +-- ValueError + | +-- UnicodeError + | +-- UnicodeDecodeError + | +-- UnicodeEncodeError + | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning diff --git a/Lib/test/list_tests.py b/Lib/test/list_tests.py index 468a1bc418..0d893f2205 100644 --- a/Lib/test/list_tests.py +++ b/Lib/test/list_tests.py @@ -451,7 +451,7 @@ class CommonTest(seq_tests.CommonTest): self.assertEqual(u, list("ham")) def test_iadd(self): - super(CommonTest, self).test_iadd() + super().test_iadd() u = self.type2test([0, 1]) u2 = u u += [2, 3] diff --git a/Lib/test/output/test_class b/Lib/test/output/test_class index f6ba4757b3..d0fed75263 100644 --- a/Lib/test/output/test_class +++ b/Lib/test/output/test_class @@ -46,8 +46,7 @@ __abs__: () __int__: () __int__: () __float__: () -__oct__: () -__hex__: () +__index__: () __hash__: () __repr__: () __str__: () diff --git a/Lib/test/output/test_tokenize b/Lib/test/output/test_tokenize index a46824ddb2..c3bb8b024c 100644 --- a/Lib/test/output/test_tokenize +++ b/Lib/test/output/test_tokenize @@ -124,66 +124,80 @@ test_tokenize 39,5-39,7: OP '!=' 39,8-39,11: NUMBER '255' 39,11-39,12: NEWLINE '\n' -40,0-40,4: NUMBER '0377' -40,5-40,7: OP '!=' -40,8-40,11: NUMBER '255' -40,11-40,12: NEWLINE '\n' +40,0-40,5: NUMBER '0o377' +40,6-40,8: OP '!=' +40,9-40,12: NUMBER '255' +40,12-40,13: NEWLINE '\n' 41,0-41,10: NUMBER '2147483647' 41,13-41,15: OP '!=' -41,16-41,28: NUMBER '017777777777' -41,28-41,29: NEWLINE '\n' +41,16-41,29: NUMBER '0o17777777777' +41,29-41,30: NEWLINE '\n' 42,0-42,1: OP '-' 42,1-42,11: NUMBER '2147483647' 42,11-42,12: OP '-' 42,12-42,13: NUMBER '1' 42,14-42,16: OP '!=' -42,17-42,29: NUMBER '020000000000' -42,29-42,30: NEWLINE '\n' -43,0-43,12: NUMBER '037777777777' -43,13-43,15: OP '!=' -43,16-43,17: OP '-' -43,17-43,18: NUMBER '1' -43,18-43,19: NEWLINE '\n' +42,17-42,30: NUMBER '0o20000000000' +42,30-42,31: NEWLINE '\n' +43,0-43,13: NUMBER '0o37777777777' +43,14-43,16: OP '!=' +43,17-43,18: OP '-' +43,18-43,19: NUMBER '1' +43,19-43,20: NEWLINE '\n' 44,0-44,10: NUMBER '0xffffffff' 44,11-44,13: OP '!=' 44,14-44,15: OP '-' 44,15-44,16: NUMBER '1' -44,16-44,17: NEWLINE '\n' +44,16-44,17: OP ';' +44,18-44,31: NUMBER '0o37777777777' +44,32-44,34: OP '!=' +44,35-44,36: OP '-' +44,36-44,37: NUMBER '1' +44,37-44,38: OP ';' +44,39-44,40: OP '-' +44,40-44,49: NUMBER '0o1234567' +44,50-44,52: OP '==' +44,53-44,64: NUMBER '0O001234567' +44,64-44,65: OP ';' +44,66-44,73: NUMBER '0b10101' +44,74-44,76: OP '==' +44,77-44,87: NUMBER '0B00010101' +44,87-44,88: NEWLINE '\n' 45,0-45,1: NL '\n' 46,0-46,15: COMMENT '# Long integers' 46,15-46,16: NL '\n' 47,0-47,1: NAME 'x' 47,2-47,3: OP '=' -47,4-47,6: NUMBER '0L' -47,6-47,7: NEWLINE '\n' +47,4-47,5: NUMBER '0' +47,5-47,6: NEWLINE '\n' 48,0-48,1: NAME 'x' 48,2-48,3: OP '=' -48,4-48,6: NUMBER '0l' -48,6-48,7: NEWLINE '\n' +48,4-48,5: NUMBER '0' +48,5-48,6: NEWLINE '\n' 49,0-49,1: NAME 'x' 49,2-49,3: OP '=' -49,4-49,23: NUMBER '0xffffffffffffffffL' -49,23-49,24: NEWLINE '\n' +49,4-49,22: NUMBER '0xffffffffffffffff' +49,22-49,23: NEWLINE '\n' 50,0-50,1: NAME 'x' 50,2-50,3: OP '=' -50,4-50,23: NUMBER '0xffffffffffffffffl' -50,23-50,24: NEWLINE '\n' +50,4-50,22: NUMBER '0xffffffffffffffff' +50,22-50,23: NEWLINE '\n' 51,0-51,1: NAME 'x' 51,2-51,3: OP '=' -51,4-51,23: NUMBER '077777777777777777L' +51,4-51,23: NUMBER '0o77777777777777777' 51,23-51,24: NEWLINE '\n' 52,0-52,1: NAME 'x' 52,2-52,3: OP '=' -52,4-52,23: NUMBER '077777777777777777l' +52,4-52,23: NUMBER '0B11101010111111111' 52,23-52,24: NEWLINE '\n' 53,0-53,1: NAME 'x' 53,2-53,3: OP '=' -53,4-53,35: NUMBER '123456789012345678901234567890L' -53,35-53,36: NEWLINE '\n' +53,4-53,34: NUMBER '123456789012345678901234567890' +53,34-53,35: NEWLINE '\n' 54,0-54,1: NAME 'x' 54,2-54,3: OP '=' -54,4-54,35: NUMBER '123456789012345678901234567890l' -54,35-54,36: NEWLINE '\n' +54,4-54,34: NUMBER '123456789012345678901234567890' +54,34-54,35: NEWLINE '\n' 55,0-55,1: NL '\n' 56,0-56,24: COMMENT '# Floating-point numbers' 56,24-56,25: NL '\n' diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py index de0b9f0fff..5dfc9d484d 100755 --- a/Lib/test/regrtest.py +++ b/Lib/test/regrtest.py @@ -697,7 +697,7 @@ def dash_R_cleanup(fs, ps, pic): import gc, copy_reg import _strptime, linecache, dircache import urlparse, urllib, urllib2, mimetypes, doctest - import struct, filecmp + import struct, filecmp, collections from distutils.dir_util import _path_created # Restore some original values. @@ -707,6 +707,10 @@ def dash_R_cleanup(fs, ps, pic): sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) + # Clear ABC registries. + for obj in [collections.Hashable, collections.Iterable]: + obj._ABCMeta__registry.clear() + # Clear assorted module caches. _path_created.clear() re.purge() diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py index 4dfbb1bd6e..0ce212ceb2 100644 --- a/Lib/test/string_tests.py +++ b/Lib/test/string_tests.py @@ -211,6 +211,32 @@ class BaseTest(unittest.TestCase): self.checkraises(TypeError, 'hello', 'rindex') self.checkraises(TypeError, 'hello', 'rindex', 42) + def test_lower(self): + self.checkequal('hello', 'HeLLo', 'lower') + self.checkequal('hello', 'hello', 'lower') + self.checkraises(TypeError, 'hello', 'lower', 42) + + def test_upper(self): + self.checkequal('HELLO', 'HeLLo', 'upper') + self.checkequal('HELLO', 'HELLO', 'upper') + self.checkraises(TypeError, 'hello', 'upper', 42) + + def test_expandtabs(self): + self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') + self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) + self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4) + self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4) + self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') + self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) + self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4) + self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1) + + self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42) + # This test is only valid when sizeof(int) == sizeof(void*) == 4. + if sys.maxint < (1 << 32) and struct.calcsize('P') == 4: + self.checkraises(OverflowError, + '\ta\n\tb', 'expandtabs', sys.maxint) + def test_split(self): # by a char self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|') diff --git a/Lib/test/test_abc.py b/Lib/test/test_abc.py new file mode 100644 index 0000000000..aecb80011b --- /dev/null +++ b/Lib/test/test_abc.py @@ -0,0 +1,123 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Unit tests for abc.py.""" + +import sys +import unittest +from test import test_support + +import abc + + +class TestABC(unittest.TestCase): + + def test_abstractmethod_basics(self): + @abc.abstractmethod + def foo(self): pass + self.assertEqual(foo.__isabstractmethod__, True) + def bar(self): pass + self.assertEqual(hasattr(bar, "__isabstractmethod__"), False) + + def test_abstractmethod_integration(self): + class C(metaclass=abc.ABCMeta): + @abc.abstractmethod + def foo(self): pass # abstract + def bar(self): pass # concrete + self.assertEqual(C.__abstractmethods__, {"foo"}) + self.assertRaises(TypeError, C) # because foo is abstract + class D(C): + def bar(self): pass # concrete override of concrete + self.assertEqual(D.__abstractmethods__, {"foo"}) + self.assertRaises(TypeError, D) # because foo is still abstract + class E(D): + def foo(self): pass + self.assertEqual(E.__abstractmethods__, set()) + E() # now foo is concrete, too + class F(E): + @abc.abstractmethod + def bar(self): pass # abstract override of concrete + self.assertEqual(F.__abstractmethods__, {"bar"}) + self.assertRaises(TypeError, F) # because bar is abstract now + + def test_registration_basics(self): + class A(metaclass=abc.ABCMeta): + pass + class B: + pass + b = B() + self.assertEqual(issubclass(B, A), False) + self.assertEqual(isinstance(b, A), False) + A.register(B) + self.assertEqual(issubclass(B, A), True) + self.assertEqual(isinstance(b, A), True) + class C(B): + pass + c = C() + self.assertEqual(issubclass(C, A), True) + self.assertEqual(isinstance(c, A), True) + + def test_registration_builtins(self): + class A(metaclass=abc.ABCMeta): + pass + A.register(int) + self.assertEqual(isinstance(42, A), True) + self.assertEqual(issubclass(int, A), True) + class B(A): + pass + B.register(basestring) + self.assertEqual(isinstance("", A), True) + self.assertEqual(issubclass(str, A), True) + + def test_registration_edge_cases(self): + class A(metaclass=abc.ABCMeta): + pass + A.register(A) # should pass silently + class A1(A): + pass + self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed + class B: + pass + A1.register(B) # ok + A1.register(B) # should pass silently + class C(A): + pass + A.register(C) # should pass silently + self.assertRaises(RuntimeError, C.register, A) # cycles not allowed + C.register(B) # ok + + def test_registration_transitiveness(self): + class A(metaclass=abc.ABCMeta): + pass + self.failUnless(issubclass(A, A)) + class B(metaclass=abc.ABCMeta): + pass + self.failIf(issubclass(A, B)) + self.failIf(issubclass(B, A)) + class C(metaclass=abc.ABCMeta): + pass + A.register(B) + class B1(B): + pass + self.failUnless(issubclass(B1, A)) + class C1(C): + pass + B1.register(C1) + self.failIf(issubclass(C, B)) + self.failIf(issubclass(C, B1)) + self.failUnless(issubclass(C1, A)) + self.failUnless(issubclass(C1, B)) + self.failUnless(issubclass(C1, B1)) + C1.register(int) + class MyInt(int): + pass + self.failUnless(issubclass(MyInt, A)) + self.failUnless(isinstance(42, A)) + + +def test_main(): + test_support.run_unittest(TestABC) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 2eb64f3c87..0d4c219c78 100755 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -704,7 +704,7 @@ class BaseTest(unittest.TestCase): class StringTest(BaseTest): def test_setitem(self): - super(StringTest, self).test_setitem() + super().test_setitem() a = array.array(self.typecode, self.example) self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2]) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 1c1998d1e7..a2fde023e3 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -728,8 +728,27 @@ class BuiltinTest(unittest.TestCase): self.assertRaises(TypeError, int, 1, 12) - self.assertEqual(int('0123', 0), 83) + # tests with base 0 + self.assertRaises(ValueError, int, ' 0123 ', 0) # old octal syntax + self.assertEqual(int('000', 0), 0) + self.assertEqual(int('0o123', 0), 83) + self.assertEqual(int('0x123', 0), 291) + self.assertEqual(int('0b100', 0), 4) + self.assertEqual(int(' 0O123 ', 0), 83) + self.assertEqual(int(' 0X123 ', 0), 291) + self.assertEqual(int(' 0B100 ', 0), 4) + + # without base still base 10 + self.assertEqual(int('0123'), 123) + self.assertEqual(int('0123', 10), 123) + + # tests with prefix and base != 0 self.assertEqual(int('0x123', 16), 291) + self.assertEqual(int('0o123', 8), 83) + self.assertEqual(int('0b100', 2), 4) + self.assertEqual(int('0X123', 16), 291) + self.assertEqual(int('0O123', 8), 83) + self.assertEqual(int('0B100', 2), 4) # SF bug 1334662: int(string, base) wrong answers # Various representations of 2**32 evaluated to 0 @@ -1269,10 +1288,10 @@ class BuiltinTest(unittest.TestCase): self.assertEquals(next(it, 42), 42) def test_oct(self): - self.assertEqual(oct(100), '0144') - self.assertEqual(oct(100), '0144') - self.assertEqual(oct(-100), '-0144') - self.assertEqual(oct(-100), '-0144') + self.assertEqual(oct(100), '0o144') + self.assertEqual(oct(100), '0o144') + self.assertEqual(oct(-100), '-0o144') + self.assertEqual(oct(-100), '-0o144') self.assertRaises(TypeError, oct, ()) def write_testfile(self): diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index efb4c98c9b..1083321705 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -716,6 +716,12 @@ class BytesAsStringTest(test.string_tests.BaseTest): pass def test_find(self): pass + def test_expandtabs(self): + pass + def test_upper(self): + pass + def test_lower(self): + pass def test_main(): diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py index 260d9b2a85..0bf18a15e4 100644 --- a/Lib/test/test_cgi.py +++ b/Lib/test/test_cgi.py @@ -50,7 +50,7 @@ def do_test(buf, method): raise ValueError, "unknown method: %s" % method try: return cgi.parse(fp, env, strict_parsing=1) - except StandardError as err: + except Exception as err: return ComparableException(err) # A list of test cases. Each test case is a a two-tuple that contains diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py index ded3f1a899..003b4a51e6 100644 --- a/Lib/test/test_class.py +++ b/Lib/test/test_class.py @@ -80,18 +80,14 @@ class AllTests: print("__int__:", args) return 1 + def __index__(self, *args): + print("__index__:", args) + return 1 + def __float__(self, *args): print("__float__:", args) return 1.0 - def __oct__(self, *args): - print("__oct__:", args) - return '01' - - def __hex__(self, *args): - print("__hex__:", args) - return '0x1' - def __cmp__(self, *args): print("__cmp__:", args) return 0 @@ -237,7 +233,6 @@ int(testme) int(testme) float(testme) oct(testme) -hex(testme) # And the rest... @@ -287,8 +282,6 @@ class BadTypeClass: __float__ = __int__ __str__ = __int__ __repr__ = __int__ - __oct__ = __int__ - __hex__ = __int__ def check_exc(stmt, exception): """Raise TestFailed if executing 'stmt' does not raise 'exception' diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index f5dad7d223..13401e9443 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -1,6 +1,14 @@ +"""Unit tests for collections.py.""" + import unittest from test import test_support from collections import NamedTuple +from collections import Hashable, Iterable, Iterator +from collections import Sized, Container, Callable +from collections import Set, MutableSet +from collections import Mapping, MutableMapping +from collections import Sequence, MutableSequence + class TestNamedTuple(unittest.TestCase): @@ -51,11 +59,187 @@ class TestNamedTuple(unittest.TestCase): self.assertRaises(AttributeError, eval, 'p.z', locals()) +class TestOneTrickPonyABCs(unittest.TestCase): + + def test_Hashable(self): + # Check some non-hashables + non_samples = [bytes(), list(), set(), dict()] + for x in non_samples: + self.failIf(isinstance(x, Hashable), repr(x)) + self.failIf(issubclass(type(x), Hashable), repr(type(x))) + # Check some hashables + samples = [None, + int(), float(), complex(), + str(), unicode(), + tuple(), frozenset(), + int, list, object, type, + ] + for x in samples: + self.failUnless(isinstance(x, Hashable), repr(x)) + self.failUnless(issubclass(type(x), Hashable), repr(type(x))) + self.assertRaises(TypeError, Hashable) + # Check direct subclassing + class H(Hashable): + def __hash__(self): + return super().__hash__() + self.assertEqual(hash(H()), 0) + self.failIf(issubclass(int, H)) + + def test_Iterable(self): + # Check some non-iterables + non_samples = [None, 42, 3.14, 1j] + for x in non_samples: + self.failIf(isinstance(x, Iterable), repr(x)) + self.failIf(issubclass(type(x), Iterable), repr(type(x))) + # Check some iterables + samples = [bytes(), str(), unicode(), + tuple(), list(), set(), frozenset(), dict(), + dict().keys(), dict().items(), dict().values(), + (lambda: (yield))(), + (x for x in []), + ] + for x in samples: + self.failUnless(isinstance(x, Iterable), repr(x)) + self.failUnless(issubclass(type(x), Iterable), repr(type(x))) + # Check direct subclassing + class I(Iterable): + def __iter__(self): + return super().__iter__() + self.assertEqual(list(I()), []) + self.failIf(issubclass(str, I)) + + def test_Iterator(self): + non_samples = [None, 42, 3.14, 1j, b"", "", u"", (), [], {}, set()] + for x in non_samples: + self.failIf(isinstance(x, Iterator), repr(x)) + self.failIf(issubclass(type(x), Iterator), repr(type(x))) + samples = [iter(bytes()), iter(str()), iter(unicode()), + iter(tuple()), iter(list()), iter(dict()), + iter(set()), iter(frozenset()), + iter(dict().keys()), iter(dict().items()), + iter(dict().values()), + (lambda: (yield))(), + (x for x in []), + ] + for x in samples: + self.failUnless(isinstance(x, Iterator), repr(x)) + self.failUnless(issubclass(type(x), Iterator), repr(type(x))) + + def test_Sized(self): + non_samples = [None, 42, 3.14, 1j, + (lambda: (yield))(), + (x for x in []), + ] + for x in non_samples: + self.failIf(isinstance(x, Sized), repr(x)) + self.failIf(issubclass(type(x), Sized), repr(type(x))) + samples = [bytes(), str(), unicode(), + tuple(), list(), set(), frozenset(), dict(), + dict().keys(), dict().items(), dict().values(), + ] + for x in samples: + self.failUnless(isinstance(x, Sized), repr(x)) + self.failUnless(issubclass(type(x), Sized), repr(type(x))) + + def test_Container(self): + non_samples = [None, 42, 3.14, 1j, + (lambda: (yield))(), + (x for x in []), + ] + for x in non_samples: + self.failIf(isinstance(x, Container), repr(x)) + self.failIf(issubclass(type(x), Container), repr(type(x))) + samples = [bytes(), str(), unicode(), + tuple(), list(), set(), frozenset(), dict(), + dict().keys(), dict().items(), + ] + for x in samples: + self.failUnless(isinstance(x, Container), repr(x)) + self.failUnless(issubclass(type(x), Container), repr(type(x))) + + def test_Callable(self): + non_samples = [None, 42, 3.14, 1j, + "", b"", (), [], {}, set(), + (lambda: (yield))(), + (x for x in []), + ] + for x in non_samples: + self.failIf(isinstance(x, Callable), repr(x)) + self.failIf(issubclass(type(x), Callable), repr(type(x))) + samples = [lambda: None, + type, int, object, + len, + list.append, [].append, + ] + for x in samples: + self.failUnless(isinstance(x, Callable), repr(x)) + self.failUnless(issubclass(type(x), Callable), repr(type(x))) + + def test_direct_subclassing(self): + for B in Hashable, Iterable, Iterator, Sized, Container, Callable: + class C(B): + pass + self.failUnless(issubclass(C, B)) + self.failIf(issubclass(int, C)) + + def test_registration(self): + for B in Hashable, Iterable, Iterator, Sized, Container, Callable: + class C: + __hash__ = None # Make sure it isn't hashable by default + self.failIf(issubclass(C, B), B.__name__) + B.register(C) + self.failUnless(issubclass(C, B)) + + +class TestCollectionABCs(unittest.TestCase): + + # XXX For now, we only test some virtual inheritance properties. + # We should also test the proper behavior of the collection ABCs + # as real base classes or mix-in classes. + + def test_Set(self): + for sample in [set, frozenset]: + self.failUnless(isinstance(sample(), Set)) + self.failUnless(issubclass(sample, Set)) + + def test_MutableSet(self): + self.failUnless(isinstance(set(), MutableSet)) + self.failUnless(issubclass(set, MutableSet)) + self.failIf(isinstance(frozenset(), MutableSet)) + self.failIf(issubclass(frozenset, MutableSet)) + + def test_Mapping(self): + for sample in [dict]: + self.failUnless(isinstance(sample(), Mapping)) + self.failUnless(issubclass(sample, Mapping)) + + def test_MutableMapping(self): + for sample in [dict]: + self.failUnless(isinstance(sample(), MutableMapping)) + self.failUnless(issubclass(sample, MutableMapping)) + + def test_Sequence(self): + for sample in [tuple, list, bytes, str]: + self.failUnless(isinstance(sample(), Sequence)) + self.failUnless(issubclass(sample, Sequence)) + self.failUnless(issubclass(basestring, Sequence)) + + def test_MutableSequence(self): + for sample in [tuple, str]: + self.failIf(isinstance(sample(), MutableSequence)) + self.failIf(issubclass(sample, MutableSequence)) + for sample in [list, bytes]: + self.failUnless(isinstance(sample(), MutableSequence)) + self.failUnless(issubclass(sample, MutableSequence)) + self.failIf(issubclass(basestring, MutableSequence)) + + def test_main(verbose=None): import collections as CollectionsModule - test_classes = [TestNamedTuple] + test_classes = [TestNamedTuple, TestOneTrickPonyABCs, TestCollectionABCs] test_support.run_unittest(*test_classes) test_support.run_doctest(CollectionsModule, verbose) + if __name__ == "__main__": test_main(verbose=True) diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index 4e29eab0ef..b5949fd4ce 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -36,6 +36,9 @@ class TestSpecifics(unittest.TestCase): def test_syntax_error(self): self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec") + def test_none_keyword_arg(self): + self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec") + def test_duplicate_global_local(self): try: exec('def f(a): global a; a = 1') @@ -158,21 +161,22 @@ if 1: def test_literals_with_leading_zeroes(self): for arg in ["077787", "0xj", "0x.", "0e", "090000000000000", - "080000000000000", "000000000000009", "000000000000008"]: + "080000000000000", "000000000000009", "000000000000008", + "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2", + "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777", + "000777", "000000000000007"]: self.assertRaises(SyntaxError, eval, arg) - self.assertEqual(eval("0777"), 511) - self.assertEqual(eval("000777"), 511) self.assertEqual(eval("0xff"), 255) - self.assertEqual(eval("0XfF"), 255) self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777.0"), 777) self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777) self.assertEqual(eval("0777e1"), 7770) self.assertEqual(eval("0e0"), 0) - self.assertEqual(eval("0000E-012"), 0) + self.assertEqual(eval("0000e-012"), 0) self.assertEqual(eval("09.5"), 9.5) self.assertEqual(eval("0777j"), 777j) + self.assertEqual(eval("000"), 0) self.assertEqual(eval("00j"), 0j) self.assertEqual(eval("00.0"), 0) self.assertEqual(eval("0e3"), 0) @@ -181,9 +185,12 @@ if 1: self.assertEqual(eval("090000000000000e0"), 90000000000000.) self.assertEqual(eval("090000000000000e-0"), 90000000000000.) self.assertEqual(eval("090000000000000j"), 90000000000000j) - self.assertEqual(eval("000000000000007"), 7) self.assertEqual(eval("000000000000008."), 8.) self.assertEqual(eval("000000000000009."), 9.) + self.assertEqual(eval("0b101010"), 42) + self.assertEqual(eval("-0b000000000010"), -2) + self.assertEqual(eval("0o777"), 511) + self.assertEqual(eval("-0o0000010"), -8) def test_unary_minus(self): # Verify treatment of unary minus on negative numbers SF bug #660455 diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index bcbd096455..7dc8442648 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -2126,17 +2126,14 @@ def inherits(): class octlong(int): __slots__ = [] def __str__(self): - s = oct(self) - if s[-1] == 'L': - s = s[:-1] - return s + return oct(self) def __add__(self, other): return self.__class__(super(octlong, self).__add__(other)) __radd__ = __add__ - vereq(str(octlong(3) + 5), "010") + vereq(str(octlong(3) + 5), "0o10") # (Note that overriding __radd__ here only seems to work # because the example uses a short int left argument.) - vereq(str(5 + octlong(3000)), "05675") + vereq(str(5 + octlong(3000)), "0o5675") a = octlong(12345) vereq(a, 12345) vereq(int(a), 12345) diff --git a/Lib/test/test_dumbdbm.py b/Lib/test/test_dumbdbm.py index c7d29ec008..d03d861d6e 100644 --- a/Lib/test/test_dumbdbm.py +++ b/Lib/test/test_dumbdbm.py @@ -45,17 +45,17 @@ class DumbDBMTestCase(unittest.TestCase): return try: - old_umask = os.umask(0002) - f = dumbdbm.open(_fname, 'c', 0637) + old_umask = os.umask(0o002) + f = dumbdbm.open(_fname, 'c', 0o637) f.close() finally: os.umask(old_umask) - expected_mode = 0635 + expected_mode = 0o635 if os.name != 'posix': # Windows only supports setting the read-only attribute. # This shouldn't fail, but doesn't work like Unix either. - expected_mode = 0666 + expected_mode = 0o666 import stat st = os.stat(_fname + '.dat') diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index ace1f1f3c9..085768dc15 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -121,7 +121,7 @@ testboth("%#+027.23X", big, "+0X0001234567890ABCDEF12345") # same, except no 0 flag testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345") -big = 012345670123456701234567012345670 # 32 octal digits +big = 0o12345670123456701234567012345670 # 32 octal digits testboth("%o", big, "12345670123456701234567012345670") testboth("%o", -big, "-12345670123456701234567012345670") testboth("%5o", -big, "-12345670123456701234567012345670") @@ -141,33 +141,36 @@ testboth("%.33o", big, "012345670123456701234567012345670") testboth("%34.33o", big, " 012345670123456701234567012345670") testboth("%-34.33o", big, "012345670123456701234567012345670 ") testboth("%o", big, "12345670123456701234567012345670") -testboth("%#o", big, "012345670123456701234567012345670") -testboth("%#o", -big, "-012345670123456701234567012345670") -testboth("%#.34o", -big, "-0012345670123456701234567012345670") -testboth("%#+.34o", big, "+0012345670123456701234567012345670") -testboth("%# .34o", big, " 0012345670123456701234567012345670") -testboth("%#+.34o", big, "+0012345670123456701234567012345670") -testboth("%#-+.34o", big, "+0012345670123456701234567012345670") -testboth("%#-+37.34o", big, "+0012345670123456701234567012345670 ") -testboth("%#+37.34o", big, " +0012345670123456701234567012345670") +testboth("%#o", big, "0o12345670123456701234567012345670") +testboth("%#o", -big, "-0o12345670123456701234567012345670") +testboth("%#.34o", -big, "-0o0012345670123456701234567012345670") +testboth("%#+.34o", big, "+0o0012345670123456701234567012345670") +testboth("%# .34o", big, " 0o0012345670123456701234567012345670") +testboth("%#-+.34o", big, "+0o0012345670123456701234567012345670") +testboth("%#-+39.34o", big, "+0o0012345670123456701234567012345670 ") +testboth("%#+39.34o", big, " +0o0012345670123456701234567012345670") # next one gets one leading zero from precision testboth("%.33o", big, "012345670123456701234567012345670") -# base marker shouldn't change that, since "0" is redundant -testboth("%#.33o", big, "012345670123456701234567012345670") -# but reduce precision, and base marker should add a zero -testboth("%#.32o", big, "012345670123456701234567012345670") -# one leading zero from precision, and another from "0" flag & width +# one leading zero from precision +testboth("%#.33o", big, "0o012345670123456701234567012345670") +# leading zero vanishes +testboth("%#.32o", big, "0o12345670123456701234567012345670") +# one leading zero from precision, and another from '0' flag & width testboth("%034.33o", big, "0012345670123456701234567012345670") -# base marker shouldn't change that -testboth("%0#34.33o", big, "0012345670123456701234567012345670") +# max width includes base marker; padding zeroes come after marker +testboth("%0#38.33o", big, "0o000012345670123456701234567012345670") +# padding spaces come before marker +testboth("%#36.33o", big, " 0o012345670123456701234567012345670") # Some small ints, in both Python int and long flavors). testboth("%d", 42, "42") testboth("%d", -42, "-42") testboth("%#x", 1, "0x1") testboth("%#X", 1, "0X1") -testboth("%#o", 1, "01") -testboth("%#o", 0, "0") +testboth("%#o", 1, "0o1") +testboth("%#o", 1, "0o1") +testboth("%#o", 0, "0o0") +testboth("%#o", 0, "0o0") testboth("%o", 0, "0") testboth("%d", 0, "0") testboth("%#x", 0, "0x0") @@ -176,8 +179,10 @@ testboth("%#X", 0, "0X0") testboth("%x", 0x42, "42") testboth("%x", -0x42, "-42") -testboth("%o", 042, "42") -testboth("%o", -042, "-42") +testboth("%o", 0o42, "42") +testboth("%o", -0o42, "-42") +testboth("%o", 0o42, "42") +testboth("%o", -0o42, "-42") # Test exception for unknown format characters if verbose: @@ -216,14 +221,6 @@ test_exc('no format', '1', TypeError, test_exc('no format', '1', TypeError, "not all arguments converted during string formatting") -class Foobar(int): - def __oct__(self): - # Returning a non-string should not blow up. - return self + 1 - -test_exc('%o', Foobar(), TypeError, - "expected string, int found") - if maxsize == 2**31-1: # crashes 2.2.1 and earlier: try: diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 711d636f04..8f45382984 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -27,26 +27,32 @@ class TokenTests(unittest.TestCase): self.assertEquals(x, 0, 'backslash ending comment') def testPlainIntegers(self): + self.assertEquals(type(000), type(0)) self.assertEquals(0xff, 255) - self.assertEquals(0377, 255) - self.assertEquals(2147483647, 017777777777) + self.assertEquals(0o377, 255) + self.assertEquals(2147483647, 0o17777777777) + self.assertEquals(0b1001, 9) from sys import maxint if maxint == 2147483647: - self.assertEquals(-2147483647-1, -020000000000) + self.assertEquals(-2147483647-1, -0o20000000000) # XXX -2147483648 - self.assert_(037777777777 > 0) + self.assert_(0o37777777777 > 0) self.assert_(0xffffffff > 0) - for s in '2147483648', '040000000000', '0x100000000': + self.assert_(0b1111111111111111111111111111111 > 0) + for s in ('2147483648', '0o40000000000', '0x100000000', + '0b10000000000000000000000000000000'): try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) elif maxint == 9223372036854775807: - self.assertEquals(-9223372036854775807-1, -01000000000000000000000) - self.assert_(01777777777777777777777 > 0) + self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000) + self.assert_(0o1777777777777777777777 > 0) self.assert_(0xffffffffffffffff > 0) - for s in '9223372036854775808', '02000000000000000000000', \ - '0x10000000000000000': + self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0) + for s in '9223372036854775808', '0o2000000000000000000000', \ + '0x10000000000000000', \ + '0b100000000000000000000000000000000000000000000000000000000000000': try: x = eval(s) except OverflowError: @@ -56,13 +62,13 @@ class TokenTests(unittest.TestCase): def testLongIntegers(self): x = 0 - x = 0 - x = 0xffffffffffffffff x = 0xffffffffffffffff - x = 077777777777777777 - x = 077777777777777777 - x = 123456789012345678901234567890 + x = 0Xffffffffffffffff + x = 0o77777777777777777 + x = 0O77777777777777777 x = 123456789012345678901234567890 + x = 0b100000000000000000000000000000000000000000000000000000000000000000000 + x = 0B111111111111111111111111111111111111111111111111111111111111111111111 def testFloats(self): x = 3.14 diff --git a/Lib/test/test_hexoct.py b/Lib/test/test_hexoct.py index 5e86beabab..afd696afc5 100644 --- a/Lib/test/test_hexoct.py +++ b/Lib/test/test_hexoct.py @@ -65,49 +65,49 @@ class TextHexOct(unittest.TestCase): def test_oct_baseline(self): # Baseline tests self.assertEqual(00, 0) - self.assertEqual(020, 16) + self.assertEqual(0o20, 16) if platform_long_is_32_bits: - self.assertEqual(017777777777, 2147483647) + self.assertEqual(0o17777777777, 2147483647) else: - self.assertEqual(0777777777777777777777, 9223372036854775807) + self.assertEqual(0o777777777777777777777, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(00), 0) - self.assertEqual(-(020), -16) + self.assertEqual(-(0o20), -16) if platform_long_is_32_bits: - self.assertEqual(-(017777777777), -2147483647) + self.assertEqual(-(0o17777777777), -2147483647) else: - self.assertEqual(-(0777777777777777777777), -9223372036854775807) + self.assertEqual(-(0o777777777777777777777), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-00, 0) - self.assertEqual(-020, -16) + self.assertEqual(-0o20, -16) if platform_long_is_32_bits: - self.assertEqual(-017777777777, -2147483647) + self.assertEqual(-0o17777777777, -2147483647) else: - self.assertEqual(-0777777777777777777777, -9223372036854775807) + self.assertEqual(-0o777777777777777777777, -9223372036854775807) def test_oct_unsigned(self): if platform_long_is_32_bits: # Positive constants - self.assertEqual(020000000000, 2147483648) - self.assertEqual(037777777777, 4294967295) + self.assertEqual(0o20000000000, 2147483648) + self.assertEqual(0o37777777777, 4294967295) # Ditto with a minus sign and parentheses - self.assertEqual(-(020000000000), -2147483648) - self.assertEqual(-(037777777777), -4294967295) + self.assertEqual(-(0o20000000000), -2147483648) + self.assertEqual(-(0o37777777777), -4294967295) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-020000000000, -2147483648) - self.assertEqual(-037777777777, -4294967295) + self.assertEqual(-0o20000000000, -2147483648) + self.assertEqual(-0o37777777777, -4294967295) else: # Positive constants - self.assertEqual(01000000000000000000000, 9223372036854775808) - self.assertEqual(01777777777777777777777, 18446744073709551615) + self.assertEqual(0o1000000000000000000000, 9223372036854775808) + self.assertEqual(0o1777777777777777777777, 18446744073709551615) # Ditto with a minus sign and parentheses - self.assertEqual(-(01000000000000000000000), -9223372036854775808) - self.assertEqual(-(01777777777777777777777), -18446744073709551615) + self.assertEqual(-(0o1000000000000000000000), -9223372036854775808) + self.assertEqual(-(0o1777777777777777777777), -18446744073709551615) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 - self.assertEqual(-01000000000000000000000, -9223372036854775808) - self.assertEqual(-01777777777777777777777, -18446744073709551615) + self.assertEqual(-0o1000000000000000000000, -9223372036854775808) + self.assertEqual(-0o1777777777777777777777, -18446744073709551615) def test_main(): test_support.run_unittest(TextHexOct) diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py index ea78773f7b..f7f561ad73 100644 --- a/Lib/test/test_list.py +++ b/Lib/test/test_list.py @@ -5,7 +5,7 @@ class ListTest(list_tests.CommonTest): type2test = list def test_truth(self): - super(ListTest, self).test_truth() + super().test_truth() self.assert_(not []) self.assert_([42]) @@ -13,7 +13,7 @@ class ListTest(list_tests.CommonTest): self.assert_([] is not []) def test_len(self): - super(ListTest, self).test_len() + super().test_len() self.assertEqual(len([]), 0) self.assertEqual(len([0]), 1) self.assertEqual(len([0, 1, 2]), 3) diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py index c38056da0f..9e56d31c8c 100644 --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -195,9 +195,6 @@ class LongTest(unittest.TestCase): self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2)) def slow_format(self, x, base): - if (x, base) == (0, 8): - # this is an oddball! - return "0" digits = [] sign = 0 if x < 0: @@ -208,7 +205,7 @@ class LongTest(unittest.TestCase): digits.reverse() digits = digits or [0] return '-'[:sign] + \ - {8: '0', 10: '', 16: '0x'}[base] + \ + {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \ "".join(map(lambda i: "0123456789abcdef"[i], digits)) def check_format_1(self, x): diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py index f41ad34caf..472f6204b4 100644 --- a/Lib/test/test_multibytecodec.py +++ b/Lib/test/test_multibytecodec.py @@ -136,6 +136,16 @@ class Test_IncrementalDecoder(unittest.TestCase): self.assertRaises(UnicodeDecodeError, decoder.decode, '', True) self.assertEqual(decoder.decode('B@$'), '\u4e16') +class Test_StreamReader(unittest.TestCase): + def test_bug1728403(self): + try: + open(TESTFN, 'w').write('\xa1') + f = codecs.open(TESTFN, encoding='cp949') + self.assertRaises(UnicodeDecodeError, f.read, 2) + finally: + try: f.close() + except: pass + os.unlink(TESTFN) class Test_StreamWriter(unittest.TestCase): if len('\U00012345') == 2: # UCS2 diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py index b290198514..28ad055641 100644 --- a/Lib/test/test_peepholer.py +++ b/Lib/test/test_peepholer.py @@ -39,16 +39,24 @@ class TestTranforms(unittest.TestCase): asm = dis_single(line) self.assert_(elem in asm) - def test_none_as_constant(self): - # LOAD_GLOBAL None --> LOAD_CONST None + def test_global_as_constant(self): + # LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False def f(x): None + None return x - asm = disassemble(f) - for elem in ('LOAD_GLOBAL',): - self.assert_(elem not in asm) - for elem in ('LOAD_CONST', '(None)'): - self.assert_(elem in asm) + def g(x): + True + return x + def h(x): + False + return x + for func, name in ((f, 'None'), (g, 'True'), (h, 'False')): + asm = disassemble(func) + for elem in ('LOAD_GLOBAL',): + self.assert_(elem not in asm) + for elem in ('LOAD_CONST', '('+name+')'): + self.assert_(elem in asm) def f(): 'Adding a docstring made this test fail in Py2.5.0' return None diff --git a/Lib/test/test_pep352.py b/Lib/test/test_pep352.py index 90766ba505..dc47737feb 100644 --- a/Lib/test/test_pep352.py +++ b/Lib/test/test_pep352.py @@ -131,22 +131,22 @@ class UsageTests(unittest.TestCase): """Catching 'object_' should raise a TypeError.""" try: try: - raise StandardError + raise Exception except object_: pass except TypeError: pass - except StandardError: + except Exception: self.fail("TypeError expected when catching %s" % type(object_)) try: try: - raise StandardError + raise Exception except (object_,): pass except TypeError: return - except StandardError: + except Exception: self.fail("TypeError expected when catching %s as specified in a " "tuple" % type(object_)) diff --git a/Lib/test/test_repr.py b/Lib/test/test_repr.py index 5059c08c98..d4db894f5f 100644 --- a/Lib/test/test_repr.py +++ b/Lib/test/test_repr.py @@ -10,6 +10,7 @@ import unittest from test.test_support import run_unittest from repr import repr as r # Don't shadow builtin repr +from repr import Repr def nestedTuple(nesting): @@ -34,6 +35,18 @@ class ReprTests(unittest.TestCase): expected = repr(s)[:13] + "..." + repr(s)[-14:] eq(r(s), expected) + def test_tuple(self): + eq = self.assertEquals + eq(r((1,)), "(1,)") + + t3 = (1, 2, 3) + eq(r(t3), "(1, 2, 3)") + + r2 = Repr() + r2.maxtuple = 2 + expected = repr(t3)[:-2] + "...)" + eq(r2.repr(t3), expected) + def test_container(self): from array import array from collections import deque diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 6fa377966f..2ef01f00dd 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -1,4 +1,7 @@ + import unittest +import struct +import sys from test import test_support, string_tests @@ -88,6 +91,15 @@ class StrTest( self.assertEqual(str8(Foo9("foo")), "string") self.assertEqual(str(Foo9("foo")), "not unicode") + def test_expandtabs_overflows_gracefully(self): + # This test only affects 32-bit platforms because expandtabs can only take + # an int as the max value, not a 64-bit C long. If expandtabs is changed + # to take a 64-bit long, this test should apply to all platforms. + if sys.maxint > (1 << 32) or struct.calcsize('P') != 4: + return + self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxint) + + def test_main(): test_support.run_unittest(StrTest) diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index 0e1909eb42..81f83927eb 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -190,6 +190,15 @@ class TimeRETests(unittest.TestCase): "locale data that contains regex metacharacters is not" " properly escaped") + def test_whitespace_substitution(self): + # When pattern contains whitespace, make sure it is taken into account + # so as to not allow to subpatterns to end up next to each other and + # "steal" characters from each other. + pattern = self.time_re.pattern('%j %H') + self.failUnless(not re.match(pattern, "180")) + self.failUnless(re.match(pattern, "18 0")) + + class StrptimeTests(unittest.TestCase): """Tests for _strptime.strptime.""" @@ -463,8 +472,8 @@ class CalculationTests(unittest.TestCase): "of the year") test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " "ending on Monday") - test_helper((2007, 01, 07), "First Sunday of 2007") - test_helper((2007, 01, 14), "Second Sunday of 2007") + test_helper((2007, 1, 7), "First Sunday of 2007") + test_helper((2007, 1, 14), "Second Sunday of 2007") test_helper((2006, 12, 31), "Last Sunday of 2006") test_helper((2006, 12, 24), "Second to last Sunday of 2006") diff --git a/Lib/test/test_structmembers.py b/Lib/test/test_structmembers.py index 599c6fb9cb..c3d01c876f 100644 --- a/Lib/test/test_structmembers.py +++ b/Lib/test/test_structmembers.py @@ -2,7 +2,8 @@ from _testcapi import test_structmembersType, \ CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ SHRT_MAX, SHRT_MIN, USHRT_MAX, \ INT_MAX, INT_MIN, UINT_MAX, \ - LONG_MAX, LONG_MIN, ULONG_MAX + LONG_MAX, LONG_MIN, ULONG_MAX, \ + LLONG_MAX, LLONG_MIN, ULLONG_MAX import warnings, unittest from test import test_support @@ -39,6 +40,23 @@ class ReadWriteTests(unittest.TestCase): ts.T_ULONG=ULONG_MAX self.assertEquals(ts.T_ULONG, ULONG_MAX) + ## T_LONGLONG and T_ULONGLONG may not be present on some platforms + if hasattr(ts, 'T_LONGLONG'): + ts.T_LONGLONG=LLONG_MAX + self.assertEquals(ts.T_LONGLONG, LLONG_MAX) + ts.T_LONGLONG=LLONG_MIN + self.assertEquals(ts.T_LONGLONG, LLONG_MIN) + + ts.T_ULONGLONG=ULLONG_MAX + self.assertEquals(ts.T_ULONGLONG, ULLONG_MAX) + + ## make sure these will accept a plain int as well as a long + ts.T_LONGLONG=3 + self.assertEquals(ts.T_LONGLONG, 3) + ts.T_ULONGLONG=4 + self.assertEquals(ts.T_ULONGLONG, 4) + + class TestWarnings(unittest.TestCase): def has_warned(self, w): self.assert_(w.category is RuntimeWarning) diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index b44e83a57b..2421a6b110 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -528,7 +528,7 @@ class ProcessTestCase(unittest.TestCase): os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" % sys.executable) os.close(f) - os.chmod(fname, 0700) + os.chmod(fname, 0o700) p = subprocess.Popen(fname) p.wait() os.remove(fname) @@ -570,7 +570,7 @@ class ProcessTestCase(unittest.TestCase): os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" % sys.executable) os.close(f) - os.chmod(fname, 0700) + os.chmod(fname, 0o700) rc = subprocess.call(fname) os.remove(fname) self.assertEqual(rc, 47) diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py index 3c0346da56..28a08c5cd3 100644 --- a/Lib/test/test_sundry.py +++ b/Lib/test/test_sundry.py @@ -1,6 +1,7 @@ """Do a minimal test of all the modules that aren't otherwise tested.""" from test.test_support import guard_warnings_filter +import sys import warnings with guard_warnings_filter(): @@ -18,6 +19,53 @@ with guard_warnings_filter(): import cmd import code import compileall + + import distutils.archive_util + import distutils.bcppcompiler + import distutils.ccompiler + import distutils.cmd + import distutils.core + import distutils.cygwinccompiler + import distutils.dep_util + import distutils.dir_util + import distutils.emxccompiler + import distutils.errors + import distutils.extension + import distutils.file_util + import distutils.filelist + import distutils.log + if sys.platform.startswith('win'): + import distutils.msvccompiler + import distutils.mwerkscompiler + import distutils.sysconfig + import distutils.text_file + import distutils.unixccompiler + import distutils.util + import distutils.version + + import distutils.command.bdist_dumb + if sys.platform.startswith('win'): + import distutils.command.bdist_msi + import distutils.command.bdist + import distutils.command.bdist_rpm + import distutils.command.bdist_wininst + import distutils.command.build_clib + import distutils.command.build_ext + import distutils.command.build + import distutils.command.build_py + import distutils.command.build_scripts + import distutils.command.clean + import distutils.command.config + import distutils.command.install_data + import distutils.command.install_egg_info + import distutils.command.install_headers + import distutils.command.install_lib + import distutils.command.install + import distutils.command.install_scripts + import distutils.command.register + import distutils.command.sdist + import distutils.command.upload + import encodings import formatter import ftplib @@ -37,7 +85,6 @@ with guard_warnings_filter(): import os2emxpath import pdb import pipes - #import poplib import pstats import py_compile import pydoc diff --git a/Lib/test/test_super.py b/Lib/test/test_super.py new file mode 100644 index 0000000000..fc303eac73 --- /dev/null +++ b/Lib/test/test_super.py @@ -0,0 +1,79 @@ +"""Unit tests for new super() implementation.""" + +import sys +import unittest +from test import test_support + + +class A: + def f(self): + return 'A' + @classmethod + def cm(cls): + return (cls, 'A') + +class B(A): + def f(self): + return super().f() + 'B' + @classmethod + def cm(cls): + return (cls, super().cm(), 'B') + +class C(A): + def f(self): + return super().f() + 'C' + @classmethod + def cm(cls): + return (cls, super().cm(), 'C') + +class D(C, B): + def f(self): + return super().f() + 'D' + def cm(cls): + return (cls, super().cm(), 'D') + +class E(D): + pass + +class F(E): + f = E.f + +class G(A): + pass + + +class TestSuper(unittest.TestCase): + + def testBasicsWorking(self): + self.assertEqual(D().f(), 'ABCD') + + def testClassGetattrWorking(self): + self.assertEqual(D.f(D()), 'ABCD') + + def testSubclassNoOverrideWorking(self): + self.assertEqual(E().f(), 'ABCD') + self.assertEqual(E.f(E()), 'ABCD') + + def testUnboundMethodTransferWorking(self): + self.assertEqual(F().f(), 'ABCD') + self.assertEqual(F.f(F()), 'ABCD') + + def testClassMethodsStillWorking(self): + self.assertEqual(A.cm(), (A, 'A')) + self.assertEqual(A().cm(), (A, 'A')) + self.assertEqual(G.cm(), (G, 'A')) + self.assertEqual(G().cm(), (G, 'A')) + + def testSuperInClassMethodsWorking(self): + d = D() + self.assertEqual(d.cm(), (d, (D, (D, (D, 'A'), 'B'), 'C'), 'D')) + e = E() + self.assertEqual(e.cm(), (e, (E, (E, (E, 'A'), 'B'), 'C'), 'D')) + + +def test_main(): + test_support.run_unittest(TestSuper) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index 39504e1452..50c5bbede7 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -164,7 +164,7 @@ class MiscReadTest(ReadTest): def test_check_members(self): for tarinfo in self.tar: - self.assert_(int(tarinfo.mtime) == 07606136617, + self.assert_(int(tarinfo.mtime) == 0o7606136617, "wrong mtime for %s" % tarinfo.name) if not tarinfo.name.startswith("ustar/"): continue @@ -299,7 +299,7 @@ class MemberReadTest(ReadTest): self.assert_(md5sum(self.tar.extractfile(tarinfo).read()) == chksum, "wrong md5sum for %s" % tarinfo.name) - kwargs["mtime"] = 07606136617 + kwargs["mtime"] = 0o7606136617 kwargs["uid"] = 1000 kwargs["gid"] = 100 if "old-v7" not in tarinfo.name: @@ -978,7 +978,7 @@ class LimitsTest(unittest.TestCase): # uid > 8 digits tarinfo = tarfile.TarInfo("name") - tarinfo.uid = 010000000 + tarinfo.uid = 0o10000000 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT) def test_gnu_limits(self): @@ -991,7 +991,7 @@ class LimitsTest(unittest.TestCase): # uid >= 256 ** 7 tarinfo = tarfile.TarInfo("name") - tarinfo.uid = 04000000000000000000 + tarinfo.uid = 0o4000000000000000000 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT) def test_pax_limits(self): @@ -1003,7 +1003,7 @@ class LimitsTest(unittest.TestCase): tarinfo.tobuf(tarfile.PAX_FORMAT) tarinfo = tarfile.TarInfo("name") - tarinfo.uid = 04000000000000000000 + tarinfo.uid = 0o4000000000000000000 tarinfo.tobuf(tarfile.PAX_FORMAT) diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 8c2eb23d20..caa8f4e734 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -264,7 +264,7 @@ class test__mkstemp_inner(TC): file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) - expected = 0600 + expected = 0o600 if sys.platform in ('win32', 'os2emx', 'mac'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. @@ -482,8 +482,8 @@ class test_mkdtemp(TC): dir = self.do_create() try: mode = stat.S_IMODE(os.stat(dir).st_mode) - mode &= 0777 # Mask off sticky bits inherited from /tmp - expected = 0700 + mode &= 0o777 # Mask off sticky bits inherited from /tmp + expected = 0o700 if sys.platform in ('win32', 'os2emx', 'mac'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. @@ -517,7 +517,7 @@ class test_mktemp(TC): self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf) # Create the file. This will raise an exception if it's # mysteriously appeared in the meanwhile. - os.close(os.open(self.name, self._bflags, 0600)) + os.close(os.open(self.name, self._bflags, 0o600)) def __del__(self): self._unlink(self.name) diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index 95557c0ce1..b76cea14e0 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -3,6 +3,7 @@ import test.test_support from test.test_support import verbose import random +import sys import threading import thread import time @@ -201,8 +202,47 @@ class ThreadTests(unittest.TestCase): t.join() # else the thread is still running, and we have no way to kill it +class ThreadingExceptionTests(unittest.TestCase): + # A RuntimeError should be raised if Thread.start() is called + # multiple times. + def test_start_thread_again(self): + thread = threading.Thread() + thread.start() + self.assertRaises(RuntimeError, thread.start) + + def test_releasing_unacquired_rlock(self): + rlock = threading.RLock() + self.assertRaises(RuntimeError, rlock.release) + + def test_waiting_on_unacquired_condition(self): + cond = threading.Condition() + self.assertRaises(RuntimeError, cond.wait) + + def test_notify_on_unacquired_condition(self): + cond = threading.Condition() + self.assertRaises(RuntimeError, cond.notify) + + def test_semaphore_with_negative_value(self): + self.assertRaises(ValueError, threading.Semaphore, value = -1) + self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxint) + + def test_joining_current_thread(self): + currentThread = threading.currentThread() + self.assertRaises(RuntimeError, currentThread.join); + + def test_joining_inactive_thread(self): + thread = threading.Thread() + self.assertRaises(RuntimeError, thread.join) + + def test_daemonize_active_thread(self): + thread = threading.Thread() + thread.start() + self.assertRaises(RuntimeError, thread.setDaemon, True) + + def test_main(): - test.test_support.run_unittest(ThreadTests) + test.test_support.run_unittest(ThreadTests, + ThreadingExceptionTests) if __name__ == "__main__": test_main() diff --git a/Lib/test/test_tuple.py b/Lib/test/test_tuple.py index 00dcd393d7..1da0ef35d8 100644 --- a/Lib/test/test_tuple.py +++ b/Lib/test/test_tuple.py @@ -5,30 +5,30 @@ class TupleTest(seq_tests.CommonTest): type2test = tuple def test_constructors(self): - super(TupleTest, self).test_len() + super().test_len() # calling built-in types without argument must return empty self.assertEqual(tuple(), ()) def test_truth(self): - super(TupleTest, self).test_truth() + super().test_truth() self.assert_(not ()) self.assert_((42, )) def test_len(self): - super(TupleTest, self).test_len() + super().test_len() self.assertEqual(len(()), 0) self.assertEqual(len((0,)), 1) self.assertEqual(len((0, 1, 2)), 3) def test_iadd(self): - super(TupleTest, self).test_iadd() + super().test_iadd() u = (0, 1) u2 = u u += (2, 3) self.assert_(u is not u2) def test_imul(self): - super(TupleTest, self).test_imul() + super().test_imul() u = (0, 1) u2 = u u *= 3 diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py index 76674d5c71..fbad9843b8 100644 --- a/Lib/test/test_unicode.py +++ b/Lib/test/test_unicode.py @@ -6,7 +6,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" -import unittest, sys, codecs, new +import unittest, sys, struct, codecs, new from test import test_support, string_tests # Error handling (bad decoder return) @@ -785,8 +785,13 @@ class UnicodeTest( self.assertEqual(repr(s1()), '\\n') self.assertEqual(repr(s2()), '\\n') - - + def test_expandtabs_overflows_gracefully(self): + # This test only affects 32-bit platforms because expandtabs can only take + # an int as the max value, not a 64-bit C long. If expandtabs is changed + # to take a 64-bit long, this test should apply to all platforms. + if sys.maxint > (1 << 32) or struct.calcsize('P') != 4: + return + self.assertRaises(OverflowError, u't\tt\t'.expandtabs, sys.maxint) def test_main(): diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py index 2fc64cda0e..9cf48df816 100644 --- a/Lib/test/test_unicode_file.py +++ b/Lib/test/test_unicode_file.py @@ -48,7 +48,7 @@ class TestUnicodeFiles(unittest.TestCase): self.failUnless(os.path.exists(os.path.abspath(filename))) self.failUnless(os.path.isfile(os.path.abspath(filename))) self.failUnless(os.access(os.path.abspath(filename), os.R_OK)) - os.chmod(filename, 0777) + os.chmod(filename, 0o777) os.utime(filename, None) os.utime(filename, (time.time(), time.time())) # Copy/rename etc tests using the same filename diff --git a/Lib/test/test_unittest.py b/Lib/test/test_unittest.py index 327d65fbf3..98066e436c 100644 --- a/Lib/test/test_unittest.py +++ b/Lib/test/test_unittest.py @@ -16,23 +16,23 @@ from unittest import TestCase class LoggingResult(unittest.TestResult): def __init__(self, log): self._events = log - super(LoggingResult, self).__init__() + super().__init__() def startTest(self, test): self._events.append('startTest') - super(LoggingResult, self).startTest(test) + super().startTest(test) def stopTest(self, test): self._events.append('stopTest') - super(LoggingResult, self).stopTest(test) + super().stopTest(test) def addFailure(self, *args): self._events.append('addFailure') - super(LoggingResult, self).addFailure(*args) + super().addFailure(*args) def addError(self, *args): self._events.append('addError') - super(LoggingResult, self).addError(*args) + super().addError(*args) class TestEquality(object): # Check for a valid __eq__ implementation diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 10d8c46dea..dbcfe26de3 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -544,7 +544,7 @@ class HandlerTests(unittest.TestCase): class NullFTPHandler(urllib2.FTPHandler): def __init__(self, data): self.data = data - def connect_ftp(self, user, passwd, host, port, dirs): + def connect_ftp(self, user, passwd, host, port, dirs, timeout=None): self.user, self.passwd = user, passwd self.host, self.port = host, port self.dirs = dirs @@ -567,7 +567,9 @@ class HandlerTests(unittest.TestCase): "localhost", ftplib.FTP_PORT, "A", [], "baz.gif", None), # XXX really this should guess image/gif ]: - r = h.ftp_open(Request(url)) + req = Request(url) + req.timeout = None + r = h.ftp_open(req) # ftp authentication not yet implemented by FTPHandler self.assert_(h.user == h.passwd == "") self.assertEqual(h.host, socket.gethostbyname(host)) @@ -682,8 +684,9 @@ class HandlerTests(unittest.TestCase): self.req_headers = [] self.data = None self.raise_on_endheaders = False - def __call__(self, host): + def __call__(self, host, timeout=None): self.host = host + self.timeout = timeout return self def set_debuglevel(self, level): self.level = level @@ -706,6 +709,7 @@ class HandlerTests(unittest.TestCase): url = "http://example.com/" for method, data in [("GET", None), ("POST", "blah")]: req = Request(url, data, {"Foo": "bar"}) + req.timeout = None req.add_unredirected_header("Spam", "eggs") http = MockHTTPClass() r = h.do_open(http, req) diff --git a/Lib/test/test_urllib2_localnet.py b/Lib/test/test_urllib2_localnet.py new file mode 100644 index 0000000000..737ecbd2b1 --- /dev/null +++ b/Lib/test/test_urllib2_localnet.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python + +import sys +import threading +import urlparse +import urllib2 +import BaseHTTPServer +import unittest +import hashlib +from test import test_support + +# Loopback http server infrastructure + +class LoopbackHttpServer(BaseHTTPServer.HTTPServer): + """HTTP server w/ a few modifications that make it useful for + loopback testing purposes. + """ + + def __init__(self, server_address, RequestHandlerClass): + BaseHTTPServer.HTTPServer.__init__(self, + server_address, + RequestHandlerClass) + + # Set the timeout of our listening socket really low so + # that we can stop the server easily. + self.socket.settimeout(1.0) + + def get_request(self): + """BaseHTTPServer method, overridden.""" + + request, client_address = self.socket.accept() + + # It's a loopback connection, so setting the timeout + # really low shouldn't affect anything, but should make + # deadlocks less likely to occur. + request.settimeout(10.0) + + return (request, client_address) + +class LoopbackHttpServerThread(threading.Thread): + """Stoppable thread that runs a loopback http server.""" + + def __init__(self, port, RequestHandlerClass): + threading.Thread.__init__(self) + self._RequestHandlerClass = RequestHandlerClass + self._stop = False + self._port = port + self._server_address = ('127.0.0.1', self._port) + self.ready = threading.Event() + self.error = None + + def stop(self): + """Stops the webserver if it's currently running.""" + + # Set the stop flag. + self._stop = True + + self.join() + + def run(self): + protocol = "HTTP/1.0" + + try: + self._RequestHandlerClass.protocol_version = protocol + httpd = LoopbackHttpServer(self._server_address, + self._RequestHandlerClass) + + sa = httpd.socket.getsockname() + #print "Serving HTTP on", sa[0], "port", sa[1], "..." + except: + # Fail "gracefully" if we are unable to start. + self.ready.set() + self.error = sys.exc_info()[1] + raise + + self.ready.set() + while not self._stop: + httpd.handle_request() + +# Authentication infrastructure + +class DigestAuthHandler: + """Handler for performing digest authentication.""" + + def __init__(self): + self._request_num = 0 + self._nonces = [] + self._users = {} + self._realm_name = "Test Realm" + self._qop = "auth" + + def set_qop(self, qop): + self._qop = qop + + def set_users(self, users): + assert isinstance(users, dict) + self._users = users + + def set_realm(self, realm): + self._realm_name = realm + + def _generate_nonce(self): + self._request_num += 1 + nonce = hashlib.md5(str(self._request_num)).hexdigest() + self._nonces.append(nonce) + return nonce + + def _create_auth_dict(self, auth_str): + first_space_index = auth_str.find(" ") + auth_str = auth_str[first_space_index+1:] + + parts = auth_str.split(",") + + auth_dict = {} + for part in parts: + name, value = part.split("=") + name = name.strip() + if value[0] == '"' and value[-1] == '"': + value = value[1:-1] + else: + value = value.strip() + auth_dict[name] = value + return auth_dict + + def _validate_auth(self, auth_dict, password, method, uri): + final_dict = {} + final_dict.update(auth_dict) + final_dict["password"] = password + final_dict["method"] = method + final_dict["uri"] = uri + HA1_str = "%(username)s:%(realm)s:%(password)s" % final_dict + HA1 = hashlib.md5(HA1_str).hexdigest() + HA2_str = "%(method)s:%(uri)s" % final_dict + HA2 = hashlib.md5(HA2_str).hexdigest() + final_dict["HA1"] = HA1 + final_dict["HA2"] = HA2 + response_str = "%(HA1)s:%(nonce)s:%(nc)s:" \ + "%(cnonce)s:%(qop)s:%(HA2)s" % final_dict + response = hashlib.md5(response_str).hexdigest() + + return response == auth_dict["response"] + + def _return_auth_challenge(self, request_handler): + request_handler.send_response(407, "Proxy Authentication Required") + request_handler.send_header("Content-Type", "text/html") + request_handler.send_header( + 'Proxy-Authenticate', 'Digest realm="%s", ' + 'qop="%s",' + 'nonce="%s", ' % \ + (self._realm_name, self._qop, self._generate_nonce())) + # XXX: Not sure if we're supposed to add this next header or + # not. + #request_handler.send_header('Connection', 'close') + request_handler.end_headers() + request_handler.wfile.write("Proxy Authentication Required.") + return False + + def handle_request(self, request_handler): + """Performs digest authentication on the given HTTP request + handler. Returns True if authentication was successful, False + otherwise. + + If no users have been set, then digest auth is effectively + disabled and this method will always return True. + """ + + if len(self._users) == 0: + return True + + if 'Proxy-Authorization' not in request_handler.headers: + return self._return_auth_challenge(request_handler) + else: + auth_dict = self._create_auth_dict( + request_handler.headers['Proxy-Authorization'] + ) + if auth_dict["username"] in self._users: + password = self._users[ auth_dict["username"] ] + else: + return self._return_auth_challenge(request_handler) + if not auth_dict.get("nonce") in self._nonces: + return self._return_auth_challenge(request_handler) + else: + self._nonces.remove(auth_dict["nonce"]) + + auth_validated = False + + # MSIE uses short_path in its validation, but Python's + # urllib2 uses the full path, so we're going to see if + # either of them works here. + + for path in [request_handler.path, request_handler.short_path]: + if self._validate_auth(auth_dict, + password, + request_handler.command, + path): + auth_validated = True + + if not auth_validated: + return self._return_auth_challenge(request_handler) + return True + +# Proxy test infrastructure + +class FakeProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): + """This is a 'fake proxy' that makes it look like the entire + internet has gone down due to a sudden zombie invasion. It main + utility is in providing us with authentication support for + testing. + """ + + digest_auth_handler = DigestAuthHandler() + + def log_message(self, format, *args): + # Uncomment the next line for debugging. + #sys.stderr.write(format % args) + pass + + def do_GET(self): + (scm, netloc, path, params, query, fragment) = urlparse.urlparse( + self.path, 'http') + self.short_path = path + if self.digest_auth_handler.handle_request(self): + self.send_response(200, "OK") + self.send_header("Content-Type", "text/html") + self.end_headers() + self.wfile.write("You've reached %s!<BR>" % self.path) + self.wfile.write("Our apologies, but our server is down due to " + "a sudden zombie invasion.") + +# Test cases + +class ProxyAuthTests(unittest.TestCase): + URL = "http://www.foo.com" + + PORT = 8080 + USER = "tester" + PASSWD = "test123" + REALM = "TestRealm" + + PROXY_URL = "http://127.0.0.1:%d" % PORT + + def setUp(self): + FakeProxyHandler.digest_auth_handler.set_users({ + self.USER : self.PASSWD + }) + FakeProxyHandler.digest_auth_handler.set_realm(self.REALM) + + self.server = LoopbackHttpServerThread(self.PORT, FakeProxyHandler) + self.server.start() + self.server.ready.wait() + if self.server.error: + raise self.server.error + + handler = urllib2.ProxyHandler({"http" : self.PROXY_URL}) + self._digest_auth_handler = urllib2.ProxyDigestAuthHandler() + self.opener = urllib2.build_opener(handler, self._digest_auth_handler) + + def tearDown(self): + self.server.stop() + + def test_proxy_with_bad_password_raises_httperror(self): + self._digest_auth_handler.add_password(self.REALM, self.URL, + self.USER, self.PASSWD+"bad") + FakeProxyHandler.digest_auth_handler.set_qop("auth") + self.assertRaises(urllib2.HTTPError, + self.opener.open, + self.URL) + + def test_proxy_with_no_password_raises_httperror(self): + FakeProxyHandler.digest_auth_handler.set_qop("auth") + self.assertRaises(urllib2.HTTPError, + self.opener.open, + self.URL) + + def test_proxy_qop_auth_works(self): + self._digest_auth_handler.add_password(self.REALM, self.URL, + self.USER, self.PASSWD) + FakeProxyHandler.digest_auth_handler.set_qop("auth") + result = self.opener.open(self.URL) + while result.read(): + pass + result.close() + + def test_proxy_qop_auth_int_works_or_throws_urlerror(self): + self._digest_auth_handler.add_password(self.REALM, self.URL, + self.USER, self.PASSWD) + FakeProxyHandler.digest_auth_handler.set_qop("auth-int") + try: + result = self.opener.open(self.URL) + except urllib2.URLError: + # It's okay if we don't support auth-int, but we certainly + # shouldn't receive any kind of exception here other than + # a URLError. + result = None + if result: + while result.read(): + pass + result.close() + +def test_main(): + # We will NOT depend on the network resource flag + # (Lib/test/regrtest.py -u network) since all tests here are only + # localhost. However, if this is a bad rationale, then uncomment + # the next line. + #test_support.requires("network") + + test_support.run_unittest(ProxyAuthTests) + +if __name__ == "__main__": + test_main() diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index 537b738d80..89ddaa4390 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -267,6 +267,49 @@ class OtherNetworkTests(unittest.TestCase): return handlers +class TimeoutTest(unittest.TestCase): + def test_http_basic(self): + u = urllib2.urlopen("http://www.python.org") + self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) + + def test_http_NoneWithdefault(self): + prev = socket.getdefaulttimeout() + socket.setdefaulttimeout(60) + try: + u = urllib2.urlopen("http://www.python.org", timeout=None) + self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60) + finally: + socket.setdefaulttimeout(prev) + + def test_http_Value(self): + u = urllib2.urlopen("http://www.python.org", timeout=120) + self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120) + + def test_http_NoneNodefault(self): + u = urllib2.urlopen("http://www.python.org", timeout=None) + self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) + + def test_ftp_basic(self): + u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/") + self.assertTrue(u.fp.fp._sock.gettimeout() is None) + + def test_ftp_NoneWithdefault(self): + prev = socket.getdefaulttimeout() + socket.setdefaulttimeout(60) + try: + u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=None) + self.assertEqual(u.fp.fp._sock.gettimeout(), 60) + finally: + socket.setdefaulttimeout(prev) + + def test_ftp_NoneNodefault(self): + u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=None) + self.assertTrue(u.fp.fp._sock.gettimeout() is None) + + def test_ftp_Value(self): + u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=60) + self.assertEqual(u.fp.fp._sock.gettimeout(), 60) + def test_main(): test_support.requires("network") @@ -275,6 +318,7 @@ def test_main(): AuthTests, OtherNetworkTests, CloseSocketTest, + TimeoutTest, ) if __name__ == "__main__": diff --git a/Lib/test/test_userlist.py b/Lib/test/test_userlist.py index fc9508f8cc..32c7733f09 100644 --- a/Lib/test/test_userlist.py +++ b/Lib/test/test_userlist.py @@ -8,7 +8,7 @@ class UserListTest(list_tests.CommonTest): type2test = UserList def test_getslice(self): - super(UserListTest, self).test_getslice() + super().test_getslice() l = [0, 1, 2, 3, 4] u = self.type2test(l) for i in range(-3, 6): @@ -30,7 +30,7 @@ class UserListTest(list_tests.CommonTest): self.assertEqual(u2, list("spameggs")) def test_iadd(self): - super(UserListTest, self).test_iadd() + super().test_iadd() u = [0, 1] u += UserList([0, 1]) self.assertEqual(u, [0, 1, 0, 1]) diff --git a/Lib/test/test_uu.py b/Lib/test/test_uu.py index 548cafb401..181e361d17 100644 --- a/Lib/test/test_uu.py +++ b/Lib/test/test_uu.py @@ -24,21 +24,21 @@ class UUTest(unittest.TestCase): inp = cStringIO.StringIO(plaintext) out = cStringIO.StringIO() uu.encode(inp, out, "t1") - self.assertEqual(out.getvalue(), encodedtextwrapped % (0666, "t1")) + self.assertEqual(out.getvalue(), encodedtextwrapped % (0o666, "t1")) inp = cStringIO.StringIO(plaintext) out = cStringIO.StringIO() - uu.encode(inp, out, "t1", 0644) - self.assertEqual(out.getvalue(), encodedtextwrapped % (0644, "t1")) + uu.encode(inp, out, "t1", 0o644) + self.assertEqual(out.getvalue(), encodedtextwrapped % (0o644, "t1")) def test_decode(self): - inp = cStringIO.StringIO(encodedtextwrapped % (0666, "t1")) + inp = cStringIO.StringIO(encodedtextwrapped % (0o666, "t1")) out = cStringIO.StringIO() uu.decode(inp, out) self.assertEqual(out.getvalue(), plaintext) inp = cStringIO.StringIO( "UUencoded files may contain many lines,\n" + "even some that have 'begin' in them.\n" + - encodedtextwrapped % (0666, "t1") + encodedtextwrapped % (0o666, "t1") ) out = cStringIO.StringIO() uu.decode(inp, out) @@ -75,14 +75,14 @@ class UUStdIOTest(unittest.TestCase): def test_encode(self): sys.stdin = cStringIO.StringIO(plaintext) sys.stdout = cStringIO.StringIO() - uu.encode("-", "-", "t1", 0666) + uu.encode("-", "-", "t1", 0o666) self.assertEqual( sys.stdout.getvalue(), - encodedtextwrapped % (0666, "t1") + encodedtextwrapped % (0o666, "t1") ) def test_decode(self): - sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0666, "t1")) + sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0o666, "t1")) sys.stdout = cStringIO.StringIO() uu.decode("-", "-") self.assertEqual(sys.stdout.getvalue(), plaintext) @@ -120,21 +120,21 @@ class UUFileTest(unittest.TestCase): fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') - uu.encode(fin, fout, self.tmpin, mode=0644) + uu.encode(fin, fout, self.tmpin, mode=0o644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() - self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) + self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() - self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) + self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) finally: self._kill(fin) @@ -143,7 +143,7 @@ class UUFileTest(unittest.TestCase): def test_decode(self): try: f = open(self.tmpin, 'w') - f.write(encodedtextwrapped % (0644, self.tmpout)) + f.write(encodedtextwrapped % (0o644, self.tmpout)) f.close() f = open(self.tmpin, 'r') @@ -161,7 +161,7 @@ class UUFileTest(unittest.TestCase): def test_decodetwice(self): # Verify that decode() will refuse to overwrite an existing file try: - f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) + f = cStringIO.StringIO(encodedtextwrapped % (0o644, self.tmpout)) f = open(self.tmpin, 'r') uu.decode(f) diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index 99a5178a6b..92d80318b3 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -651,10 +651,10 @@ class SubclassableWeakrefTestCase(unittest.TestCase): class MyRef(weakref.ref): def __init__(self, ob, callback=None, value=42): self.value = value - super(MyRef, self).__init__(ob, callback) + super().__init__(ob, callback) def __call__(self): self.called = True - return super(MyRef, self).__call__() + return super().__call__() o = Object("foo") mr = MyRef(o, value=24) self.assert_(mr() is o) @@ -1091,7 +1091,7 @@ None >>> import weakref >>> class ExtendedRef(weakref.ref): ... def __init__(self, ob, callback=None, **annotations): -... super(ExtendedRef, self).__init__(ob, callback) +... super().__init__(ob, callback) ... self.__counter = 0 ... for k, v in annotations.items(): ... setattr(self, k, v) @@ -1099,7 +1099,7 @@ None ... '''Return a pair containing the referent and the number of ... times the reference has been called. ... ''' -... ob = super(ExtendedRef, self).__call__() +... ob = super().__call__() ... if ob is not None: ... self.__counter += 1 ... ob = (ob, self.__counter) diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py index bc8a7cf27f..791cca7666 100644 --- a/Lib/test/test_xmlrpc.py +++ b/Lib/test/test_xmlrpc.py @@ -15,9 +15,9 @@ alist = [{'astring': 'foo@bar.baz.spam', 'ukey\u4000': 'regular value', 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), 'datetime2': xmlrpclib.DateTime( - (2005, 02, 10, 11, 41, 23, 0, 1, -1)), + (2005, 2, 10, 11, 41, 23, 0, 1, -1)), 'datetime3': xmlrpclib.DateTime( - datetime.datetime(2005, 02, 10, 11, 41, 23)), + datetime.datetime(2005, 2, 10, 11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): @@ -31,7 +31,7 @@ class XMLRPCTestCase(unittest.TestCase): # by the marshalling code. This can't be done via test_dump_load() # since with use_datetime set to 1 the unmarshaller would create # datetime objects for the 'datetime[123]' keys as well - dt = datetime.datetime(2005, 02, 10, 11, 41, 23) + dt = datetime.datetime(2005, 2, 10, 11, 41, 23) s = xmlrpclib.dumps((dt,)) (newdt,), m = xmlrpclib.loads(s, use_datetime=1) self.assertEquals(newdt, dt) @@ -44,7 +44,7 @@ class XMLRPCTestCase(unittest.TestCase): # This checks that an unwrapped datetime.date object can be handled # by the marshalling code. This can't be done via test_dump_load() # since the unmarshaller produces a datetime object - d = datetime.datetime(2005, 02, 10, 11, 41, 23).date() + d = datetime.datetime(2005, 2, 10, 11, 41, 23).date() s = xmlrpclib.dumps((d,)) (newd,), m = xmlrpclib.loads(s, use_datetime=1) self.assertEquals(newd.date(), d) @@ -58,7 +58,7 @@ class XMLRPCTestCase(unittest.TestCase): # This checks that an unwrapped datetime.time object can be handled # by the marshalling code. This can't be done via test_dump_load() # since the unmarshaller produces a datetime object - t = datetime.datetime(2005, 02, 10, 11, 41, 23).time() + t = datetime.datetime(2005, 2, 10, 11, 41, 23).time() s = xmlrpclib.dumps((t,)) (newt,), m = xmlrpclib.loads(s, use_datetime=1) today = datetime.datetime.now().date().strftime("%Y%m%d") diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index 53c5504170..8daac4b499 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -364,7 +364,7 @@ class BadFileZipImportTestCase(unittest.TestCase): finally: # If we leave "the read-only bit" set on Windows, nothing can # delete TESTMOD, and later tests suffer bogus failures. - os.chmod(TESTMOD, 0666) + os.chmod(TESTMOD, 0o666) test_support.unlink(TESTMOD) def testNotZipFile(self): diff --git a/Lib/test/tf_inherit_check.py b/Lib/test/tf_inherit_check.py index a8b80d2726..0fd108914e 100644 --- a/Lib/test/tf_inherit_check.py +++ b/Lib/test/tf_inherit_check.py @@ -19,7 +19,7 @@ try: sys.stderr.write("fd %d is open in child" % fd) sys.exit(1) -except StandardError: +except Exception: if verbose: raise sys.exit(1) diff --git a/Lib/test/tokenize_tests.txt b/Lib/test/tokenize_tests.txt index b1aa020bfb..30e7a8d2f0 100644 --- a/Lib/test/tokenize_tests.txt +++ b/Lib/test/tokenize_tests.txt @@ -37,21 +37,21 @@ x = 0 # Ordinary integers 0xff != 255 -0377 != 255 -2147483647 != 017777777777 --2147483647-1 != 020000000000 -037777777777 != -1 -0xffffffff != -1 +0o377 != 255 +2147483647 != 0o17777777777 +-2147483647-1 != 0o20000000000 +0o37777777777 != -1 +0xffffffff != -1; 0o37777777777 != -1; -0o1234567 == 0O001234567; 0b10101 == 0B00010101 # Long integers -x = 0L -x = 0l -x = 0xffffffffffffffffL -x = 0xffffffffffffffffl -x = 077777777777777777L -x = 077777777777777777l -x = 123456789012345678901234567890L -x = 123456789012345678901234567890l +x = 0 +x = 0 +x = 0xffffffffffffffff +x = 0xffffffffffffffff +x = 0o77777777777777777 +x = 0B11101010111111111 +x = 123456789012345678901234567890 +x = 123456789012345678901234567890 # Floating-point numbers x = 3.14 |