assert int(3).__ror__(-3) == -1 assert int(3).__ror__(4) == 7 assert int(0).__rand__(0) == 0 assert int(1).__rand__(0) == 0 assert int(0).__rand__(1) == 0 assert int(1).__rand__(1) == 1 assert int(3).__rand__(-3) == 1 assert int(3).__rand__(4) == 0 assert int(0).__rxor__(0) == 0 assert int(1).__rxor__(0) == 1 assert int(0).__rxor__(1) == 1 assert int(1).__rxor__(1) == 0 assert int(3).__rxor__(-3) == -2 assert int(3).__rxor__(4) == 7 assert int(4).__lshift__(1) == 8 assert int(4).__rshift__(1) == 2 assert int(4).__rlshift__(1) == 16 assert int(4).__rrshift__(1) == 0 # Test underscores in numbers: assert 1_2 == 12 assert 1_2_3 == 123 assert 1_2.3_4 == 12.34 assert 1_2.3_4e0_0 == 12.34 with assertRaises(SyntaxError): eval('1__2')
# assert(math.exp(True) == math.exp(1.0)) # # class Conversible(): # def __float__(self): # print("Converting to float now!") # return 1.1111 # # assert math.log(1.1111) == math.log(Conversible()) # roundings assert int.__trunc__ assert int.__floor__ assert int.__ceil__ # assert float.__trunc__ with assertRaises(AttributeError): assert float.__floor__ with assertRaises(AttributeError): assert float.__ceil__ assert math.trunc(2) == 2 assert math.ceil(3) == 3 assert math.floor(4) == 4 assert math.trunc(2.2) == 2 assert math.ceil(3.3) == 4 assert math.floor(4.4) == 4 class A(object): def __trunc__(self):
count += 1 assert count == len(a) res = set() for key in a.keys(): res.add(key) assert res == set(['a', 'b']) # Deleted values are correctly skipped over: x = {'a': 1, 'b': 2, 'c': 3, 'd': 3} del x['c'] it = iter(x.items()) assert ('a', 1) == next(it) assert ('b', 2) == next(it) assert ('d', 3) == next(it) with assertRaises(StopIteration): next(it) # Iterating a dictionary is just its keys: assert ['a', 'b', 'd'] == list(x) # Iterating view captures dictionary when iterated. data = {1: 2, 3: 4} items = data.items() assert list(items) == [(1, 2), (3, 4)] data[5] = 6 assert list(items) == [(1, 2), (3, 4), (5, 6)] # Values can be changed during iteration. data = {1: 2, 3: 4} items = iter(data.items())
from testutils import assertRaises 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 assertRaises(subprocess.TimeoutExpired): assert p.wait(1) p.wait() assert p.returncode == 0 p = subprocess.Popen(["echo", "test"], stdout=subprocess.PIPE) p.wait() if "win" not in sys.platform: # unix test_output = b"test\n" else: # windows test_output = b"test\r\n"
if os.name == "posix": connector_fd = connector.fileno() connection_fd = connection.fileno() os.write(connector_fd, MESSAGE_A) connection.send(MESSAGE_B) recv_a = connection.recv(len(MESSAGE_A)) recv_b = os.read(connector_fd, (len(MESSAGE_B))) assert recv_a == MESSAGE_A assert recv_b == MESSAGE_B connection.close() connector.close() listener.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with assertRaises(TypeError): s.connect(("127.0.0.1", 8888, 8888)) with assertRaises(OSError): # Lets hope nobody is listening on port 1 s.connect(("127.0.0.1", 1)) with assertRaises(TypeError): s.bind(("127.0.0.1", 8888, 8888)) with assertRaises(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): s.bind((888, 8888))
assert len(result) <= 8*1024 assert len(result) >= 0 assert isinstance(result, bytes) with FileIO('README.md') as fio: res = fio.read() assert len(result) <= 8*1024 assert len(result) >= 0 assert isinstance(result, bytes) fd = os.open('README.md', os.O_RDONLY) with FileIO(fd) as fio: res2 = fio.read() assert res == res2 fi = FileIO('README.md') fi.read() fi.close() assert fi.closefd assert fi.closed with assertRaises(ValueError): fi.read() with FileIO('README.md') as fio: nres = fio.read(1) assert len(nres) == 1 nres = fio.read(2) assert len(nres) == 2
from testutils import assertRaises assert '__builtins__' in globals() # assert type(__builtins__).__name__ == 'module' with assertRaises(AttributeError): __builtins__.__builtins__ __builtins__.x = 'new' assert x == 'new' # noqa: F821 exec('assert "__builtins__" in globals()', dict()) exec('assert __builtins__ == 7', {'__builtins__': 7}) exec('assert not isinstance(__builtins__, dict)') exec('assert isinstance(__builtins__, dict)', {}) namespace = {} exec('', namespace) assert namespace['__builtins__'] == __builtins__.__dict__ # with assertRaises(NameError): # exec('print(__builtins__)', {'__builtins__': {}}) # __builtins__ is deletable but names are alive del __builtins__ with assertRaises(NameError): __builtins__ # noqa: F821 assert print
from testutils import assertRaises class A(dict): def a(): pass def b(): pass assert A.__dict__['a'] == A.a with assertRaises(KeyError) as cm: A.__dict__['not here'] assert cm.exception.args[0] == "not here" assert 'b' in A.__dict__ assert 'c' not in A.__dict__ assert '__dict__' in A.__dict__
from testutils import assert_raises, assertRaises 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) # noqa: F821 assert_raises(NameError, lambda: y) # noqa: F821 with assertRaises(NameError): del y # noqa: F821
raise NameError from ex except NameError as ex2: assert ex2.__cause__ == cause assert ex2.__context__ == cause try: raise ZeroDivisionError from None except ZeroDivisionError as ex: assert ex.__cause__ == None try: raise ZeroDivisionError except ZeroDivisionError as ex: assert ex.__cause__ == None with assertRaises(TypeError): raise ZeroDivisionError from 5 try: raise ZeroDivisionError from NameError except ZeroDivisionError as ex: assert type(ex.__cause__) == NameError with assertRaises(NameError): try: raise NameError except: raise with assertRaises(RuntimeError): raise
import itertools from testutils import assertRaises # itertools.chain tests chain = itertools.chain # empty assert list(chain()) == [] 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): list(chain(1)) x = chain("ab", 1) assert next(x) == 'a' assert next(x) == 'b' with assertRaises(TypeError): next(x) # itertools.count tests # default arguments c = itertools.count() assert next(c) == 0 assert next(c) == 1 assert next(c) == 2 # positional
# magic methods should only be implemented for other ints assert (1).__eq__(1) == True assert (1).__ne__(1) == False assert (1).__gt__(1) == False assert (1).__ge__(1) == True assert (1).__lt__(1) == False assert (1).__le__(1) == 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 assertRaises(ZeroDivisionError): (2).__truediv__(0) assert (2).__rtruediv__(1) == 0.5 assert (-2).__floordiv__(3) == -1 with assertRaises(ZeroDivisionError): (2).__floordiv__(0) assert (-3).__rfloordiv__(2) == -1 assert (-2).__divmod__(3) == (-1, 1) with assertRaises(ZeroDivisionError): (2).__divmod__(0) assert (-3).__rdivmod__(2) == (-1, -1) assert (2).__pow__(3) == 8 assert (10).__pow__(-1) == 0.1 assert (2).__rpow__(3) == 9 assert (10).__mod__(5) == 0 assert (10).__mod__(6) == 4
# float start + step # c = itertools.count(0.5, 0.5) # assert next(c) == 0.5 # assert next(c) == 1 # assert next(c) == 1.5 # itertools.repeat tests # no times r = itertools.repeat(5) assert next(r) == 5 assert next(r) == 5 assert next(r) == 5 # times r = itertools.repeat(1, 2) assert next(r) == 1 assert next(r) == 1 with assertRaises(StopIteration): next(r) # timees = 0 r = itertools.repeat(1, 0) with assertRaises(StopIteration): next(r) # negative times r = itertools.repeat(1, -1) with assertRaises(StopIteration): next(r)
assert count == len(a) res = set() for key in a.keys(): res.add(key) assert res == set(['a', 'b']) x = {} x[1] = 1 assert x[1] == 1 x[7] = 7 x[2] = 2 x[(5, 6)] = 5 with assertRaises(KeyError): x["not here"] with assertRaises(TypeError): x[[]] # Unhashable type. x["here"] = "here" assert x.get("not here", "default") == "default" assert x.get("here", "default") == "here" assert x.get("not here") == None class LengthDict(dict): def __getitem__(self, k): return len(k)
from testutils import assertRaises # new assert bytearray([1, 2, 3]) assert bytearray((1, 2, 3)) assert bytearray(range(4)) assert bytearray(3) assert b"bla" assert (bytearray("bla", "utf8") == bytearray("bla", encoding="utf-8") == bytearray(b"bla")) with assertRaises(TypeError): bytearray("bla") with assertRaises(TypeError): bytearray("bla", encoding=b"jilj") assert bytearray( b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" ) == bytearray(range(0, 256)) assert bytearray( b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" ) == bytearray(range(0, 256)) assert bytearray(b"omkmok\Xaa") == bytearray( [111, 109, 107, 109, 111, 107, 92, 88, 97, 97]) a = bytearray(b"abcd") b = bytearray(b"ab") c = bytearray(b"abcd") # repr assert repr(bytearray([0, 1, 2])) == repr(bytearray(b"\x00\x01\x02")) assert (repr(bytearray(
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 assertRaises(AttributeError): _ = a.c with assertRaises(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')