diff --git a/tests/snippets/attr.py b/tests/snippets/attr.py index 0e9f1eb9b..98ed19cb4 100644 --- a/tests/snippets/attr.py +++ b/tests/snippets/attr.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises class A: @@ -16,10 +16,10 @@ assert a.b == 12 assert getattr(a, 'b') == 12 # test non-existent attribute -with assertRaises(AttributeError): +with assert_raises(AttributeError): _ = a.c -with assertRaises(AttributeError): +with assert_raises(AttributeError): getattr(a, 'c') assert getattr(a, 'c', 21) == 21 @@ -32,21 +32,21 @@ assert a.c == 20 # test delete attribute delattr(a, 'c') assert not hasattr(a, 'c') -with assertRaises(AttributeError): +with assert_raises(AttributeError): _ = a.c # test setting attribute on builtin -with assertRaises(AttributeError): +with assert_raises(AttributeError): object().a = 1 -with assertRaises(AttributeError): +with assert_raises(AttributeError): del object().a -with assertRaises(AttributeError): +with assert_raises(AttributeError): setattr(object(), 'a', 2) -with assertRaises(AttributeError): +with assert_raises(AttributeError): delattr(object(), 'a') attrs = {} @@ -79,13 +79,13 @@ class GetRaise: assert not hasattr(GetRaise(AttributeError()), 'a') -with assertRaises(AttributeError): +with assert_raises(AttributeError): getattr(GetRaise(AttributeError()), 'a') assert getattr(GetRaise(AttributeError()), 'a', 11) == 11 -with assertRaises(KeyError): +with assert_raises(KeyError): hasattr(GetRaise(KeyError()), 'a') -with assertRaises(KeyError): +with assert_raises(KeyError): getattr(GetRaise(KeyError()), 'a') -with assertRaises(KeyError): +with assert_raises(KeyError): getattr(GetRaise(KeyError()), 'a', 11) diff --git a/tests/snippets/bools.py b/tests/snippets/bools.py index b3f52df06..e3d824b5c 100644 --- a/tests/snippets/bools.py +++ b/tests/snippets/bools.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises assert True assert not False @@ -133,7 +133,7 @@ class TestBoolThrowError: def __bool__(self): return object() -with assertRaises(TypeError): +with assert_raises(TypeError): bool(TestBoolThrowError()) class TestLenThrowError: @@ -141,14 +141,14 @@ class TestLenThrowError: return object() -with assertRaises(TypeError): +with assert_raises(TypeError): bool(TestLenThrowError()) # Verify that TypeError occurs when bad things are returned # from __bool__(). This isn't really a bool test, but # it's related. def check(o): - with assertRaises(TypeError): + with assert_raises(TypeError): bool(o) class Foo(object): @@ -176,5 +176,8 @@ class Eggs: def __len__(self): return -1 -with assertRaises(ValueError): - bool(Eggs()) \ No newline at end of file +with assert_raises(ValueError): + bool(Eggs()) + +with assert_raises(TypeError): + bool(TestLenThrowError()) diff --git a/tests/snippets/builtin_all.py b/tests/snippets/builtin_all.py index 4195d5f2e..cf0eea393 100644 --- a/tests/snippets/builtin_all.py +++ b/tests/snippets/builtin_all.py @@ -6,5 +6,5 @@ assert not all([False]) assert all([]) assert not all([False, TestFailingBool()]) -assert_raises(RuntimeError, lambda: all(TestFailingIter())) -assert_raises(RuntimeError, lambda: all([TestFailingBool()])) +assert_raises(RuntimeError, all, TestFailingIter()) +assert_raises(RuntimeError, all, [TestFailingBool()]) diff --git a/tests/snippets/builtin_chr.py b/tests/snippets/builtin_chr.py index 1ad642a58..9b95452bd 100644 --- a/tests/snippets/builtin_chr.py +++ b/tests/snippets/builtin_chr.py @@ -4,5 +4,5 @@ assert "a" == chr(97) assert "é" == chr(233) assert "🤡" == chr(129313) -assert_raises(TypeError, lambda: chr(), "chr() takes exactly one argument (0 given)") -assert_raises(ValueError, lambda: chr(0x110005), "ValueError: chr() arg not in range(0x110000)") +assert_raises(TypeError, chr, _msg='chr() takes exactly one argument (0 given)') +assert_raises(ValueError, chr, 0x110005, _msg='ValueError: chr() arg not in range(0x110000)') diff --git a/tests/snippets/builtin_complex.py b/tests/snippets/builtin_complex.py index f751a95a5..ba36c2885 100644 --- a/tests/snippets/builtin_complex.py +++ b/tests/snippets/builtin_complex.py @@ -37,37 +37,19 @@ assert complex(2, -3) / 2 == complex(1, -1.5) assert 5 / complex(3, -4) == complex(0.6, 0.8) # __mod__, __rmod__ - -assert_raises( - TypeError, - lambda: complex(2, -3) % 2, - "can't mod complex numbers.") -assert_raises( - TypeError, - lambda: 2 % complex(2, -3), - "can't mod complex numbers.") +# "can't mod complex numbers. +assert_raises(TypeError, lambda: complex(2, -3) % 2) +assert_raises(TypeError, lambda: 2 % complex(2, -3)) # __floordiv__, __rfloordiv__ - -assert_raises( - TypeError, - lambda: complex(2, -3) // 2, - "can't take floor of complex number.") -assert_raises( - TypeError, - lambda: 2 // complex(2, -3), - "can't take floor of complex number.") +# can't take floor of complex number. +assert_raises(TypeError, lambda: complex(2, -3) // 2) +assert_raises(TypeError, lambda: 2 // complex(2, -3)) # __divmod__, __rdivmod__ - -assert_raises( - TypeError, - lambda: divmod(complex(2, -3), 2), - "can't take floor or mod of complex number.") -assert_raises( - TypeError, - lambda: divmod(2, complex(2, -3)), - "can't take floor or mod of complex number.") +# "can't take floor or mod of complex number." +assert_raises(TypeError, lambda: divmod(complex(2, -3), 2)) +assert_raises(TypeError, lambda: divmod(2, complex(2, -3))) # __pow__, __rpow__ @@ -135,10 +117,9 @@ assert_raises(TypeError, lambda: 'str' + 1j) assert_raises(TypeError, lambda: 'str' - 1j) # overflow -msg = 'int too large to convert to float' -assert_raises(OverflowError, lambda: complex(10 ** 1000, 0), msg) -assert_raises(OverflowError, lambda: complex(0, 10 ** 1000), msg) -assert_raises(OverflowError, lambda: 0j + 10 ** 1000, msg) +assert_raises(OverflowError, lambda: complex(10 ** 1000, 0)) +assert_raises(OverflowError, lambda: complex(0, 10 ** 1000)) +assert_raises(OverflowError, lambda: 0j + 10 ** 1000) # str/repr assert '(1+1j)' == str(1+1j) diff --git a/tests/snippets/builtin_divmod.py b/tests/snippets/builtin_divmod.py index ce9bdfba8..5a9443afe 100644 --- a/tests/snippets/builtin_divmod.py +++ b/tests/snippets/builtin_divmod.py @@ -5,5 +5,5 @@ assert divmod(8,11) == (0, 8) assert divmod(0.873, 0.252) == (3.0, 0.11699999999999999) assert divmod(-86340, 86400) == (-1, 60) -assert_raises(ZeroDivisionError, lambda: divmod(5, 0), 'divmod by zero') -assert_raises(ZeroDivisionError, lambda: divmod(5.0, 0.0), 'divmod by zero') +assert_raises(ZeroDivisionError, divmod, 5, 0, _msg='divmod by zero') +assert_raises(ZeroDivisionError, divmod, 5.0, 0.0, _msg='divmod by zero') diff --git a/tests/snippets/builtin_format.py b/tests/snippets/builtin_format.py index 55a6a3da1..039c61121 100644 --- a/tests/snippets/builtin_format.py +++ b/tests/snippets/builtin_format.py @@ -2,13 +2,13 @@ from testutils import assert_raises assert format(5, "b") == "101" -assert_raises(TypeError, lambda: format(2, 3), 'format called with number') +assert_raises(TypeError, format, 2, 3, _msg='format called with number') assert format({}) == "{}" -assert_raises(TypeError, lambda: format({}, 'b'), 'format_spec not empty for dict') +assert_raises(TypeError, format, {}, 'b', _msg='format_spec not empty for dict') class BadFormat: def __format__(self, spec): return 42 -assert_raises(TypeError, lambda: format(BadFormat())) +assert_raises(TypeError, format, BadFormat()) diff --git a/tests/snippets/builtin_hex.py b/tests/snippets/builtin_hex.py index f6f25ab58..fac5e09c2 100644 --- a/tests/snippets/builtin_hex.py +++ b/tests/snippets/builtin_hex.py @@ -3,4 +3,4 @@ from testutils import assert_raises assert hex(16) == '0x10' assert hex(-16) == '-0x10' -assert_raises(TypeError, lambda: hex({}), 'ord() called with dict') +assert_raises(TypeError, hex, {}, _msg='ord() called with dict') diff --git a/tests/snippets/builtin_max.py b/tests/snippets/builtin_max.py index 1494ecd80..cb6212365 100644 --- a/tests/snippets/builtin_max.py +++ b/tests/snippets/builtin_max.py @@ -16,17 +16,17 @@ assert max({ }) == "b" assert max([1, 2], default=0) == 2 assert max([], default=0) == 0 -assert_raises(ValueError, lambda: max([])) +assert_raises(ValueError, max, []) # key parameter assert max(1, 2, -3, key=abs) == -3 assert max([1, 2, -3], key=abs) == -3 # no argument -assert_raises(TypeError, lambda: max()) +assert_raises(TypeError, max) # one non-iterable argument -assert_raises(TypeError, lambda: max(1)) +assert_raises(TypeError, max, 1) # custom class @@ -51,4 +51,4 @@ class MyNotComparable(): pass -assert_raises(TypeError, lambda: max(MyNotComparable(), MyNotComparable())) +assert_raises(TypeError, max, MyNotComparable(), MyNotComparable()) diff --git a/tests/snippets/builtin_min.py b/tests/snippets/builtin_min.py index ed45eff58..50ebc91f5 100644 --- a/tests/snippets/builtin_min.py +++ b/tests/snippets/builtin_min.py @@ -17,17 +17,17 @@ assert min({ assert min([1, 2], default=0) == 1 assert min([], default=0) == 0 -assert_raises(ValueError, lambda: min([])) +assert_raises(ValueError, min, []) # key parameter assert min(1, 2, -3, key=abs) == 1 assert min([1, 2, -3], key=abs) == 1 # no argument -assert_raises(TypeError, lambda: min()) +assert_raises(TypeError, min) # one non-iterable argument -assert_raises(TypeError, lambda: min(1)) +assert_raises(TypeError, min, 1) # custom class @@ -52,4 +52,4 @@ class MyNotComparable(): pass -assert_raises(TypeError, lambda: min(MyNotComparable(), MyNotComparable())) +assert_raises(TypeError, min, MyNotComparable(), MyNotComparable()) diff --git a/tests/snippets/builtin_open.py b/tests/snippets/builtin_open.py index d7c310a92..f2c783f2a 100644 --- a/tests/snippets/builtin_open.py +++ b/tests/snippets/builtin_open.py @@ -3,7 +3,7 @@ from testutils import assert_raises fd = open('README.md') assert 'RustPython' in fd.read() -assert_raises(FileNotFoundError, lambda: open('DoesNotExist')) +assert_raises(FileNotFoundError, open, 'DoesNotExist') # Use open as a context manager with open('README.md', 'rt') as fp: diff --git a/tests/snippets/builtin_ord.py b/tests/snippets/builtin_ord.py index c9bc40f5f..271728b84 100644 --- a/tests/snippets/builtin_ord.py +++ b/tests/snippets/builtin_ord.py @@ -6,8 +6,8 @@ assert ord("🤡") == 129313 assert ord(b'a') == 97 assert ord(bytearray(b'a')) == 97 -assert_raises(TypeError, lambda: ord(), "ord() is called with no argument") -assert_raises(TypeError, lambda: ord(""), "ord() is called with an empty string") -assert_raises(TypeError, lambda: ord("ab"), "ord() is called with more than one character") -assert_raises(TypeError, lambda: ord(b"ab"), "ord() expected a character, but string of length 2 found") -assert_raises(TypeError, lambda: ord(1), "ord() expected a string, bytes or bytearray, but found int") +assert_raises(TypeError, ord, _msg='ord() is called with no argument') +assert_raises(TypeError, ord, "", _msg='ord() is called with an empty string') +assert_raises(TypeError, ord, "ab", _msg='ord() is called with more than one character') +assert_raises(TypeError, ord, b"ab", _msg='ord() expected a character, but string of length 2 found') +assert_raises(TypeError, ord, 1, _msg='ord() expected a string, bytes or bytearray, but found int') diff --git a/tests/snippets/builtin_range.py b/tests/snippets/builtin_range.py index cde601009..43883cc5d 100644 --- a/tests/snippets/builtin_range.py +++ b/tests/snippets/builtin_range.py @@ -13,18 +13,18 @@ assert range(4, 10).index(6) == 2 assert range(4, 10, 2).index(6) == 1 assert range(10, 4, -2).index(8) == 1 -assert_raises(ValueError, lambda: range(10).index(-1), 'out of bounds') -assert_raises(ValueError, lambda: range(10).index(10), 'out of bounds') -assert_raises(ValueError, lambda: range(4, 10, 2).index(5), 'out of step') -assert_raises(ValueError, lambda: range(10).index('foo'), 'not an int') -assert_raises(ValueError, lambda: range(1, 10, 0), 'step is zero') +assert_raises(ValueError, lambda: range(10).index(-1), _msg='out of bounds') +assert_raises(ValueError, lambda: range(10).index(10), _msg='out of bounds') +assert_raises(ValueError, lambda: range(4, 10, 2).index(5), _msg='out of step') +assert_raises(ValueError, lambda: range(10).index('foo'), _msg='not an int') +assert_raises(ValueError, lambda: range(1, 10, 0), _msg='step is zero') # get tests assert range(10)[0] == 0 assert range(10)[9] == 9 assert range(10, 0, -1)[0] == 10 assert range(10, 0, -1)[9] == 1 -assert_raises(IndexError, lambda: range(10)[10], 'out of bound') +assert_raises(IndexError, lambda: range(10)[10], _msg='out of bound') # slice tests assert range(10)[0:3] == range(3) @@ -100,7 +100,7 @@ assert range(i).stop is i # negative index assert range(10)[-1] == 9 -assert_raises(IndexError, lambda: range(10)[-11], 'out of bound') +assert_raises(IndexError, lambda: range(10)[-11], _msg='out of bound') assert range(10)[-2:4] == range(8, 4) assert range(10)[-6:-2] == range(4, 8) assert range(50, 0, -2)[-5] == 10 diff --git a/tests/snippets/builtin_round.py b/tests/snippets/builtin_round.py index 6d116b307..5526c551e 100644 --- a/tests/snippets/builtin_round.py +++ b/tests/snippets/builtin_round.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises assert round(0) == 0 assert isinstance(round(0), int) @@ -15,7 +15,7 @@ assert isinstance(round(0, 0), int) assert round(0.0, 0) == 0.0 # Cannot check the type assert isinstance(round(0.0, 0), float) -with assertRaises(TypeError): +with assert_raises(TypeError): round(0, 0.0) -with assertRaises(TypeError): +with assert_raises(TypeError): round(0.0, 0.0) diff --git a/tests/snippets/builtin_slice.py b/tests/snippets/builtin_slice.py index 46592769e..6c2dd847b 100644 --- a/tests/snippets/builtin_slice.py +++ b/tests/snippets/builtin_slice.py @@ -20,7 +20,7 @@ assert b[-10:1] == [1] assert b[0:0] == [] assert b[1:0] == [] -assert_raises(ValueError, lambda: b[::0], "zero step slice") +assert_raises(ValueError, lambda: b[::0], _msg='zero step slice') assert b[::-1] == [2, 1] assert b[1::-1] == [2, 1] diff --git a/tests/snippets/builtins_module.py b/tests/snippets/builtins_module.py index d3daffc54..0f1544dc2 100644 --- a/tests/snippets/builtins_module.py +++ b/tests/snippets/builtins_module.py @@ -1,8 +1,8 @@ -from testutils import assertRaises +from testutils import assert_raises assert '__builtins__' in globals() # assert type(__builtins__).__name__ == 'module' -with assertRaises(AttributeError): +with assert_raises(AttributeError): __builtins__.__builtins__ __builtins__.x = 'new' @@ -17,12 +17,12 @@ namespace = {} exec('', namespace) assert namespace['__builtins__'] == __builtins__.__dict__ -# with assertRaises(NameError): +# with assert_raises(NameError): # exec('print(__builtins__)', {'__builtins__': {}}) # __builtins__ is deletable but names are alive del __builtins__ -with assertRaises(NameError): +with assert_raises(NameError): __builtins__ # noqa: F821 assert print diff --git a/tests/snippets/bytearray.py b/tests/snippets/bytearray.py index f69edeac1..3d577d613 100644 --- a/tests/snippets/bytearray.py +++ b/tests/snippets/bytearray.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises # new assert bytearray([1, 2, 3]) @@ -9,9 +9,9 @@ assert b"bla" assert ( bytearray("bla", "utf8") == bytearray("bla", encoding="utf-8") == bytearray(b"bla") ) -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray("bla") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray("bla", encoding=b"jilj") assert bytearray( @@ -56,7 +56,7 @@ assert bytearray(b"foobar").__lt__(2) == NotImplemented assert bytearray(b"foobar").__le__(2) == NotImplemented # # hash -with assertRaises(TypeError): +with assert_raises(TypeError): hash(bytearray(b"abcd")) # unashable # # iter @@ -75,7 +75,7 @@ assert bytearray(b"d") in bytearray(b"abcd") assert bytearray(b"dc") not in bytearray(b"abcd") assert 97 in bytearray(b"abcd") assert 150 not in bytearray(b"abcd") -with assertRaises(ValueError): +with assert_raises(ValueError): 350 in bytearray(b"abcd") @@ -147,7 +147,7 @@ try: bytearray.fromhex("6Z2") except ValueError as e: str(e) == "non-hexadecimal number found in fromhex() arg at position 1" -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray.fromhex(b"hhjjk") # center assert [bytearray(b"koki").center(i, b"|") for i in range(3, 10)] == [ @@ -171,11 +171,11 @@ assert [bytearray(b"kok").center(i, b"|") for i in range(2, 10)] == [ b"|||kok|||", ] bytearray(b"kok").center(4) == b" kok" # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").center(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").center(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").center(b"ba") assert bytearray(b"kok").center(5, bytearray(b"x")) == b"xkokx" bytearray(b"kok").center(-5) == b"kok" @@ -203,11 +203,11 @@ assert [bytearray(b"kok").ljust(i, b"|") for i in range(2, 10)] == [ ] bytearray(b"kok").ljust(4) == b"kok " # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").ljust(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").ljust(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").ljust(b"ba") assert bytearray(b"kok").ljust(5, bytearray(b"x")) == b"kokxx" assert bytearray(b"kok").ljust(-5) == b"kok" @@ -235,11 +235,11 @@ assert [bytearray(b"kok").rjust(i, b"|") for i in range(2, 10)] == [ bytearray(b"kok").rjust(4) == b" kok" # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").rjust(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").rjust(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"b").rjust(b"ba") assert bytearray(b"kok").rjust(5, bytearray(b"x")) == b"xxkok" assert bytearray(b"kok").rjust(-5) == b"kok" @@ -261,7 +261,7 @@ assert bytearray(b"azeazerazeazopia").count(b"aze", None, 7) == 2 assert bytearray(b"azeazerazeazopia").count(b"aze", 2, 7) == 1 assert bytearray(b"azeazerazeazopia").count(b"aze", -13, -10) == 1 assert bytearray(b"azeazerazeazopia").count(b"aze", 1, 10000) == 2 -with assertRaises(ValueError): +with assert_raises(ValueError): bytearray(b"ilj").count(3550) assert bytearray(b"azeazerazeazopia").count(97) == 5 @@ -269,7 +269,7 @@ assert bytearray(b"azeazerazeazopia").count(97) == 5 assert bytearray(b"").join( (b"jiljl", bytearray(b"kmoomk"), memoryview(b"aaaa")) ) == bytearray(b"jiljlkmoomkaaaa") -with assertRaises(TypeError): +with assert_raises(TypeError): bytearray(b"").join((b"km", "kl")) @@ -294,13 +294,13 @@ assert bytearray(b"abcd").index(b"cd") == 2 assert bytearray(b"abcd").index(b"cd", 0) == 2 assert bytearray(b"abcd").index(b"cd", 1) == 2 assert bytearray(b"abcd").index(99) == 2 -with assertRaises(ValueError): +with assert_raises(ValueError): bytearray(b"abcde").index(b"c", 3, 1) -with assertRaises(ValueError): +with assert_raises(ValueError): bytearray(b"abcd").index(b"cdaaaaa") -with assertRaises(ValueError): +with assert_raises(ValueError): bytearray(b"abcd").index(b"b", 3, 4) -with assertRaises(ValueError): +with assert_raises(ValueError): bytearray(b"abcd").index(1) @@ -696,9 +696,9 @@ assert a == bytearray(b'dlrow ,olleh') a = bytearray(b'test') a[0] = 1 assert a == bytearray(b'\x01est') -with assertRaises(TypeError): +with assert_raises(TypeError): a[0] = b'a' -with assertRaises(TypeError): +with assert_raises(TypeError): a[0] = memoryview(b'a') a[:2] = [0, 9] assert a == bytearray(b'\x00\x09st') diff --git a/tests/snippets/bytes.py b/tests/snippets/bytes.py index 821d60325..d6a0c45a4 100644 --- a/tests/snippets/bytes.py +++ b/tests/snippets/bytes.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises # new assert bytes([1, 2, 3]) @@ -7,9 +7,9 @@ assert bytes(range(4)) assert bytes(3) assert b"bla" assert bytes("bla", "utf8") == bytes("bla", encoding="utf-8") == b"bla" -with assertRaises(TypeError): +with assert_raises(TypeError): bytes("bla") -with assertRaises(TypeError): +with assert_raises(TypeError): bytes("bla", encoding=b"jilj") assert ( @@ -72,7 +72,7 @@ assert b"d" in b"abcd" assert b"dc" not in b"abcd" assert 97 in b"abcd" assert 150 not in b"abcd" -with assertRaises(ValueError): +with assert_raises(ValueError): 350 in b"abcd" @@ -144,7 +144,7 @@ try: bytes.fromhex("6Z2") except ValueError as e: str(e) == "non-hexadecimal number found in fromhex() arg at position 1" -with assertRaises(TypeError): +with assert_raises(TypeError): bytes.fromhex(b"hhjjk") # center assert [b"koki".center(i, b"|") for i in range(3, 10)] == [ @@ -168,11 +168,11 @@ assert [b"kok".center(i, b"|") for i in range(2, 10)] == [ b"|||kok|||", ] b"kok".center(4) == b" kok" # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".center(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".center(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".center(b"ba") assert b"kok".center(5, bytearray(b"x")) == b"xkokx" b"kok".center(-5) == b"kok" @@ -200,11 +200,11 @@ assert [b"kok".ljust(i, b"|") for i in range(2, 10)] == [ ] b"kok".ljust(4) == b"kok " # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".ljust(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".ljust(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".ljust(b"ba") assert b"kok".ljust(5, bytearray(b"x")) == b"kokxx" assert b"kok".ljust(-5) == b"kok" @@ -232,11 +232,11 @@ assert [b"kok".rjust(i, b"|") for i in range(2, 10)] == [ b"kok".rjust(4) == b" kok" # " test no arg" -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".rjust(2, "a") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".rjust(2, b"ba") -with assertRaises(TypeError): +with assert_raises(TypeError): b"b".rjust(b"ba") assert b"kok".rjust(5, bytearray(b"x")) == b"xxkok" assert b"kok".rjust(-5) == b"kok" @@ -258,7 +258,7 @@ assert b"azeazerazeazopia".count(b"aze", None, 7) == 2 assert b"azeazerazeazopia".count(b"aze", 2, 7) == 1 assert b"azeazerazeazopia".count(b"aze", -13, -10) == 1 assert b"azeazerazeazopia".count(b"aze", 1, 10000) == 2 -with assertRaises(ValueError): +with assert_raises(ValueError): b"ilj".count(3550) assert b"azeazerazeazopia".count(97) == 5 @@ -267,7 +267,7 @@ assert ( b"".join((b"jiljl", bytearray(b"kmoomk"), memoryview(b"aaaa"))) == b"jiljlkmoomkaaaa" ) -with assertRaises(TypeError): +with assert_raises(TypeError): b"".join((b"km", "kl")) @@ -292,13 +292,13 @@ assert b"abcd".index(b"cd") == 2 assert b"abcd".index(b"cd", 0) == 2 assert b"abcd".index(b"cd", 1) == 2 assert b"abcd".index(99) == 2 -with assertRaises(ValueError): +with assert_raises(ValueError): b"abcde".index(b"c", 3, 1) -with assertRaises(ValueError): +with assert_raises(ValueError): b"abcd".index(b"cdaaaaa") -with assertRaises(ValueError): +with assert_raises(ValueError): b"abcd".index(b"b", 3, 4) -with assertRaises(ValueError): +with assert_raises(ValueError): b"abcd".index(1) diff --git a/tests/snippets/delete.py b/tests/snippets/delete.py index 2e476c7a1..9e863768f 100644 --- a/tests/snippets/delete.py +++ b/tests/snippets/delete.py @@ -1,4 +1,4 @@ -from testutils import assert_raises, assertRaises +from testutils import assert_raises a = 1 del a @@ -17,5 +17,5 @@ del (x, y) assert_raises(NameError, lambda: x) # noqa: F821 assert_raises(NameError, lambda: y) # noqa: F821 -with assertRaises(NameError): +with assert_raises(NameError): del y # noqa: F821 diff --git a/tests/snippets/dict.py b/tests/snippets/dict.py index 1ea2c6692..bf17c7ccb 100644 --- a/tests/snippets/dict.py +++ b/tests/snippets/dict.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises assert dict(a=2, b=3) == {'a': 2, 'b': 3} assert dict({'a': 2, 'b': 3}, b=4) == {'a': 2, 'b': 4} @@ -49,10 +49,10 @@ it = iter(x.items()) assert ('a', 1) == next(it) assert ('b', 2) == next(it) assert ('d', 3) == next(it) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(it) -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: del x[10] assert cm.exception.args[0] == 10 @@ -79,14 +79,14 @@ a = iter(d.items()) d['a'] = 2 b = iter(d.items()) assert ('a', 2) == next(b) -with assertRaises(RuntimeError): +with assert_raises(RuntimeError): next(a) del d['a'] -with assertRaises(RuntimeError): +with assert_raises(RuntimeError): next(b) # View isn't itself an iterator. -with assertRaises(TypeError): +with assert_raises(TypeError): next(data.keys()) assert len(data.keys()) == 2 @@ -99,7 +99,7 @@ x[7] = 7 x[2] = 2 x[(5, 6)] = 5 -with assertRaises(TypeError): +with assert_raises(TypeError): x[[]] # Unhashable type. x["here"] = "here" @@ -169,27 +169,27 @@ y.update(y) assert y == {'a': 2, 'b': 12, 'c': 19, 'd': -1} # hasn't changed # KeyError has object that used as key as an .args[0] -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x['not here'] assert cm.exception.args[0] == "not here" -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x.pop('not here') assert cm.exception.args[0] == "not here" -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x[10] assert cm.exception.args[0] == 10 -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x.pop(10) assert cm.exception.args[0] == 10 class MyClass: pass obj = MyClass() -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x[obj] assert cm.exception.args[0] == obj -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x.pop(obj) assert cm.exception.args[0] == obj @@ -201,7 +201,7 @@ assert x == {} x = {1: 'a'} assert (1, 'a') == x.popitem() assert x == {} -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: x.popitem() assert cm.exception.args == ('popitem(): dictionary is empty',) diff --git a/tests/snippets/division_by_zero.py b/tests/snippets/division_by_zero.py index d8b900636..702d60517 100644 --- a/tests/snippets/division_by_zero.py +++ b/tests/snippets/division_by_zero.py @@ -6,6 +6,6 @@ assert_raises(ZeroDivisionError, lambda: 5 / (2-2)) assert_raises(ZeroDivisionError, lambda: 5 % 0) assert_raises(ZeroDivisionError, lambda: 5 // 0) assert_raises(ZeroDivisionError, lambda: 5.3 // (-0.0)) -assert_raises(ZeroDivisionError, lambda: divmod(5, 0)) +assert_raises(ZeroDivisionError, divmod, 5, 0) assert issubclass(ZeroDivisionError, ArithmeticError) diff --git a/tests/snippets/division_of_big_ints.py b/tests/snippets/division_of_big_ints.py index 9595ae603..dcc2e5a36 100644 --- a/tests/snippets/division_of_big_ints.py +++ b/tests/snippets/division_of_big_ints.py @@ -10,10 +10,10 @@ assert 95.238095 <= res <= 95.238096 assert 10**500 / (2*10**(500-308)) == 5e307 assert 10**500 / (10**(500-308)) == 1e308 -assert_raises(OverflowError, lambda: 10**500 / (10**(500-309)), 'too big result') +assert_raises(OverflowError, lambda: 10**500 / (10**(500-309)), _msg='too big result') # a bit more than f64::MAX = 1.7976931348623157e+308_f64 assert (2 * 10**308) / 2 == 1e308 # when dividing too big int by a float, the operation should fail -assert_raises(OverflowError, lambda: (2 * 10**308) / 2.0, 'division of big int by float') +assert_raises(OverflowError, lambda: (2 * 10**308) / 2.0, _msg='division of big int by float') diff --git a/tests/snippets/floats.py b/tests/snippets/floats.py index 6139295f4..943b1d9ae 100644 --- a/tests/snippets/floats.py +++ b/tests/snippets/floats.py @@ -95,8 +95,8 @@ assert float('2.99e-23') == 2.99e-23 assert float(b'3.14') == 3.14 assert float(b'2.99e-23') == 2.99e-23 -assert_raises(ValueError, lambda: float('foo')) -assert_raises(OverflowError, lambda: float(2**10000)) +assert_raises(ValueError, float, 'foo') +assert_raises(OverflowError, float, 2**10000) # check eq and hash for small numbers @@ -137,11 +137,11 @@ assert 2.0.__rmod__(2) == 0.0 assert_raises(ZeroDivisionError, lambda: 2.0 / 0) assert_raises(ZeroDivisionError, lambda: 2.0 // 0) assert_raises(ZeroDivisionError, lambda: 2.0 % 0) -assert_raises(ZeroDivisionError, lambda: divmod(2.0, 0)) +assert_raises(ZeroDivisionError, divmod, 2.0, 0) assert_raises(ZeroDivisionError, lambda: 2 / 0.0) assert_raises(ZeroDivisionError, lambda: 2 // 0.0) assert_raises(ZeroDivisionError, lambda: 2 % 0.0) -# assert_raises(ZeroDivisionError, lambda: divmod(2, 0.0)) +# assert_raises(ZeroDivisionError, divmod, 2, 0.0) assert 1.2.__int__() == 1 assert 1.2.__float__() == 1.2 diff --git a/tests/snippets/func_defaults.py b/tests/snippets/func_defaults.py index 5fcf93047..071cc9bef 100644 --- a/tests/snippets/func_defaults.py +++ b/tests/snippets/func_defaults.py @@ -5,8 +5,8 @@ def no_args(): no_args() -assert_raises(TypeError, lambda: no_args('one_arg'), '1 arg to no_args') -assert_raises(TypeError, lambda: no_args(kw='should fail'), 'kwarg to no_args') +assert_raises(TypeError, no_args, 'one_arg', _msg='1 arg to no_args') +assert_raises(TypeError, no_args, kw='should fail', _msg='kwarg to no_args') def one_arg(arg): @@ -15,7 +15,7 @@ def one_arg(arg): one_arg('one_arg') assert "arg" == one_arg(arg="arg") -assert_raises(TypeError, lambda: one_arg(), 'no args to one_arg') +assert_raises(TypeError, one_arg, _msg='no args to one_arg') assert_raises(TypeError, lambda: one_arg(wrong_arg='wont work'), 'incorrect kwarg to one_arg') diff --git a/tests/snippets/function.py b/tests/snippets/function.py index c80ab7ea1..92eb198c5 100644 --- a/tests/snippets/function.py +++ b/tests/snippets/function.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises __name__ = "function" @@ -93,5 +93,5 @@ def f8() -> int: assert f8() == 10 -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec('print(keyword=10, 20)') diff --git a/tests/snippets/function_args.py b/tests/snippets/function_args.py index 86c92617a..903a43f9b 100644 --- a/tests/snippets/function_args.py +++ b/tests/snippets/function_args.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises def sum(x, y): @@ -55,10 +55,10 @@ def va3(x, *, a, b=2, c=9): assert va3(1, a=1, b=10) == 20 -with assertRaises(TypeError): +with assert_raises(TypeError): va3(1, 2, 3, a=1, b=10) -with assertRaises(TypeError): +with assert_raises(TypeError): va3(1, b=10) diff --git a/tests/snippets/generators.py b/tests/snippets/generators.py index a5c1a8411..f23e5918a 100644 --- a/tests/snippets/generators.py +++ b/tests/snippets/generators.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises r = [] @@ -63,7 +63,7 @@ assert next(g) == 3 g = catch_exception() assert next(g) == 1 -with assertRaises(KeyError): +with assert_raises(KeyError): assert g.throw(KeyError, KeyError(), None) == 2 diff --git a/tests/snippets/global_nonlocal.py b/tests/snippets/global_nonlocal.py index 9768f2dbe..59dcfd8bc 100644 --- a/tests/snippets/global_nonlocal.py +++ b/tests/snippets/global_nonlocal.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises # Test global and nonlocal funkyness @@ -33,7 +33,7 @@ b = 2 global b """ -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(src) # Invalid syntax: @@ -41,7 +41,7 @@ src = """ nonlocal c """ -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(src) @@ -53,7 +53,7 @@ def f(): c = 2 """ -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(src) # Invalid syntax: @@ -62,7 +62,7 @@ def a(): nonlocal a """ -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(src) # class X: diff --git a/tests/snippets/hash.py b/tests/snippets/hash.py index b108db705..bd98199db 100644 --- a/tests/snippets/hash.py +++ b/tests/snippets/hash.py @@ -1,5 +1,5 @@ -from testutils import assertRaises +from testutils import assert_raises class A: @@ -13,11 +13,11 @@ assert type(hash(1)) is int assert type(hash(1.1)) is int assert type(hash("")) is int -with assertRaises(TypeError): +with assert_raises(TypeError): hash({}) -with assertRaises(TypeError): +with assert_raises(TypeError): hash(set()) -with assertRaises(TypeError): +with assert_raises(TypeError): hash([]) diff --git a/tests/snippets/import.py b/tests/snippets/import.py index 2996a27cc..309160d50 100644 --- a/tests/snippets/import.py +++ b/tests/snippets/import.py @@ -65,8 +65,8 @@ with OverrideImportContext(): #else: # raise AssertionError('X should not be imported') -from testutils import assertRaises +from testutils import assert_raises -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec('import') diff --git a/tests/snippets/ints.py b/tests/snippets/ints.py index 4bb1a5127..b3ae5b457 100644 --- a/tests/snippets/ints.py +++ b/tests/snippets/ints.py @@ -1,4 +1,4 @@ -from testutils import assert_raises, assertRaises +from testutils import assert_raises # int to int comparisons @@ -36,15 +36,15 @@ assert (2).__rsub__(1) == -1 assert (2).__mul__(1) == 2 assert (2).__rmul__(1) == 2 assert (2).__truediv__(1) == 2.0 -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): (2).__truediv__(0) assert (2).__rtruediv__(1) == 0.5 assert (-2).__floordiv__(3) == -1 -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): (2).__floordiv__(0) assert (-3).__rfloordiv__(2) == -1 assert (-2).__divmod__(3) == (-1, 1) -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): (2).__divmod__(0) assert (-3).__rdivmod__(2) == (-1, -1) assert (2).__pow__(3) == 8 @@ -52,11 +52,11 @@ assert (10).__pow__(-1) == 0.1 assert (2).__rpow__(3) == 9 assert (10).__mod__(5) == 0 assert (10).__mod__(6) == 4 -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): (10).__mod__(0) assert (5).__rmod__(10) == 0 assert (6).__rmod__(10) == 4 -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): (0).__rmod__(10) # real/imag attributes @@ -110,28 +110,28 @@ assert int('0o100', base=0) == 64 assert int('0O100', base=0) == 64 assert int('0xFF', base=0) == 255 assert int('0XFF', base=0) == 255 -with assertRaises(ValueError): +with assert_raises(ValueError): int('0xFF', base=10) -with assertRaises(ValueError): +with assert_raises(ValueError): int('0oFF', base=10) -with assertRaises(ValueError): +with assert_raises(ValueError): int('0bFF', base=10) -with assertRaises(ValueError): +with assert_raises(ValueError): int('0bFF', base=10) -with assertRaises(ValueError): +with assert_raises(ValueError): int(b"F\xc3\xb8\xc3\xb6\xbbB\xc3\xa5r") -with assertRaises(ValueError): +with assert_raises(ValueError): int(b"F\xc3\xb8\xc3\xb6\xbbB\xc3\xa5r") # underscore assert int('0xFF_FF_FF', base=16) == 16_777_215 -with assertRaises(ValueError): +with assert_raises(ValueError): int("_123_") -with assertRaises(ValueError): +with assert_raises(ValueError): int("123_") -with assertRaises(ValueError): +with assert_raises(ValueError): int("_123") -with assertRaises(ValueError): +with assert_raises(ValueError): int("1__23") # signed @@ -160,20 +160,20 @@ assert (-1024).to_bytes(4, 'little', signed=True) == b'\x00\xfc\xff\xff' assert (2147483647).to_bytes(8, 'big', signed=False) == b'\x00\x00\x00\x00\x7f\xff\xff\xff' assert (-2147483648).to_bytes(8, 'little', signed=True) == b'\x00\x00\x00\x80\xff\xff\xff\xff' -with assertRaises(ValueError): +with assert_raises(ValueError): # check base first int(' 1 ', base=1) -with assertRaises(ValueError): +with assert_raises(ValueError): int(' 1 ', base=37) -with assertRaises(TypeError): +with assert_raises(TypeError): int(base=2) -with assertRaises(TypeError): +with assert_raises(TypeError): int(1, base=2) -with assertRaises(TypeError): +with assert_raises(TypeError): # check that first parameter is truly positional only int(val_options=1) @@ -189,14 +189,14 @@ class B(object): b = B() b.__int__ = lambda: 20 -with assertRaises(TypeError): +with assert_raises(TypeError): assert int(b) == 20 class C(object): def __int__(self): return 'str' -with assertRaises(TypeError): +with assert_raises(TypeError): int(C()) class I(int): diff --git a/tests/snippets/invalid_syntax.py b/tests/snippets/invalid_syntax.py index 3c9c6d46c..8a4c8a738 100644 --- a/tests/snippets/invalid_syntax.py +++ b/tests/snippets/invalid_syntax.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises src = """ def valid_func(): @@ -14,5 +14,5 @@ except SyntaxError as ex: else: raise AssertionError("Must throw syntax error") -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): compile('0xX', 'test.py', 'exec') diff --git a/tests/snippets/iterable.py b/tests/snippets/iterable.py index 45bb1cf4d..bd3e1dcd7 100644 --- a/tests/snippets/iterable.py +++ b/tests/snippets/iterable.py @@ -29,4 +29,4 @@ test_container(C()) class C: pass assert_raises(TypeError, lambda: 5 in C()) -assert_raises(TypeError, lambda: iter(C)) +assert_raises(TypeError, iter, C) diff --git a/tests/snippets/list.py b/tests/snippets/list.py index e8e731de9..bf92337de 100644 --- a/tests/snippets/list.py +++ b/tests/snippets/list.py @@ -87,7 +87,7 @@ a.remove(1) assert len(a) == 2 assert not 1 in a -assert_raises(ValueError, lambda: a.remove(10), 'Remove not exist element') +assert_raises(ValueError, lambda: a.remove(10), _msg='Remove not exist element') foo = bar = [1] foo += [2] @@ -142,7 +142,7 @@ for size in [1, 2, 3, 4, 5, 8, 10, 100, 1000]: lst.sort() assert lst == orig assert sorted(lst) == orig - assert_raises(ZeroDivisionError, lambda: sorted(lst, key=lambda x: 1/x)) + assert_raises(ZeroDivisionError, sorted, lst, key=lambda x: 1/x) lst.reverse() assert sorted(lst) == orig assert sorted(lst, reverse=True) == lst diff --git a/tests/snippets/mappingproxy.py b/tests/snippets/mappingproxy.py index 254f2a925..fa3b17bee 100644 --- a/tests/snippets/mappingproxy.py +++ b/tests/snippets/mappingproxy.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises class A(dict): def a(): @@ -9,7 +9,7 @@ class A(dict): assert A.__dict__['a'] == A.a -with assertRaises(KeyError) as cm: +with assert_raises(KeyError) as cm: A.__dict__['not here'] assert cm.exception.args[0] == "not here" diff --git a/tests/snippets/math_basics.py b/tests/snippets/math_basics.py index ffead8ecd..ef6f587ce 100644 --- a/tests/snippets/math_basics.py +++ b/tests/snippets/math_basics.py @@ -29,18 +29,12 @@ assert round(1.5) == 2 assert round(-0.5) == 0 assert round(-1.5) == -2 -assert_raises( - ValueError, - lambda: round(float('nan')), - 'ValueError: cannot convert float NaN to integer') -assert_raises( - OverflowError, - lambda: round(float('inf')), - 'OverflowError: cannot convert float infinity to integer') -assert_raises( - OverflowError, - lambda: round(-float('inf')), - 'OverflowError: cannot convert float infinity to integer') +# ValueError: cannot convert float NaN to integer +assert_raises(ValueError, round, float('nan')) +# OverflowError: cannot convert float infinity to integer +assert_raises(OverflowError, round, float('inf')) +# OverflowError: cannot convert float infinity to integer +assert_raises(OverflowError, round, -float('inf')) assert pow(0, 0) == 1 assert pow(2, 2) == 4 @@ -52,23 +46,8 @@ assert pow(-1, 10**1000+1) == -1 assert pow(-1, 10**1000) == 1 assert pow(2, 4, 5) == 1 -assert_raises( - TypeError, - lambda: pow(2, 4, 5.0), - 'pow() 3rd argument not allowed unless all arguments are integers') -assert_raises( - TypeError, - lambda: pow(2, 4.0, 5), - 'pow() 3rd argument not allowed unless all arguments are integers') -assert_raises( - TypeError, - lambda: pow(2.0, 4, 5), - 'pow() 3rd argument not allowed unless all arguments are integers') -assert_raises( - ValueError, - lambda: pow(2, -1, 5), - 'pow() 2nd argument cannot be negative when 3rd argument specified') -assert_raises( - ValueError, - lambda: pow(2, 2, 0), - 'pow() 3rd argument cannot be 0') +assert_raises(TypeError, pow, 2, 4, 5.0) +assert_raises(TypeError, pow, 2, 4.0, 5) +assert_raises(TypeError, pow, 2.0, 4, 5) +assert_raises(ValueError, pow, 2, -1, 5) +assert_raises(ValueError, pow, 2, 2, 0) diff --git a/tests/snippets/math_module.py b/tests/snippets/math_module.py index 92b6f30a6..f85a7337a 100644 --- a/tests/snippets/math_module.py +++ b/tests/snippets/math_module.py @@ -1,5 +1,5 @@ import math -from testutils import assertRaises, assert_raises +from testutils import assert_raises # assert(math.exp(2) == math.exp(2.0)) # assert(math.exp(True) == math.exp(1.0)) @@ -17,9 +17,9 @@ assert int.__floor__ assert int.__ceil__ # assert float.__trunc__ -with assertRaises(AttributeError): +with assert_raises(AttributeError): assert float.__floor__ -with assertRaises(AttributeError): +with assert_raises(AttributeError): assert float.__ceil__ assert math.trunc(2) == 2 @@ -72,11 +72,11 @@ assert math.trunc(A()) == 'trunc' assert math.ceil(A()) == 'ceil' assert math.floor(A()) == 'floor' -with assertRaises(TypeError): +with assert_raises(TypeError): math.trunc(object()) -with assertRaises(TypeError): +with assert_raises(TypeError): math.ceil(object()) -with assertRaises(TypeError): +with assert_raises(TypeError): math.floor(object()) assert str(math.frexp(0.0)) == str((+0.0, 0)) diff --git a/tests/snippets/numbers.py b/tests/snippets/numbers.py index 1e6b03777..c6aee97ec 100644 --- a/tests/snippets/numbers.py +++ b/tests/snippets/numbers.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises x = 5 x.__init__(6) @@ -70,5 +70,5 @@ assert 1_2_3 == 123 assert 1_2.3_4 == 12.34 assert 1_2.3_4e0_0 == 12.34 -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): eval('1__2') diff --git a/tests/snippets/printing.py b/tests/snippets/printing.py index b2c9ca55d..db53c80ed 100644 --- a/tests/snippets/printing.py +++ b/tests/snippets/printing.py @@ -3,8 +3,8 @@ import io print(2 + 3) -assert_raises(TypeError, lambda: print('test', end=4), 'wrong type passed to end') -assert_raises(TypeError, lambda: print('test', sep=['a']), 'wrong type passed to sep') +assert_raises(TypeError, print, 'test', end=4, _msg='wrong type passed to end') +assert_raises(TypeError, print, 'test', sep=['a'], _msg='wrong type passed to sep') try: print('test', end=None, sep=None, flush=None) diff --git a/tests/snippets/property.py b/tests/snippets/property.py index afcfe16ec..2a97c99b3 100644 --- a/tests/snippets/property.py +++ b/tests/snippets/property.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises class Fubar: @@ -53,10 +53,10 @@ p = property(lambda x: x[0]) assert p.__get__((2,), tuple) == 2 assert p.__get__((2,)) == 2 -with assertRaises(AttributeError): +with assert_raises(AttributeError): null_property.__get__((), tuple) -with assertRaises(TypeError): +with assert_raises(TypeError): property.__new__(object) assert p.__doc__ is None diff --git a/tests/snippets/set.py b/tests/snippets/set.py index 50b8f97d8..06e988693 100644 --- a/tests/snippets/set.py +++ b/tests/snippets/set.py @@ -1,4 +1,4 @@ -from testutils import assert_raises, assertRaises +from testutils import assert_raises assert set([1,2]) == set([1,2]) assert not set([1,2,3]) == set([1,2]) @@ -29,10 +29,10 @@ assert not set([1,3]) < set([1,2]) assert (set() == []) is False assert set().__eq__([]) == NotImplemented -assert_raises(TypeError, lambda: set() < [], "'<' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() <= [], "'<=' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() > [], "'>' not supported between instances of 'set' and 'list'") -assert_raises(TypeError, lambda: set() >= [], "'>=' not supported between instances of 'set' and 'list'") +assert_raises(TypeError, lambda: set() < [], _msg="'<' not supported between instances of 'set' and 'list'") +assert_raises(TypeError, lambda: set() <= [], _msg="'<=' not supported between instances of 'set' and 'list'") +assert_raises(TypeError, lambda: set() > [], _msg="'>' not supported between instances of 'set' and 'list'") +assert_raises(TypeError, lambda: set() >= [], _msg="'>=' not supported between instances of 'set' and 'list'") assert set().issuperset([]) assert set().issubset([]) assert not set().issuperset([1, 2, 3]) @@ -40,12 +40,12 @@ assert set().issubset([1, 2]) assert (set() == 3) is False assert set().__eq__(3) == NotImplemented -assert_raises(TypeError, lambda: set() < 3, "'int' object is not iterable") -assert_raises(TypeError, lambda: set() <= 3, "'int' object is not iterable") -assert_raises(TypeError, lambda: set() > 3, "'int' object is not iterable") -assert_raises(TypeError, lambda: set() >= 3, "'int' object is not iterable") -assert_raises(TypeError, lambda: set().issuperset(3), "'int' object is not iterable") -assert_raises(TypeError, lambda: set().issubset(3), "'int' object is not iterable") +assert_raises(TypeError, lambda: set() < 3, _msg="'int' object is not iterable") +assert_raises(TypeError, lambda: set() <= 3, _msg="'int' object is not iterable") +assert_raises(TypeError, lambda: set() > 3, _msg="'int' object is not iterable") +assert_raises(TypeError, lambda: set() >= 3, _msg="'int' object is not iterable") +assert_raises(TypeError, set().issuperset, 3, _msg="'int' object is not iterable") +assert_raises(TypeError, set().issubset, 3, _msg="'int' object is not iterable") class Hashable(object): def __init__(self, obj): @@ -109,8 +109,8 @@ assert_raises(TypeError, lambda: set() ^ []) assert_raises(TypeError, lambda: set() + []) assert_raises(TypeError, lambda: set() - []) -assert_raises(TypeError, lambda: set([[]])) -assert_raises(TypeError, lambda: set().add([])) +assert_raises(TypeError, set, [[]]) +assert_raises(TypeError, set().add, []) a = set([1, 2, 3]) assert a.discard(1) is None @@ -147,9 +147,9 @@ assert a == b a = set([1,2,3]) a |= set([3,4,5]) assert a == set([1,2,3,4,5]) -with assertRaises(TypeError): +with assert_raises(TypeError): a |= 1 -with assertRaises(TypeError): +with assert_raises(TypeError): a |= [1,2,3] a = set([1,2,3]) @@ -160,9 +160,9 @@ assert_raises(TypeError, lambda: a.intersection_update(1)) a = set([1,2,3]) a &= set([2,3,4,5]) assert a == set([2,3]) -with assertRaises(TypeError): +with assert_raises(TypeError): a &= 1 -with assertRaises(TypeError): +with assert_raises(TypeError): a &= [1,2,3] a = set([1,2,3]) @@ -173,9 +173,9 @@ assert_raises(TypeError, lambda: a.difference_update(1)) a = set([1,2,3]) a -= set([3,4,5]) assert a == set([1,2]) -with assertRaises(TypeError): +with assert_raises(TypeError): a -= 1 -with assertRaises(TypeError): +with assert_raises(TypeError): a -= [1,2,3] a = set([1,2,3]) @@ -186,9 +186,9 @@ assert_raises(TypeError, lambda: a.difference_update(1)) a = set([1,2,3]) a ^= set([3,4,5]) assert a == set([1,2,4,5]) -with assertRaises(TypeError): +with assert_raises(TypeError): a ^= 1 -with assertRaises(TypeError): +with assert_raises(TypeError): a ^= [1,2,3] # frozen set @@ -261,7 +261,7 @@ assert frozenset([1,2,3]).isdisjoint(frozenset([5,6])) == True assert frozenset([1,2,3]).isdisjoint(frozenset([2,5,6])) == False assert frozenset([1,2,3]).isdisjoint([5,6]) == True -assert_raises(TypeError, lambda: frozenset([[]])) +assert_raises(TypeError, frozenset, [[]]) a = frozenset([1,2,3]) b = set() diff --git a/tests/snippets/stdlib_binascii.py b/tests/snippets/stdlib_binascii.py index e56b3e47d..1d5ee8b3a 100644 --- a/tests/snippets/stdlib_binascii.py +++ b/tests/snippets/stdlib_binascii.py @@ -1,5 +1,5 @@ import binascii -from testutils import assertRaises +from testutils import assert_raises # hexlify tests @@ -11,7 +11,7 @@ assert h(1000 * b"x") == 1000 * b"78" # assert h(bytearray(b"a")) = b"61" assert binascii.b2a_hex(b"aa") == b"6161" -with assertRaises(TypeError): +with assert_raises(TypeError): h("a") @@ -28,10 +28,10 @@ assert binascii.a2b_hex(b"6161") == b"aa" # unhexlify on strings not supported yet # assert uh("abcd") == b"\xab\xcd" -with assertRaises(ValueError): +with assert_raises(ValueError): uh(b"a") # Odd-length string -with assertRaises(ValueError): +with assert_raises(ValueError): uh(b"nn") # Non-hexadecimal digit found assert binascii.crc32(b"hello world") == 222957957 diff --git a/tests/snippets/stdlib_datetime.py b/tests/snippets/stdlib_datetime.py index 30862154c..5302117f3 100644 --- a/tests/snippets/stdlib_datetime.py +++ b/tests/snippets/stdlib_datetime.py @@ -18,39 +18,9 @@ from datetime import timezone from datetime import date, datetime import time as _time -from testutils import assertRaises - -def _assert_print(f, args): - raised = True - try: - f() - raised = False - finally: - if raised: - print('Assertion Failure:', *args) - -def _typed(obj): - return '{}({})'.format(type(obj), obj) - - -def assert_equal(a, b): - _assert_print(lambda: a == b, [_typed(a), '==', _typed(b)]) - - -def assert_true(e): - _assert_print(lambda: e is True, [_typed(e), 'is True']) - - -def assert_false(e): - _assert_print(lambda: e is False, [_typed(e), 'is False']) - - -def assert_isinstance(obj, klass): - _assert_print(lambda: isinstance(obj, klass), ['isisntance(', _typed(obj), ',', klass, ')']) - -def assert_in(a, b): - _assert_print(lambda: a in b, [a, 'in', b]) - +from testutils import ( + assert_raises, assert_equal, assert_true, assert_false, assert_isinstance, + assert_in) # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. @@ -131,7 +101,7 @@ class _TZInfo(tzinfo): # def test_refcnt_crash_bug_22044(self): tz1 = _TZInfo() dt1 = datetime(2014, 7, 21, 11, 32, 3, 0, tz1) -with assertRaises(TypeError): +with assert_raises(TypeError): dt1.utcoffset() # def test_non_abstractness(self): @@ -140,11 +110,11 @@ with assertRaises(TypeError): # NotImplementedError. useless = tzinfo() dt = datetime.max -with assertRaises(NotImplementedError): +with assert_raises(NotImplementedError): useless.tzname(dt) -with assertRaises(NotImplementedError): +with assert_raises(NotImplementedError): useless.utcoffset(dt) -with assertRaises(NotImplementedError): +with assert_raises(NotImplementedError): useless.dst(dt) # def test_subclass_must_override(self): @@ -157,9 +127,9 @@ ne = NotEnough(3, "NotByALongShot") assert_isinstance(ne, tzinfo) dt = datetime.now() -assertRaises(NotImplementedError, ne.tzname, dt) -assertRaises(NotImplementedError, ne.utcoffset, dt) -assertRaises(NotImplementedError, ne.dst, dt) +assert_raises(NotImplementedError, ne.tzname, dt) +assert_raises(NotImplementedError, ne.utcoffset, dt) +assert_raises(NotImplementedError, ne.dst, dt) # XXX: bug #1302 # def test_normal(self): @@ -205,14 +175,14 @@ class TestTimeZone(unittest.TestCase): # invalid offsets for invalid in [timedelta(microseconds=1), timedelta(1, 1), timedelta(seconds=1), timedelta(1), -timedelta(1)]: - assertRaises(ValueError, timezone, invalid) - assertRaises(ValueError, timezone, -invalid) + assert_raises(ValueError, timezone, invalid) + assert_raises(ValueError, timezone, -invalid) - with assertRaises(TypeError): timezone(None) - with assertRaises(TypeError): timezone(42) - with assertRaises(TypeError): timezone(ZERO, None) - with assertRaises(TypeError): timezone(ZERO, 42) - with assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra') + with assert_raises(TypeError): timezone(None) + with assert_raises(TypeError): timezone(42) + with assert_raises(TypeError): timezone(ZERO, None) + with assert_raises(TypeError): timezone(ZERO, 42) + with assert_raises(TypeError): timezone(ZERO, 'ABC', 'extra') def test_inheritance(self): assert_isinstance(timezone.utc, tzinfo) @@ -225,15 +195,15 @@ class TestTimeZone(unittest.TestCase): assert_equal(offset, timezone(offset).utcoffset(dummy)) assert_equal(-offset, timezone(-offset).utcoffset(dummy)) - with assertRaises(TypeError): self.EST.utcoffset('') - with assertRaises(TypeError): self.EST.utcoffset(5) + with assert_raises(TypeError): self.EST.utcoffset('') + with assert_raises(TypeError): self.EST.utcoffset(5) def test_dst(self): self.assertIsNone(timezone.utc.dst(self.DT)) - with assertRaises(TypeError): self.EST.dst('') - with assertRaises(TypeError): self.EST.dst(5) + with assert_raises(TypeError): self.EST.dst('') + with assert_raises(TypeError): self.EST.dst(5) def test_tzname(self): assert_equal('UTC+00:00', timezone(ZERO).tzname(None)) @@ -242,13 +212,13 @@ class TestTimeZone(unittest.TestCase): assert_equal('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None)) assert_equal('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None)) - with assertRaises(TypeError): self.EST.tzname('') - with assertRaises(TypeError): self.EST.tzname(5) + with assert_raises(TypeError): self.EST.tzname('') + with assert_raises(TypeError): self.EST.tzname(5) def test_fromutc(self): - with assertRaises(ValueError): + with assert_raises(ValueError): timezone.utc.fromutc(self.DT) - with assertRaises(TypeError): + with assert_raises(TypeError): timezone.utc.fromutc('not datetime') for tz in [self.EST, self.ACDT, Eastern]: utctime = self.DT.replace(tzinfo=tz) @@ -261,7 +231,7 @@ class TestTimeZone(unittest.TestCase): self.assertNotEqual(timezone(ZERO), timezone(HOUR)) assert_equal(timezone(HOUR), timezone(HOUR)) assert_equal(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST')) - with assertRaises(TypeError): timezone(ZERO) < timezone(ZERO) + with assert_raises(TypeError): timezone(ZERO) < timezone(ZERO) assert_in(timezone(ZERO), {timezone(ZERO)}) assert_true(timezone(ZERO) != None) assert_false(timezone(ZERO) == None) @@ -329,15 +299,15 @@ for theclass in timedelta, date, time: # def test_harmful_mixed_comparison(self): me = theclass(1, 1, 1) - assertRaises(TypeError, lambda: me < ()) - assertRaises(TypeError, lambda: me <= ()) - assertRaises(TypeError, lambda: me > ()) - assertRaises(TypeError, lambda: me >= ()) + assert_raises(TypeError, lambda: me < ()) + assert_raises(TypeError, lambda: me <= ()) + assert_raises(TypeError, lambda: me > ()) + assert_raises(TypeError, lambda: me >= ()) - assertRaises(TypeError, lambda: () < me) - assertRaises(TypeError, lambda: () <= me) - assertRaises(TypeError, lambda: () > me) - assertRaises(TypeError, lambda: () >= me) + assert_raises(TypeError, lambda: () < me) + assert_raises(TypeError, lambda: () <= me) + assert_raises(TypeError, lambda: () > me) + assert_raises(TypeError, lambda: () >= me) ''' ############################################################################# @@ -459,25 +429,25 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): # Add/sub ints or floats should be illegal for i in 1, 1.0: - assertRaises(TypeError, lambda: a+i) - assertRaises(TypeError, lambda: a-i) - assertRaises(TypeError, lambda: i+a) - assertRaises(TypeError, lambda: i-a) + assert_raises(TypeError, lambda: a+i) + assert_raises(TypeError, lambda: a-i) + assert_raises(TypeError, lambda: i+a) + assert_raises(TypeError, lambda: i-a) # Division of int by timedelta doesn't make sense. # Division by zero doesn't make sense. zero = 0 - assertRaises(TypeError, lambda: zero // a) - assertRaises(ZeroDivisionError, lambda: a // zero) - assertRaises(ZeroDivisionError, lambda: a / zero) - assertRaises(ZeroDivisionError, lambda: a / 0.0) - assertRaises(TypeError, lambda: a / '') + assert_raises(TypeError, lambda: zero // a) + assert_raises(ZeroDivisionError, lambda: a // zero) + assert_raises(ZeroDivisionError, lambda: a / zero) + assert_raises(ZeroDivisionError, lambda: a / 0.0) + assert_raises(TypeError, lambda: a / '') @support.requires_IEEE_754 def test_disallowed_special(self): a = timedelta(42) - assertRaises(ValueError, a.__mul__, NAN) - assertRaises(ValueError, a.__truediv__, NAN) + assert_raises(ValueError, a.__mul__, NAN) + assert_raises(ValueError, a.__truediv__, NAN) def test_basic_attributes(self): days, seconds, us = 1, 7, 31 @@ -567,14 +537,14 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): assert_equal(badarg == t1, False) assert_equal(badarg != t1, True) - assertRaises(TypeError, lambda: t1 <= badarg) - assertRaises(TypeError, lambda: t1 < badarg) - assertRaises(TypeError, lambda: t1 > badarg) - assertRaises(TypeError, lambda: t1 >= badarg) - assertRaises(TypeError, lambda: badarg <= t1) - assertRaises(TypeError, lambda: badarg < t1) - assertRaises(TypeError, lambda: badarg > t1) - assertRaises(TypeError, lambda: badarg >= t1) + assert_raises(TypeError, lambda: t1 <= badarg) + assert_raises(TypeError, lambda: t1 < badarg) + assert_raises(TypeError, lambda: t1 > badarg) + assert_raises(TypeError, lambda: t1 >= badarg) + assert_raises(TypeError, lambda: badarg <= t1) + assert_raises(TypeError, lambda: badarg < t1) + assert_raises(TypeError, lambda: badarg > t1) + assert_raises(TypeError, lambda: badarg >= t1) def test_str(self): td = timedelta @@ -638,28 +608,28 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): td = timedelta.min + tiny td -= tiny # no problem - assertRaises(OverflowError, td.__sub__, tiny) - assertRaises(OverflowError, td.__add__, -tiny) + assert_raises(OverflowError, td.__sub__, tiny) + assert_raises(OverflowError, td.__add__, -tiny) td = timedelta.max - tiny td += tiny # no problem - assertRaises(OverflowError, td.__add__, tiny) - assertRaises(OverflowError, td.__sub__, -tiny) + assert_raises(OverflowError, td.__add__, tiny) + assert_raises(OverflowError, td.__sub__, -tiny) - assertRaises(OverflowError, lambda: -timedelta.max) + assert_raises(OverflowError, lambda: -timedelta.max) day = timedelta(1) - assertRaises(OverflowError, day.__mul__, 10**9) - assertRaises(OverflowError, day.__mul__, 1e9) - assertRaises(OverflowError, day.__truediv__, 1e-20) - assertRaises(OverflowError, day.__truediv__, 1e-10) - assertRaises(OverflowError, day.__truediv__, 9e-10) + assert_raises(OverflowError, day.__mul__, 10**9) + assert_raises(OverflowError, day.__mul__, 1e9) + assert_raises(OverflowError, day.__truediv__, 1e-20) + assert_raises(OverflowError, day.__truediv__, 1e-10) + assert_raises(OverflowError, day.__truediv__, 9e-10) @support.requires_IEEE_754 def _test_overflow_special(self): day = timedelta(1) - assertRaises(OverflowError, day.__mul__, INF) - assertRaises(OverflowError, day.__mul__, -INF) + assert_raises(OverflowError, day.__mul__, INF) + assert_raises(OverflowError, day.__mul__, -INF) def test_microsecond_rounding(self): td = timedelta @@ -749,10 +719,10 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): assert_equal(t // minute, 2) zerotd = timedelta(0) - assertRaises(ZeroDivisionError, truediv, t, zerotd) - assertRaises(ZeroDivisionError, floordiv, t, zerotd) + assert_raises(ZeroDivisionError, truediv, t, zerotd) + assert_raises(ZeroDivisionError, floordiv, t, zerotd) - # assertRaises(TypeError, truediv, t, 2) + # assert_raises(TypeError, truediv, t, 2) # note: floor division of a timedelta by an integer *is* # currently permitted. @@ -767,9 +737,9 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): assert_equal(r, timedelta(seconds=30)) zerotd = timedelta(0) - assertRaises(ZeroDivisionError, mod, t, zerotd) + assert_raises(ZeroDivisionError, mod, t, zerotd) - assertRaises(TypeError, mod, t, 10) + assert_raises(TypeError, mod, t, 10) def test_divmod(self): t = timedelta(minutes=2, seconds=30) @@ -784,9 +754,9 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): assert_equal(r, timedelta(seconds=30)) zerotd = timedelta(0) - assertRaises(ZeroDivisionError, divmod, t, zerotd) + assert_raises(ZeroDivisionError, divmod, t, zerotd) - assertRaises(TypeError, divmod, t, 10) + assert_raises(TypeError, divmod, t, 10) ############################################################################# @@ -908,7 +878,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): b = a.fromordinal(aord) assert_equal(a, b) - assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) + assert_raises(ValueError, lambda: a.fromordinal(aord - 1)) b = a + timedelta(days=1) assert_equal(b.toordinal(), aord + 1) @@ -920,7 +890,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): b = a.fromordinal(aord) assert_equal(a, b) - assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) + assert_raises(ValueError, lambda: a.fromordinal(aord + 1)) b = a - timedelta(days=1) assert_equal(b.toordinal(), aord - 1) @@ -930,23 +900,23 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): # bad years self.theclass(MINYEAR, 1, 1) # no exception self.theclass(MAXYEAR, 1, 1) # no exception - assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + assert_raises(ValueError, self.theclass, MINYEAR-1, 1, 1) + assert_raises(ValueError, self.theclass, MAXYEAR+1, 1, 1) # bad months self.theclass(2000, 1, 1) # no exception self.theclass(2000, 12, 1) # no exception - assertRaises(ValueError, self.theclass, 2000, 0, 1) - assertRaises(ValueError, self.theclass, 2000, 13, 1) + assert_raises(ValueError, self.theclass, 2000, 0, 1) + assert_raises(ValueError, self.theclass, 2000, 13, 1) # bad days self.theclass(2000, 2, 29) # no exception self.theclass(2004, 2, 29) # no exception self.theclass(2400, 2, 29) # no exception - assertRaises(ValueError, self.theclass, 2000, 2, 30) - assertRaises(ValueError, self.theclass, 2001, 2, 29) - assertRaises(ValueError, self.theclass, 2100, 2, 29) - assertRaises(ValueError, self.theclass, 1900, 2, 29) - assertRaises(ValueError, self.theclass, 2000, 1, 0) - assertRaises(ValueError, self.theclass, 2000, 1, 32) + assert_raises(ValueError, self.theclass, 2000, 2, 30) + assert_raises(ValueError, self.theclass, 2001, 2, 29) + assert_raises(ValueError, self.theclass, 2100, 2, 29) + assert_raises(ValueError, self.theclass, 1900, 2, 29) + assert_raises(ValueError, self.theclass, 2000, 1, 0) + assert_raises(ValueError, self.theclass, 2000, 1, 32) def test_hash_equality(self): d = self.theclass(2000, 12, 31) @@ -1006,22 +976,22 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): # Add/sub ints or floats should be illegal for i in 1, 1.0: - assertRaises(TypeError, lambda: a+i) - assertRaises(TypeError, lambda: a-i) - assertRaises(TypeError, lambda: i+a) - assertRaises(TypeError, lambda: i-a) + assert_raises(TypeError, lambda: a+i) + assert_raises(TypeError, lambda: a-i) + assert_raises(TypeError, lambda: i+a) + assert_raises(TypeError, lambda: i-a) # delta - date is senseless. - assertRaises(TypeError, lambda: day - a) + assert_raises(TypeError, lambda: day - a) # mixing date and (delta or date) via * or // is senseless - assertRaises(TypeError, lambda: day * a) - assertRaises(TypeError, lambda: a * day) - assertRaises(TypeError, lambda: day // a) - assertRaises(TypeError, lambda: a // day) - assertRaises(TypeError, lambda: a * a) - assertRaises(TypeError, lambda: a // a) + assert_raises(TypeError, lambda: day * a) + assert_raises(TypeError, lambda: a * day) + assert_raises(TypeError, lambda: day // a) + assert_raises(TypeError, lambda: a // day) + assert_raises(TypeError, lambda: a * a) + assert_raises(TypeError, lambda: a // a) # date + date is senseless - assertRaises(TypeError, lambda: a + a) + assert_raises(TypeError, lambda: a + a) def test_overflow(self): tiny = self.theclass.resolution @@ -1029,13 +999,13 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): for delta in [tiny, timedelta(1), timedelta(2)]: dt = self.theclass.min + delta dt -= delta # no problem - assertRaises(OverflowError, dt.__sub__, delta) - assertRaises(OverflowError, dt.__add__, -delta) + assert_raises(OverflowError, dt.__sub__, delta) + assert_raises(OverflowError, dt.__add__, -delta) dt = self.theclass.max - delta dt += delta # no problem - assertRaises(OverflowError, dt.__add__, delta) - assertRaises(OverflowError, dt.__sub__, -delta) + assert_raises(OverflowError, dt.__add__, delta) + assert_raises(OverflowError, dt.__sub__, -delta) def test_fromtimestamp(self): import time @@ -1054,7 +1024,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - assertRaises(OverflowError, self.theclass.fromtimestamp, + assert_raises(OverflowError, self.theclass.fromtimestamp, insane) def test_today(self): @@ -1164,9 +1134,9 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): assert_equal(t.strftime(""), "") # SF bug #761337 assert_equal(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 - assertRaises(TypeError, t.strftime) # needs an arg - assertRaises(TypeError, t.strftime, "one", "two") # too many args - assertRaises(TypeError, t.strftime, 42) # arg wrong type + assert_raises(TypeError, t.strftime) # needs an arg + assert_raises(TypeError, t.strftime, "one", "two") # too many args + assert_raises(TypeError, t.strftime, 42) # arg wrong type # test that unicode input is allowed (issue 2782) assert_equal(t.strftime("%m"), "03") @@ -1175,9 +1145,9 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): assert_equal(t.strftime("'%z' '%Z'"), "'' ''") #make sure that invalid format specifiers are handled correctly - #assertRaises(ValueError, t.strftime, "%e") - #assertRaises(ValueError, t.strftime, "%") - #assertRaises(ValueError, t.strftime, "%#") + #assert_raises(ValueError, t.strftime, "%e") + #assert_raises(ValueError, t.strftime, "%") + #assert_raises(ValueError, t.strftime, "%#") #oh well, some systems just ignore those invalid ones. #at least, excercise them to make sure that no crashes @@ -1303,13 +1273,13 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): assert_equal(badarg == t1, False) assert_equal(badarg != t1, True) - assertRaises(TypeError, lambda: t1 < badarg) - assertRaises(TypeError, lambda: t1 > badarg) - assertRaises(TypeError, lambda: t1 >= badarg) - assertRaises(TypeError, lambda: badarg <= t1) - assertRaises(TypeError, lambda: badarg < t1) - assertRaises(TypeError, lambda: badarg > t1) - assertRaises(TypeError, lambda: badarg >= t1) + assert_raises(TypeError, lambda: t1 < badarg) + assert_raises(TypeError, lambda: t1 > badarg) + assert_raises(TypeError, lambda: t1 >= badarg) + assert_raises(TypeError, lambda: badarg <= t1) + assert_raises(TypeError, lambda: badarg < t1) + assert_raises(TypeError, lambda: badarg > t1) + assert_raises(TypeError, lambda: badarg >= t1) def test_mixed_compare(self): our = self.theclass(2000, 4, 5) @@ -1321,8 +1291,8 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): assert_equal(1 != our, True) # But the ordering is undefined - assertRaises(TypeError, lambda: our < 1) - assertRaises(TypeError, lambda: 1 < our) + assert_raises(TypeError, lambda: our < 1) + assert_raises(TypeError, lambda: 1 < our) # Repeat those tests with a different class @@ -1334,8 +1304,8 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): assert_equal(their == our, False) assert_equal(our != their, True) assert_equal(their != our, True) - assertRaises(TypeError, lambda: our < their) - assertRaises(TypeError, lambda: their < our) + assert_raises(TypeError, lambda: our < their) + assert_raises(TypeError, lambda: their < our) # However, if the other class explicitly defines ordering # relative to our class, it is allowed to do so @@ -1399,7 +1369,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): # Out of bounds. base = cls(2000, 2, 29) - assertRaises(ValueError, base.replace, year=2001) + assert_raises(ValueError, base.replace, year=2001) def test_subclass_date(self): @@ -1449,10 +1419,10 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase): if not issubclass(self.theclass, datetime): base = base[:4] for month_byte in b'9', b'\0', b'\r', b'\xff': - assertRaises(TypeError, self.theclass, + assert_raises(TypeError, self.theclass, base[:2] + month_byte + base[3:]) # Good bytes, but bad tzinfo: - assertRaises(TypeError, self.theclass, + assert_raises(TypeError, self.theclass, bytes([1] * len(base)), 'EST') for ord_byte in range(1, 13): @@ -1594,50 +1564,50 @@ class TestDateTime(TestDate): return None return MyStr('name') t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name')) - assertRaises(TypeError, t.strftime, '%Z') + assert_raises(TypeError, t.strftime, '%Z') def test_bad_constructor_arguments(self): # bad years self.theclass(MINYEAR, 1, 1) # no exception self.theclass(MAXYEAR, 1, 1) # no exception - assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + assert_raises(ValueError, self.theclass, MINYEAR-1, 1, 1) + assert_raises(ValueError, self.theclass, MAXYEAR+1, 1, 1) # bad months self.theclass(2000, 1, 1) # no exception self.theclass(2000, 12, 1) # no exception - assertRaises(ValueError, self.theclass, 2000, 0, 1) - assertRaises(ValueError, self.theclass, 2000, 13, 1) + assert_raises(ValueError, self.theclass, 2000, 0, 1) + assert_raises(ValueError, self.theclass, 2000, 13, 1) # bad days self.theclass(2000, 2, 29) # no exception self.theclass(2004, 2, 29) # no exception self.theclass(2400, 2, 29) # no exception - assertRaises(ValueError, self.theclass, 2000, 2, 30) - assertRaises(ValueError, self.theclass, 2001, 2, 29) - assertRaises(ValueError, self.theclass, 2100, 2, 29) - assertRaises(ValueError, self.theclass, 1900, 2, 29) - assertRaises(ValueError, self.theclass, 2000, 1, 0) - assertRaises(ValueError, self.theclass, 2000, 1, 32) + assert_raises(ValueError, self.theclass, 2000, 2, 30) + assert_raises(ValueError, self.theclass, 2001, 2, 29) + assert_raises(ValueError, self.theclass, 2100, 2, 29) + assert_raises(ValueError, self.theclass, 1900, 2, 29) + assert_raises(ValueError, self.theclass, 2000, 1, 0) + assert_raises(ValueError, self.theclass, 2000, 1, 32) # bad hours self.theclass(2000, 1, 31, 0) # no exception self.theclass(2000, 1, 31, 23) # no exception - assertRaises(ValueError, self.theclass, 2000, 1, 31, -1) - assertRaises(ValueError, self.theclass, 2000, 1, 31, 24) + assert_raises(ValueError, self.theclass, 2000, 1, 31, -1) + assert_raises(ValueError, self.theclass, 2000, 1, 31, 24) # bad minutes self.theclass(2000, 1, 31, 23, 0) # no exception self.theclass(2000, 1, 31, 23, 59) # no exception - assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1) - assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60) + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, -1) + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, 60) # bad seconds self.theclass(2000, 1, 31, 23, 59, 0) # no exception self.theclass(2000, 1, 31, 23, 59, 59) # no exception - assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) - assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) # bad microseconds self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception - assertRaises(ValueError, self.theclass, + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 59, -1) - assertRaises(ValueError, self.theclass, + assert_raises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 59, 1000000) @@ -1715,22 +1685,22 @@ class TestDateTime(TestDate): (((a - week) - day) - hour) - millisec) # Add/sub ints or floats should be illegal for i in 1, 1.0: - assertRaises(TypeError, lambda: a+i) - assertRaises(TypeError, lambda: a-i) - assertRaises(TypeError, lambda: i+a) - assertRaises(TypeError, lambda: i-a) + assert_raises(TypeError, lambda: a+i) + assert_raises(TypeError, lambda: a-i) + assert_raises(TypeError, lambda: i+a) + assert_raises(TypeError, lambda: i-a) # delta - datetime is senseless. - assertRaises(TypeError, lambda: day - a) + assert_raises(TypeError, lambda: day - a) # mixing datetime and (delta or datetime) via * or // is senseless - assertRaises(TypeError, lambda: day * a) - assertRaises(TypeError, lambda: a * day) - assertRaises(TypeError, lambda: day // a) - assertRaises(TypeError, lambda: a // day) - assertRaises(TypeError, lambda: a * a) - assertRaises(TypeError, lambda: a // a) + assert_raises(TypeError, lambda: day * a) + assert_raises(TypeError, lambda: a * day) + assert_raises(TypeError, lambda: day // a) + assert_raises(TypeError, lambda: a // day) + assert_raises(TypeError, lambda: a * a) + assert_raises(TypeError, lambda: a // a) # datetime + datetime is senseless - assertRaises(TypeError, lambda: a + a) + assert_raises(TypeError, lambda: a + a) def test_pickling(self): args = 6, 7, 23, 20, 59, 1, 64**2 @@ -1897,7 +1867,7 @@ class TestDateTime(TestDate): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - assertRaises(OverflowError, self.theclass.fromtimestamp, + assert_raises(OverflowError, self.theclass.fromtimestamp, insane) def test_insane_utcfromtimestamp(self): @@ -1906,7 +1876,7 @@ class TestDateTime(TestDate): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - assertRaises(OverflowError, self.theclass.utcfromtimestamp, + assert_raises(OverflowError, self.theclass.utcfromtimestamp, insane) @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): @@ -1982,13 +1952,13 @@ class TestDateTime(TestDate): assert_equal(t, dt.time()) assert_equal(dt, combine(dt.date(), dt.time())) - assertRaises(TypeError, combine) # need an arg - assertRaises(TypeError, combine, d) # need two args - assertRaises(TypeError, combine, t, d) # args reversed - assertRaises(TypeError, combine, d, t, 1) # too many args - assertRaises(TypeError, combine, "date", "time") # wrong types - assertRaises(TypeError, combine, d, "time") # wrong type - assertRaises(TypeError, combine, "date", t) # wrong type + assert_raises(TypeError, combine) # need an arg + assert_raises(TypeError, combine, d) # need two args + assert_raises(TypeError, combine, t, d) # args reversed + assert_raises(TypeError, combine, d, t, 1) # too many args + assert_raises(TypeError, combine, "date", "time") # wrong types + assert_raises(TypeError, combine, d, "time") # wrong type + assert_raises(TypeError, combine, "date", t) # wrong type def test_replace(self): cls = self.theclass @@ -2013,32 +1983,32 @@ class TestDateTime(TestDate): # Out of bounds. base = cls(2000, 2, 29) - assertRaises(ValueError, base.replace, year=2001) + assert_raises(ValueError, base.replace, year=2001) def test_astimezone(self): # Pretty boring! The TZ test is more interesting here. astimezone() # simply can't be applied to a naive object. dt = self.theclass.now() f = FixedOffset(44, "") - assertRaises(ValueError, dt.astimezone) # naive - assertRaises(TypeError, dt.astimezone, f, f) # too many args - assertRaises(TypeError, dt.astimezone, dt) # arg wrong type - assertRaises(ValueError, dt.astimezone, f) # naive - assertRaises(ValueError, dt.astimezone, tz=f) # naive + assert_raises(ValueError, dt.astimezone) # naive + assert_raises(TypeError, dt.astimezone, f, f) # too many args + assert_raises(TypeError, dt.astimezone, dt) # arg wrong type + assert_raises(ValueError, dt.astimezone, f) # naive + assert_raises(ValueError, dt.astimezone, tz=f) # naive class Bogus(tzinfo): def utcoffset(self, dt): return None def dst(self, dt): return timedelta(0) bog = Bogus() - assertRaises(ValueError, dt.astimezone, bog) # naive - assertRaises(ValueError, + assert_raises(ValueError, dt.astimezone, bog) # naive + assert_raises(ValueError, dt.replace(tzinfo=bog).astimezone, f) class AlsoBogus(tzinfo): def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return None alsobog = AlsoBogus() - assertRaises(ValueError, dt.astimezone, alsobog) # also naive + assert_raises(ValueError, dt.astimezone, alsobog) # also naive def test_subclass_datetime(self): @@ -2146,36 +2116,36 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): assert_equal(badarg == t1, False) assert_equal(badarg != t1, True) - assertRaises(TypeError, lambda: t1 <= badarg) - assertRaises(TypeError, lambda: t1 < badarg) - assertRaises(TypeError, lambda: t1 > badarg) - assertRaises(TypeError, lambda: t1 >= badarg) - assertRaises(TypeError, lambda: badarg <= t1) - assertRaises(TypeError, lambda: badarg < t1) - assertRaises(TypeError, lambda: badarg > t1) - assertRaises(TypeError, lambda: badarg >= t1) + assert_raises(TypeError, lambda: t1 <= badarg) + assert_raises(TypeError, lambda: t1 < badarg) + assert_raises(TypeError, lambda: t1 > badarg) + assert_raises(TypeError, lambda: t1 >= badarg) + assert_raises(TypeError, lambda: badarg <= t1) + assert_raises(TypeError, lambda: badarg < t1) + assert_raises(TypeError, lambda: badarg > t1) + assert_raises(TypeError, lambda: badarg >= t1) def test_bad_constructor_arguments(self): # bad hours self.theclass(0, 0) # no exception self.theclass(23, 0) # no exception - assertRaises(ValueError, self.theclass, -1, 0) - assertRaises(ValueError, self.theclass, 24, 0) + assert_raises(ValueError, self.theclass, -1, 0) + assert_raises(ValueError, self.theclass, 24, 0) # bad minutes self.theclass(23, 0) # no exception self.theclass(23, 59) # no exception - assertRaises(ValueError, self.theclass, 23, -1) - assertRaises(ValueError, self.theclass, 23, 60) + assert_raises(ValueError, self.theclass, 23, -1) + assert_raises(ValueError, self.theclass, 23, 60) # bad seconds self.theclass(23, 59, 0) # no exception self.theclass(23, 59, 59) # no exception - assertRaises(ValueError, self.theclass, 23, 59, -1) - assertRaises(ValueError, self.theclass, 23, 59, 60) + assert_raises(ValueError, self.theclass, 23, 59, -1) + assert_raises(ValueError, self.theclass, 23, 59, 60) # bad microseconds self.theclass(23, 59, 59, 0) # no exception self.theclass(23, 59, 59, 999999) # no exception - assertRaises(ValueError, self.theclass, 23, 59, 59, -1) - assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000) + assert_raises(ValueError, self.theclass, 23, 59, 59, -1) + assert_raises(ValueError, self.theclass, 23, 59, 59, 1000000) def test_hash_equality(self): d = self.theclass(23, 30, 17) @@ -2236,7 +2206,7 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): def test_1653736(self): # verify it doesn't accept extra keyword arguments t = self.theclass(second=1) - assertRaises(TypeError, t.isoformat, foo=3) + assert_raises(TypeError, t.isoformat, foo=3) def test_strftime(self): t = self.theclass(1, 2, 3, 4) @@ -2339,10 +2309,10 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): # Out of bounds. base = cls(1) - assertRaises(ValueError, base.replace, hour=24) - assertRaises(ValueError, base.replace, minute=-1) - assertRaises(ValueError, base.replace, second=100) - assertRaises(ValueError, base.replace, microsecond=1000000) + assert_raises(ValueError, base.replace, hour=24) + assert_raises(ValueError, base.replace, minute=-1) + assert_raises(ValueError, base.replace, second=100) + assert_raises(ValueError, base.replace, microsecond=1000000) def test_subclass_time(self): @@ -2374,7 +2344,7 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase): # see TestDate.test_backdoor_resistance(). base = '2:59.0' for hour_byte in ' ', '9', chr(24), '\xff': - assertRaises(TypeError, self.theclass, + assert_raises(TypeError, self.theclass, hour_byte + base[1:]) # A mixin for classes with a tzinfo= argument. Subclasses must define @@ -2402,12 +2372,12 @@ class TZInfoBase: def test_bad_tzinfo_classes(self): cls = self.theclass - assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12) + assert_raises(TypeError, cls, 1, 1, 1, tzinfo=12) class NiceTry(object): def __init__(self): pass def utcoffset(self, dt): pass - assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry) + assert_raises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry) class BetterTry(tzinfo): def __init__(self): pass @@ -2442,7 +2412,7 @@ class TZInfoBase: t = t.timetz() assert_equal(str(t), "01:02:03" + tag) else: - assertRaises(ValueError, str, t) + assert_raises(ValueError, str, t) def test_tzinfo_classes(self): cls = self.theclass @@ -2472,25 +2442,25 @@ class TZInfoBase: def dst(self, dt): return 7 def tzname(self, dt): return 0 t = cls(1, 1, 1, tzinfo=C4()) - assertRaises(TypeError, t.utcoffset) - assertRaises(TypeError, t.dst) - assertRaises(TypeError, t.tzname) + assert_raises(TypeError, t.utcoffset) + assert_raises(TypeError, t.dst) + assert_raises(TypeError, t.tzname) # Offset out of range. class C6(tzinfo): def utcoffset(self, dt): return timedelta(hours=-24) def dst(self, dt): return timedelta(hours=24) t = cls(1, 1, 1, tzinfo=C6()) - assertRaises(ValueError, t.utcoffset) - assertRaises(ValueError, t.dst) + assert_raises(ValueError, t.utcoffset) + assert_raises(ValueError, t.dst) # Not a whole number of minutes. class C7(tzinfo): def utcoffset(self, dt): return timedelta(seconds=61) def dst(self, dt): return timedelta(microseconds=-81) t = cls(1, 1, 1, tzinfo=C7()) - assertRaises(ValueError, t.utcoffset) - assertRaises(ValueError, t.dst) + assert_raises(ValueError, t.utcoffset) + assert_raises(ValueError, t.dst) def test_aware_compare(self): cls = self.theclass @@ -2572,19 +2542,19 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): assert_equal(t2.utcoffset(), timedelta(minutes=0)) assert_equal(t3.utcoffset(), timedelta(minutes=60)) self.assertIsNone(t4.utcoffset()) - assertRaises(TypeError, t1.utcoffset, "no args") + assert_raises(TypeError, t1.utcoffset, "no args") assert_equal(t1.tzname(), "EST") assert_equal(t2.tzname(), "UTC") assert_equal(t3.tzname(), "MET") self.assertIsNone(t4.tzname()) - assertRaises(TypeError, t1.tzname, "no args") + assert_raises(TypeError, t1.tzname, "no args") assert_equal(t1.dst(), timedelta(minutes=1)) assert_equal(t2.dst(), timedelta(minutes=-2)) assert_equal(t3.dst(), timedelta(minutes=3)) self.assertIsNone(t4.dst()) - assertRaises(TypeError, t1.dst, "no args") + assert_raises(TypeError, t1.dst, "no args") assert_equal(hash(t1), hash(t2)) assert_equal(hash(t1), hash(t3)) @@ -2594,8 +2564,8 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): assert_equal(t1, t3) assert_equal(t2, t3) self.assertNotEqual(t4, t5) # mixed tz-aware & naive - assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive - assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive + assert_raises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive + assert_raises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive assert_equal(str(t1), "07:47:00-05:00") assert_equal(str(t2), "12:47:00+00:00") @@ -2632,12 +2602,12 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): def tzname(self, dt): return self.tz t = time(2, 3, 4, tzinfo=Badtzname()) assert_equal(t.strftime("%H:%M:%S"), "02:03:04") - assertRaises(TypeError, t.strftime, "%Z") + assert_raises(TypeError, t.strftime, "%Z") # Issue #6697: if '_Fast' in str(type(self)): Badtzname.tz = '\ud800' - assertRaises(ValueError, t.strftime, "%Z") + assert_raises(ValueError, t.strftime, "%Z") def test_hash_edge_cases(self): # Offsets that overflow a basic time. @@ -2691,11 +2661,11 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): # But this should yield a value error -- the utcoffset is bogus. t = cls(0, tzinfo=FixedOffset(24*60, "")) - assertRaises(ValueError, lambda: bool(t)) + assert_raises(ValueError, bool, t) # Likewise. t = cls(0, tzinfo=FixedOffset(-24*60, "")) - assertRaises(ValueError, lambda: bool(t)) + assert_raises(ValueError, bool, t) def test_replace(self): cls = self.theclass @@ -2731,10 +2701,10 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): # Out of bounds. base = cls(1) - assertRaises(ValueError, base.replace, hour=24) - assertRaises(ValueError, base.replace, minute=-1) - assertRaises(ValueError, base.replace, second=100) - assertRaises(ValueError, base.replace, microsecond=1000000) + assert_raises(ValueError, base.replace, hour=24) + assert_raises(ValueError, base.replace, minute=-1) + assert_raises(ValueError, base.replace, second=100) + assert_raises(ValueError, base.replace, microsecond=1000000) def test_mixed_compare(self): t1 = time(1, 2, 3) @@ -2873,7 +2843,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): return timedelta(minutes=1440) # out of bounds t1 = self.theclass(2, 2, 2, tzinfo=Bogus()) t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, "")) - assertRaises(ValueError, lambda: t1 == t2) + assert_raises(ValueError, lambda: t1 == t2) def test_pickling(self): # Try one without a tzinfo. @@ -2908,7 +2878,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # OTOH, an OOB offset should blow up. t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, "")) - assertRaises(ValueError, hash, t) + assert_raises(ValueError, hash, t) def test_zones(self): est = FixedOffset(-300, "EST") @@ -2966,13 +2936,13 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): assert_equal(nowaware.timetz(), timeaware) # Can't mix aware and non-aware. - assertRaises(TypeError, lambda: now - nowaware) - assertRaises(TypeError, lambda: nowaware - now) + assert_raises(TypeError, lambda: now - nowaware) + assert_raises(TypeError, lambda: nowaware - now) # And adding datetime's doesn't make sense, aware or not. - assertRaises(TypeError, lambda: now + nowaware) - assertRaises(TypeError, lambda: nowaware + now) - assertRaises(TypeError, lambda: nowaware + nowaware) + assert_raises(TypeError, lambda: now + nowaware) + assert_raises(TypeError, lambda: nowaware + now) + assert_raises(TypeError, lambda: nowaware + nowaware) # Subtracting should yield 0. assert_equal(now - now, timedelta(0)) @@ -2991,7 +2961,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): diff = nowawareplus - delta self.assertIs(diff.tzinfo, tz55) assert_equal(nowaware, diff) - assertRaises(TypeError, lambda: delta - nowawareplus) + assert_raises(TypeError, lambda: delta - nowawareplus) assert_equal(nowawareplus - nowaware, delta) # Make up a random timezone. @@ -3033,12 +3003,12 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): self.assertIs(another.tzinfo, again.tzinfo) assert_equal(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. - assertRaises(TypeError, meth, 16) - assertRaises(TypeError, meth, tzinfo=16) + assert_raises(TypeError, meth, 16) + assert_raises(TypeError, meth, tzinfo=16) # Bad keyword name. - assertRaises(TypeError, meth, tinfo=off42) + assert_raises(TypeError, meth, tinfo=off42) # Too many args. - assertRaises(TypeError, meth, off42, off42) + assert_raises(TypeError, meth, off42, off42) # We don't know which time zone we're in, and don't have a tzinfo # class to represent it, so seeing whether a tz argument actually @@ -3072,14 +3042,14 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): self.assertIs(another.tzinfo, again.tzinfo) assert_equal(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. - assertRaises(TypeError, meth, ts, 16) - assertRaises(TypeError, meth, ts, tzinfo=16) + assert_raises(TypeError, meth, ts, 16) + assert_raises(TypeError, meth, ts, tzinfo=16) # Bad keyword name. - assertRaises(TypeError, meth, ts, tinfo=off42) + assert_raises(TypeError, meth, ts, tinfo=off42) # Too many args. - assertRaises(TypeError, meth, ts, off42, off42) + assert_raises(TypeError, meth, ts, off42, off42) # Too few args. - assertRaises(TypeError, meth) + assert_raises(TypeError, meth) # Try to make sure tz= actually does some conversion. timestamp = 1000000000 @@ -3101,8 +3071,8 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Try with and without naming the keyword; for whatever reason, # utcnow() doesn't accept a tzinfo argument. off42 = FixedOffset(42, "42") - assertRaises(TypeError, meth, off42) - assertRaises(TypeError, meth, tzinfo=off42) + assert_raises(TypeError, meth, off42) + assert_raises(TypeError, meth, tzinfo=off42) def test_tzinfo_utcfromtimestamp(self): import time @@ -3113,8 +3083,8 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Try with and without naming the keyword; for whatever reason, # utcfromtimestamp() doesn't accept a tzinfo argument. off42 = FixedOffset(42, "42") - assertRaises(TypeError, meth, ts, off42) - assertRaises(TypeError, meth, ts, tzinfo=off42) + assert_raises(TypeError, meth, ts, off42) + assert_raises(TypeError, meth, ts, tzinfo=off42) def test_tzinfo_timetuple(self): # TestDateTime tested most of this. datetime adds a twist to the @@ -3142,15 +3112,15 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): assert_equal(flag, t.tm_isdst) # dst() returns wrong type. - assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple) + assert_raises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple) # dst() at the edge. assert_equal(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1) assert_equal(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1) # dst() out of range. - assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple) - assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) + assert_raises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple) + assert_raises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) def test_utctimetuple(self): class DST(tzinfo): @@ -3163,7 +3133,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): cls = self.theclass # This can't work: DST didn't implement utcoffset. - assertRaises(NotImplementedError, + assert_raises(NotImplementedError, cls(1, 1, 1, tzinfo=DST(0)).utcoffset) class UOFS(DST): @@ -3207,7 +3177,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): def utcoffset(self, dt): return "EST" d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS()) - assertRaises(TypeError, d.utctimetuple) + assert_raises(TypeError, d.utctimetuple) # Check that utctimetuple() is the same as # astimezone(utc).timetuple() @@ -3221,16 +3191,16 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # raised. tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439)) # That goes back 1 minute less than a full day. - assertRaises(OverflowError, tiny.utctimetuple) + assert_raises(OverflowError, tiny.utctimetuple) huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439)) # That goes forward 1 minute less than a full day. - assertRaises(OverflowError, huge.utctimetuple) + assert_raises(OverflowError, huge.utctimetuple) # More overflow cases tiny = cls.min.replace(tzinfo=timezone(MINUTE)) - assertRaises(OverflowError, tiny.utctimetuple) + assert_raises(OverflowError, tiny.utctimetuple) huge = cls.max.replace(tzinfo=timezone(-MINUTE)) - assertRaises(OverflowError, huge.utctimetuple) + assert_raises(OverflowError, huge.utctimetuple) def test_tzinfo_isoformat(self): zero = FixedOffset(0, "+00:00") @@ -3290,7 +3260,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): # Out of bounds. base = cls(2000, 2, 29) - assertRaises(ValueError, base.replace, year=2001) + assert_raises(ValueError, base.replace, year=2001) def test_more_astimezone(self): # The inherited test_astimezone covered some trivial and error cases. @@ -3301,7 +3271,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): dt = self.theclass.now(tz=f44m) self.assertIs(dt.tzinfo, f44m) # Replacing with degenerate tzinfo raises an exception. - assertRaises(ValueError, dt.astimezone, fnone) + assert_raises(ValueError, dt.astimezone, fnone) # Replacing with same tzinfo makes no change. x = dt.astimezone(dt.tzinfo) self.assertIs(x.tzinfo, f44m) @@ -3691,7 +3661,7 @@ class TestTimezoneConversions(unittest.TestCase): # Does blow up. class notok(ok): def dst(self, dt): return None - assertRaises(ValueError, now.astimezone, notok()) + assert_raises(ValueError, now.astimezone, notok()) # Sometimes blow up. In the following, tzinfo.dst() # implementation may return None or not None depending on @@ -3704,17 +3674,17 @@ class TestTimezoneConversions(unittest.TestCase): else: return 10*HOUR dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real) - assertRaises(ValueError, dt.astimezone, tricky_notok()) + assert_raises(ValueError, dt.astimezone, tricky_notok()) def test_fromutc(self): - assertRaises(TypeError, Eastern.fromutc) # not enough args + assert_raises(TypeError, Eastern.fromutc) # not enough args now = datetime.utcnow().replace(tzinfo=utc_real) - assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo + assert_raises(ValueError, Eastern.fromutc, now) # wrong tzinfo now = now.replace(tzinfo=Eastern) # insert correct tzinfo enow = Eastern.fromutc(now) # doesn't blow up assert_equal(enow.tzinfo, Eastern) # has right tzinfo member - assertRaises(TypeError, Eastern.fromutc, now, now) # too many args - assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type + assert_raises(TypeError, Eastern.fromutc, now, now) # too many args + assert_raises(TypeError, Eastern.fromutc, date.today()) # wrong type # Always converts UTC to standard time. class FauxUSTimeZone(USTimeZone): @@ -3781,14 +3751,14 @@ assert_true(as_date != as_datetime) assert_true(as_datetime != as_date) assert_false(as_date == as_datetime) assert_false(as_datetime == as_date) -assertRaises(TypeError, lambda: as_date < as_datetime) -assertRaises(TypeError, lambda: as_datetime < as_date) -assertRaises(TypeError, lambda: as_date <= as_datetime) -assertRaises(TypeError, lambda: as_datetime <= as_date) -assertRaises(TypeError, lambda: as_date > as_datetime) -assertRaises(TypeError, lambda: as_datetime > as_date) -assertRaises(TypeError, lambda: as_date >= as_datetime) -assertRaises(TypeError, lambda: as_datetime >= as_date) +assert_raises(TypeError, lambda: as_date < as_datetime) +assert_raises(TypeError, lambda: as_datetime < as_date) +assert_raises(TypeError, lambda: as_date <= as_datetime) +assert_raises(TypeError, lambda: as_datetime <= as_date) +assert_raises(TypeError, lambda: as_date > as_datetime) +assert_raises(TypeError, lambda: as_datetime > as_date) +assert_raises(TypeError, lambda: as_date >= as_datetime) +assert_raises(TypeError, lambda: as_datetime >= as_date) # Neverthelss, comparison should work with the base-class (date) # projection if use of a date method is forced. diff --git a/tests/snippets/stdlib_functools.py b/tests/snippets/stdlib_functools.py index bd95f0e81..0bdafcb3b 100644 --- a/tests/snippets/stdlib_functools.py +++ b/tests/snippets/stdlib_functools.py @@ -1,5 +1,5 @@ from functools import reduce -from testutils import assertRaises +from testutils import assert_raises class Squares: def __init__(self, max): @@ -31,20 +31,20 @@ assert reduce(add, Squares(0), 0) == 0 assert reduce(42, "1") == "1" assert reduce(42, "", "1") == "1" -with assertRaises(TypeError): +with assert_raises(TypeError): reduce() -with assertRaises(TypeError): +with assert_raises(TypeError): reduce(42, 42) -with assertRaises(TypeError): +with assert_raises(TypeError): reduce(42, 42, 42) class TestFailingIter: def __iter__(self): raise RuntimeError -with assertRaises(RuntimeError): +with assert_raises(RuntimeError): reduce(add, TestFailingIter()) assert reduce(add, [], None) == None @@ -53,7 +53,7 @@ assert reduce(add, [], 42) == 42 class BadSeq: def __getitem__(self, index): raise ValueError -with assertRaises(ValueError): +with assert_raises(ValueError): reduce(42, BadSeq()) # Test reduce()'s use of iterators. @@ -68,7 +68,7 @@ class SequenceClass: assert reduce(add, SequenceClass(5)) == 10 assert reduce(add, SequenceClass(5), 42) == 52 -with assertRaises(TypeError): +with assert_raises(TypeError): reduce(add, SequenceClass(0)) assert reduce(add, SequenceClass(0), 42) == 42 diff --git a/tests/snippets/stdlib_io.py b/tests/snippets/stdlib_io.py index 66226187b..3dda7278c 100644 --- a/tests/snippets/stdlib_io.py +++ b/tests/snippets/stdlib_io.py @@ -1,6 +1,6 @@ from io import BufferedReader, FileIO, StringIO, BytesIO import os -from testutils import assertRaises +from testutils import assert_raises fi = FileIO('README.md') assert fi.seekable() @@ -31,7 +31,7 @@ fi.close() assert fi.closefd assert fi.closed -with assertRaises(ValueError): +with assert_raises(ValueError): fi.read() with FileIO('README.md') as fio: diff --git a/tests/snippets/stdlib_itertools.py b/tests/snippets/stdlib_itertools.py index eff1813a5..2c588fcf2 100644 --- a/tests/snippets/stdlib_itertools.py +++ b/tests/snippets/stdlib_itertools.py @@ -1,6 +1,6 @@ import itertools -from testutils import assertRaises +from testutils import assert_raises # itertools.chain tests @@ -12,13 +12,13 @@ assert list(chain([], "", b"", ())) == [] assert list(chain([1, 2, 3, 4])) == [1, 2, 3, 4] assert list(chain("ab", "cd", (), 'e')) == ['a', 'b', 'c', 'd', 'e'] -with assertRaises(TypeError): +with assert_raises(TypeError): list(chain(1)) x = chain("ab", 1) assert next(x) == 'a' assert next(x) == 'b' -with assertRaises(TypeError): +with assert_raises(TypeError): next(x) # itertools.count tests @@ -88,17 +88,17 @@ assert next(r) == 5 r = itertools.repeat(1, 2) assert next(r) == 1 assert next(r) == 1 -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(r) # timees = 0 r = itertools.repeat(1, 0) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(r) # negative times r = itertools.repeat(1, -1) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(r) @@ -108,7 +108,7 @@ starmap = itertools.starmap assert list(starmap(pow, zip(range(3), range(1,7)))) == [0**1, 1**2, 2**3] assert list(starmap(pow, [])) == [] assert list(starmap(pow, [iter([4,5])])) == [4**5] -with assertRaises(TypeError): +with assert_raises(TypeError): starmap(pow) @@ -119,40 +119,40 @@ from itertools import takewhile as tw t = tw(lambda n: n < 5, [1, 2, 5, 1, 3]) assert next(t) == 1 assert next(t) == 2 -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(t) # not iterable -with assertRaises(TypeError): +with assert_raises(TypeError): tw(lambda n: n < 1, 1) # not callable t = tw(5, [1, 2]) -with assertRaises(TypeError): +with assert_raises(TypeError): next(t) # non-bool predicate t = tw(lambda n: n, [1, 2, 0]) assert next(t) == 1 assert next(t) == 2 -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(t) # bad predicate prototype t = tw(lambda: True, [1]) -with assertRaises(TypeError): +with assert_raises(TypeError): next(t) # StopIteration before attempting to call (bad) predicate t = tw(lambda: True, []) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(t) # doesn't try again after the first predicate failure t = tw(lambda n: n < 1, [1, 0]) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(t) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(t) @@ -191,7 +191,7 @@ assert 2 == next(it) assert 4 == next(it) assert 6 == next(it) assert 8 == next(it) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(it) l = [0, 1, None, False, True, [], {}] @@ -208,7 +208,7 @@ it = itertools.dropwhile(lambda x: x<5, [1,4,6,4,1]) assert 6 == next(it) assert 4 == next(it) assert 1 == next(it) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(it) @@ -222,7 +222,7 @@ assert 17 == next(it) assert 26 == next(it) assert 34 == next(it) assert 42 == next(it) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(it) it = itertools.accumulate([3, 2, 4, 1, 0, 5, 8], lambda a, v: a*v) @@ -233,5 +233,5 @@ assert 24 == next(it) assert 0 == next(it) assert 0 == next(it) assert 0 == next(it) -with assertRaises(StopIteration): +with assert_raises(StopIteration): next(it) diff --git a/tests/snippets/stdlib_socket.py b/tests/snippets/stdlib_socket.py index ddd8d6ccc..377e81858 100644 --- a/tests/snippets/stdlib_socket.py +++ b/tests/snippets/stdlib_socket.py @@ -1,6 +1,6 @@ import socket import os -from testutils import assertRaises +from testutils import assert_raises MESSAGE_A = b'aaaa' MESSAGE_B= b'bbbbb' @@ -39,30 +39,30 @@ connector.close() listener.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -with assertRaises(TypeError): +with assert_raises(TypeError): s.connect(("127.0.0.1", 8888, 8888)) -with assertRaises(OSError): +with assert_raises(OSError): # Lets hope nobody is listening on port 1 s.connect(("127.0.0.1", 1)) -with assertRaises(TypeError): +with assert_raises(TypeError): s.bind(("127.0.0.1", 8888, 8888)) -with assertRaises(OSError): +with assert_raises(OSError): # Lets hope nobody run this test on machine with ip 1.2.3.4 s.bind(("1.2.3.4", 8888)) -with assertRaises(TypeError): +with assert_raises(TypeError): s.bind((888, 8888)) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("127.0.0.1", 0)) -with assertRaises(OSError): +with assert_raises(OSError): s.recv(100) -with assertRaises(OSError): +with assert_raises(OSError): s.send(MESSAGE_A) s.close() @@ -105,21 +105,21 @@ sock1.close() sock3.close() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) -with assertRaises(OSError): +with assert_raises(OSError): s.bind(("1.2.3.4", 888)) s.close() ### Errors -with assertRaises(OSError): +with assert_raises(OSError): socket.socket(100, socket.SOCK_STREAM) -with assertRaises(OSError): +with assert_raises(OSError): socket.socket(socket.AF_INET, 1000) -with assertRaises(OSError): +with assert_raises(OSError): socket.inet_aton("test") -with assertRaises(OverflowError): +with assert_raises(OverflowError): socket.htonl(-1) assert socket.htonl(0)==0 @@ -132,7 +132,7 @@ assert socket.inet_aton("255.255.255.255")==b"\xff\xff\xff\xff" assert socket.inet_ntoa(b"\x7f\x00\x00\x01")=="127.0.0.1" assert socket.inet_ntoa(b"\xff\xff\xff\xff")=="255.255.255.255" -with assertRaises(OSError): +with assert_raises(OSError): socket.inet_ntoa(b"\xff\xff\xff\xff\xff") with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: @@ -145,5 +145,5 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: connector.connect(("127.0.0.1", listener.getsockname()[1])) (connection, addr) = listener.accept() connection.settimeout(1.0) - with assertRaises(OSError): + with assert_raises(OSError): connection.recv(len(MESSAGE_A)) diff --git a/tests/snippets/stdlib_subprocess.py b/tests/snippets/stdlib_subprocess.py index 9e04f4934..7e9adaf7f 100644 --- a/tests/snippets/stdlib_subprocess.py +++ b/tests/snippets/stdlib_subprocess.py @@ -3,7 +3,7 @@ import time import sys import signal -from testutils import assertRaises +from testutils import assert_raises p = subprocess.Popen(["echo", "test"]) @@ -18,7 +18,7 @@ p = subprocess.Popen(["sleep", "2"]) assert p.poll() is None -with assertRaises(subprocess.TimeoutExpired): +with assert_raises(subprocess.TimeoutExpired): assert p.wait(1) p.wait() diff --git a/tests/snippets/stdlib_types.py b/tests/snippets/stdlib_types.py index b8011bf40..479004b6c 100644 --- a/tests/snippets/stdlib_types.py +++ b/tests/snippets/stdlib_types.py @@ -1,10 +1,10 @@ import types -from testutils import assertRaises +from testutils import assert_raises ns = types.SimpleNamespace(a=2, b='Rust') assert ns.a == 2 assert ns.b == "Rust" -with assertRaises(AttributeError): +with assert_raises(AttributeError): _ = ns.c diff --git a/tests/snippets/strings.py b/tests/snippets/strings.py index 0e3499570..535fc9a8a 100644 --- a/tests/snippets/strings.py +++ b/tests/snippets/strings.py @@ -220,10 +220,10 @@ assert "%f" % (1.23456789012) == "1.234568" assert "%f" % (123) == "123.000000" assert "%f" % (-123) == "-123.000000" -assert_raises(TypeError, lambda: "My name is %s and I'm %(age)d years old" % ("Foo", 25), msg="format requires a mapping") -assert_raises(TypeError, lambda: "My name is %(name)s" % "Foo", msg="format requires a mapping") -assert_raises(ValueError, lambda: "This %(food}s is great!" % {"food": "cookie"}, msg="incomplete format key") -assert_raises(ValueError, lambda: "My name is %" % "Foo", msg="incomplete format") +assert_raises(TypeError, lambda: "My name is %s and I'm %(age)d years old" % ("Foo", 25), _msg='format requires a mapping') +assert_raises(TypeError, lambda: "My name is %(name)s" % "Foo", _msg='format requires a mapping') +assert_raises(ValueError, lambda: "This %(food}s is great!" % {"food": "cookie"}, _msg='incomplete format key') +assert_raises(ValueError, lambda: "My name is %" % "Foo", _msg='incomplete format') assert 'a' < 'b' assert 'a' <= 'b' @@ -285,7 +285,7 @@ assert next(str_iter) == "7" assert next(str_iter) == "8" assert next(str_iter) == "9" assert next(str_iter, None) == None -assert_raises(StopIteration, lambda: next(str_iter)) +assert_raises(StopIteration, next, str_iter) str_iter_reversed = reversed(iterable_str) @@ -299,7 +299,7 @@ assert next(str_iter_reversed) == "3" assert next(str_iter_reversed) == "2" assert next(str_iter_reversed) == "1" assert next(str_iter_reversed, None) == None -assert_raises(StopIteration, lambda: next(str_iter_reversed)) +assert_raises(StopIteration, next, str_iter_reversed) assert str.__rmod__('%i', 30) == NotImplemented assert_raises(TypeError, lambda: str.__rmod__(30, '%i')) diff --git a/tests/snippets/subclass_str.py b/tests/snippets/subclass_str.py index 706566ec6..3ec266d5c 100644 --- a/tests/snippets/subclass_str.py +++ b/tests/snippets/subclass_str.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises x = "An interesting piece of text" assert x is str(x) @@ -18,5 +18,5 @@ assert y + " other" == "1 other" assert y.x == "substr" ## Base strings currently get an attribute dict, but shouldn't. -# with assertRaises(AttributeError): +# with assert_raises(AttributeError): # "hello".x = 5 diff --git a/tests/snippets/test_abc.py b/tests/snippets/test_abc.py index 391932c36..a4c200241 100644 --- a/tests/snippets/test_abc.py +++ b/tests/snippets/test_abc.py @@ -1,6 +1,6 @@ import abc -from testutils import assertRaises +from testutils import assert_raises class CustomInterface(abc.ABC): @@ -14,7 +14,7 @@ class CustomInterface(abc.ABC): # TODO raise an error if there are in any abstract methods not fulfilled -# with assertRaises(TypeError): +# with assert_raises(TypeError): # CustomInterface() diff --git a/tests/snippets/testutils.py b/tests/snippets/testutils.py index 468fbb2c8..19d58ea4a 100644 --- a/tests/snippets/testutils.py +++ b/tests/snippets/testutils.py @@ -1,46 +1,26 @@ -def assert_raises(exc_type, expr, msg=None): - """ - Helper function to assert `expr` raises an exception of type `exc_type`. - Args: - expr: Callable - exec_type: Exception - Returns: - None - Raises: - Assertion error on failure - """ - try: - expr() - except exc_type: - pass - else: - failmsg = '{} was not raised'.format(exc_type.__name__) - if msg is not None: - failmsg += ': {}'.format(msg) - assert False, failmsg - - -def assertRaises(expected, *args, **kw): - if not args: - assert not kw - return _assertRaises(expected) - else: +def assert_raises(expected, *args, _msg=None, **kw): + if args: f, f_args = args[0], args[1:] - with _assertRaises(expected): + with AssertRaises(expected, _msg): f(*f_args, **kw) + else: + assert not kw + return AssertRaises(expected, _msg) -class _assertRaises: - def __init__(self, expected): +class AssertRaises: + def __init__(self, expected, msg): self.expected = expected self.exception = None + self.failmsg = msg def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: - failmsg = '{} was not raised'.format(self.expected.__name__) + failmsg = self.failmsg or \ + '{} was not raised'.format(self.expected.__name__) assert False, failmsg if not issubclass(exc_type, self.expected): return False @@ -56,3 +36,34 @@ class TestFailingBool: class TestFailingIter: def __iter__(self): raise RuntimeError + + +def _assert_print(f, args): + raised = True + try: + f() + raised = False + finally: + if raised: + print('Assertion Failure:', *args) + +def _typed(obj): + return '{}({})'.format(type(obj), obj) + + +def assert_equal(a, b): + _assert_print(lambda: a == b, [_typed(a), '==', _typed(b)]) + + +def assert_true(e): + _assert_print(lambda: e is True, [_typed(e), 'is True']) + + +def assert_false(e): + _assert_print(lambda: e is False, [_typed(e), 'is False']) + +def assert_isinstance(obj, klass): + _assert_print(lambda: isinstance(obj, klass), ['isisntance(', _typed(obj), ',', klass, ')']) + +def assert_in(a, b): + _assert_print(lambda: a in b, [a, 'in', b]) diff --git a/tests/snippets/try_exceptions.py b/tests/snippets/try_exceptions.py index d8be93f33..c646e0937 100644 --- a/tests/snippets/try_exceptions.py +++ b/tests/snippets/try_exceptions.py @@ -1,4 +1,4 @@ -from testutils import assertRaises +from testutils import assert_raises try: raise BaseException() @@ -118,7 +118,7 @@ try: except ZeroDivisionError as ex: assert ex.__cause__ == None -with assertRaises(TypeError): +with assert_raises(TypeError): raise ZeroDivisionError from 5 try: @@ -126,13 +126,13 @@ try: except ZeroDivisionError as ex: assert type(ex.__cause__) == NameError -with assertRaises(NameError): +with assert_raises(NameError): try: raise NameError except: raise -with assertRaises(RuntimeError): +with assert_raises(RuntimeError): raise context = None @@ -171,13 +171,13 @@ except NameError as ex2: def f(): raise -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): try: 1/0 except: f() -with assertRaises(ZeroDivisionError): +with assert_raises(ZeroDivisionError): try: 1/0 except ZeroDivisionError: @@ -254,7 +254,7 @@ except NameError as ex2: # the else clause requires at least one except clause: -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(""" try: pass @@ -264,7 +264,7 @@ else: # Try requires at least except or finally (or both) -with assertRaises(SyntaxError): +with assert_raises(SyntaxError): exec(""" try: pass diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index e89092965..f4a54ddbf 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -279,19 +279,17 @@ fn getgroups() -> nix::Result> { use std::ptr; let ret = unsafe { libc::getgroups(0, ptr::null_mut()) }; let mut groups = Vec::::with_capacity(Errno::result(ret)? as usize); - loop { - let ret = unsafe { - libc::getgroups( - groups.capacity() as c_int, - groups.as_mut_ptr() as *mut gid_t, - ) - }; + let ret = unsafe { + libc::getgroups( + groups.capacity() as c_int, + groups.as_mut_ptr() as *mut gid_t, + ) + }; - return Errno::result(ret).map(|s| { - unsafe { groups.set_len(s as usize) }; - groups - }); - } + Errno::result(ret).map(|s| { + unsafe { groups.set_len(s as usize) }; + groups + }) } #[cfg(any(target_os = "linux", target_os = "android"))]