@@@ lbuf needs test
[mLib-python] / test.py
CommitLineData
efb0bf0e
MW
1#! /usr/bin/python
2### -*- coding: utf-8 -*-
3
965caf5f
MW
4import contextlib as CTX
5import fcntl as FC
6import os as OS
7import socket as S
efb0bf0e
MW
8import sys as SYS
9import mLib as M
10
11if SYS.version_info >= (3,):
12 def _bin(text): return text.encode()
13 def _text(bin): return bin.decode()
803869bc 14 xrange = range
efb0bf0e
MW
15else:
16 def _bin(text): return text
17 def _text(bin): return bin
18
19def must_equal(x, y):
20 if x == y: pass
21 else: raise AssertionError("%r != %r" % (x, y))
22
23## Done!
24print(";; test begins (Python %s)" % SYS.version)
25
26## crc32
965caf5f 27print(";; test crc32...")
efb0bf0e
MW
28must_equal(M.crc32(_bin("abc")), 0x352441c2)
29must_equal(M.CRC32().chunk(_bin("a")).chunk(_bin("bc")).done(), 0x352441c2)
30
31## unihash
965caf5f 32print(";; test unihash...")
efb0bf0e
MW
33assert M.Unihash().key is None
34must_equal(M.Unihash.hash(_bin("abc")), 0xbf71f6a2)
35must_equal(M.Unihash().chunk(_bin("a")).chunk(_bin("bc")).done(), 0xbf71f6a2)
36key = M.UnihashKey(0x8498a262)
37assert M.Unihash(key).key is key
38must_equal(M.Unihash.hash(_bin("abc"), key), 0xecd1e2a2)
39must_equal(key.hash(_bin("abc")), 0xecd1e2a2)
40must_equal(M.Unihash(key).chunk(_bin("a")).chunk(_bin("bc")).done(), 0xecd1e2a2)
41M.setglobalkey(0x8498a262)
42must_equal(M.Unihash.hash(_bin("abc")), 0xecd1e2a2)
43
44## atom
965caf5f 45print(";; test atom...")
efb0bf0e
MW
46foo = M.Atom("foo")
47bar = M.Atom("bär")
48assert foo != bar
49assert foo is M.Atom("foo")
50assert bar is M.Atom("bär")
51assert foo.internedp
52must_equal(foo.name, "foo")
53must_equal(bar.name, "bär")
54gen = M.Atom()
55assert gen is not M.Atom()
56assert not gen.internedp
57all = set(M.atoms())
58assert foo in all
59assert bar in all
60
61## assoc, sym
62def test_mapping(mapcls, keya, keyz):
63 tab = mapcls()
64 tab[keya] = 69; must_equal(tab[keya], 69)
65 tab[keya] = 42; must_equal(tab[keya], 42)
66 tab[keyz] = 'zing'; must_equal(tab[keyz], 'zing')
67 del tab[keyz]
68 try: tab[keyz]
69 except KeyError: pass
70 else: assert False
71 must_equal(list(tab.keys()), [keya])
72 must_equal(list(tab.values()), [42])
73 must_equal(list(tab.items()), [(keya, 42)])
965caf5f 74print(";; test assoc...")
efb0bf0e 75test_mapping(M.AssocTable, foo, bar)
965caf5f 76print(";; test sym...")
efb0bf0e
MW
77test_mapping(M.SymTable, 'foo', 'bar')
78
965caf5f
MW
79## str
80print(";; test str...")
81must_equal(M.word(" foo bar baz"), ("foo", "bar baz"))
82must_equal(M.word(" 'foo \\' bar' baz ", quotep = True),
83 ("foo ' bar", "baz "))
84must_equal(M.split(' one "two \\" three" four five six', 3, quotep = True),
85 (["one", 'two " three', "four"], "five six"))
86assert M.match("foo*bar", "food is served at the bar")
87must_equal(M.sanitize("some awful string!", 12), "some_awful_s")
88assert M.versioncmp("1.2.5~pre99", "1.2.5") < 0
89assert M.versioncmp("1.2.5pre99", "1.2.5") > 0
90
91## codec
92ref = _bin("just >some ?string to encode")
93def test_codecclass(enccls, deccls, encref):
94 enc = enccls("!", 8, M.CDCF_LOWERC)
95 e = enc.encode(ref[:10])
96 e += enc.encode(ref[10:])
97 e += enc.done()
98 must_equal(e, encref)
99 encref = encref.replace("!", "")
100 dec = deccls(M.CDCF_IGNCASE)
101 d = dec.decode(encref[:15])
102 d += dec.decode(encref[15:])
103 d += dec.done()
104 must_equal(d, ref)
105 try: deccls().decode("???")
106 except M.CodecError as e:
107 if e.err == M.CDCERR_INVCH: pass
108 else: raise
109 else: assert False
110def test_oldcodec(enccls, deccls, encref):
111 enc = enccls()
112 enc.indent = "!"
113 enc.maxline = 8
114 e = enc.encode(ref[:10])
115 e += enc.encode(ref[10:])
116 e += enc.done()
117 must_equal(e, encref)
118 encref = encref.replace("!", "")
119 dec = deccls()
120 d = dec.decode(encref[:15])
121 d += dec.decode(encref[15:])
122 d += dec.done()
123 must_equal(d, ref)
124
125print(";; test base64...")
126test_codecclass(M.Base64Encoder, M.Base64Decoder,
127 "anVzdCA+!c29tZSA/!c3RyaW5n!IHRvIGVu!Y29kZQ==")
128test_codecclass(M.File64Encoder, M.File64Decoder,
129 "anVzdCA+!c29tZSA%!c3RyaW5n!IHRvIGVu!Y29kZQ==")
130test_codecclass(M.Base64URLEncoder, M.Base64URLDecoder,
131 "anVzdCA-!c29tZSA_!c3RyaW5n!IHRvIGVu!Y29kZQ==")
132test_oldcodec(M.Base64Encode, M.Base64Decode,
133 "anVzdCA+!c29tZSA/!c3RyaW5n!IHRvIGVu!Y29kZQ==")
134
135print(";; test base32...")
136test_codecclass(M.Base32Encoder, M.Base32Decoder,
137 "nj2xg5ba!hzzw63lf!ea7xg5ds!nfxgoidu!n4qgk3td!n5sgk===")
138test_codecclass(M.Base32HexEncoder, M.Base32HexDecoder,
139 "d9qn6t10!7ppmurb5!40vn6t3i!d5n6e83k!dsg6arj3!dti6a===")
140test_oldcodec(M.Base32Encode, M.Base32Decode,
141 "NJ2XG5BA!HZZW63LF!EA7XG5DS!NFXGOIDU!N4QGK3TD!N5SGK===")
142
143print(";; test hex...")
144test_codecclass(M.HexEncoder, M.HexDecoder,
145 "6a757374!203e736f!6d65203f!73747269!6e672074!6f20656e!636f6465")
146test_oldcodec(M.HexEncode, M.HexDecode,
147 "6a757374!203e736f!6d65203f!73747269!6e672074!6f20656e!636f6465")
148
149## url
150print(";; test url...")
151uenc = M.URLEncode()
152uenc.encode("one", "some/string!")
153uenc.strictp = True
154uenc.encode("two", "some other/string!")
155uenc.laxp = True
156uenc.encode("three", "another!string")
157r = uenc.result
158must_equal(r, "one=some/string%21&two=some+other%2fstring%21&three=another!string")
159must_equal(list(M.URLDecode(r)),
160 [("one", "some/string!"),
161 ("two", "some other/string!"),
162 ("three", "another!string")])
163
164## report
165@CTX.contextmanager
166def stderr_test(want_out):
167 pin, pout = OS.pipe()
168 fin = OS.fdopen(pin, 'r')
169 olderr = OS.dup(2)
170 OS.dup2(pout, 2)
171 OS.close(pout)
172 try:
173 yield
174 OS.close(2)
175 out = fin.read()
176 finally:
177 fin.close()
178 OS.dup2(olderr, 2)
179 must_equal(out, want_out)
180print(";; test report...")
181M.ego("my/path/name")
182must_equal(M.quis, "name")
183with stderr_test("name: test moaning\n"):
184 M.moan("test moaning")
185with stderr_test("name: test death\n"):
186 try: M.die("test death")
187 except SystemExit as e: assert e.code == 126
188 else: assert False
189
190## fwatch
191print(";; test fwatch...")
192fd = OS.open(",test-stamp", OS.O_WRONLY | OS.O_CREAT, 0o666)
193fw = M.FWatch(fd)
194assert not fw.update()
195OS.write(fd, _bin("stuff\n"))
196assert fw.update()
197assert fw.file is fd
198fd2 = OS.open(",test-stamp.new", OS.O_WRONLY | OS.O_CREAT, 0o666)
199OS.rename(",test-stamp.new", ",test-stamp")
200assert not fw.update()
201fw.file = ",test-stamp"
202assert fw.update()
203OS.close(fd)
204OS.close(fd2)
205OS.unlink(",test-stamp")
206
207## fdflags
208print(";; test fdflags...")
209pin, pout = OS.pipe()
210ofl = FC.fcntl(pin, FC.F_GETFL)
211ofd = FC.fcntl(pout, FC.F_GETFD)
212fout = OS.fdopen(pout, 'wb')
213M.fdflags(pin, fbic = OS.O_NONBLOCK, fxor = OS.O_NONBLOCK)
214assert FC.fcntl(pin, FC.F_GETFL) == ofl | OS.O_NONBLOCK
215M.fdflags(pin, fbic = OS.O_NONBLOCK, fxor = 0)
216assert FC.fcntl(pin, FC.F_GETFL) == ofl&~OS.O_NONBLOCK
217M.fdflags(fout, fdbic = FC.FD_CLOEXEC, fdxor = FC.FD_CLOEXEC)
218assert FC.fcntl(pout, FC.F_GETFD) == ofd | FC.FD_CLOEXEC
219M.fdflags(fout, fdbic = FC.FD_CLOEXEC, fdxor = 0)
220assert FC.fcntl(pout, FC.F_GETFD) == ofd&~FC.FD_CLOEXEC
221OS.close(pin)
222fout.close()
223
224## fdpass
225print(";; test fdpass...")
226pin, pout = OS.pipe()
227fin = OS.fdopen(pin, 'r')
228OS.write(pout, _bin("Hello, world!"))
229OS.close(pout)
230sk0, sk1 = S.socketpair(S.AF_UNIX, S.SOCK_STREAM)
231M.fdsend(sk0, fin, _bin("Have a pipe!"))
232fin.close()
233sk0.close()
234fd, msg = M.fdrecv(sk1, 16)
235sk1.close()
236must_equal(msg, _bin("Have a pipe!"))
237data = OS.read(fd, 16)
238OS.close(fd)
239must_equal(data, _bin("Hello, world!"))
240
241## mdup
803869bc
MW
242print(";; test mdup...")
243def mkfd():
244 fd = OS.open(",delete-me", OS.O_WRONLY | OS.O_CREAT, 0o666)
245 OS.unlink(",delete-me")
246 return fd
247def fid(fd):
248 st = OS.fstat(fd)
249 return st.st_dev, st.st_ino
250initial = [mkfd() for i in xrange(5)]
251ref = [fid(fd) for fd in initial]
252op = [(initial[0], initial[1]),
253 (initial[1], initial[2]),
254 (initial[2], initial[0]),
255 (initial[0], initial[3]),
256 (initial[3], -1),
257 (initial[0], initial[4])]
258M.mdup(op)
259for have, want in op:
260 if want != -1: must_equal(have, want)
261must_equal(op[0][0], initial[1]); must_equal(fid(op[0][0]), ref[0])
262must_equal(op[1][0], initial[2]); must_equal(fid(op[1][0]), ref[1])
263must_equal(op[2][0], initial[0]); must_equal(fid(op[2][0]), ref[2])
264must_equal(op[3][0], initial[3]); must_equal(fid(op[3][0]), ref[0])
265pass; must_equal(fid(op[4][0]), ref[3])
266must_equal(op[5][0], initial[4]); must_equal(fid(op[5][0]), ref[0])
267for fd, _ in op: OS.close(fd)
268
269## (not testing detachtty and daemonize)
270
965caf5f
MW
271
272
efb0bf0e
MW
273## Done!
274print(";; test completed OK")