def powtest(type): if type != float: for i in range(-1000, 1000): assert_equal(pow(type(i), 0), 1) assert_equal(pow(type(i), 1), type(i)) assert_equal(pow(type(0), 1), type(0)) assert_equal(pow(type(1), 1), type(1)) for i in range(-100, 100): assert_equal(pow(type(i), 3), i * i * i) pow2 = 1 for i in range(0, 31): assert_equal(pow(2, i), pow2) if i != 30: pow2 = pow2 * 2 for othertype in (int, ): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) for j in range(1, 11): jj = -othertype(j) pow(ii, jj) for othertype in int, float: for i in range(1, 100): zero = type(0) exp = -othertype(i / 10.0) if exp == 0: continue assert_raises(ZeroDivisionError, pow, zero, exp) il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 asseq = assert_equal if type == float: il = 1 asseq = assert_almost_equal elif type == int: jl = 0 elif type == int: jl, jh = 0, 15 for i in range(il, ih + 1): for j in range(jl, jh + 1): for k in range(kl, kh + 1): if j == 1 and k % 2 == 0: # FIXME: num-bigint bug for this case # https://github.com/rust-num/num-bigint/pull/113 continue if i < 0 or k < 0: # FIXME: num-bigint bug for negative base or mod # https://github.com/rust-num/num-bigint/pull/114 continue if k != 0: if type == float or j < 0: assert_raises(TypeError, pow, type(i), j, k) continue asseq(pow(type(i), j, k), pow(type(i), j) % type(k))
def powtest(type): if type != float: for i in range(-1000, 1000): assert_equal(pow(type(i), 0), 1) assert_equal(pow(type(i), 1), type(i)) assert_equal(pow(type(0), 1), type(0)) assert_equal(pow(type(1), 1), type(1)) for i in range(-100, 100): assert_equal(pow(type(i), 3), i * i * i) pow2 = 1 for i in range(0, 31): assert_equal(pow(2, i), pow2) if i != 30: pow2 = pow2 * 2 for othertype in (int, ): for i in list(range(-10, 0)) + list(range(1, 10)): ii = type(i) for j in range(1, 11): jj = -othertype(j) pow(ii, jj) for othertype in int, float: for i in range(1, 100): zero = type(0) exp = -othertype(i / 10.0) if exp == 0: continue assert_raises(ZeroDivisionError, pow, zero, exp) il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 asseq = assert_equal if type == float: il = 1 asseq = assert_almost_equal elif type == int: jl = 0 elif type == int: jl, jh = 0, 15 for i in range(il, ih + 1): for j in range(jl, jh + 1): for k in range(kl, kh + 1): if k != 0: if type == float or j < 0: assert_raises(TypeError, pow, type(i), j, k) continue asseq(pow(type(i), j, k), pow(type(i), j) % type(k))
def test_dunion_other_types(): def perf_test_or(other_obj): d = {1: 2} return d.__or__(other_obj) is NotImplemented def perf_test_ror(other_obj): d = {1: 2} return d.__ror__(other_obj) is NotImplemented test_fct = {'__or__': perf_test_or, '__ror__': perf_test_ror} others = ['FooBar', 42, [36], set([19]), ['aa'], None] for tfn, tf in test_fct.items(): for other in others: assert tf(other), f"Failed: dict {tfn}, accepted {other}" # __ior__() has different behavior and needs to be tested separately d = {1: 2} assert_raises( ValueError, lambda: d.__ior__('FooBar'), _msg='dictionary update sequence element #0 has length 1; 2 is required' ) assert_raises(TypeError, lambda: d.__ior__(42), _msg='\'int\' object is not iterable') assert_raises( TypeError, lambda: d.__ior__([36]), _msg= 'cannot convert dictionary update sequence element #0 to a sequence') assert_raises( TypeError, lambda: d.__ior__(set([36])), _msg= 'cannot convert dictionary update sequence element #0 to a sequence') res = d.__ior__(['aa']) assert res == {1: 2, 'a': 'a'}, f"unexpected result of dict union {res=}" assert_raises(TypeError, lambda: d.__ior__(None), _msg='TypeError: \'NoneType\' object is not iterable')
def test_resizable(): b = bytearray(b'123') b.append(4) m = memoryview(b) assert_raises(BufferError, lambda: b.append(5)) m.release() b.append(6) m2 = memoryview(b) m4 = memoryview(m2) assert_raises(BufferError, lambda: b.append(5)) m3 = memoryview(m2) assert_raises(BufferError, lambda: b.append(5)) m2.release() assert_raises(BufferError, lambda: b.append(5)) m3.release() m4.release() b.append(7)
def test_delim(): iter = ['one|two|three', 'four|five|six'] reader = csv.reader(iter, delimiter='|') [one, two, three] = next(reader) [four, five, six] = next(reader) assert one == 'one' assert two == 'two' assert three == 'three' assert four == 'four' assert five == 'five' assert six == 'six' with assert_raises(TypeError): iter = ['one,,two,,three'] csv.reader(iter, delimiter=',,')
from testutils import assert_raises def no_args(): pass 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') def one_arg(arg): return 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, lambda: one_arg(wrong_arg='wont work'), 'incorrect kwarg to one_arg') assert_raises(TypeError, lambda: one_arg('one_arg', 'two_arg'), 'two args to one_arg') assert_raises(TypeError, lambda: one_arg('one_arg', extra_arg='wont work'), 'no TypeError raised: extra kwarg to one_arg') assert_raises(TypeError, lambda: one_arg('one_arg', arg='duplicate'), 'same pos and kwarg to one_arg')
assert set([1, 2]) <= set([1, 2, 3]) assert set([1, 2]) <= set([1, 2]) assert not set([1, 3]) <= set([1, 2]) assert set([1, 2]).issubset(set([1, 2, 3])) assert set([1, 2]).issubset(set([1, 2])) assert not set([1, 3]).issubset(set([1, 2])) assert set([1, 2]) < set([1, 2, 3]) assert not set([1, 2]) < set([1, 2]) assert not set([1, 3]) < set([1, 2]) assert (set() == []) is False assert set().__eq__([]) == NotImplemented 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]) assert set().issubset([1, 2])
import os import time import stat import sys from testutils import assert_raises fd = os.open('README.md', os.O_RDONLY) assert fd > 0 os.close(fd) assert_raises(OSError, lambda: os.read(fd, 10)) assert_raises(FileNotFoundError, lambda: os.open('DOES_NOT_EXIST', os.O_RDONLY)) assert_raises(FileNotFoundError, lambda: os.open('DOES_NOT_EXIST', os.O_WRONLY)) assert_raises(FileNotFoundError, lambda: os.rename('DOES_NOT_EXIST', 'DOES_NOT_EXIST 2')) try: os.open('DOES_NOT_EXIST', 0) except OSError as err: assert err.errno == 2 assert os.O_RDONLY == 0 assert os.O_WRONLY == 1 assert os.O_RDWR == 2 ENV_KEY = "TEST_ENV_VAR" ENV_VALUE = "value" assert os.getenv(ENV_KEY) == None
""" assert len(""" " \" """) == 5 assert len("é") == 1 assert len("é") == 2 assert len("あ") == 1 assert type("") is str assert type(b"") is bytes assert str(1) == "1" assert str(2.1) == "2.1" assert str() == "" assert str("abc") == "abc" assert_raises(TypeError, lambda: str("abc", "utf-8")) assert str(b"abc", "utf-8") == "abc" assert str(b"abc", encoding="ascii") == "abc" assert repr("a") == "'a'" assert repr("can't") == '"can\'t"' assert repr('"won\'t"') == "'\"won\\'t\"'" assert repr('\n\t') == "'\\n\\t'" assert str(["a", "b", "can't"]) == "['a', 'b', \"can't\"]" assert "xy" * 3 == "xyxyxy" assert "x" * 0 == "" assert "x" * -1 == "" assert 3 * "xy" == "xyxyxy"
def __len__(self): return 1 assert bool(TestMagicMethodBoolTrueLenFalse()) is True assert bool(TestMagicMethodBoolFalseLenTrue()) is False # Test magic method throw error class TestBoolThrowError: def __bool__(self): return object() with assert_raises(TypeError): bool(TestBoolThrowError()) class TestLenThrowError: def __len__(self): return object() 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.
assert 1j != 10**1000 # __mul__, __rmul__ assert complex(2, -3) * complex(-5, 7) == complex(11, 29) assert complex(2, -3) * 5 == complex(10, -15) assert 5 * complex(2, -3) == complex(2, -3) * 5 # __truediv__, __rtruediv__ 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.") # __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.") # __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)),
from testutils import assert_raises p = subprocess.Popen(["echo", "test"]) time.sleep(0.1) assert p.returncode is None assert p.poll() == 0 assert p.returncode == 0 p = subprocess.Popen(["sleep", "2"]) assert p.poll() is None with assert_raises(subprocess.TimeoutExpired): assert p.wait(1) p.wait() assert p.returncode == 0 p = subprocess.Popen(["echo", "test"], stdout=subprocess.PIPE) p.wait() is_unix = "win" not in sys.platform or "darwin" in sys.platform assert p.stdout.read().strip() == b"test" p = subprocess.Popen(["sleep", "2"]) p.terminate()
assert bar.foo == 0 bar.foo = 5 assert bar.a == 5 del bar.foo assert bar.a == 4 del bar.foo assert bar.a == 3 null_property = property() assert type(null_property) is property p = property(lambda x: x[0]) assert p.__get__((2, ), tuple) == 2 assert p.__get__((2, )) == 2 with assert_raises(AttributeError): null_property.__get__((), tuple) with assert_raises(TypeError): property.__new__(object) assert p.__doc__ is None # Test property instance __doc__ attribute: p.__doc__ = '222' assert p.__doc__ == '222' p1 = property("a", "b", "c") assert p1.fget == "a" assert p1.fset == "b"
import signal import time import sys from testutils import assert_raises assert_raises(TypeError, lambda: signal.signal(signal.SIGINT, 2)) signals = [] def handler(signum, frame): signals.append(signum) signal.signal(signal.SIGILL, signal.SIG_IGN) assert signal.getsignal(signal.SIGILL) is signal.SIG_IGN old_signal = signal.signal(signal.SIGILL, signal.SIG_DFL) assert old_signal is signal.SIG_IGN assert signal.getsignal(signal.SIGILL) is signal.SIG_DFL # unix if "win" not in sys.platform: signal.signal(signal.SIGALRM, handler) assert signal.getsignal(signal.SIGALRM) is handler signal.alarm(1) time.sleep(2.0) assert signals == [signal.SIGALRM] signal.signal(signal.SIGALRM, signal.SIG_IGN)
assert zlib.adler32(b"456") == zlib.adler32(b"456", 1) # compression lorem = bytes("Lorem ipsum dolor sit amet", "utf-8") compressed_lorem_list = [ b"x\x01\x01\x1a\x00\xe5\xffLorem ipsum dolor sit amet\x83\xd5\t\xc5", b"x\x01\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x^\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x^\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x^\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x^\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x\x9c\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x\xda\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x\xda\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", b"x\xda\xf3\xc9/J\xcdU\xc8,(.\xcdUH\xc9\xcf\xc9/R(\xce,QH\xccM-\x01\x00\x83\xd5\t\xc5", ] for level, text in enumerate(compressed_lorem_list): assert zlib.compress(lorem, level) == text # default level assert zlib.compress(lorem) == zlib.compress(lorem, -1) == zlib.compress(lorem, 6) # decompression for text in compressed_lorem_list: assert zlib.decompress(text) == lorem assert_raises(zlib.error, lambda: zlib.compress(b"123", -40)) assert_raises(zlib.error, lambda: zlib.compress(b"123", 10))
assert '[1]' == json.dumps((1, )) assert '[1]' == json_dump((1, )) assert '[[1]]' == json.dumps(((1, ), )) assert '[[1]]' == json_dump(((1, ), )) # tuples don't round-trip through json assert [1, "string", 1.0, True] == json.loads(json.dumps((1, "string", 1.0, True))) assert '{}' == json.dumps({}) assert '{}' == json_dump({}) assert round_trip_test({'a': 'b'}) # should reject non-str keys in jsons assert_raises(json.JSONDecodeError, lambda: json.loads('{3: "abc"}')) assert_raises(json.JSONDecodeError, lambda: json_load('{3: "abc"}')) # should serialize non-str keys as strings assert json.dumps({'3': 'abc'}) == json.dumps({3: 'abc'}) assert 1 == json.loads("1") assert 1 == json.loads(b"1") assert 1 == json.loads(bytearray(b"1")) assert 1 == json_load("1") assert 1 == json_load(b"1") assert 1 == json_load(bytearray(b"1")) assert -1 == json.loads("-1") assert -1 == json.loads(b"-1") assert -1 == json.loads(bytearray(b"-1"))
# magic methods should only be implemented for other ints assert (1).__eq__(1) is True assert (1).__ne__(1) is False assert (1).__gt__(1) is False assert (1).__ge__(1) is True assert (1).__lt__(1) is False assert (1).__le__(1) is True assert (1).__add__(1) == 2 assert (1).__radd__(1) == 2 assert (2).__sub__(1) == 1 assert (2).__rsub__(1) == -1 assert (2).__mul__(1) == 2 assert (2).__rmul__(1) == 2 assert (2).__truediv__(1) == 2.0 with assert_raises(ZeroDivisionError): (2).__truediv__(0) assert (2).__rtruediv__(1) == 0.5 assert (-2).__floordiv__(3) == -1 with assert_raises(ZeroDivisionError): (2).__floordiv__(0) assert (-3).__rfloordiv__(2) == -1 assert (-2).__divmod__(3) == (-1, 1) with assert_raises(ZeroDivisionError): (2).__divmod__(0) assert (-3).__rdivmod__(2) == (-1, -1) assert (2).__pow__(3) == 8 assert (10).__pow__(-1) == 0.1 with assert_raises(ZeroDivisionError): (0).__pow__(-1) assert (2).__rpow__(3) == 9
def __exit__(self, exc_type, exc_val, exc_tb): builtins.__import__ = self.original_import with OverrideImportContext(): def fake_import(name, globals=None, locals=None, fromlist=(), level=0): return len(name) builtins.__import__ = fake_import import test assert test == 4 # TODO: Once we can determine current directory, use that to construct this # path: #import sys #sys.path.append("snippets/import_directory") #import nested_target #try: # X #except NameError: # pass #else: # raise AssertionError('X should not be imported') from testutils import assert_raises with assert_raises(SyntaxError): exec('import')
assert math.isinf(float('inf')) assert math.isinf(float('Inf')) assert math.isinf(float('+Inf')) assert math.isinf(float('-Inf')) assert float('+Inf') > 0 assert float('-Inf') < 0 assert float('3.14') == 3.14 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)) # check that magic methods are implemented for ints and floats assert 1.0.__add__(1.0) == 2.0 assert 1.0.__radd__(1.0) == 2.0 assert 2.0.__sub__(1.0) == 1.0 assert 2.0.__rmul__(1.0) == 2.0 assert 1.0.__truediv__(2.0) == 0.5 assert 1.0.__rtruediv__(2.0) == 2.0 assert 1.0.__add__(1) == 2.0 assert 1.0.__radd__(1) == 2.0 assert 2.0.__sub__(1) == 1.0 assert 2.0.__rmul__(1) == 2.0
class A: pass a = A() a.b = 10 assert hasattr(a, 'b') assert a.b == 10 # test override attribute setattr(a, 'b', 12) assert a.b == 12 assert getattr(a, 'b') == 12 # test non-existent attribute with assert_raises(AttributeError): _ = a.c with assert_raises(AttributeError): getattr(a, 'c') assert getattr(a, 'c', 21) == 21 # test set attribute setattr(a, 'c', 20) assert hasattr(a, 'c') assert a.c == 20 # test delete attribute delattr(a, 'c') assert not hasattr(a, 'c')
def check(o): with assert_raises(TypeError): bool(o)
assert a / 2 == 2 assert 2 == a / 2 assert a % 3 == 1 assert a - 3 == 1 assert -a == -4 assert +a == 4 assert round(1.2) == 1 assert round(1.8) == 2 assert round(0.5) == 0 assert round(1.5) == 2 assert round(-0.5) == 0 assert round(-1.5) == -2 # 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 assert pow(1, 2.0) == 1.0 assert pow(2.0, 1) == 2.0 assert pow(0, 10**1000) == 0 assert pow(1, 10**1000) == 1 assert pow(-1, 10**1000 + 1) == -1 assert pow(-1, 10**1000) == 1 assert pow(2, 4, 5) == 1
assert set([1, 2, 3]) & set([4, 5]) == set([]) assert set([1, 2, 3]) & set([1, 2, 3, 4, 5]) == set([1, 2, 3]) assert set([1, 2, 3]).difference(set([1, 2])) == set([3]) assert set([1, 2, 3]).difference(set([5, 6])) == set([1, 2, 3]) assert set([1, 2, 3]) - set([4, 5]) == set([1, 2, 3]) assert set([1, 2, 3]) - set([1, 2, 3, 4, 5]) == set([]) assert set([1, 2, 3]).symmetric_difference(set([1, 2])) == set([3]) assert set([1, 2, 3]).symmetric_difference(set([5, 6])) == set([1, 2, 3, 5, 6]) assert set([1, 2, 3]) ^ set([4, 5]) == set([1, 2, 3, 4, 5]) assert set([1, 2, 3]) ^ set([1, 2, 3, 4, 5]) == set([4, 5]) assert_raises(TypeError, lambda: set([[]])) assert_raises(TypeError, lambda: set().add([])) a = set([1, 2, 3]) assert a.discard(1) is None assert not 1 in a assert a.discard(42) is None a = set([1, 2, 3]) b = a.copy() assert len(a) == 3 assert len(b) == 3 b.clear() assert len(a) == 3 assert len(b) == 0
assert 1j != 10 ** 1000 # __mul__, __rmul__ assert complex(2, -3) * complex(-5, 7) == complex(11, 29) assert complex(2, -3) * 5 == complex(10, -15) assert 5 * complex(2, -3) == complex(2, -3) * 5 # __truediv__, __rtruediv__ assert complex(2, -3) / 2 == complex(1, -1.5) assert 5 / complex(3, -4) == complex(0.6, 0.8) # __mod__, __rmod__ # "can't mod complex numbers. assert_raises(TypeError, lambda: complex(2, -3) % 2) assert_raises(TypeError, lambda: 2 % complex(2, -3)) # __floordiv__, __rfloordiv__ # 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__ # "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__ # assert 1j ** 2 == -1
from testutils import assert_raises assert divmod(11, 3) == (3, 2) 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, divmod, 5, 0, _msg='divmod by zero') assert_raises(ZeroDivisionError, divmod, 5.0, 0.0, _msg='divmod by zero')
import os import time import stat from testutils import assert_raises fd = os.open('README.md', 0) assert fd > 0 os.close(fd) assert_raises(OSError, lambda: os.read(fd, 10)) assert_raises(FileNotFoundError, lambda: os.open('DOES_NOT_EXIST', 0)) assert os.O_RDONLY == 0 assert os.O_WRONLY == 1 assert os.O_RDWR == 2 ENV_KEY = "TEST_ENV_VAR" ENV_VALUE = "value" assert os.getenv(ENV_KEY) == None assert ENV_KEY not in os.environ assert os.getenv(ENV_KEY, 5) == 5 os.environ[ENV_KEY] = ENV_VALUE assert ENV_KEY in os.environ assert os.getenv(ENV_KEY) == ENV_VALUE del os.environ[ENV_KEY] assert ENV_KEY not in os.environ assert os.getenv(ENV_KEY) == None if os.name == "posix":
assert (1).__radd__(1) == 2 assert (2).__sub__(1) == 1 assert (2).__rsub__(1) == -1 assert (2).__mul__(1) == 2 assert (2).__rmul__(1) == 2 assert (2).__truediv__(1) == 2.0 assert (2).__rtruediv__(1) == 0.5 assert (2).__pow__(3) == 8 assert (10).__pow__(-1) == 0.1 assert (2).__rpow__(3) == 9 # real/imag attributes assert (1).real == 1 assert (1).imag == 0 assert_raises(OverflowError, lambda: 1 << 10**100000) assert (1).__eq__(1.0) == NotImplemented assert (1).__ne__(1.0) == NotImplemented assert (1).__gt__(1.0) == NotImplemented assert (1).__ge__(1.0) == NotImplemented assert (1).__lt__(1.0) == NotImplemented assert (1).__le__(1.0) == NotImplemented assert (1).__add__(1.0) == NotImplemented assert (2).__sub__(1.0) == NotImplemented assert (1).__radd__(1.0) == NotImplemented assert (2).__rsub__(1.0) == NotImplemented assert (2).__mul__(1.0) == NotImplemented assert (2).__rmul__(1.0) == NotImplemented assert (2).__truediv__(1.0) == NotImplemented assert (2).__rtruediv__(1.0) == NotImplemented
from testutils import assert_raises a = 1 del a class MyObject: pass foo = MyObject() foo.bar = 2 assert hasattr(foo, 'bar') del foo.bar assert not hasattr(foo, 'bar') x = 1 y = 2 del (x, y) assert_raises(NameError, lambda: x) assert_raises(NameError, lambda: y)
assert max(0, 0) == 0 assert max(1, 0) == 1 assert max(1., 0.) == 1. assert max(-1, 0) == 0 assert max(1, 2, 3) == 3 # iterables assert max([1, 2, 3]) == 3 assert max((1, 2, 3)) == 3 assert max({ "a": 0, "b": 1, }) == "b" assert max([1, 2], default=0) == 2 assert max([], default=0) == 0 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, max) # one non-iterable argument assert_raises(TypeError, max, 1) # custom class class MyComparable(): nb = 0
assert repr("a") == "'a'" assert repr("can't") == '"can\'t"' assert repr('"won\'t"') == "'\"won\\'t\"'" assert repr('\n\t') == "'\\n\\t'" assert str(["a", "b", "can't"]) == "['a', 'b', \"can't\"]" assert "xy" * 3 == "xyxyxy" assert "x" * 0 == "" assert "x" * -1 == "" assert 3 * "xy" == "xyxyxy" assert 0 * "x" == "" assert -1 * "x" == "" assert_raises(OverflowError, lambda: 'xy' * 234234234234234234234234234234) a = 'Hallo' assert a.lower() == 'hallo' assert a.upper() == 'HALLO' assert a.startswith('H') assert a.startswith(('H', 1)) assert a.startswith(('A', 'H')) assert not a.startswith('f') assert not a.startswith(('A', 'f')) assert a.endswith('llo') assert a.endswith(('lo', 1)) assert a.endswith(('A', 'lo')) assert not a.endswith('on') assert not a.endswith(('A', 'll')) assert a.zfill(8) == '000Hallo'