1import os 2import shutil 3 4import pytest 5 6from zict.file import File 7from . import utils_test 8 9 10@pytest.yield_fixture 11def fn(): 12 filename = ".tmp" 13 if os.path.exists(filename): 14 shutil.rmtree(filename) 15 16 yield filename 17 18 if os.path.exists(filename): 19 shutil.rmtree(filename) 20 21 22def test_mapping(fn): 23 """ 24 Test mapping interface for File(). 25 """ 26 z = File(fn) 27 utils_test.check_mapping(z) 28 29 30def test_implementation(fn): 31 z = File(fn) 32 assert not z 33 34 z["x"] = b"123" 35 assert os.listdir(fn) == ["x"] 36 with open(os.path.join(fn, "x"), "rb") as f: 37 assert f.read() == b"123" 38 39 assert "x" in z 40 41 42def test_str(fn): 43 z = File(fn) 44 assert fn in str(z) 45 assert fn in repr(z) 46 assert z.mode in str(z) 47 assert z.mode in repr(z) 48 49 50def test_setitem_typeerror(fn): 51 z = File(fn) 52 with pytest.raises(TypeError): 53 z["x"] = 123 54 55 56def test_contextmanager(fn): 57 with File(fn) as z: 58 z["x"] = b"123" 59 60 with open(os.path.join(fn, "x"), "rb") as f: 61 assert f.read() == b"123" 62 63 64def test_delitem(fn): 65 z = File(fn) 66 67 z["x"] = b"123" 68 assert os.path.exists(os.path.join(z.directory, "x")) 69 del z["x"] 70 assert not os.path.exists(os.path.join(z.directory, "x")) 71 72 73def test_missing_key(fn): 74 z = File(fn) 75 76 with pytest.raises(KeyError): 77 z["x"] 78 79 80def test_arbitrary_chars(fn): 81 z = File(fn) 82 83 # Avoid hitting the Windows max filename length 84 chunk = 16 85 for i in range(1, 128, chunk): 86 key = "".join(["foo_"] + [chr(i) for i in range(i, min(128, i + chunk))]) 87 with pytest.raises(KeyError): 88 z[key] 89 z[key] = b"foo" 90 assert z[key] == b"foo" 91 assert list(z) == [key] 92 assert list(z.keys()) == [key] 93 assert list(z.items()) == [(key, b"foo")] 94 assert list(z.values()) == [b"foo"] 95 96 zz = File(fn) 97 assert zz[key] == b"foo" 98 assert list(zz) == [key] 99 assert list(zz.keys()) == [key] 100 assert list(zz.items()) == [(key, b"foo")] 101 assert list(zz.values()) == [b"foo"] 102 del zz 103 104 del z[key] 105 with pytest.raises(KeyError): 106 z[key] 107 108 109def test_write_list_of_bytes(fn): 110 z = File(fn) 111 112 z["x"] = [b"123", b"4567"] 113 assert z["x"] == b"1234567" 114