diff --git a/.gitattributes b/.gitattributes index 4b8fa786c807b3ff10fe37e45a83fede8da76a04..7ed3be65d82bcaeb9bbeb5f559b53c744ea5bedb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1024,3 +1024,45 @@ omnilmm/lib/python3.10/site-packages/matplotlib/__pycache__/patches.cpython-310. omnilmm/lib/python3.10/site-packages/matplotlib/__pycache__/widgets.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text omnilmm/lib/python3.10/site-packages/matplotlib/__pycache__/figure.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text omnilmm/lib/python3.10/pydoc_data/__pycache__/topics.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/html/__pycache__/entities.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_tkinter.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/zlib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_testbuffer.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_hashlib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_heapq.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_codecs_cn.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_sha3.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_codecs_kr.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/cmath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/unicodedata.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_json.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_pickle.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_csv.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_decimal.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/select.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_curses.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_asyncio.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_multibytecodec.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_blake2.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_struct.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_testcapi.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/array.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_elementtree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_datetime.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/audioop.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_ctypes.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/binascii.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_codecs_hk.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_zoneinfo.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_xxsubinterpreters.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_testclinic.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_socket.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/readline.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_codecs_tw.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +omnilmm/lib/python3.10/lib-dynload/_lzma.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/omnilmm/lib/python3.10/__pycache__/glob.cpython-310.pyc b/omnilmm/lib/python3.10/__pycache__/glob.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..879f92a548874169b0253913e37ab7ec81da2e67 Binary files /dev/null and b/omnilmm/lib/python3.10/__pycache__/glob.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/__pycache__/pydoc.cpython-310.pyc b/omnilmm/lib/python3.10/__pycache__/pydoc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7782c4726628504481f5ae9d313661826ef0323 Binary files /dev/null and b/omnilmm/lib/python3.10/__pycache__/pydoc.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/__pycache__/wave.cpython-310.pyc b/omnilmm/lib/python3.10/__pycache__/wave.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d7b77eb572e2b2f9283862b44076e58363745a3 Binary files /dev/null and b/omnilmm/lib/python3.10/__pycache__/wave.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/__pycache__/zipfile.cpython-310.pyc b/omnilmm/lib/python3.10/__pycache__/zipfile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0016300a27eb4da7c3cc2f2dae8f7493083e23f9 Binary files /dev/null and b/omnilmm/lib/python3.10/__pycache__/zipfile.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/html/__pycache__/entities.cpython-310.pyc b/omnilmm/lib/python3.10/html/__pycache__/entities.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1233e502e6006b37940ee5d283b30d645f4abc18 --- /dev/null +++ b/omnilmm/lib/python3.10/html/__pycache__/entities.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f639bcf090e65d074c5c56fa79ad59fe482e2ff1716c63f7358c850eec8067d5 +size 144684 diff --git a/omnilmm/lib/python3.10/lib-dynload/_asyncio.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_asyncio.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5dd434018a5264cb91bcfa1b0923055292a3af8d --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_asyncio.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10e10c5a50a6caa77c0d10cbc2042a1266fd91f591e9238c5185929972c195d4 +size 228752 diff --git a/omnilmm/lib/python3.10/lib-dynload/_bisect.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_bisect.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4b9bad3ca452d434e21077ede4656553305c0cf1 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_bisect.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_blake2.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_blake2.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6865dfbbcc6a331853f02faefaabb2a6de750fa0 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_blake2.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f39890de7e68c5a35b8b58df1ccbefb2449ae5e7011b3da531623e520706d74 +size 251704 diff --git a/omnilmm/lib/python3.10/lib-dynload/_bz2.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_bz2.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d8b197c5b2312f88531f1f2ccbece989a7947d8f Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_bz2.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_cn.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_cn.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a4af8fdb8373a332c0e5974935c3b6d55dc1f391 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_codecs_cn.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b14d3e61301517081521dec48fd707bd8bb954496ef3d3853e7e884f036ede1d +size 197208 diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_hk.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_hk.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..312896d3de63b457e7ea0f7d6acfb90e4d2f3cd6 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_codecs_hk.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5028632a8d7f167721ab2e0de42fb9e1c4ea5a80161005dabfb5c559f784dcb +size 194368 diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_iso2022.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_iso2022.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c0d38ba3b16a1b2af97bf7f37c163bdcba733bb4 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_codecs_iso2022.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..86526c0a02cfb3c368a0ebe4fa011c98e8de5b34 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_codecs_jp.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdc9d9bed1fce91debd6c129742280fffed2bb488b5a3184508938481ace9b27 +size 327976 diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_kr.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_kr.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f366a578ce9f172da771d8094702b7f9532c6d0d --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_codecs_kr.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5814ccaffdc000bca85b530ab79430806da47406e083147384ae3d826f4abf74 +size 180840 diff --git a/omnilmm/lib/python3.10/lib-dynload/_codecs_tw.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_codecs_tw.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c416f2b005e883e2e6d2987f08e9a41b8bdd61b6 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_codecs_tw.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:148bfe2a46df83fdece3e335e31ff78e92a273a1bfe660764988c88682ea3066 +size 143232 diff --git a/omnilmm/lib/python3.10/lib-dynload/_crypt.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_crypt.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..16fded91759690ab3b8f69790bcfc0fbb6c34978 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_crypt.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_csv.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_csv.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f065025b4131d0caddd95ef29660397a28ff318e --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_csv.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54c23d5033e7faf000004ed531de1c2530a6737895f5592aadcc92c60dd84289 +size 142696 diff --git a/omnilmm/lib/python3.10/lib-dynload/_ctypes.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_ctypes.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..dba3e32d3c1883e2ea0b195906c131d812c0a2f1 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_ctypes.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:679b8c5b2ea999168ab98fd52076ae0bfde863226dcb5d24431a7bb16dafaa9a +size 548912 diff --git a/omnilmm/lib/python3.10/lib-dynload/_ctypes_test.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_ctypes_test.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..29c0182f833835c7b9c1b94890aa0ead1db6b2af Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_ctypes_test.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_curses.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_curses.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d11d49308809fe50e413448e624ed87401d0b8f4 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_curses.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf00a0480e575042eafa4aeff7267e56f9c35b9d96f2386d74adaa4f01e1e856 +size 485160 diff --git a/omnilmm/lib/python3.10/lib-dynload/_curses_panel.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_curses_panel.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..12b54b2d2671eb19002b106c5838da5568e65082 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_curses_panel.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_datetime.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_datetime.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9e975ac314375f275dda194d402c064de880beb0 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_datetime.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d929ec19b7987cf9a92d8d767c11edfdae6c92a791ad7342cc7ba4ed433ad35b +size 580080 diff --git a/omnilmm/lib/python3.10/lib-dynload/_decimal.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_decimal.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..dc98ac98baeba7fd523681fb5ca4469664fab886 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_decimal.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc76e957d5709b4ea4778b19d26be671770cd04d9a6ce7cf94a5b43c94285a26 +size 1420752 diff --git a/omnilmm/lib/python3.10/lib-dynload/_elementtree.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_elementtree.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..dfcb6a7220c3d679c65c0f90684f3ff136a6a4d4 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_elementtree.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f9679081554fa8307d3a423d59f499173ad32ee49fa5eb0f0f72ac9a726ff51 +size 341528 diff --git a/omnilmm/lib/python3.10/lib-dynload/_hashlib.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_hashlib.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f1b44eaccacbfb80295ed93164e120e5aa0a518f --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_hashlib.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7659752e97445bb76f914fdcf6ec997a6e14685dd153391e71810cd16affff61 +size 211136 diff --git a/omnilmm/lib/python3.10/lib-dynload/_heapq.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_heapq.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c635cc1333b386c699a55b495487fe8ed8a00ba5 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_heapq.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30f63ea4a3964958706a3f93b6e43bd0449bbf2b93bfd8ca2fa3800896ab3203 +size 104536 diff --git a/omnilmm/lib/python3.10/lib-dynload/_json.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_json.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0527c40438f8f56230a38066011d7eeed10e3c6c --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_json.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3081d1ac56357ce60483ba7afb3ee8b69796ffa64e4076c2d8559215cf44924b +size 163064 diff --git a/omnilmm/lib/python3.10/lib-dynload/_lsprof.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_lsprof.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c30d8a75cab2f549d1ceec812483c41936eb6113 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_lsprof.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_lzma.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_lzma.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9592dbb3b24ff7d766b21626b3f4809a2d9536e6 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_lzma.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebfdcab2537ab089e99839348e41c28e8ce2b63d58d095f94c9f80a753748b0b +size 145376 diff --git a/omnilmm/lib/python3.10/lib-dynload/_md5.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_md5.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6f1d58f3b66489e20791f2d8190ea4b005207a93 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_md5.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_multibytecodec.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_multibytecodec.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d91073531b1f8711832031a3aaa98e883395eef5 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_multibytecodec.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95a8a6ef641c30f1c6412acc5a7bedb92027e5e853a31c96aa99fe16910521d3 +size 200648 diff --git a/omnilmm/lib/python3.10/lib-dynload/_multiprocessing.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_multiprocessing.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..19d59011a10332e7125bd289daceaa69be0745f8 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_multiprocessing.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_opcode.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_opcode.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9839b2ece3eb3bcf3ed9ee692c7f94d36c253e9f Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_opcode.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_pickle.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_pickle.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1d7a280d3ab84ab611389189b11ce3696a7079ec --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_pickle.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2203f7e42b7eef0b969e855e1e7e21f201c8f892d0fb9ec1d1da56d8b19148b2 +size 532384 diff --git a/omnilmm/lib/python3.10/lib-dynload/_posixshmem.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_posixshmem.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..01ac97003294bb4d0f7edff458641df75d3400bf Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_posixshmem.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_posixsubprocess.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_posixsubprocess.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3be0c116f1b57ba8557baa6eff66b48db4756236 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_posixsubprocess.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_queue.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_queue.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ae818145bbb48e70d9cee503b15a0969e99ad4ba Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_queue.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_random.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_random.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1abd4c97ba0a549ccc3d775fe6185c7e4f6254c7 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_random.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_sha1.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_sha1.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..671342a8950ba9753a703d2a98f9eccb7dce8960 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_sha1.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_sha3.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_sha3.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..26ebf20e53c84fe4833f7b8ac4d97be18e54af8a --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_sha3.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfd947ecb3f4850a48e102e86210f66a9b533e5559f5cc34fe2377c22e6cdba1 +size 349128 diff --git a/omnilmm/lib/python3.10/lib-dynload/_sha512.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_sha512.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ec5d86d9d5a0836dbfb327b48efacef8cc89ea92 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_sha512.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_socket.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_socket.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a9520a9e8f9941190622ce14b47c48dd2aacd05e --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_socket.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:457b4b1f4e960408aea7e2a1cbb92a8840ac68a682ecf5baf3450ee0e796fc00 +size 283680 diff --git a/omnilmm/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a6b6a0a9b06913ce811a13ce2de55add354cc11f --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9771273c8374a0ec1bb7a2833d00509de027b74a923242822f38e4d98a6bba4a +size 489832 diff --git a/omnilmm/lib/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6ad2823c17467f6239779923e470a62e018338cf --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f93473eb2cfe128149c6d2973086402faa935d68856a103c752d0b513925432e +size 499736 diff --git a/omnilmm/lib/python3.10/lib-dynload/_statistics.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_statistics.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a3f8c695b233b1a80fafb939dfe15488717c65b3 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_statistics.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_struct.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_struct.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b83063d3a70b7f284f4194c8485f2737d88da356 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_struct.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:263a18f8985b343b3af8c5b693968de0bc58951f895f1816a9a55b9734b33e2c +size 219400 diff --git a/omnilmm/lib/python3.10/lib-dynload/_testbuffer.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testbuffer.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f03ddb89a3c9715ee1b5b3a38f195ad78cee8280 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_testbuffer.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ed57af9112bf2cdf37cc84755d4f6ebdc415664549ccdbff21e13c06be362b9 +size 187944 diff --git a/omnilmm/lib/python3.10/lib-dynload/_testcapi.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testcapi.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..54236c98cc34c952197ef015ec182eaeb5c9a8b0 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_testcapi.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:517b2b45e3943262d02807cad5b34e724b384e85553fd62b495e012d5ed897a0 +size 481232 diff --git a/omnilmm/lib/python3.10/lib-dynload/_testclinic.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testclinic.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..33cb95091f88b746f4e9036866383fa78be59921 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_testclinic.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d21d17fa352f1e585afb8240dcbe49ad67b9bed71232b699c294b97820792559 +size 205672 diff --git a/omnilmm/lib/python3.10/lib-dynload/_testimportmultiple.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testimportmultiple.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3dbeb6267720de87adb2f8b6e33afc2cf990b34b Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_testimportmultiple.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_testinternalcapi.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testinternalcapi.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b09b15db1821505db1ad89d56d3bd3ed5925e3b1 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_testinternalcapi.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_testmultiphase.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_testmultiphase.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..899f44b180200e7dfc8e19ce3831700205345e40 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_testmultiphase.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_tkinter.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_tkinter.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2f2fbb6b176066e5c19bc80f9574058f1449b0a3 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_tkinter.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:491759f95bbf444170913747915a383de9acd7ee39f8d7069a67a7d5a25ddde0 +size 218000 diff --git a/omnilmm/lib/python3.10/lib-dynload/_uuid.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_uuid.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4b47afea48506995a67bfc3ff9896dd608076889 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_uuid.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_xxsubinterpreters.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_xxsubinterpreters.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..948982a251152c9cc718a6fc00f417e0dd224e0a --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_xxsubinterpreters.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:462ae2906ffebca406891ed2955376243f777336816acb18c6efc32aa1249e8d +size 149936 diff --git a/omnilmm/lib/python3.10/lib-dynload/_xxtestfuzz.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_xxtestfuzz.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8775ae80b96b32b39d56f3fa7fe0dd2606ee7da2 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/_xxtestfuzz.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/_zoneinfo.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/_zoneinfo.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3539ace13c178bd50a3b2f8fdc19a809edf6e1e7 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/_zoneinfo.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb38a8e751825aa95af436b17da44762c3f446a02c33ee193788d4ab02124017 +size 160600 diff --git a/omnilmm/lib/python3.10/lib-dynload/array.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/array.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7f4a8b1c4a2334b4d1caee553b66de7ed7bb214a --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/array.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12e45ee9da9d37cf82992df35fed43551d3f6990306c9cc7652b776334253b6f +size 231120 diff --git a/omnilmm/lib/python3.10/lib-dynload/audioop.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/audioop.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..04706099c4d0ff19edafcf0325b88501829c4f1f --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/audioop.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:233abb4b71e0236796b6cff91d7e78ae2723b52ed42ffba821d385f8d91534d2 +size 231584 diff --git a/omnilmm/lib/python3.10/lib-dynload/binascii.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/binascii.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f0398eec8d391bb76bf09f0d52a463038a5a0f1e --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/binascii.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fe7e9e043cae383510159adef847a131bb35d03d64f3293d6cc40c4a94c4815 +size 122768 diff --git a/omnilmm/lib/python3.10/lib-dynload/cmath.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/cmath.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5ae90ed418913af8018d3b6b60bfcc79db397a80 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/cmath.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b3c62248b7978049139ec6099e06b016fd8c8951c0d3c0d7993f4e332c0073a +size 194648 diff --git a/omnilmm/lib/python3.10/lib-dynload/fcntl.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/fcntl.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..67541d42a4800d9b6a3b7b509e9ecc21f2136379 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/fcntl.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/grp.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/grp.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7812db00ac54ace7060f863f8ec9e186e977c31c Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/grp.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..daf6b60f7d91a11a0a46a5638943bdd8f15452b7 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/math.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:928c3a7004d4c116d53bee3f89cda66e8fe059f4104ada956a9a4cf7002a88a2 +size 259288 diff --git a/omnilmm/lib/python3.10/lib-dynload/mmap.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/mmap.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..966010d37691d86bae1cf4b5a2ff6570981b770d Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/mmap.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/nis.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/nis.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9230e8a1860698401efce0ea6218c95ecd16a046 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/nis.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/ossaudiodev.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/ossaudiodev.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e0c62e42e13b6af7ff13eedef9d96361fde099a1 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/ossaudiodev.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d9dcc0e0dd4110c4c54d3d2f8e610984b245c94d --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/pyexpat.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cbdb91532750441b91f2c00d77ed92887fbb785bbeebc1f8fd233c0d4c9eff2 +size 983848 diff --git a/omnilmm/lib/python3.10/lib-dynload/readline.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/readline.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..cc72a5af63a72b065f228ddfcc90327df6c56e2e --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/readline.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96bcc678065c5ffab0324a9b557a7511f7fda79d85d84fafb7f2012261f4cee7 +size 112992 diff --git a/omnilmm/lib/python3.10/lib-dynload/resource.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/resource.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0346be40625f1b34fa66990ba0ae182507c789d2 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/resource.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/select.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/select.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2089bdfeb7e483f804176d3211477c10cba15c4b --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/select.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:854664e98e53f855778a476978040a576a949c167674187de51479decdf0c2fd +size 113568 diff --git a/omnilmm/lib/python3.10/lib-dynload/spwd.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/spwd.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e55118950911319ef0ac87319160ecbdde85934d Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/spwd.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/syslog.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/syslog.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..eee0cc3fc18b83193be4dcbd97e0c3ac4b22e617 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/syslog.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/unicodedata.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/unicodedata.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..18c825a23659cb9244405369cedffd5b4c75ee76 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/unicodedata.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:202faa427cd954a6b067d966af08d45f9d98cf08c41bbd3a2013327c18a3c43c +size 1208032 diff --git a/omnilmm/lib/python3.10/lib-dynload/xxlimited.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/xxlimited.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..58be903db80ea1f5c2bff07cfcb3c0a66215ff6f Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/xxlimited.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/xxlimited_35.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/xxlimited_35.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7239b1a0721a9ff0754e70ee16d4b7929a42e966 Binary files /dev/null and b/omnilmm/lib/python3.10/lib-dynload/xxlimited_35.cpython-310-x86_64-linux-gnu.so differ diff --git a/omnilmm/lib/python3.10/lib-dynload/zlib.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/lib-dynload/zlib.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f32d37df58621763bab1b6cdae5cb41663840ff5 --- /dev/null +++ b/omnilmm/lib/python3.10/lib-dynload/zlib.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:929a59e6c7f4e6f654078755d54b107b21c2ada9a80d19e72c8c118918159d9f +size 138024 diff --git a/omnilmm/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so b/omnilmm/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..baaef9702ce08011e691e84d06b64a294fd53015 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca34df237b40c8b8c75cb3c4e7eb582cb9092572ad25e0333ddff4432a384ce +size 376960 diff --git a/omnilmm/lib/python3.10/test/__init__.py b/omnilmm/lib/python3.10/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b93054b3ecf3a5af96f4772e7208e7a18b5dd4a4 --- /dev/null +++ b/omnilmm/lib/python3.10/test/__init__.py @@ -0,0 +1 @@ +# Dummy file to make this directory a package. diff --git a/omnilmm/lib/python3.10/test/__pycache__/__init__.cpython-310.pyc b/omnilmm/lib/python3.10/test/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ac4b8df0b10a429bd7e1471c06a5a0406edc363 Binary files /dev/null and b/omnilmm/lib/python3.10/test/__pycache__/__init__.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/__pycache__/test_script_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/__pycache__/test_script_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a17fd4b5de5f60915359cad0b1e8b9eae72be167 Binary files /dev/null and b/omnilmm/lib/python3.10/test/__pycache__/test_script_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/__pycache__/test_support.cpython-310.pyc b/omnilmm/lib/python3.10/test/__pycache__/test_support.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40432000a167715ab0d5b114f49bf7096203bd8b Binary files /dev/null and b/omnilmm/lib/python3.10/test/__pycache__/test_support.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__init__.py b/omnilmm/lib/python3.10/test/support/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7cf1e28581ed92a15182dec7ef12671e8c496cc --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/__init__.py @@ -0,0 +1,2124 @@ +"""Supporting definitions for the Python regression tests.""" + +if __name__ != 'test.support': + raise ImportError('support must be imported from the test package') + +import contextlib +import functools +import os +import re +import stat +import sys +import sysconfig +import time +import types +import unittest +import warnings + +from .testresult import get_test_runner + + +try: + from _testcapi import unicode_legacy_string +except ImportError: + unicode_legacy_string = None + +__all__ = [ + # globals + "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast", + # exceptions + "Error", "TestFailed", "TestDidNotRun", "ResourceDenied", + # io + "record_original_stdout", "get_original_stdout", "captured_stdout", + "captured_stdin", "captured_stderr", + # unittest + "is_resource_enabled", "requires", "requires_freebsd_version", + "requires_linux_version", "requires_mac_ver", + "check_syntax_error", + "BasicTestRunner", "run_unittest", "run_doctest", + "requires_gzip", "requires_bz2", "requires_lzma", + "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute", + "requires_IEEE_754", "requires_zlib", + "anticipate_failure", "load_package_tests", "detect_api_mismatch", + "check__all__", "skip_if_buggy_ucrt_strfptime", + "check_disallow_instantiation", "check_sanitizer", "skip_if_sanitizer", + # sys + "is_jython", "is_android", "check_impl_detail", "unix_shell", + "setswitchinterval", + # network + "open_urlresource", + # processes + "reap_children", + # miscellaneous + "run_with_locale", "swap_item", "findfile", + "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict", + "run_with_tz", "PGO", "missing_compiler_executable", + "ALWAYS_EQ", "NEVER_EQ", "LARGEST", "SMALLEST", + "LOOPBACK_TIMEOUT", "INTERNET_TIMEOUT", "SHORT_TIMEOUT", "LONG_TIMEOUT", + ] + + +# Timeout in seconds for tests using a network server listening on the network +# local loopback interface like 127.0.0.1. +# +# The timeout is long enough to prevent test failure: it takes into account +# that the client and the server can run in different threads or even different +# processes. +# +# The timeout should be long enough for connect(), recv() and send() methods +# of socket.socket. +LOOPBACK_TIMEOUT = 5.0 +if sys.platform == 'win32' and ' 32 bit (ARM)' in sys.version: + # bpo-37553: test_socket.SendfileUsingSendTest is taking longer than 2 + # seconds on Windows ARM32 buildbot + LOOPBACK_TIMEOUT = 10 +elif sys.platform == 'vxworks': + LOOPBACK_TIMEOUT = 10 + +# Timeout in seconds for network requests going to the internet. The timeout is +# short enough to prevent a test to wait for too long if the internet request +# is blocked for whatever reason. +# +# Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed, +# but skip the test instead: see transient_internet(). +INTERNET_TIMEOUT = 60.0 + +# Timeout in seconds to mark a test as failed if the test takes "too long". +# +# The timeout value depends on the regrtest --timeout command line option. +# +# If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use +# LONG_TIMEOUT instead. +SHORT_TIMEOUT = 30.0 + +# Timeout in seconds to detect when a test hangs. +# +# It is long enough to reduce the risk of test failure on the slowest Python +# buildbots. It should not be used to mark a test as failed if the test takes +# "too long". The timeout value depends on the regrtest --timeout command line +# option. +LONG_TIMEOUT = 5 * 60.0 + + +class Error(Exception): + """Base class for regression test exceptions.""" + +class TestFailed(Error): + """Test failed.""" + +class TestFailedWithDetails(TestFailed): + """Test failed.""" + def __init__(self, msg, errors, failures): + self.msg = msg + self.errors = errors + self.failures = failures + super().__init__(msg, errors, failures) + + def __str__(self): + return self.msg + +class TestDidNotRun(Error): + """Test did not run any subtests.""" + +class ResourceDenied(unittest.SkipTest): + """Test skipped because it requested a disallowed resource. + + This is raised when a test calls requires() for a resource that + has not be enabled. It is used to distinguish between expected + and unexpected skips. + """ + +def anticipate_failure(condition): + """Decorator to mark a test that is known to be broken in some cases + + Any use of this decorator should have a comment identifying the + associated tracker issue. + """ + if condition: + return unittest.expectedFailure + return lambda f: f + +def load_package_tests(pkg_dir, loader, standard_tests, pattern): + """Generic load_tests implementation for simple test packages. + + Most packages can implement load_tests using this function as follows: + + def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) + """ + if pattern is None: + pattern = "test*" + top_dir = os.path.dirname( # Lib + os.path.dirname( # test + os.path.dirname(__file__))) # support + package_tests = loader.discover(start_dir=pkg_dir, + top_level_dir=top_dir, + pattern=pattern) + standard_tests.addTests(package_tests) + return standard_tests + + +def get_attribute(obj, name): + """Get an attribute, raising SkipTest if AttributeError is raised.""" + try: + attribute = getattr(obj, name) + except AttributeError: + raise unittest.SkipTest("object %r has no attribute %r" % (obj, name)) + else: + return attribute + +verbose = 1 # Flag set to 0 by regrtest.py +use_resources = None # Flag set to [] by regrtest.py +max_memuse = 0 # Disable bigmem tests (they will still be run with + # small sizes, to make sure they work.) +real_max_memuse = 0 +junit_xml_list = None # list of testsuite XML elements +failfast = False + +# _original_stdout is meant to hold stdout at the time regrtest began. +# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever. +# The point is to have some flavor of stdout the user can actually see. +_original_stdout = None +def record_original_stdout(stdout): + global _original_stdout + _original_stdout = stdout + +def get_original_stdout(): + return _original_stdout or sys.stdout + + +def _force_run(path, func, *args): + try: + return func(*args) + except OSError as err: + if verbose >= 2: + print('%s: %s' % (err.__class__.__name__, err)) + print('re-run %s%r' % (func.__name__, args)) + os.chmod(path, stat.S_IRWXU) + return func(*args) + + +# Check whether a gui is actually available +def _is_gui_available(): + if hasattr(_is_gui_available, 'result'): + return _is_gui_available.result + import platform + reason = None + if sys.platform.startswith('win') and platform.win32_is_iot(): + reason = "gui is not available on Windows IoT Core" + elif sys.platform.startswith('win'): + # if Python is running as a service (such as the buildbot service), + # gui interaction may be disallowed + import ctypes + import ctypes.wintypes + UOI_FLAGS = 1 + WSF_VISIBLE = 0x0001 + class USEROBJECTFLAGS(ctypes.Structure): + _fields_ = [("fInherit", ctypes.wintypes.BOOL), + ("fReserved", ctypes.wintypes.BOOL), + ("dwFlags", ctypes.wintypes.DWORD)] + dll = ctypes.windll.user32 + h = dll.GetProcessWindowStation() + if not h: + raise ctypes.WinError() + uof = USEROBJECTFLAGS() + needed = ctypes.wintypes.DWORD() + res = dll.GetUserObjectInformationW(h, + UOI_FLAGS, + ctypes.byref(uof), + ctypes.sizeof(uof), + ctypes.byref(needed)) + if not res: + raise ctypes.WinError() + if not bool(uof.dwFlags & WSF_VISIBLE): + reason = "gui not available (WSF_VISIBLE flag not set)" + elif sys.platform == 'darwin': + # The Aqua Tk implementations on OS X can abort the process if + # being called in an environment where a window server connection + # cannot be made, for instance when invoked by a buildbot or ssh + # process not running under the same user id as the current console + # user. To avoid that, raise an exception if the window manager + # connection is not available. + from ctypes import cdll, c_int, pointer, Structure + from ctypes.util import find_library + + app_services = cdll.LoadLibrary(find_library("ApplicationServices")) + + if app_services.CGMainDisplayID() == 0: + reason = "gui tests cannot run without OS X window manager" + else: + class ProcessSerialNumber(Structure): + _fields_ = [("highLongOfPSN", c_int), + ("lowLongOfPSN", c_int)] + psn = ProcessSerialNumber() + psn_p = pointer(psn) + if ( (app_services.GetCurrentProcess(psn_p) < 0) or + (app_services.SetFrontProcess(psn_p) < 0) ): + reason = "cannot run without OS X gui process" + + # check on every platform whether tkinter can actually do anything + if not reason: + try: + from tkinter import Tk + root = Tk() + root.withdraw() + root.update() + root.destroy() + except Exception as e: + err_string = str(e) + if len(err_string) > 50: + err_string = err_string[:50] + ' [...]' + reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__, + err_string) + + _is_gui_available.reason = reason + _is_gui_available.result = not reason + + return _is_gui_available.result + +def is_resource_enabled(resource): + """Test whether a resource is enabled. + + Known resources are set by regrtest.py. If not running under regrtest.py, + all resources are assumed enabled unless use_resources has been set. + """ + return use_resources is None or resource in use_resources + +def requires(resource, msg=None): + """Raise ResourceDenied if the specified resource is not available.""" + if not is_resource_enabled(resource): + if msg is None: + msg = "Use of the %r resource not enabled" % resource + raise ResourceDenied(msg) + if resource == 'gui' and not _is_gui_available(): + raise ResourceDenied(_is_gui_available.reason) + +def _requires_unix_version(sysname, min_version): + """Decorator raising SkipTest if the OS is `sysname` and the version is less + than `min_version`. + + For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if + the FreeBSD version is less than 7.2. + """ + import platform + min_version_txt = '.'.join(map(str, min_version)) + version_txt = platform.release().split('-', 1)[0] + if platform.system() == sysname: + try: + version = tuple(map(int, version_txt.split('.'))) + except ValueError: + skip = False + else: + skip = version < min_version + else: + skip = False + + return unittest.skipIf( + skip, + f"{sysname} version {min_version_txt} or higher required, not " + f"{version_txt}" + ) + + +def requires_freebsd_version(*min_version): + """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is + less than `min_version`. + + For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD + version is less than 7.2. + """ + return _requires_unix_version('FreeBSD', min_version) + +def requires_linux_version(*min_version): + """Decorator raising SkipTest if the OS is Linux and the Linux version is + less than `min_version`. + + For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux + version is less than 2.6.32. + """ + return _requires_unix_version('Linux', min_version) + +def requires_mac_ver(*min_version): + """Decorator raising SkipTest if the OS is Mac OS X and the OS X + version if less than min_version. + + For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version + is lesser than 10.5. + """ + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kw): + if sys.platform == 'darwin': + import platform + version_txt = platform.mac_ver()[0] + try: + version = tuple(map(int, version_txt.split('.'))) + except ValueError: + pass + else: + if version < min_version: + min_version_txt = '.'.join(map(str, min_version)) + raise unittest.SkipTest( + "Mac OS X %s or higher required, not %s" + % (min_version_txt, version_txt)) + return func(*args, **kw) + wrapper.min_version = min_version + return wrapper + return decorator + + +def check_sanitizer(*, address=False, memory=False, ub=False): + """Returns True if Python is compiled with sanitizer support""" + if not (address or memory or ub): + raise ValueError('At least one of address, memory, or ub must be True') + + + _cflags = sysconfig.get_config_var('CFLAGS') or '' + _config_args = sysconfig.get_config_var('CONFIG_ARGS') or '' + memory_sanitizer = ( + '-fsanitize=memory' in _cflags or + '--with-memory-sanitizer' in _config_args + ) + address_sanitizer = ( + '-fsanitize=address' in _cflags or + '--with-memory-sanitizer' in _config_args + ) + ub_sanitizer = ( + '-fsanitize=undefined' in _cflags or + '--with-undefined-behavior-sanitizer' in _config_args + ) + return ( + (memory and memory_sanitizer) or + (address and address_sanitizer) or + (ub and ub_sanitizer) + ) + + +def skip_if_sanitizer(reason=None, *, address=False, memory=False, ub=False): + """Decorator raising SkipTest if running with a sanitizer active.""" + if not reason: + reason = 'not working with sanitizers active' + skip = check_sanitizer(address=address, memory=memory, ub=ub) + return unittest.skipIf(skip, reason) + + +def system_must_validate_cert(f): + """Skip the test on TLS certificate validation failures.""" + @functools.wraps(f) + def dec(*args, **kwargs): + try: + f(*args, **kwargs) + except OSError as e: + if "CERTIFICATE_VERIFY_FAILED" in str(e): + raise unittest.SkipTest("system does not contain " + "necessary certificates") + raise + return dec + +# A constant likely larger than the underlying OS pipe buffer size, to +# make writes blocking. +# Windows limit seems to be around 512 B, and many Unix kernels have a +# 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure. +# (see issue #17835 for a discussion of this number). +PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1 + +# A constant likely larger than the underlying OS socket buffer size, to make +# writes blocking. +# The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl +# on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643 +# for a discussion of this number. +SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1 + +# decorator for skipping tests on non-IEEE 754 platforms +requires_IEEE_754 = unittest.skipUnless( + float.__getformat__("double").startswith("IEEE"), + "test requires IEEE 754 doubles") + +def requires_zlib(reason='requires zlib'): + try: + import zlib + except ImportError: + zlib = None + return unittest.skipUnless(zlib, reason) + +def requires_gzip(reason='requires gzip'): + try: + import gzip + except ImportError: + gzip = None + return unittest.skipUnless(gzip, reason) + +def requires_bz2(reason='requires bz2'): + try: + import bz2 + except ImportError: + bz2 = None + return unittest.skipUnless(bz2, reason) + +def requires_lzma(reason='requires lzma'): + try: + import lzma + except ImportError: + lzma = None + return unittest.skipUnless(lzma, reason) + +requires_legacy_unicode_capi = unittest.skipUnless(unicode_legacy_string, + 'requires legacy Unicode C API') + +is_jython = sys.platform.startswith('java') + +is_android = hasattr(sys, 'getandroidapilevel') + +if sys.platform not in ('win32', 'vxworks'): + unix_shell = '/system/bin/sh' if is_android else '/bin/sh' +else: + unix_shell = None + +# Define the URL of a dedicated HTTP server for the network tests. +# The URL must use clear-text HTTP: no redirection to encrypted HTTPS. +TEST_HTTP_URL = "http://www.pythontest.net" + +# Set by libregrtest/main.py so we can skip tests that are not +# useful for PGO +PGO = False + +# Set by libregrtest/main.py if we are running the extended (time consuming) +# PGO task. If this is True, PGO is also True. +PGO_EXTENDED = False + +# TEST_HOME_DIR refers to the top level directory of the "test" package +# that contains Python's regression test suite +TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__)) +TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR) + +# TEST_DATA_DIR is used as a target download location for remote resources +TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data") + + +def darwin_malloc_err_warning(test_name): + """Assure user that loud errors generated by macOS libc's malloc are + expected.""" + if sys.platform != 'darwin': + return + + import shutil + msg = ' NOTICE ' + detail = (f'{test_name} may generate "malloc can\'t allocate region"\n' + 'warnings on macOS systems. This behavior is known. Do not\n' + 'report a bug unless tests are also failing. See bpo-40928.') + + padding, _ = shutil.get_terminal_size() + print(msg.center(padding, '-')) + print(detail) + print('-' * padding) + + +def findfile(filename, subdir=None): + """Try to find a file on sys.path or in the test directory. If it is not + found the argument passed to the function is returned (this does not + necessarily signal failure; could still be the legitimate path). + + Setting *subdir* indicates a relative path to use to find the file + rather than looking directly in the path directories. + """ + if os.path.isabs(filename): + return filename + if subdir is not None: + filename = os.path.join(subdir, filename) + path = [TEST_HOME_DIR] + sys.path + for dn in path: + fn = os.path.join(dn, filename) + if os.path.exists(fn): return fn + return filename + + +def sortdict(dict): + "Like repr(dict), but in sorted order." + items = sorted(dict.items()) + reprpairs = ["%r: %r" % pair for pair in items] + withcommas = ", ".join(reprpairs) + return "{%s}" % withcommas + +def check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None): + with testcase.assertRaisesRegex(SyntaxError, errtext) as cm: + compile(statement, '', 'exec') + err = cm.exception + testcase.assertIsNotNone(err.lineno) + if lineno is not None: + testcase.assertEqual(err.lineno, lineno) + testcase.assertIsNotNone(err.offset) + if offset is not None: + testcase.assertEqual(err.offset, offset) + + +def open_urlresource(url, *args, **kw): + import urllib.request, urllib.parse + from .os_helper import unlink + try: + import gzip + except ImportError: + gzip = None + + check = kw.pop('check', None) + + filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL! + + fn = os.path.join(TEST_DATA_DIR, filename) + + def check_valid_file(fn): + f = open(fn, *args, **kw) + if check is None: + return f + elif check(f): + f.seek(0) + return f + f.close() + + if os.path.exists(fn): + f = check_valid_file(fn) + if f is not None: + return f + unlink(fn) + + # Verify the requirement before downloading the file + requires('urlfetch') + + if verbose: + print('\tfetching %s ...' % url, file=get_original_stdout()) + opener = urllib.request.build_opener() + if gzip: + opener.addheaders.append(('Accept-Encoding', 'gzip')) + f = opener.open(url, timeout=INTERNET_TIMEOUT) + if gzip and f.headers.get('Content-Encoding') == 'gzip': + f = gzip.GzipFile(fileobj=f) + try: + with open(fn, "wb") as out: + s = f.read() + while s: + out.write(s) + s = f.read() + finally: + f.close() + + f = check_valid_file(fn) + if f is not None: + return f + raise TestFailed('invalid resource %r' % fn) + + +@contextlib.contextmanager +def captured_output(stream_name): + """Return a context manager used by captured_stdout/stdin/stderr + that temporarily replaces the sys stream *stream_name* with a StringIO.""" + import io + orig_stdout = getattr(sys, stream_name) + setattr(sys, stream_name, io.StringIO()) + try: + yield getattr(sys, stream_name) + finally: + setattr(sys, stream_name, orig_stdout) + +def captured_stdout(): + """Capture the output of sys.stdout: + + with captured_stdout() as stdout: + print("hello") + self.assertEqual(stdout.getvalue(), "hello\\n") + """ + return captured_output("stdout") + +def captured_stderr(): + """Capture the output of sys.stderr: + + with captured_stderr() as stderr: + print("hello", file=sys.stderr) + self.assertEqual(stderr.getvalue(), "hello\\n") + """ + return captured_output("stderr") + +def captured_stdin(): + """Capture the input to sys.stdin: + + with captured_stdin() as stdin: + stdin.write('hello\\n') + stdin.seek(0) + # call test code that consumes from sys.stdin + captured = input() + self.assertEqual(captured, "hello") + """ + return captured_output("stdin") + + +def gc_collect(): + """Force as many objects as possible to be collected. + + In non-CPython implementations of Python, this is needed because timely + deallocation is not guaranteed by the garbage collector. (Even in CPython + this can be the case in case of reference cycles.) This means that __del__ + methods may be called later than expected and weakrefs may remain alive for + longer than expected. This function tries its best to force all garbage + objects to disappear. + """ + import gc + gc.collect() + if is_jython: + time.sleep(0.1) + gc.collect() + gc.collect() + +@contextlib.contextmanager +def disable_gc(): + import gc + have_gc = gc.isenabled() + gc.disable() + try: + yield + finally: + if have_gc: + gc.enable() + + +def python_is_optimized(): + """Find if Python was built with optimizations.""" + cflags = sysconfig.get_config_var('PY_CFLAGS') or '' + final_opt = "" + for opt in cflags.split(): + if opt.startswith('-O'): + final_opt = opt + return final_opt not in ('', '-O0', '-Og') + + +_header = 'nP' +_align = '0n' +if hasattr(sys, "getobjects"): + _header = '2P' + _header + _align = '0P' +_vheader = _header + 'n' + +def calcobjsize(fmt): + import struct + return struct.calcsize(_header + fmt + _align) + +def calcvobjsize(fmt): + import struct + return struct.calcsize(_vheader + fmt + _align) + + +_TPFLAGS_HAVE_GC = 1<<14 +_TPFLAGS_HEAPTYPE = 1<<9 + +def check_sizeof(test, o, size): + import _testinternalcapi + result = sys.getsizeof(o) + # add GC header size + if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\ + ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))): + size += _testinternalcapi.SIZEOF_PYGC_HEAD + msg = 'wrong size for %s: got %d, expected %d' \ + % (type(o), result, size) + test.assertEqual(result, size, msg) + +#======================================================================= +# Decorator for running a function in a different locale, correctly resetting +# it afterwards. + +@contextlib.contextmanager +def run_with_locale(catstr, *locales): + try: + import locale + category = getattr(locale, catstr) + orig_locale = locale.setlocale(category) + except AttributeError: + # if the test author gives us an invalid category string + raise + except: + # cannot retrieve original locale, so do nothing + locale = orig_locale = None + else: + for loc in locales: + try: + locale.setlocale(category, loc) + break + except: + pass + + try: + yield + finally: + if locale and orig_locale: + locale.setlocale(category, orig_locale) + +#======================================================================= +# Decorator for running a function in a specific timezone, correctly +# resetting it afterwards. + +def run_with_tz(tz): + def decorator(func): + def inner(*args, **kwds): + try: + tzset = time.tzset + except AttributeError: + raise unittest.SkipTest("tzset required") + if 'TZ' in os.environ: + orig_tz = os.environ['TZ'] + else: + orig_tz = None + os.environ['TZ'] = tz + tzset() + + # now run the function, resetting the tz on exceptions + try: + return func(*args, **kwds) + finally: + if orig_tz is None: + del os.environ['TZ'] + else: + os.environ['TZ'] = orig_tz + time.tzset() + + inner.__name__ = func.__name__ + inner.__doc__ = func.__doc__ + return inner + return decorator + +#======================================================================= +# Big-memory-test support. Separate from 'resources' because memory use +# should be configurable. + +# Some handy shorthands. Note that these are used for byte-limits as well +# as size-limits, in the various bigmem tests +_1M = 1024*1024 +_1G = 1024 * _1M +_2G = 2 * _1G +_4G = 4 * _1G + +MAX_Py_ssize_t = sys.maxsize + +def set_memlimit(limit): + global max_memuse + global real_max_memuse + sizes = { + 'k': 1024, + 'm': _1M, + 'g': _1G, + 't': 1024*_1G, + } + m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit, + re.IGNORECASE | re.VERBOSE) + if m is None: + raise ValueError('Invalid memory limit %r' % (limit,)) + memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()]) + real_max_memuse = memlimit + if memlimit > MAX_Py_ssize_t: + memlimit = MAX_Py_ssize_t + if memlimit < _2G - 1: + raise ValueError('Memory limit %r too low to be useful' % (limit,)) + max_memuse = memlimit + +class _MemoryWatchdog: + """An object which periodically watches the process' memory consumption + and prints it out. + """ + + def __init__(self): + self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid()) + self.started = False + + def start(self): + import warnings + try: + f = open(self.procfile, 'r') + except OSError as e: + warnings.warn('/proc not available for stats: {}'.format(e), + RuntimeWarning) + sys.stderr.flush() + return + + import subprocess + with f: + watchdog_script = findfile("memory_watchdog.py") + self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script], + stdin=f, + stderr=subprocess.DEVNULL) + self.started = True + + def stop(self): + if self.started: + self.mem_watchdog.terminate() + self.mem_watchdog.wait() + + +def bigmemtest(size, memuse, dry_run=True): + """Decorator for bigmem tests. + + 'size' is a requested size for the test (in arbitrary, test-interpreted + units.) 'memuse' is the number of bytes per unit for the test, or a good + estimate of it. For example, a test that needs two byte buffers, of 4 GiB + each, could be decorated with @bigmemtest(size=_4G, memuse=2). + + The 'size' argument is normally passed to the decorated test method as an + extra argument. If 'dry_run' is true, the value passed to the test method + may be less than the requested value. If 'dry_run' is false, it means the + test doesn't support dummy runs when -M is not specified. + """ + def decorator(f): + def wrapper(self): + size = wrapper.size + memuse = wrapper.memuse + if not real_max_memuse: + maxsize = 5147 + else: + maxsize = size + + if ((real_max_memuse or not dry_run) + and real_max_memuse < maxsize * memuse): + raise unittest.SkipTest( + "not enough memory: %.1fG minimum needed" + % (size * memuse / (1024 ** 3))) + + if real_max_memuse and verbose: + print() + print(" ... expected peak memory use: {peak:.1f}G" + .format(peak=size * memuse / (1024 ** 3))) + watchdog = _MemoryWatchdog() + watchdog.start() + else: + watchdog = None + + try: + return f(self, maxsize) + finally: + if watchdog: + watchdog.stop() + + wrapper.size = size + wrapper.memuse = memuse + return wrapper + return decorator + +def bigaddrspacetest(f): + """Decorator for tests that fill the address space.""" + def wrapper(self): + if max_memuse < MAX_Py_ssize_t: + if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31: + raise unittest.SkipTest( + "not enough memory: try a 32-bit build instead") + else: + raise unittest.SkipTest( + "not enough memory: %.1fG minimum needed" + % (MAX_Py_ssize_t / (1024 ** 3))) + else: + return f(self) + return wrapper + +#======================================================================= +# unittest integration. + +class BasicTestRunner: + def run(self, test): + result = unittest.TestResult() + test(result) + return result + +def _id(obj): + return obj + +def requires_resource(resource): + if resource == 'gui' and not _is_gui_available(): + return unittest.skip(_is_gui_available.reason) + if is_resource_enabled(resource): + return _id + else: + return unittest.skip("resource {0!r} is not enabled".format(resource)) + +def cpython_only(test): + """ + Decorator for tests only applicable on CPython. + """ + return impl_detail(cpython=True)(test) + +def impl_detail(msg=None, **guards): + if check_impl_detail(**guards): + return _id + if msg is None: + guardnames, default = _parse_guards(guards) + if default: + msg = "implementation detail not available on {0}" + else: + msg = "implementation detail specific to {0}" + guardnames = sorted(guardnames.keys()) + msg = msg.format(' or '.join(guardnames)) + return unittest.skip(msg) + +def _parse_guards(guards): + # Returns a tuple ({platform_name: run_me}, default_value) + if not guards: + return ({'cpython': True}, False) + is_true = list(guards.values())[0] + assert list(guards.values()) == [is_true] * len(guards) # all True or all False + return (guards, not is_true) + +# Use the following check to guard CPython's implementation-specific tests -- +# or to run them only on the implementation(s) guarded by the arguments. +def check_impl_detail(**guards): + """This function returns True or False depending on the host platform. + Examples: + if check_impl_detail(): # only on CPython (default) + if check_impl_detail(jython=True): # only on Jython + if check_impl_detail(cpython=False): # everywhere except on CPython + """ + guards, default = _parse_guards(guards) + return guards.get(sys.implementation.name, default) + + +def no_tracing(func): + """Decorator to temporarily turn off tracing for the duration of a test.""" + if not hasattr(sys, 'gettrace'): + return func + else: + @functools.wraps(func) + def wrapper(*args, **kwargs): + original_trace = sys.gettrace() + try: + sys.settrace(None) + return func(*args, **kwargs) + finally: + sys.settrace(original_trace) + return wrapper + + +def refcount_test(test): + """Decorator for tests which involve reference counting. + + To start, the decorator does not run the test if is not run by CPython. + After that, any trace function is unset during the test to prevent + unexpected refcounts caused by the trace function. + + """ + return no_tracing(cpython_only(test)) + + +def _filter_suite(suite, pred): + """Recursively filter test cases in a suite based on a predicate.""" + newtests = [] + for test in suite._tests: + if isinstance(test, unittest.TestSuite): + _filter_suite(test, pred) + newtests.append(test) + else: + if pred(test): + newtests.append(test) + suite._tests = newtests + +def _run_suite(suite): + """Run tests from a unittest.TestSuite-derived class.""" + runner = get_test_runner(sys.stdout, + verbosity=verbose, + capture_output=(junit_xml_list is not None)) + + result = runner.run(suite) + + if junit_xml_list is not None: + junit_xml_list.append(result.get_xml_element()) + + if not result.testsRun and not result.skipped: + raise TestDidNotRun + if not result.wasSuccessful(): + if len(result.errors) == 1 and not result.failures: + err = result.errors[0][1] + elif len(result.failures) == 1 and not result.errors: + err = result.failures[0][1] + else: + err = "multiple errors occurred" + if not verbose: err += "; run in verbose mode for details" + errors = [(str(tc), exc_str) for tc, exc_str in result.errors] + failures = [(str(tc), exc_str) for tc, exc_str in result.failures] + raise TestFailedWithDetails(err, errors, failures) + + +# By default, don't filter tests +_match_test_func = None + +_accept_test_patterns = None +_ignore_test_patterns = None + + +def match_test(test): + # Function used by support.run_unittest() and regrtest --list-cases + if _match_test_func is None: + return True + else: + return _match_test_func(test.id()) + + +def _is_full_match_test(pattern): + # If a pattern contains at least one dot, it's considered + # as a full test identifier. + # Example: 'test.test_os.FileTests.test_access'. + # + # ignore patterns which contain fnmatch patterns: '*', '?', '[...]' + # or '[!...]'. For example, ignore 'test_access*'. + return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern)) + + +def set_match_tests(accept_patterns=None, ignore_patterns=None): + global _match_test_func, _accept_test_patterns, _ignore_test_patterns + + + if accept_patterns is None: + accept_patterns = () + if ignore_patterns is None: + ignore_patterns = () + + accept_func = ignore_func = None + + if accept_patterns != _accept_test_patterns: + accept_patterns, accept_func = _compile_match_function(accept_patterns) + if ignore_patterns != _ignore_test_patterns: + ignore_patterns, ignore_func = _compile_match_function(ignore_patterns) + + # Create a copy since patterns can be mutable and so modified later + _accept_test_patterns = tuple(accept_patterns) + _ignore_test_patterns = tuple(ignore_patterns) + + if accept_func is not None or ignore_func is not None: + def match_function(test_id): + accept = True + ignore = False + if accept_func: + accept = accept_func(test_id) + if ignore_func: + ignore = ignore_func(test_id) + return accept and not ignore + + _match_test_func = match_function + + +def _compile_match_function(patterns): + if not patterns: + func = None + # set_match_tests(None) behaves as set_match_tests(()) + patterns = () + elif all(map(_is_full_match_test, patterns)): + # Simple case: all patterns are full test identifier. + # The test.bisect_cmd utility only uses such full test identifiers. + func = set(patterns).__contains__ + else: + import fnmatch + regex = '|'.join(map(fnmatch.translate, patterns)) + # The search *is* case sensitive on purpose: + # don't use flags=re.IGNORECASE + regex_match = re.compile(regex).match + + def match_test_regex(test_id): + if regex_match(test_id): + # The regex matches the whole identifier, for example + # 'test.test_os.FileTests.test_access'. + return True + else: + # Try to match parts of the test identifier. + # For example, split 'test.test_os.FileTests.test_access' + # into: 'test', 'test_os', 'FileTests' and 'test_access'. + return any(map(regex_match, test_id.split("."))) + + func = match_test_regex + + return patterns, func + + +def run_unittest(*classes): + """Run tests from unittest.TestCase-derived classes.""" + valid_types = (unittest.TestSuite, unittest.TestCase) + suite = unittest.TestSuite() + for cls in classes: + if isinstance(cls, str): + if cls in sys.modules: + suite.addTest(unittest.findTestCases(sys.modules[cls])) + else: + raise ValueError("str arguments must be keys in sys.modules") + elif isinstance(cls, valid_types): + suite.addTest(cls) + else: + suite.addTest(unittest.makeSuite(cls)) + _filter_suite(suite, match_test) + _run_suite(suite) + +#======================================================================= +# Check for the presence of docstrings. + +# Rather than trying to enumerate all the cases where docstrings may be +# disabled, we just check for that directly + +def _check_docstrings(): + """Just used to check if docstrings are enabled""" + +MISSING_C_DOCSTRINGS = (check_impl_detail() and + sys.platform != 'win32' and + not sysconfig.get_config_var('WITH_DOC_STRINGS')) + +HAVE_DOCSTRINGS = (_check_docstrings.__doc__ is not None and + not MISSING_C_DOCSTRINGS) + +requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS, + "test requires docstrings") + + +#======================================================================= +# doctest driver. + +def run_doctest(module, verbosity=None, optionflags=0): + """Run doctest on the given module. Return (#failures, #tests). + + If optional argument verbosity is not specified (or is None), pass + support's belief about verbosity on to doctest. Else doctest's + usual behavior is used (it searches sys.argv for -v). + """ + + import doctest + + if verbosity is None: + verbosity = verbose + else: + verbosity = None + + f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags) + if f: + raise TestFailed("%d of %d doctests failed" % (f, t)) + if verbose: + print('doctest (%s) ... %d tests with zero failures' % + (module.__name__, t)) + return f, t + + +#======================================================================= +# Support for saving and restoring the imported modules. + +def print_warning(msg): + # bpo-39983: Print into sys.__stderr__ to display the warning even + # when sys.stderr is captured temporarily by a test + for line in msg.splitlines(): + print(f"Warning -- {line}", file=sys.__stderr__, flush=True) + + +# Flag used by saved_test_environment of test.libregrtest.save_env, +# to check if a test modified the environment. The flag should be set to False +# before running a new test. +# +# For example, threading_helper.threading_cleanup() sets the flag is the function fails +# to cleanup threads. +environment_altered = False + +def reap_children(): + """Use this function at the end of test_main() whenever sub-processes + are started. This will help ensure that no extra children (zombies) + stick around to hog resources and create problems when looking + for refleaks. + """ + global environment_altered + + # Need os.waitpid(-1, os.WNOHANG): Windows is not supported + if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')): + return + + # Reap all our dead child processes so we don't leave zombies around. + # These hog resources and might be causing some of the buildbots to die. + while True: + try: + # Read the exit status of any child process which already completed + pid, status = os.waitpid(-1, os.WNOHANG) + except OSError: + break + + if pid == 0: + break + + print_warning(f"reap_children() reaped child process {pid}") + environment_altered = True + + +@contextlib.contextmanager +def swap_attr(obj, attr, new_val): + """Temporary swap out an attribute with a new object. + + Usage: + with swap_attr(obj, "attr", 5): + ... + + This will set obj.attr to 5 for the duration of the with: block, + restoring the old value at the end of the block. If `attr` doesn't + exist on `obj`, it will be created and then deleted at the end of the + block. + + The old value (or None if it doesn't exist) will be assigned to the + target of the "as" clause, if there is one. + """ + if hasattr(obj, attr): + real_val = getattr(obj, attr) + setattr(obj, attr, new_val) + try: + yield real_val + finally: + setattr(obj, attr, real_val) + else: + setattr(obj, attr, new_val) + try: + yield + finally: + if hasattr(obj, attr): + delattr(obj, attr) + +@contextlib.contextmanager +def swap_item(obj, item, new_val): + """Temporary swap out an item with a new object. + + Usage: + with swap_item(obj, "item", 5): + ... + + This will set obj["item"] to 5 for the duration of the with: block, + restoring the old value at the end of the block. If `item` doesn't + exist on `obj`, it will be created and then deleted at the end of the + block. + + The old value (or None if it doesn't exist) will be assigned to the + target of the "as" clause, if there is one. + """ + if item in obj: + real_val = obj[item] + obj[item] = new_val + try: + yield real_val + finally: + obj[item] = real_val + else: + obj[item] = new_val + try: + yield + finally: + if item in obj: + del obj[item] + +def args_from_interpreter_flags(): + """Return a list of command-line arguments reproducing the current + settings in sys.flags and sys.warnoptions.""" + import subprocess + return subprocess._args_from_interpreter_flags() + +def optim_args_from_interpreter_flags(): + """Return a list of command-line arguments reproducing the current + optimization settings in sys.flags.""" + import subprocess + return subprocess._optim_args_from_interpreter_flags() + + +class Matcher(object): + + _partial_matches = ('msg', 'message') + + def matches(self, d, **kwargs): + """ + Try to match a single dict with the supplied arguments. + + Keys whose values are strings and which are in self._partial_matches + will be checked for partial (i.e. substring) matches. You can extend + this scheme to (for example) do regular expression matching, etc. + """ + result = True + for k in kwargs: + v = kwargs[k] + dv = d.get(k) + if not self.match_value(k, dv, v): + result = False + break + return result + + def match_value(self, k, dv, v): + """ + Try to match a single stored value (dv) with a supplied value (v). + """ + if type(v) != type(dv): + result = False + elif type(dv) is not str or k not in self._partial_matches: + result = (v == dv) + else: + result = dv.find(v) >= 0 + return result + + +_buggy_ucrt = None +def skip_if_buggy_ucrt_strfptime(test): + """ + Skip decorator for tests that use buggy strptime/strftime + + If the UCRT bugs are present time.localtime().tm_zone will be + an empty string, otherwise we assume the UCRT bugs are fixed + + See bpo-37552 [Windows] strptime/strftime return invalid + results with UCRT version 17763.615 + """ + import locale + global _buggy_ucrt + if _buggy_ucrt is None: + if(sys.platform == 'win32' and + locale.getdefaultlocale()[1] == 'cp65001' and + time.localtime().tm_zone == ''): + _buggy_ucrt = True + else: + _buggy_ucrt = False + return unittest.skip("buggy MSVC UCRT strptime/strftime")(test) if _buggy_ucrt else test + +class PythonSymlink: + """Creates a symlink for the current Python executable""" + def __init__(self, link=None): + from .os_helper import TESTFN + + self.link = link or os.path.abspath(TESTFN) + self._linked = [] + self.real = os.path.realpath(sys.executable) + self._also_link = [] + + self._env = None + + self._platform_specific() + + if sys.platform == "win32": + def _platform_specific(self): + import glob + import _winapi + + if os.path.lexists(self.real) and not os.path.exists(self.real): + # App symlink appears to not exist, but we want the + # real executable here anyway + self.real = _winapi.GetModuleFileName(0) + + dll = _winapi.GetModuleFileName(sys.dllhandle) + src_dir = os.path.dirname(dll) + dest_dir = os.path.dirname(self.link) + self._also_link.append(( + dll, + os.path.join(dest_dir, os.path.basename(dll)) + )) + for runtime in glob.glob(os.path.join(glob.escape(src_dir), "vcruntime*.dll")): + self._also_link.append(( + runtime, + os.path.join(dest_dir, os.path.basename(runtime)) + )) + + self._env = {k.upper(): os.getenv(k) for k in os.environ} + self._env["PYTHONHOME"] = os.path.dirname(self.real) + if sysconfig.is_python_build(True): + self._env["PYTHONPATH"] = os.path.dirname(os.__file__) + else: + def _platform_specific(self): + pass + + def __enter__(self): + os.symlink(self.real, self.link) + self._linked.append(self.link) + for real, link in self._also_link: + os.symlink(real, link) + self._linked.append(link) + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + for link in self._linked: + try: + os.remove(link) + except IOError as ex: + if verbose: + print("failed to clean up {}: {}".format(link, ex)) + + def _call(self, python, args, env, returncode): + import subprocess + cmd = [python, *args] + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=env) + r = p.communicate() + if p.returncode != returncode: + if verbose: + print(repr(r[0])) + print(repr(r[1]), file=sys.stderr) + raise RuntimeError( + 'unexpected return code: {0} (0x{0:08X})'.format(p.returncode)) + return r + + def call_real(self, *args, returncode=0): + return self._call(self.real, args, None, returncode) + + def call_link(self, *args, returncode=0): + return self._call(self.link, args, self._env, returncode) + + +def skip_if_pgo_task(test): + """Skip decorator for tests not run in (non-extended) PGO task""" + ok = not PGO or PGO_EXTENDED + msg = "Not run for (non-extended) PGO task" + return test if ok else unittest.skip(msg)(test) + + +def detect_api_mismatch(ref_api, other_api, *, ignore=()): + """Returns the set of items in ref_api not in other_api, except for a + defined list of items to be ignored in this check. + + By default this skips private attributes beginning with '_' but + includes all magic methods, i.e. those starting and ending in '__'. + """ + missing_items = set(dir(ref_api)) - set(dir(other_api)) + if ignore: + missing_items -= set(ignore) + missing_items = set(m for m in missing_items + if not m.startswith('_') or m.endswith('__')) + return missing_items + + +def check__all__(test_case, module, name_of_module=None, extra=(), + not_exported=()): + """Assert that the __all__ variable of 'module' contains all public names. + + The module's public names (its API) are detected automatically based on + whether they match the public name convention and were defined in + 'module'. + + The 'name_of_module' argument can specify (as a string or tuple thereof) + what module(s) an API could be defined in in order to be detected as a + public API. One case for this is when 'module' imports part of its public + API from other modules, possibly a C backend (like 'csv' and its '_csv'). + + The 'extra' argument can be a set of names that wouldn't otherwise be + automatically detected as "public", like objects without a proper + '__module__' attribute. If provided, it will be added to the + automatically detected ones. + + The 'not_exported' argument can be a set of names that must not be treated + as part of the public API even though their names indicate otherwise. + + Usage: + import bar + import foo + import unittest + from test import support + + class MiscTestCase(unittest.TestCase): + def test__all__(self): + support.check__all__(self, foo) + + class OtherTestCase(unittest.TestCase): + def test__all__(self): + extra = {'BAR_CONST', 'FOO_CONST'} + not_exported = {'baz'} # Undocumented name. + # bar imports part of its API from _bar. + support.check__all__(self, bar, ('bar', '_bar'), + extra=extra, not_exported=not_exported) + + """ + + if name_of_module is None: + name_of_module = (module.__name__, ) + elif isinstance(name_of_module, str): + name_of_module = (name_of_module, ) + + expected = set(extra) + + for name in dir(module): + if name.startswith('_') or name in not_exported: + continue + obj = getattr(module, name) + if (getattr(obj, '__module__', None) in name_of_module or + (not hasattr(obj, '__module__') and + not isinstance(obj, types.ModuleType))): + expected.add(name) + test_case.assertCountEqual(module.__all__, expected) + + +def suppress_msvcrt_asserts(verbose=False): + try: + import msvcrt + except ImportError: + return + + msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS + | msvcrt.SEM_NOALIGNMENTFAULTEXCEPT + | msvcrt.SEM_NOGPFAULTERRORBOX + | msvcrt.SEM_NOOPENFILEERRORBOX) + + # CrtSetReportMode() is only available in debug build + if hasattr(msvcrt, 'CrtSetReportMode'): + for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]: + if verbose: + msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE) + msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR) + else: + msvcrt.CrtSetReportMode(m, 0) + + +class SuppressCrashReport: + """Try to prevent a crash report from popping up. + + On Windows, don't display the Windows Error Reporting dialog. On UNIX, + disable the creation of coredump file. + """ + old_value = None + old_modes = None + + def __enter__(self): + """On Windows, disable Windows Error Reporting dialogs using + SetErrorMode() and CrtSetReportMode(). + + On UNIX, try to save the previous core file size limit, then set + soft limit to 0. + """ + if sys.platform.startswith('win'): + # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx + try: + import msvcrt + except ImportError: + return + + self.old_value = msvcrt.GetErrorMode() + + msvcrt.SetErrorMode(self.old_value | msvcrt.SEM_NOGPFAULTERRORBOX) + + # bpo-23314: Suppress assert dialogs in debug builds. + # CrtSetReportMode() is only available in debug build. + if hasattr(msvcrt, 'CrtSetReportMode'): + self.old_modes = {} + for report_type in [msvcrt.CRT_WARN, + msvcrt.CRT_ERROR, + msvcrt.CRT_ASSERT]: + old_mode = msvcrt.CrtSetReportMode(report_type, + msvcrt.CRTDBG_MODE_FILE) + old_file = msvcrt.CrtSetReportFile(report_type, + msvcrt.CRTDBG_FILE_STDERR) + self.old_modes[report_type] = old_mode, old_file + + else: + try: + import resource + self.resource = resource + except ImportError: + self.resource = None + if self.resource is not None: + try: + self.old_value = self.resource.getrlimit(self.resource.RLIMIT_CORE) + self.resource.setrlimit(self.resource.RLIMIT_CORE, + (0, self.old_value[1])) + except (ValueError, OSError): + pass + + if sys.platform == 'darwin': + import subprocess + # Check if the 'Crash Reporter' on OSX was configured + # in 'Developer' mode and warn that it will get triggered + # when it is. + # + # This assumes that this context manager is used in tests + # that might trigger the next manager. + cmd = ['/usr/bin/defaults', 'read', + 'com.apple.CrashReporter', 'DialogType'] + proc = subprocess.Popen(cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + with proc: + stdout = proc.communicate()[0] + if stdout.strip() == b'developer': + print("this test triggers the Crash Reporter, " + "that is intentional", end='', flush=True) + + return self + + def __exit__(self, *ignore_exc): + """Restore Windows ErrorMode or core file behavior to initial value.""" + if self.old_value is None: + return + + if sys.platform.startswith('win'): + import msvcrt + msvcrt.SetErrorMode(self.old_value) + + if self.old_modes: + for report_type, (old_mode, old_file) in self.old_modes.items(): + msvcrt.CrtSetReportMode(report_type, old_mode) + msvcrt.CrtSetReportFile(report_type, old_file) + else: + if self.resource is not None: + try: + self.resource.setrlimit(self.resource.RLIMIT_CORE, self.old_value) + except (ValueError, OSError): + pass + + +def patch(test_instance, object_to_patch, attr_name, new_value): + """Override 'object_to_patch'.'attr_name' with 'new_value'. + + Also, add a cleanup procedure to 'test_instance' to restore + 'object_to_patch' value for 'attr_name'. + The 'attr_name' should be a valid attribute for 'object_to_patch'. + + """ + # check that 'attr_name' is a real attribute for 'object_to_patch' + # will raise AttributeError if it does not exist + getattr(object_to_patch, attr_name) + + # keep a copy of the old value + attr_is_local = False + try: + old_value = object_to_patch.__dict__[attr_name] + except (AttributeError, KeyError): + old_value = getattr(object_to_patch, attr_name, None) + else: + attr_is_local = True + + # restore the value when the test is done + def cleanup(): + if attr_is_local: + setattr(object_to_patch, attr_name, old_value) + else: + delattr(object_to_patch, attr_name) + + test_instance.addCleanup(cleanup) + + # actually override the attribute + setattr(object_to_patch, attr_name, new_value) + + +@contextlib.contextmanager +def patch_list(orig): + """Like unittest.mock.patch.dict, but for lists.""" + try: + saved = orig[:] + yield + finally: + orig[:] = saved + + +def run_in_subinterp(code): + """ + Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc + module is enabled. + """ + # Issue #10915, #15751: PyGILState_*() functions don't work with + # sub-interpreters, the tracemalloc module uses these functions internally + try: + import tracemalloc + except ImportError: + pass + else: + if tracemalloc.is_tracing(): + raise unittest.SkipTest("run_in_subinterp() cannot be used " + "if tracemalloc module is tracing " + "memory allocations") + import _testcapi + return _testcapi.run_in_subinterp(code) + + +def check_free_after_iterating(test, iter, cls, args=()): + class A(cls): + def __del__(self): + nonlocal done + done = True + try: + next(it) + except StopIteration: + pass + + done = False + it = iter(A(*args)) + # Issue 26494: Shouldn't crash + test.assertRaises(StopIteration, next, it) + # The sequence should be deallocated just after the end of iterating + gc_collect() + test.assertTrue(done) + + +def missing_compiler_executable(cmd_names=[]): + """Check if the compiler components used to build the interpreter exist. + + Check for the existence of the compiler executables whose names are listed + in 'cmd_names' or all the compiler executables when 'cmd_names' is empty + and return the first missing executable or None when none is found + missing. + + """ + # TODO (PEP 632): alternate check without using distutils + from distutils import ccompiler, sysconfig, spawn, errors + compiler = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + if compiler.compiler_type == "msvc": + # MSVC has no executables, so check whether initialization succeeds + try: + compiler.initialize() + except errors.DistutilsPlatformError: + return "msvc" + for name in compiler.executables: + if cmd_names and name not in cmd_names: + continue + cmd = getattr(compiler, name) + if cmd_names: + assert cmd is not None, \ + "the '%s' executable is not configured" % name + elif not cmd: + continue + if spawn.find_executable(cmd[0]) is None: + return cmd[0] + + +_is_android_emulator = None +def setswitchinterval(interval): + # Setting a very low gil interval on the Android emulator causes python + # to hang (issue #26939). + minimum_interval = 1e-5 + if is_android and interval < minimum_interval: + global _is_android_emulator + if _is_android_emulator is None: + import subprocess + _is_android_emulator = (subprocess.check_output( + ['getprop', 'ro.kernel.qemu']).strip() == b'1') + if _is_android_emulator: + interval = minimum_interval + return sys.setswitchinterval(interval) + + +@contextlib.contextmanager +def disable_faulthandler(): + import faulthandler + + # use sys.__stderr__ instead of sys.stderr, since regrtest replaces + # sys.stderr with a StringIO which has no file descriptor when a test + # is run with -W/--verbose3. + fd = sys.__stderr__.fileno() + + is_enabled = faulthandler.is_enabled() + try: + faulthandler.disable() + yield + finally: + if is_enabled: + faulthandler.enable(file=fd, all_threads=True) + + +class SaveSignals: + """ + Save and restore signal handlers. + + This class is only able to save/restore signal handlers registered + by the Python signal module: see bpo-13285 for "external" signal + handlers. + """ + + def __init__(self): + import signal + self.signal = signal + self.signals = signal.valid_signals() + # SIGKILL and SIGSTOP signals cannot be ignored nor caught + for signame in ('SIGKILL', 'SIGSTOP'): + try: + signum = getattr(signal, signame) + except AttributeError: + continue + self.signals.remove(signum) + self.handlers = {} + + def save(self): + for signum in self.signals: + handler = self.signal.getsignal(signum) + if handler is None: + # getsignal() returns None if a signal handler was not + # registered by the Python signal module, + # and the handler is not SIG_DFL nor SIG_IGN. + # + # Ignore the signal: we cannot restore the handler. + continue + self.handlers[signum] = handler + + def restore(self): + for signum, handler in self.handlers.items(): + self.signal.signal(signum, handler) + + +def with_pymalloc(): + import _testcapi + return _testcapi.WITH_PYMALLOC + + +class _ALWAYS_EQ: + """ + Object that is equal to anything. + """ + def __eq__(self, other): + return True + def __ne__(self, other): + return False + +ALWAYS_EQ = _ALWAYS_EQ() + +class _NEVER_EQ: + """ + Object that is not equal to anything. + """ + def __eq__(self, other): + return False + def __ne__(self, other): + return True + def __hash__(self): + return 1 + +NEVER_EQ = _NEVER_EQ() + +@functools.total_ordering +class _LARGEST: + """ + Object that is greater than anything (except itself). + """ + def __eq__(self, other): + return isinstance(other, _LARGEST) + def __lt__(self, other): + return False + +LARGEST = _LARGEST() + +@functools.total_ordering +class _SMALLEST: + """ + Object that is less than anything (except itself). + """ + def __eq__(self, other): + return isinstance(other, _SMALLEST) + def __gt__(self, other): + return False + +SMALLEST = _SMALLEST() + +def maybe_get_event_loop_policy(): + """Return the global event loop policy if one is set, else return None.""" + import asyncio.events + return asyncio.events._event_loop_policy + +# Helpers for testing hashing. +NHASHBITS = sys.hash_info.width # number of bits in hash() result +assert NHASHBITS in (32, 64) + +# Return mean and sdev of number of collisions when tossing nballs balls +# uniformly at random into nbins bins. By definition, the number of +# collisions is the number of balls minus the number of occupied bins at +# the end. +def collision_stats(nbins, nballs): + n, k = nbins, nballs + # prob a bin empty after k trials = (1 - 1/n)**k + # mean # empty is then n * (1 - 1/n)**k + # so mean # occupied is n - n * (1 - 1/n)**k + # so collisions = k - (n - n*(1 - 1/n)**k) + # + # For the variance: + # n*(n-1)*(1-2/n)**k + meanempty - meanempty**2 = + # n*(n-1)*(1-2/n)**k + meanempty * (1 - meanempty) + # + # Massive cancellation occurs, and, e.g., for a 64-bit hash code + # 1-1/2**64 rounds uselessly to 1.0. Rather than make heroic (and + # error-prone) efforts to rework the naive formulas to avoid those, + # we use the `decimal` module to get plenty of extra precision. + # + # Note: the exact values are straightforward to compute with + # rationals, but in context that's unbearably slow, requiring + # multi-million bit arithmetic. + import decimal + with decimal.localcontext() as ctx: + bits = n.bit_length() * 2 # bits in n**2 + # At least that many bits will likely cancel out. + # Use that many decimal digits instead. + ctx.prec = max(bits, 30) + dn = decimal.Decimal(n) + p1empty = ((dn - 1) / dn) ** k + meanempty = n * p1empty + occupied = n - meanempty + collisions = k - occupied + var = dn*(dn-1)*((dn-2)/dn)**k + meanempty * (1 - meanempty) + return float(collisions), float(var.sqrt()) + + +class catch_unraisable_exception: + """ + Context manager catching unraisable exception using sys.unraisablehook. + + Storing the exception value (cm.unraisable.exc_value) creates a reference + cycle. The reference cycle is broken explicitly when the context manager + exits. + + Storing the object (cm.unraisable.object) can resurrect it if it is set to + an object which is being finalized. Exiting the context manager clears the + stored object. + + Usage: + + with support.catch_unraisable_exception() as cm: + # code creating an "unraisable exception" + ... + + # check the unraisable exception: use cm.unraisable + ... + + # cm.unraisable attribute no longer exists at this point + # (to break a reference cycle) + """ + + def __init__(self): + self.unraisable = None + self._old_hook = None + + def _hook(self, unraisable): + # Storing unraisable.object can resurrect an object which is being + # finalized. Storing unraisable.exc_value creates a reference cycle. + self.unraisable = unraisable + + def __enter__(self): + self._old_hook = sys.unraisablehook + sys.unraisablehook = self._hook + return self + + def __exit__(self, *exc_info): + sys.unraisablehook = self._old_hook + del self.unraisable + + +def wait_process(pid, *, exitcode, timeout=None): + """ + Wait until process pid completes and check that the process exit code is + exitcode. + + Raise an AssertionError if the process exit code is not equal to exitcode. + + If the process runs longer than timeout seconds (LONG_TIMEOUT by default), + kill the process (if signal.SIGKILL is available) and raise an + AssertionError. The timeout feature is not available on Windows. + """ + if os.name != "nt": + import signal + + if timeout is None: + timeout = LONG_TIMEOUT + t0 = time.monotonic() + sleep = 0.001 + max_sleep = 0.1 + while True: + pid2, status = os.waitpid(pid, os.WNOHANG) + if pid2 != 0: + break + # process is still running + + dt = time.monotonic() - t0 + if dt > timeout: + try: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + except OSError: + # Ignore errors like ChildProcessError or PermissionError + pass + + raise AssertionError(f"process {pid} is still running " + f"after {dt:.1f} seconds") + + sleep = min(sleep * 2, max_sleep) + time.sleep(sleep) + else: + # Windows implementation + pid2, status = os.waitpid(pid, 0) + + exitcode2 = os.waitstatus_to_exitcode(status) + if exitcode2 != exitcode: + raise AssertionError(f"process {pid} exited with code {exitcode2}, " + f"but exit code {exitcode} is expected") + + # sanity check: it should not fail in practice + if pid2 != pid: + raise AssertionError(f"pid {pid2} != pid {pid}") + +def skip_if_broken_multiprocessing_synchronize(): + """ + Skip tests if the multiprocessing.synchronize module is missing, if there + is no available semaphore implementation, or if creating a lock raises an + OSError (on Linux only). + """ + from .import_helper import import_module + + # Skip tests if the _multiprocessing extension is missing. + import_module('_multiprocessing') + + # Skip tests if there is no available semaphore implementation: + # multiprocessing.synchronize requires _multiprocessing.SemLock. + synchronize = import_module('multiprocessing.synchronize') + + if sys.platform == "linux": + try: + # bpo-38377: On Linux, creating a semaphore fails with OSError + # if the current user does not have the permission to create + # a file in /dev/shm/ directory. + synchronize.Lock(ctx=None) + except OSError as exc: + raise unittest.SkipTest(f"broken multiprocessing SemLock: {exc!r}") + + +@contextlib.contextmanager +def infinite_recursion(max_depth=75): + original_depth = sys.getrecursionlimit() + try: + sys.setrecursionlimit(max_depth) + yield + finally: + sys.setrecursionlimit(original_depth) + + +def check_disallow_instantiation(testcase, tp, *args, **kwds): + """ + Check that given type cannot be instantiated using *args and **kwds. + + See bpo-43916: Add Py_TPFLAGS_DISALLOW_INSTANTIATION type flag. + """ + mod = tp.__module__ + name = tp.__name__ + if mod != 'builtins': + qualname = f"{mod}.{name}" + else: + qualname = f"{name}" + msg = f"cannot create '{re.escape(qualname)}' instances" + testcase.assertRaisesRegex(TypeError, msg, tp, *args, **kwds) + + +def ignore_deprecations_from(module: str, *, like: str) -> object: + token = object() + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + module=module, + message=like + fr"(?#support{id(token)})", + ) + return token + + +def clear_ignored_deprecations(*tokens: object) -> None: + if not tokens: + raise ValueError("Provide token or tokens returned by ignore_deprecations_from") + + new_filters = [] + endswith = tuple(rf"(?#support{id(token)})" for token in tokens) + for action, message, category, module, lineno in warnings.filters: + if action == "ignore" and category is DeprecationWarning: + if isinstance(message, re.Pattern): + msg = message.pattern + else: + msg = message or "" + if msg.endswith(endswith): + continue + new_filters.append((action, message, category, module, lineno)) + if warnings.filters != new_filters: + warnings.filters[:] = new_filters + warnings._filters_mutated() + + +@contextlib.contextmanager +def adjust_int_max_str_digits(max_digits): + """Temporarily change the integer string conversion length limit.""" + current = sys.get_int_max_str_digits() + try: + sys.set_int_max_str_digits(max_digits) + yield + finally: + sys.set_int_max_str_digits(current) diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/__init__.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..327cf166853b24095721299565143cebf364d236 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/__init__.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/bytecode_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/bytecode_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dea3f7667d778627a2dc051d82d165f71e4e7e06 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/bytecode_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/hashlib_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/hashlib_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82a9a2217c298e48225331bd3190e8952849949c Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/hashlib_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/import_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/import_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65c20752aa0df471ec2e7b849e56d2f939f2f3db Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/import_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/interpreters.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/interpreters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..372d7d25dbb87421db9fe7272a3cbb759461cff3 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/interpreters.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/logging_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/logging_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc62b6d1e55732fc1fff49851cb8884764c9be07 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/logging_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/os_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/os_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b79474624fd6b6548cc47add642f49a19959c9a Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/os_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/script_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/script_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95844cf0db84c3b4309c880ae6ccae7e4690a0a9 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/script_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/socket_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/socket_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..204b7ce9091a0d10d79069e41cc2c6b2f041d437 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/socket_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/testresult.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/testresult.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f77b4f1bddf99e57fd846a1698e4f567f830539 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/testresult.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/threading_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/threading_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2fada8d15e64bf98ff6cc1abeee0af2ea3972dc Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/threading_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/__pycache__/warnings_helper.cpython-310.pyc b/omnilmm/lib/python3.10/test/support/__pycache__/warnings_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3404a58e20a3858a123522e75a8efa43aab40549 Binary files /dev/null and b/omnilmm/lib/python3.10/test/support/__pycache__/warnings_helper.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/test/support/bytecode_helper.py b/omnilmm/lib/python3.10/test/support/bytecode_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..471d4a68f915aab082591921ebdc3fcfb0996426 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/bytecode_helper.py @@ -0,0 +1,42 @@ +"""bytecode_helper - support tools for testing correct bytecode generation""" + +import unittest +import dis +import io + +_UNSPECIFIED = object() + +class BytecodeTestCase(unittest.TestCase): + """Custom assertion methods for inspecting bytecode.""" + + def get_disassembly_as_string(self, co): + s = io.StringIO() + dis.dis(co, file=s) + return s.getvalue() + + def assertInBytecode(self, x, opname, argval=_UNSPECIFIED): + """Returns instr if opname is found, otherwise throws AssertionError""" + for instr in dis.get_instructions(x): + if instr.opname == opname: + if argval is _UNSPECIFIED or instr.argval == argval: + return instr + disassembly = self.get_disassembly_as_string(x) + if argval is _UNSPECIFIED: + msg = '%s not found in bytecode:\n%s' % (opname, disassembly) + else: + msg = '(%s,%r) not found in bytecode:\n%s' + msg = msg % (opname, argval, disassembly) + self.fail(msg) + + def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED): + """Throws AssertionError if opname is found""" + for instr in dis.get_instructions(x): + if instr.opname == opname: + disassembly = self.get_disassembly_as_string(x) + if argval is _UNSPECIFIED: + msg = '%s occurs in bytecode:\n%s' % (opname, disassembly) + self.fail(msg) + elif instr.argval == argval: + msg = '(%s,%r) occurs in bytecode:\n%s' + msg = msg % (opname, argval, disassembly) + self.fail(msg) diff --git a/omnilmm/lib/python3.10/test/support/hashlib_helper.py b/omnilmm/lib/python3.10/test/support/hashlib_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e6c92203ab5004d564d47bf7437f07e7a5813f --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/hashlib_helper.py @@ -0,0 +1,51 @@ +import functools +import hashlib +import unittest + +try: + import _hashlib +except ImportError: + _hashlib = None + + +def requires_hashdigest(digestname, openssl=None, usedforsecurity=True): + """Decorator raising SkipTest if a hashing algorithm is not available + + The hashing algorithm could be missing or blocked by a strict crypto + policy. + + If 'openssl' is True, then the decorator checks that OpenSSL provides + the algorithm. Otherwise the check falls back to built-in + implementations. The usedforsecurity flag is passed to the constructor. + + ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS + ValueError: unsupported hash type md4 + """ + def decorator(func_or_class): + if isinstance(func_or_class, type): + setUpClass = func_or_class.__dict__.get('setUpClass') + if setUpClass is None: + def setUpClass(cls): + super(func_or_class, cls).setUpClass() + setUpClass.__qualname__ = func_or_class.__qualname__ + '.setUpClass' + setUpClass.__module__ = func_or_class.__module__ + else: + setUpClass = setUpClass.__func__ + setUpClass = classmethod(decorator(setUpClass)) + func_or_class.setUpClass = setUpClass + return func_or_class + + @functools.wraps(func_or_class) + def wrapper(*args, **kwargs): + try: + if openssl and _hashlib is not None: + _hashlib.new(digestname, usedforsecurity=usedforsecurity) + else: + hashlib.new(digestname, usedforsecurity=usedforsecurity) + except ValueError: + raise unittest.SkipTest( + f"hash digest '{digestname}' is not available." + ) + return func_or_class(*args, **kwargs) + return wrapper + return decorator diff --git a/omnilmm/lib/python3.10/test/support/import_helper.py b/omnilmm/lib/python3.10/test/support/import_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..efa8ffad6a8e0bea33aa417b830f2e85f98a03b2 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/import_helper.py @@ -0,0 +1,220 @@ +import contextlib +import importlib +import importlib.util +import os +import shutil +import sys +import unittest +import warnings + +from .os_helper import unlink + + +@contextlib.contextmanager +def _ignore_deprecated_imports(ignore=True): + """Context manager to suppress package and module deprecation + warnings when importing them. + + If ignore is False, this context manager has no effect. + """ + if ignore: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", ".+ (module|package)", + DeprecationWarning) + yield + else: + yield + + +def unload(name): + try: + del sys.modules[name] + except KeyError: + pass + + +def forget(modname): + """'Forget' a module was ever imported. + + This removes the module from sys.modules and deletes any PEP 3147/488 or + legacy .pyc files. + """ + unload(modname) + for dirname in sys.path: + source = os.path.join(dirname, modname + '.py') + # It doesn't matter if they exist or not, unlink all possible + # combinations of PEP 3147/488 and legacy pyc files. + unlink(source + 'c') + for opt in ('', 1, 2): + unlink(importlib.util.cache_from_source(source, optimization=opt)) + + +def make_legacy_pyc(source): + """Move a PEP 3147/488 pyc file to its legacy pyc location. + + :param source: The file system path to the source file. The source file + does not need to exist, however the PEP 3147/488 pyc file must exist. + :return: The file system path to the legacy pyc file. + """ + pyc_file = importlib.util.cache_from_source(source) + up_one = os.path.dirname(os.path.abspath(source)) + legacy_pyc = os.path.join(up_one, source + 'c') + shutil.move(pyc_file, legacy_pyc) + return legacy_pyc + + +def import_module(name, deprecated=False, *, required_on=()): + """Import and return the module to be tested, raising SkipTest if + it is not available. + + If deprecated is True, any module or package deprecation messages + will be suppressed. If a module is required on a platform but optional for + others, set required_on to an iterable of platform prefixes which will be + compared against sys.platform. + """ + with _ignore_deprecated_imports(deprecated): + try: + return importlib.import_module(name) + except ImportError as msg: + if sys.platform.startswith(tuple(required_on)): + raise + raise unittest.SkipTest(str(msg)) + + +def _save_and_remove_modules(names): + orig_modules = {} + prefixes = tuple(name + '.' for name in names) + for modname in list(sys.modules): + if modname in names or modname.startswith(prefixes): + orig_modules[modname] = sys.modules.pop(modname) + return orig_modules + + +def import_fresh_module(name, fresh=(), blocked=(), deprecated=False): + """Import and return a module, deliberately bypassing sys.modules. + + This function imports and returns a fresh copy of the named Python module + by removing the named module from sys.modules before doing the import. + Note that unlike reload, the original module is not affected by + this operation. + + *fresh* is an iterable of additional module names that are also removed + from the sys.modules cache before doing the import. If one of these + modules can't be imported, None is returned. + + *blocked* is an iterable of module names that are replaced with None + in the module cache during the import to ensure that attempts to import + them raise ImportError. + + The named module and any modules named in the *fresh* and *blocked* + parameters are saved before starting the import and then reinserted into + sys.modules when the fresh import is complete. + + Module and package deprecation messages are suppressed during this import + if *deprecated* is True. + + This function will raise ImportError if the named module cannot be + imported. + """ + # NOTE: test_heapq, test_json and test_warnings include extra sanity checks + # to make sure that this utility function is working as expected + with _ignore_deprecated_imports(deprecated): + # Keep track of modules saved for later restoration as well + # as those which just need a blocking entry removed + fresh = list(fresh) + blocked = list(blocked) + names = {name, *fresh, *blocked} + orig_modules = _save_and_remove_modules(names) + for modname in blocked: + sys.modules[modname] = None + + try: + # Return None when one of the "fresh" modules can not be imported. + try: + for modname in fresh: + __import__(modname) + except ImportError: + return None + return importlib.import_module(name) + finally: + _save_and_remove_modules(names) + sys.modules.update(orig_modules) + + +class CleanImport(object): + """Context manager to force import to return a new module reference. + + This is useful for testing module-level behaviours, such as + the emission of a DeprecationWarning on import. + + Use like this: + + with CleanImport("foo"): + importlib.import_module("foo") # new reference + """ + + def __init__(self, *module_names): + self.original_modules = sys.modules.copy() + for module_name in module_names: + if module_name in sys.modules: + module = sys.modules[module_name] + # It is possible that module_name is just an alias for + # another module (e.g. stub for modules renamed in 3.x). + # In that case, we also need delete the real module to clear + # the import cache. + if module.__name__ != module_name: + del sys.modules[module.__name__] + del sys.modules[module_name] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + sys.modules.update(self.original_modules) + + +class DirsOnSysPath(object): + """Context manager to temporarily add directories to sys.path. + + This makes a copy of sys.path, appends any directories given + as positional arguments, then reverts sys.path to the copied + settings when the context ends. + + Note that *all* sys.path modifications in the body of the + context manager, including replacement of the object, + will be reverted at the end of the block. + """ + + def __init__(self, *paths): + self.original_value = sys.path[:] + self.original_object = sys.path + sys.path.extend(paths) + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + sys.path = self.original_object + sys.path[:] = self.original_value + + +def modules_setup(): + return sys.modules.copy(), + + +def modules_cleanup(oldmodules): + # Encoders/decoders are registered permanently within the internal + # codec cache. If we destroy the corresponding modules their + # globals will be set to None which will trip up the cached functions. + encodings = [(k, v) for k, v in sys.modules.items() + if k.startswith('encodings.')] + sys.modules.clear() + sys.modules.update(encodings) + # XXX: This kind of problem can affect more than just encodings. + # In particular extension modules (such as _ssl) don't cope + # with reloading properly. Really, test modules should be cleaning + # out the test specific modules they know they added (ala test_runpy) + # rather than relying on this function (as test_importhooks and test_pkg + # do currently). Implicitly imported *real* modules should be left alone + # (see issue 10556). + sys.modules.update(oldmodules) diff --git a/omnilmm/lib/python3.10/test/support/interpreters.py b/omnilmm/lib/python3.10/test/support/interpreters.py new file mode 100644 index 0000000000000000000000000000000000000000..2935708f9df1a5fd6b83e82418c6ec1471fb8832 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/interpreters.py @@ -0,0 +1,197 @@ +"""Subinterpreters High Level Module.""" + +import time +import _xxsubinterpreters as _interpreters + +# aliases: +from _xxsubinterpreters import ( + ChannelError, ChannelNotFoundError, ChannelEmptyError, + is_shareable, +) + + +__all__ = [ + 'Interpreter', 'get_current', 'get_main', 'create', 'list_all', + 'SendChannel', 'RecvChannel', + 'create_channel', 'list_all_channels', 'is_shareable', + 'ChannelError', 'ChannelNotFoundError', + 'ChannelEmptyError', + ] + + +def create(*, isolated=True): + """Return a new (idle) Python interpreter.""" + id = _interpreters.create(isolated=isolated) + return Interpreter(id, isolated=isolated) + + +def list_all(): + """Return all existing interpreters.""" + return [Interpreter(id) for id in _interpreters.list_all()] + + +def get_current(): + """Return the currently running interpreter.""" + id = _interpreters.get_current() + return Interpreter(id) + + +def get_main(): + """Return the main interpreter.""" + id = _interpreters.get_main() + return Interpreter(id) + + +class Interpreter: + """A single Python interpreter.""" + + def __init__(self, id, *, isolated=None): + if not isinstance(id, (int, _interpreters.InterpreterID)): + raise TypeError(f'id must be an int, got {id!r}') + self._id = id + self._isolated = isolated + + def __repr__(self): + data = dict(id=int(self._id), isolated=self._isolated) + kwargs = (f'{k}={v!r}' for k, v in data.items()) + return f'{type(self).__name__}({", ".join(kwargs)})' + + def __hash__(self): + return hash(self._id) + + def __eq__(self, other): + if not isinstance(other, Interpreter): + return NotImplemented + else: + return other._id == self._id + + @property + def id(self): + return self._id + + @property + def isolated(self): + if self._isolated is None: + # XXX The low-level function has not been added yet. + # See bpo-.... + self._isolated = _interpreters.is_isolated(self._id) + return self._isolated + + def is_running(self): + """Return whether or not the identified interpreter is running.""" + return _interpreters.is_running(self._id) + + def close(self): + """Finalize and destroy the interpreter. + + Attempting to destroy the current interpreter results + in a RuntimeError. + """ + return _interpreters.destroy(self._id) + + def run(self, src_str, /, *, channels=None): + """Run the given source code in the interpreter. + + This blocks the current Python thread until done. + """ + _interpreters.run_string(self._id, src_str, channels) + + +def create_channel(): + """Return (recv, send) for a new cross-interpreter channel. + + The channel may be used to pass data safely between interpreters. + """ + cid = _interpreters.channel_create() + recv, send = RecvChannel(cid), SendChannel(cid) + return recv, send + + +def list_all_channels(): + """Return a list of (recv, send) for all open channels.""" + return [(RecvChannel(cid), SendChannel(cid)) + for cid in _interpreters.channel_list_all()] + + +class _ChannelEnd: + """The base class for RecvChannel and SendChannel.""" + + def __init__(self, id): + if not isinstance(id, (int, _interpreters.ChannelID)): + raise TypeError(f'id must be an int, got {id!r}') + self._id = id + + def __repr__(self): + return f'{type(self).__name__}(id={int(self._id)})' + + def __hash__(self): + return hash(self._id) + + def __eq__(self, other): + if isinstance(self, RecvChannel): + if not isinstance(other, RecvChannel): + return NotImplemented + elif not isinstance(other, SendChannel): + return NotImplemented + return other._id == self._id + + @property + def id(self): + return self._id + + +_NOT_SET = object() + + +class RecvChannel(_ChannelEnd): + """The receiving end of a cross-interpreter channel.""" + + def recv(self, *, _sentinel=object(), _delay=10 / 1000): # 10 milliseconds + """Return the next object from the channel. + + This blocks until an object has been sent, if none have been + sent already. + """ + obj = _interpreters.channel_recv(self._id, _sentinel) + while obj is _sentinel: + time.sleep(_delay) + obj = _interpreters.channel_recv(self._id, _sentinel) + return obj + + def recv_nowait(self, default=_NOT_SET): + """Return the next object from the channel. + + If none have been sent then return the default if one + is provided or fail with ChannelEmptyError. Otherwise this + is the same as recv(). + """ + if default is _NOT_SET: + return _interpreters.channel_recv(self._id) + else: + return _interpreters.channel_recv(self._id, default) + + +class SendChannel(_ChannelEnd): + """The sending end of a cross-interpreter channel.""" + + def send(self, obj): + """Send the object (i.e. its data) to the channel's receiving end. + + This blocks until the object is received. + """ + _interpreters.channel_send(self._id, obj) + # XXX We are missing a low-level channel_send_wait(). + # See bpo-32604 and gh-19829. + # Until that shows up we fake it: + time.sleep(2) + + def send_nowait(self, obj): + """Send the object to the channel's receiving end. + + If the object is immediately received then return True + (else False). Otherwise this is the same as send(). + """ + # XXX Note that at the moment channel_send() only ever returns + # None. This should be fixed when channel_send_wait() is added. + # See bpo-32604 and gh-19829. + return _interpreters.channel_send(self._id, obj) diff --git a/omnilmm/lib/python3.10/test/support/logging_helper.py b/omnilmm/lib/python3.10/test/support/logging_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..12fcca4f0f08d9b445ac84f6a1920c8bcb3badf4 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/logging_helper.py @@ -0,0 +1,29 @@ +import logging.handlers + +class TestHandler(logging.handlers.BufferingHandler): + def __init__(self, matcher): + # BufferingHandler takes a "capacity" argument + # so as to know when to flush. As we're overriding + # shouldFlush anyway, we can set a capacity of zero. + # You can call flush() manually to clear out the + # buffer. + logging.handlers.BufferingHandler.__init__(self, 0) + self.matcher = matcher + + def shouldFlush(self): + return False + + def emit(self, record): + self.format(record) + self.buffer.append(record.__dict__) + + def matches(self, **kwargs): + """ + Look for a saved dict whose keys/values match the supplied arguments. + """ + result = False + for d in self.buffer: + if self.matcher.matches(d, **kwargs): + result = True + break + return result diff --git a/omnilmm/lib/python3.10/test/support/os_helper.py b/omnilmm/lib/python3.10/test/support/os_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..82a6de789c866e58b3c574e023d7eaaf078898e1 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/os_helper.py @@ -0,0 +1,623 @@ +import collections.abc +import contextlib +import errno +import os +import re +import stat +import sys +import time +import unittest +import warnings + + +# Filename used for testing +if os.name == 'java': + # Jython disallows @ in module names + TESTFN_ASCII = '$test' +else: + TESTFN_ASCII = '@test' + +# Disambiguate TESTFN for parallel testing, while letting it remain a valid +# module name. +TESTFN_ASCII = "{}_{}_tmp".format(TESTFN_ASCII, os.getpid()) + +# TESTFN_UNICODE is a non-ascii filename +TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f" +if sys.platform == 'darwin': + # In Mac OS X's VFS API file names are, by definition, canonically + # decomposed Unicode, encoded using UTF-8. See QA1173: + # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html + import unicodedata + TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE) + +# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be +# encoded by the filesystem encoding (in strict mode). It can be None if we +# cannot generate such filename. +TESTFN_UNENCODABLE = None +if os.name == 'nt': + # skip win32s (0) or Windows 9x/ME (1) + if sys.getwindowsversion().platform >= 2: + # Different kinds of characters from various languages to minimize the + # probability that the whole name is encodable to MBCS (issue #9819) + TESTFN_UNENCODABLE = TESTFN_ASCII + "-\u5171\u0141\u2661\u0363\uDC80" + try: + TESTFN_UNENCODABLE.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + pass + else: + print('WARNING: The filename %r CAN be encoded by the filesystem ' + 'encoding (%s). Unicode filename tests may not be effective' + % (TESTFN_UNENCODABLE, sys.getfilesystemencoding())) + TESTFN_UNENCODABLE = None +# Mac OS X denies unencodable filenames (invalid utf-8) +elif sys.platform != 'darwin': + try: + # ascii and utf-8 cannot encode the byte 0xff + b'\xff'.decode(sys.getfilesystemencoding()) + except UnicodeDecodeError: + # 0xff will be encoded using the surrogate character u+DCFF + TESTFN_UNENCODABLE = TESTFN_ASCII \ + + b'-\xff'.decode(sys.getfilesystemencoding(), 'surrogateescape') + else: + # File system encoding (eg. ISO-8859-* encodings) can encode + # the byte 0xff. Skip some unicode filename tests. + pass + +# FS_NONASCII: non-ASCII character encodable by os.fsencode(), +# or an empty string if there is no such character. +FS_NONASCII = '' +for character in ( + # First try printable and common characters to have a readable filename. + # For each character, the encoding list are just example of encodings able + # to encode the character (the list is not exhaustive). + + # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1 + '\u00E6', + # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3 + '\u0130', + # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257 + '\u0141', + # U+03C6 (Greek Small Letter Phi): cp1253 + '\u03C6', + # U+041A (Cyrillic Capital Letter Ka): cp1251 + '\u041A', + # U+05D0 (Hebrew Letter Alef): Encodable to cp424 + '\u05D0', + # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic + '\u060C', + # U+062A (Arabic Letter Teh): cp720 + '\u062A', + # U+0E01 (Thai Character Ko Kai): cp874 + '\u0E01', + + # Then try more "special" characters. "special" because they may be + # interpreted or displayed differently depending on the exact locale + # encoding and the font. + + # U+00A0 (No-Break Space) + '\u00A0', + # U+20AC (Euro Sign) + '\u20AC', +): + try: + # If Python is set up to use the legacy 'mbcs' in Windows, + # 'replace' error mode is used, and encode() returns b'?' + # for characters missing in the ANSI codepage + if os.fsdecode(os.fsencode(character)) != character: + raise UnicodeError + except UnicodeError: + pass + else: + FS_NONASCII = character + break + +# Save the initial cwd +SAVEDCWD = os.getcwd() + +# TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be +# decoded from the filesystem encoding (in strict mode). It can be None if we +# cannot generate such filename (ex: the latin1 encoding can decode any byte +# sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks +# to the surrogateescape error handler (PEP 383), but not from the filesystem +# encoding in strict mode. +TESTFN_UNDECODABLE = None +for name in ( + # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows + # accepts it to create a file or a directory, or don't accept to enter to + # such directory (when the bytes name is used). So test b'\xe7' first: + # it is not decodable from cp932. + b'\xe7w\xf0', + # undecodable from ASCII, UTF-8 + b'\xff', + # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856 + # and cp857 + b'\xae\xd5' + # undecodable from UTF-8 (UNIX and Mac OS X) + b'\xed\xb2\x80', b'\xed\xb4\x80', + # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252, + # cp1253, cp1254, cp1255, cp1257, cp1258 + b'\x81\x98', +): + try: + name.decode(sys.getfilesystemencoding()) + except UnicodeDecodeError: + TESTFN_UNDECODABLE = os.fsencode(TESTFN_ASCII) + name + break + +if FS_NONASCII: + TESTFN_NONASCII = TESTFN_ASCII + FS_NONASCII +else: + TESTFN_NONASCII = None +TESTFN = TESTFN_NONASCII or TESTFN_ASCII + + +def make_bad_fd(): + """ + Create an invalid file descriptor by opening and closing a file and return + its fd. + """ + file = open(TESTFN, "wb") + try: + return file.fileno() + finally: + file.close() + unlink(TESTFN) + + +_can_symlink = None + + +def can_symlink(): + global _can_symlink + if _can_symlink is not None: + return _can_symlink + symlink_path = TESTFN + "can_symlink" + try: + os.symlink(TESTFN, symlink_path) + can = True + except (OSError, NotImplementedError, AttributeError): + can = False + else: + os.remove(symlink_path) + _can_symlink = can + return can + + +def skip_unless_symlink(test): + """Skip decorator for tests that require functional symlink""" + ok = can_symlink() + msg = "Requires functional symlink implementation" + return test if ok else unittest.skip(msg)(test) + + +_can_xattr = None + + +def can_xattr(): + import tempfile + global _can_xattr + if _can_xattr is not None: + return _can_xattr + if not hasattr(os, "setxattr"): + can = False + else: + import platform + tmp_dir = tempfile.mkdtemp() + tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir) + try: + with open(TESTFN, "wb") as fp: + try: + # TESTFN & tempfile may use different file systems with + # different capabilities + os.setxattr(tmp_fp, b"user.test", b"") + os.setxattr(tmp_name, b"trusted.foo", b"42") + os.setxattr(fp.fileno(), b"user.test", b"") + # Kernels < 2.6.39 don't respect setxattr flags. + kernel_version = platform.release() + m = re.match(r"2.6.(\d{1,2})", kernel_version) + can = m is None or int(m.group(1)) >= 39 + except OSError: + can = False + finally: + unlink(TESTFN) + unlink(tmp_name) + rmdir(tmp_dir) + _can_xattr = can + return can + + +def skip_unless_xattr(test): + """Skip decorator for tests that require functional extended attributes""" + ok = can_xattr() + msg = "no non-broken extended attribute support" + return test if ok else unittest.skip(msg)(test) + + +def unlink(filename): + try: + _unlink(filename) + except (FileNotFoundError, NotADirectoryError): + pass + + +if sys.platform.startswith("win"): + def _waitfor(func, pathname, waitall=False): + # Perform the operation + func(pathname) + # Now setup the wait loop + if waitall: + dirname = pathname + else: + dirname, name = os.path.split(pathname) + dirname = dirname or '.' + # Check for `pathname` to be removed from the filesystem. + # The exponential backoff of the timeout amounts to a total + # of ~1 second after which the deletion is probably an error + # anyway. + # Testing on an i7@4.3GHz shows that usually only 1 iteration is + # required when contention occurs. + timeout = 0.001 + while timeout < 1.0: + # Note we are only testing for the existence of the file(s) in + # the contents of the directory regardless of any security or + # access rights. If we have made it this far, we have sufficient + # permissions to do that much using Python's equivalent of the + # Windows API FindFirstFile. + # Other Windows APIs can fail or give incorrect results when + # dealing with files that are pending deletion. + L = os.listdir(dirname) + if not (L if waitall else name in L): + return + # Increase the timeout and try again + time.sleep(timeout) + timeout *= 2 + warnings.warn('tests may fail, delete still pending for ' + pathname, + RuntimeWarning, stacklevel=4) + + def _unlink(filename): + _waitfor(os.unlink, filename) + + def _rmdir(dirname): + _waitfor(os.rmdir, dirname) + + def _rmtree(path): + from test.support import _force_run + + def _rmtree_inner(path): + for name in _force_run(path, os.listdir, path): + fullname = os.path.join(path, name) + try: + mode = os.lstat(fullname).st_mode + except OSError as exc: + print("support.rmtree(): os.lstat(%r) failed with %s" + % (fullname, exc), + file=sys.__stderr__) + mode = 0 + if stat.S_ISDIR(mode): + _waitfor(_rmtree_inner, fullname, waitall=True) + _force_run(fullname, os.rmdir, fullname) + else: + _force_run(fullname, os.unlink, fullname) + _waitfor(_rmtree_inner, path, waitall=True) + _waitfor(lambda p: _force_run(p, os.rmdir, p), path) + + def _longpath(path): + try: + import ctypes + except ImportError: + # No ctypes means we can't expands paths. + pass + else: + buffer = ctypes.create_unicode_buffer(len(path) * 2) + length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer, + len(buffer)) + if length: + return buffer[:length] + return path +else: + _unlink = os.unlink + _rmdir = os.rmdir + + def _rmtree(path): + import shutil + try: + shutil.rmtree(path) + return + except OSError: + pass + + def _rmtree_inner(path): + from test.support import _force_run + for name in _force_run(path, os.listdir, path): + fullname = os.path.join(path, name) + try: + mode = os.lstat(fullname).st_mode + except OSError: + mode = 0 + if stat.S_ISDIR(mode): + _rmtree_inner(fullname) + _force_run(path, os.rmdir, fullname) + else: + _force_run(path, os.unlink, fullname) + _rmtree_inner(path) + os.rmdir(path) + + def _longpath(path): + return path + + +def rmdir(dirname): + try: + _rmdir(dirname) + except FileNotFoundError: + pass + + +def rmtree(path): + try: + _rmtree(path) + except FileNotFoundError: + pass + + +@contextlib.contextmanager +def temp_dir(path=None, quiet=False): + """Return a context manager that creates a temporary directory. + + Arguments: + + path: the directory to create temporarily. If omitted or None, + defaults to creating a temporary directory using tempfile.mkdtemp. + + quiet: if False (the default), the context manager raises an exception + on error. Otherwise, if the path is specified and cannot be + created, only a warning is issued. + + """ + import tempfile + dir_created = False + if path is None: + path = tempfile.mkdtemp() + dir_created = True + path = os.path.realpath(path) + else: + try: + os.mkdir(path) + dir_created = True + except OSError as exc: + if not quiet: + raise + warnings.warn(f'tests may fail, unable to create ' + f'temporary directory {path!r}: {exc}', + RuntimeWarning, stacklevel=3) + if dir_created: + pid = os.getpid() + try: + yield path + finally: + # In case the process forks, let only the parent remove the + # directory. The child has a different process id. (bpo-30028) + if dir_created and pid == os.getpid(): + rmtree(path) + + +@contextlib.contextmanager +def change_cwd(path, quiet=False): + """Return a context manager that changes the current working directory. + + Arguments: + + path: the directory to use as the temporary current working directory. + + quiet: if False (the default), the context manager raises an exception + on error. Otherwise, it issues only a warning and keeps the current + working directory the same. + + """ + saved_dir = os.getcwd() + try: + os.chdir(os.path.realpath(path)) + except OSError as exc: + if not quiet: + raise + warnings.warn(f'tests may fail, unable to change the current working ' + f'directory to {path!r}: {exc}', + RuntimeWarning, stacklevel=3) + try: + yield os.getcwd() + finally: + os.chdir(saved_dir) + + +@contextlib.contextmanager +def temp_cwd(name='tempcwd', quiet=False): + """ + Context manager that temporarily creates and changes the CWD. + + The function temporarily changes the current working directory + after creating a temporary directory in the current directory with + name *name*. If *name* is None, the temporary directory is + created using tempfile.mkdtemp. + + If *quiet* is False (default) and it is not possible to + create or change the CWD, an error is raised. If *quiet* is True, + only a warning is raised and the original CWD is used. + + """ + with temp_dir(path=name, quiet=quiet) as temp_path: + with change_cwd(temp_path, quiet=quiet) as cwd_dir: + yield cwd_dir + + +def create_empty_file(filename): + """Create an empty file. If the file already exists, truncate it.""" + fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) + os.close(fd) + + +@contextlib.contextmanager +def open_dir_fd(path): + """Open a file descriptor to a directory.""" + assert os.path.isdir(path) + dir_fd = os.open(path, os.O_RDONLY) + try: + yield dir_fd + finally: + os.close(dir_fd) + + +def fs_is_case_insensitive(directory): + """Detects if the file system for the specified directory + is case-insensitive.""" + import tempfile + with tempfile.NamedTemporaryFile(dir=directory) as base: + base_path = base.name + case_path = base_path.upper() + if case_path == base_path: + case_path = base_path.lower() + try: + return os.path.samefile(base_path, case_path) + except FileNotFoundError: + return False + + +class FakePath: + """Simple implementing of the path protocol. + """ + def __init__(self, path): + self.path = path + + def __repr__(self): + return f'' + + def __fspath__(self): + if (isinstance(self.path, BaseException) or + isinstance(self.path, type) and + issubclass(self.path, BaseException)): + raise self.path + else: + return self.path + + +def fd_count(): + """Count the number of open file descriptors. + """ + if sys.platform.startswith(('linux', 'freebsd')): + try: + names = os.listdir("/proc/self/fd") + # Subtract one because listdir() internally opens a file + # descriptor to list the content of the /proc/self/fd/ directory. + return len(names) - 1 + except FileNotFoundError: + pass + + MAXFD = 256 + if hasattr(os, 'sysconf'): + try: + MAXFD = os.sysconf("SC_OPEN_MAX") + except OSError: + pass + + old_modes = None + if sys.platform == 'win32': + # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process + # on invalid file descriptor if Python is compiled in debug mode + try: + import msvcrt + msvcrt.CrtSetReportMode + except (AttributeError, ImportError): + # no msvcrt or a release build + pass + else: + old_modes = {} + for report_type in (msvcrt.CRT_WARN, + msvcrt.CRT_ERROR, + msvcrt.CRT_ASSERT): + old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, + 0) + + try: + count = 0 + for fd in range(MAXFD): + try: + # Prefer dup() over fstat(). fstat() can require input/output + # whereas dup() doesn't. + fd2 = os.dup(fd) + except OSError as e: + if e.errno != errno.EBADF: + raise + else: + os.close(fd2) + count += 1 + finally: + if old_modes is not None: + for report_type in (msvcrt.CRT_WARN, + msvcrt.CRT_ERROR, + msvcrt.CRT_ASSERT): + msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) + + return count + + +if hasattr(os, "umask"): + @contextlib.contextmanager + def temp_umask(umask): + """Context manager that temporarily sets the process umask.""" + oldmask = os.umask(umask) + try: + yield + finally: + os.umask(oldmask) + + +class EnvironmentVarGuard(collections.abc.MutableMapping): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + self._environ = os.environ + self._changed = {} + + def __getitem__(self, envvar): + return self._environ[envvar] + + def __setitem__(self, envvar, value): + # Remember the initial value on the first access + if envvar not in self._changed: + self._changed[envvar] = self._environ.get(envvar) + self._environ[envvar] = value + + def __delitem__(self, envvar): + # Remember the initial value on the first access + if envvar not in self._changed: + self._changed[envvar] = self._environ.get(envvar) + if envvar in self._environ: + del self._environ[envvar] + + def keys(self): + return self._environ.keys() + + def __iter__(self): + return iter(self._environ) + + def __len__(self): + return len(self._environ) + + def set(self, envvar, value): + self[envvar] = value + + def unset(self, envvar): + del self[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for (k, v) in self._changed.items(): + if v is None: + if k in self._environ: + del self._environ[k] + else: + self._environ[k] = v + os.environ = self._environ diff --git a/omnilmm/lib/python3.10/test/support/script_helper.py b/omnilmm/lib/python3.10/test/support/script_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..6d699c8486cd20daa8f0b906089e61978cf61ade --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/script_helper.py @@ -0,0 +1,294 @@ +# Common utility functions used by various script execution tests +# e.g. test_cmd_line, test_cmd_line_script and test_runpy + +import collections +import importlib +import sys +import os +import os.path +import subprocess +import py_compile +import zipfile + +from importlib.util import source_from_cache +from test import support +from test.support.import_helper import make_legacy_pyc + + +# Cached result of the expensive test performed in the function below. +__cached_interp_requires_environment = None + + +def interpreter_requires_environment(): + """ + Returns True if our sys.executable interpreter requires environment + variables in order to be able to run at all. + + This is designed to be used with @unittest.skipIf() to annotate tests + that need to use an assert_python*() function to launch an isolated + mode (-I) or no environment mode (-E) sub-interpreter process. + + A normal build & test does not run into this situation but it can happen + when trying to run the standard library test suite from an interpreter that + doesn't have an obvious home with Python's current home finding logic. + + Setting PYTHONHOME is one way to get most of the testsuite to run in that + situation. PYTHONPATH or PYTHONUSERSITE are other common environment + variables that might impact whether or not the interpreter can start. + """ + global __cached_interp_requires_environment + if __cached_interp_requires_environment is None: + # If PYTHONHOME is set, assume that we need it + if 'PYTHONHOME' in os.environ: + __cached_interp_requires_environment = True + return True + + # Try running an interpreter with -E to see if it works or not. + try: + subprocess.check_call([sys.executable, '-E', + '-c', 'import sys; sys.exit(0)']) + except subprocess.CalledProcessError: + __cached_interp_requires_environment = True + else: + __cached_interp_requires_environment = False + + return __cached_interp_requires_environment + + +class _PythonRunResult(collections.namedtuple("_PythonRunResult", + ("rc", "out", "err"))): + """Helper for reporting Python subprocess run results""" + def fail(self, cmd_line): + """Provide helpful details about failed subcommand runs""" + # Limit to 80 lines to ASCII characters + maxlen = 80 * 100 + out, err = self.out, self.err + if len(out) > maxlen: + out = b'(... truncated stdout ...)' + out[-maxlen:] + if len(err) > maxlen: + err = b'(... truncated stderr ...)' + err[-maxlen:] + out = out.decode('ascii', 'replace').rstrip() + err = err.decode('ascii', 'replace').rstrip() + raise AssertionError("Process return code is %d\n" + "command line: %r\n" + "\n" + "stdout:\n" + "---\n" + "%s\n" + "---\n" + "\n" + "stderr:\n" + "---\n" + "%s\n" + "---" + % (self.rc, cmd_line, + out, + err)) + + +# Executing the interpreter in a subprocess +def run_python_until_end(*args, **env_vars): + env_required = interpreter_requires_environment() + cwd = env_vars.pop('__cwd', None) + if '__isolated' in env_vars: + isolated = env_vars.pop('__isolated') + else: + isolated = not env_vars and not env_required + cmd_line = [sys.executable, '-X', 'faulthandler'] + if isolated: + # isolated mode: ignore Python environment variables, ignore user + # site-packages, and don't add the current directory to sys.path + cmd_line.append('-I') + elif not env_vars and not env_required: + # ignore Python environment variables + cmd_line.append('-E') + + # But a special flag that can be set to override -- in this case, the + # caller is responsible to pass the full environment. + if env_vars.pop('__cleanenv', None): + env = {} + if sys.platform == 'win32': + # Windows requires at least the SYSTEMROOT environment variable to + # start Python. + env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] + + # Other interesting environment variables, not copied currently: + # COMSPEC, HOME, PATH, TEMP, TMPDIR, TMP. + else: + # Need to preserve the original environment, for in-place testing of + # shared library builds. + env = os.environ.copy() + + # set TERM='' unless the TERM environment variable is passed explicitly + # see issues #11390 and #18300 + if 'TERM' not in env_vars: + env['TERM'] = '' + + env.update(env_vars) + cmd_line.extend(args) + proc = subprocess.Popen(cmd_line, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=env, cwd=cwd) + with proc: + try: + out, err = proc.communicate() + finally: + proc.kill() + subprocess._cleanup() + rc = proc.returncode + return _PythonRunResult(rc, out, err), cmd_line + + +def _assert_python(expected_success, /, *args, **env_vars): + res, cmd_line = run_python_until_end(*args, **env_vars) + if (res.rc and expected_success) or (not res.rc and not expected_success): + res.fail(cmd_line) + return res + + +def assert_python_ok(*args, **env_vars): + """ + Assert that running the interpreter with `args` and optional environment + variables `env_vars` succeeds (rc == 0) and return a (return code, stdout, + stderr) tuple. + + If the __cleanenv keyword is set, env_vars is used as a fresh environment. + + Python is started in isolated mode (command line option -I), + except if the __isolated keyword is set to False. + """ + return _assert_python(True, *args, **env_vars) + + +def assert_python_failure(*args, **env_vars): + """ + Assert that running the interpreter with `args` and optional environment + variables `env_vars` fails (rc != 0) and return a (return code, stdout, + stderr) tuple. + + See assert_python_ok() for more options. + """ + return _assert_python(False, *args, **env_vars) + + +def spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): + """Run a Python subprocess with the given arguments. + + kw is extra keyword args to pass to subprocess.Popen. Returns a Popen + object. + """ + cmd_line = [sys.executable] + if not interpreter_requires_environment(): + cmd_line.append('-E') + cmd_line.extend(args) + # Under Fedora (?), GNU readline can output junk on stderr when initialized, + # depending on the TERM setting. Setting TERM=vt100 is supposed to disable + # that. References: + # - http://reinout.vanrees.org/weblog/2009/08/14/readline-invisible-character-hack.html + # - http://stackoverflow.com/questions/15760712/python-readline-module-prints-escape-character-during-import + # - http://lists.gnu.org/archive/html/bug-readline/2007-08/msg00004.html + env = kw.setdefault('env', dict(os.environ)) + env['TERM'] = 'vt100' + return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, + stdout=stdout, stderr=stderr, + **kw) + + +def kill_python(p): + """Run the given Popen process until completion and return stdout.""" + p.stdin.close() + data = p.stdout.read() + p.stdout.close() + # try to cleanup the child so we don't appear to leak when running + # with regrtest -R. + p.wait() + subprocess._cleanup() + return data + + +def make_script(script_dir, script_basename, source, omit_suffix=False): + script_filename = script_basename + if not omit_suffix: + script_filename += os.extsep + 'py' + script_name = os.path.join(script_dir, script_filename) + # The script should be encoded to UTF-8, the default string encoding + with open(script_name, 'w', encoding='utf-8') as script_file: + script_file.write(source) + importlib.invalidate_caches() + return script_name + + +def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): + zip_filename = zip_basename+os.extsep+'zip' + zip_name = os.path.join(zip_dir, zip_filename) + with zipfile.ZipFile(zip_name, 'w') as zip_file: + if name_in_zip is None: + parts = script_name.split(os.sep) + if len(parts) >= 2 and parts[-2] == '__pycache__': + legacy_pyc = make_legacy_pyc(source_from_cache(script_name)) + name_in_zip = os.path.basename(legacy_pyc) + script_name = legacy_pyc + else: + name_in_zip = os.path.basename(script_name) + zip_file.write(script_name, name_in_zip) + #if test.support.verbose: + # with zipfile.ZipFile(zip_name, 'r') as zip_file: + # print 'Contents of %r:' % zip_name + # zip_file.printdir() + return zip_name, os.path.join(zip_name, name_in_zip) + + +def make_pkg(pkg_dir, init_source=''): + os.mkdir(pkg_dir) + make_script(pkg_dir, '__init__', init_source) + + +def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, + source, depth=1, compiled=False): + unlink = [] + init_name = make_script(zip_dir, '__init__', '') + unlink.append(init_name) + init_basename = os.path.basename(init_name) + script_name = make_script(zip_dir, script_basename, source) + unlink.append(script_name) + if compiled: + init_name = py_compile.compile(init_name, doraise=True) + script_name = py_compile.compile(script_name, doraise=True) + unlink.extend((init_name, script_name)) + pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)] + script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) + zip_filename = zip_basename+os.extsep+'zip' + zip_name = os.path.join(zip_dir, zip_filename) + with zipfile.ZipFile(zip_name, 'w') as zip_file: + for name in pkg_names: + init_name_in_zip = os.path.join(name, init_basename) + zip_file.write(init_name, init_name_in_zip) + zip_file.write(script_name, script_name_in_zip) + for name in unlink: + os.unlink(name) + #if test.support.verbose: + # with zipfile.ZipFile(zip_name, 'r') as zip_file: + # print 'Contents of %r:' % zip_name + # zip_file.printdir() + return zip_name, os.path.join(zip_name, script_name_in_zip) + + +def run_test_script(script): + # use -u to try to get the full output if the test hangs or crash + if support.verbose: + def title(text): + return f"===== {text} ======" + + name = f"script {os.path.basename(script)}" + print() + print(title(name), flush=True) + # In verbose mode, the child process inherit stdout and stdout, + # to see output in realtime and reduce the risk of losing output. + args = [sys.executable, "-E", "-X", "faulthandler", "-u", script, "-v"] + proc = subprocess.run(args) + print(title(f"{name} completed: exit code {proc.returncode}"), + flush=True) + if proc.returncode: + raise AssertionError(f"{name} failed") + else: + assert_python_ok("-u", script, "-v") diff --git a/omnilmm/lib/python3.10/test/support/socket_helper.py b/omnilmm/lib/python3.10/test/support/socket_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..38c499bf722e85c0a2a198bf51b48d4830d44482 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/socket_helper.py @@ -0,0 +1,269 @@ +import contextlib +import errno +import socket +import unittest +import sys + +from .. import support + + +HOST = "localhost" +HOSTv4 = "127.0.0.1" +HOSTv6 = "::1" + + +def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): + """Returns an unused port that should be suitable for binding. This is + achieved by creating a temporary socket with the same family and type as + the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to + the specified host address (defaults to 0.0.0.0) with the port set to 0, + eliciting an unused ephemeral port from the OS. The temporary socket is + then closed and deleted, and the ephemeral port is returned. + + Either this method or bind_port() should be used for any tests where a + server socket needs to be bound to a particular port for the duration of + the test. Which one to use depends on whether the calling code is creating + a python socket, or if an unused port needs to be provided in a constructor + or passed to an external program (i.e. the -accept argument to openssl's + s_server mode). Always prefer bind_port() over find_unused_port() where + possible. Hard coded ports should *NEVER* be used. As soon as a server + socket is bound to a hard coded port, the ability to run multiple instances + of the test simultaneously on the same host is compromised, which makes the + test a ticking time bomb in a buildbot environment. On Unix buildbots, this + may simply manifest as a failed test, which can be recovered from without + intervention in most cases, but on Windows, the entire python process can + completely and utterly wedge, requiring someone to log in to the buildbot + and manually kill the affected process. + + (This is easy to reproduce on Windows, unfortunately, and can be traced to + the SO_REUSEADDR socket option having different semantics on Windows versus + Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, + listen and then accept connections on identical host/ports. An EADDRINUSE + OSError will be raised at some point (depending on the platform and + the order bind and listen were called on each socket). + + However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE + will ever be raised when attempting to bind two identical host/ports. When + accept() is called on each socket, the second caller's process will steal + the port from the first caller, leaving them both in an awkwardly wedged + state where they'll no longer respond to any signals or graceful kills, and + must be forcibly killed via OpenProcess()/TerminateProcess(). + + The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option + instead of SO_REUSEADDR, which effectively affords the same semantics as + SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open + Source world compared to Windows ones, this is a common mistake. A quick + look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when + openssl.exe is called with the 's_server' option, for example. See + http://bugs.python.org/issue2550 for more info. The following site also + has a very thorough description about the implications of both REUSEADDR + and EXCLUSIVEADDRUSE on Windows: + https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse + + XXX: although this approach is a vast improvement on previous attempts to + elicit unused ports, it rests heavily on the assumption that the ephemeral + port returned to us by the OS won't immediately be dished back out to some + other process when we close and delete our temporary socket but before our + calling code has a chance to bind the returned port. We can deal with this + issue if/when we come across it. + """ + + with socket.socket(family, socktype) as tempsock: + port = bind_port(tempsock) + del tempsock + return port + +def bind_port(sock, host=HOST): + """Bind the socket to a free port and return the port number. Relies on + ephemeral ports in order to ensure we are using an unbound port. This is + important as many tests may be running simultaneously, especially in a + buildbot environment. This method raises an exception if the sock.family + is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR + or SO_REUSEPORT set on it. Tests should *never* set these socket options + for TCP/IP sockets. The only case for setting these options is testing + multicasting via multiple UDP sockets. + + Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. + on Windows), it will be set on the socket. This will prevent anyone else + from bind()'ing to our host/port for the duration of the test. + """ + + if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: + if hasattr(socket, 'SO_REUSEADDR'): + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: + raise support.TestFailed("tests should never set the " + "SO_REUSEADDR socket option on " + "TCP/IP sockets!") + if hasattr(socket, 'SO_REUSEPORT'): + try: + if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: + raise support.TestFailed("tests should never set the " + "SO_REUSEPORT socket option on " + "TCP/IP sockets!") + except OSError: + # Python's socket module was compiled using modern headers + # thus defining SO_REUSEPORT but this process is running + # under an older kernel that does not support SO_REUSEPORT. + pass + if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + + sock.bind((host, 0)) + port = sock.getsockname()[1] + return port + +def bind_unix_socket(sock, addr): + """Bind a unix socket, raising SkipTest if PermissionError is raised.""" + assert sock.family == socket.AF_UNIX + try: + sock.bind(addr) + except PermissionError: + sock.close() + raise unittest.SkipTest('cannot bind AF_UNIX sockets') + +def _is_ipv6_enabled(): + """Check whether IPv6 is enabled on this host.""" + if socket.has_ipv6: + sock = None + try: + sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) + sock.bind((HOSTv6, 0)) + return True + except OSError: + pass + finally: + if sock: + sock.close() + return False + +IPV6_ENABLED = _is_ipv6_enabled() + + +_bind_nix_socket_error = None +def skip_unless_bind_unix_socket(test): + """Decorator for tests requiring a functional bind() for unix sockets.""" + if not hasattr(socket, 'AF_UNIX'): + return unittest.skip('No UNIX Sockets')(test) + global _bind_nix_socket_error + if _bind_nix_socket_error is None: + from .os_helper import TESTFN, unlink + path = TESTFN + "can_bind_unix_socket" + with socket.socket(socket.AF_UNIX) as sock: + try: + sock.bind(path) + _bind_nix_socket_error = False + except OSError as e: + _bind_nix_socket_error = e + finally: + unlink(path) + if _bind_nix_socket_error: + msg = 'Requires a functional unix bind(): %s' % _bind_nix_socket_error + return unittest.skip(msg)(test) + else: + return test + + +def get_socket_conn_refused_errs(): + """ + Get the different socket error numbers ('errno') which can be received + when a connection is refused. + """ + errors = [errno.ECONNREFUSED] + if hasattr(errno, 'ENETUNREACH'): + # On Solaris, ENETUNREACH is returned sometimes instead of ECONNREFUSED + errors.append(errno.ENETUNREACH) + if hasattr(errno, 'EADDRNOTAVAIL'): + # bpo-31910: socket.create_connection() fails randomly + # with EADDRNOTAVAIL on Travis CI + errors.append(errno.EADDRNOTAVAIL) + if hasattr(errno, 'EHOSTUNREACH'): + # bpo-37583: The destination host cannot be reached + errors.append(errno.EHOSTUNREACH) + if not IPV6_ENABLED: + errors.append(errno.EAFNOSUPPORT) + return errors + + +_NOT_SET = object() + +@contextlib.contextmanager +def transient_internet(resource_name, *, timeout=_NOT_SET, errnos=()): + """Return a context manager that raises ResourceDenied when various issues + with the internet connection manifest themselves as exceptions.""" + import nntplib + import urllib.error + if timeout is _NOT_SET: + timeout = support.INTERNET_TIMEOUT + + default_errnos = [ + ('ECONNREFUSED', 111), + ('ECONNRESET', 104), + ('EHOSTUNREACH', 113), + ('ENETUNREACH', 101), + ('ETIMEDOUT', 110), + # socket.create_connection() fails randomly with + # EADDRNOTAVAIL on Travis CI. + ('EADDRNOTAVAIL', 99), + ] + default_gai_errnos = [ + ('EAI_AGAIN', -3), + ('EAI_FAIL', -4), + ('EAI_NONAME', -2), + ('EAI_NODATA', -5), + # Encountered when trying to resolve IPv6-only hostnames + ('WSANO_DATA', 11004), + ] + + denied = support.ResourceDenied("Resource %r is not available" % resource_name) + captured_errnos = errnos + gai_errnos = [] + if not captured_errnos: + captured_errnos = [getattr(errno, name, num) + for (name, num) in default_errnos] + gai_errnos = [getattr(socket, name, num) + for (name, num) in default_gai_errnos] + + def filter_error(err): + n = getattr(err, 'errno', None) + if (isinstance(err, TimeoutError) or + (isinstance(err, socket.gaierror) and n in gai_errnos) or + (isinstance(err, urllib.error.HTTPError) and + 500 <= err.code <= 599) or + (isinstance(err, urllib.error.URLError) and + (("ConnectionRefusedError" in err.reason) or + ("TimeoutError" in err.reason) or + ("EOFError" in err.reason))) or + n in captured_errnos): + if not support.verbose: + sys.stderr.write(denied.args[0] + "\n") + raise denied from err + + old_timeout = socket.getdefaulttimeout() + try: + if timeout is not None: + socket.setdefaulttimeout(timeout) + yield + except nntplib.NNTPTemporaryError as err: + if support.verbose: + sys.stderr.write(denied.args[0] + "\n") + raise denied from err + except OSError as err: + # urllib can wrap original socket errors multiple times (!), we must + # unwrap to get at the original error. + while True: + a = err.args + if len(a) >= 1 and isinstance(a[0], OSError): + err = a[0] + # The error can also be wrapped as args[1]: + # except socket.error as msg: + # raise OSError('socket error', msg).with_traceback(sys.exc_info()[2]) + elif len(a) >= 2 and isinstance(a[1], OSError): + err = a[1] + else: + break + filter_error(err) + raise + # XXX should we catch generic exceptions and look for their + # __cause__ or __context__? + finally: + socket.setdefaulttimeout(old_timeout) diff --git a/omnilmm/lib/python3.10/test/support/testresult.py b/omnilmm/lib/python3.10/test/support/testresult.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2edda0f580ab55d2e49296433f5dbf419d69d4 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/testresult.py @@ -0,0 +1,185 @@ +'''Test runner and result class for the regression test suite. + +''' + +import functools +import io +import sys +import time +import traceback +import unittest + +class RegressionTestResult(unittest.TextTestResult): + USE_XML = False + + def __init__(self, stream, descriptions, verbosity): + super().__init__(stream=stream, descriptions=descriptions, + verbosity=2 if verbosity else 0) + self.buffer = True + if self.USE_XML: + from xml.etree import ElementTree as ET + from datetime import datetime + self.__ET = ET + self.__suite = ET.Element('testsuite') + self.__suite.set('start', datetime.utcnow().isoformat(' ')) + self.__e = None + self.__start_time = None + + @classmethod + def __getId(cls, test): + try: + test_id = test.id + except AttributeError: + return str(test) + try: + return test_id() + except TypeError: + return str(test_id) + return repr(test) + + def startTest(self, test): + super().startTest(test) + if self.USE_XML: + self.__e = e = self.__ET.SubElement(self.__suite, 'testcase') + self.__start_time = time.perf_counter() + + def _add_result(self, test, capture=False, **args): + if not self.USE_XML: + return + e = self.__e + self.__e = None + if e is None: + return + ET = self.__ET + + e.set('name', args.pop('name', self.__getId(test))) + e.set('status', args.pop('status', 'run')) + e.set('result', args.pop('result', 'completed')) + if self.__start_time: + e.set('time', f'{time.perf_counter() - self.__start_time:0.6f}') + + if capture: + if self._stdout_buffer is not None: + stdout = self._stdout_buffer.getvalue().rstrip() + ET.SubElement(e, 'system-out').text = stdout + if self._stderr_buffer is not None: + stderr = self._stderr_buffer.getvalue().rstrip() + ET.SubElement(e, 'system-err').text = stderr + + for k, v in args.items(): + if not k or not v: + continue + e2 = ET.SubElement(e, k) + if hasattr(v, 'items'): + for k2, v2 in v.items(): + if k2: + e2.set(k2, str(v2)) + else: + e2.text = str(v2) + else: + e2.text = str(v) + + @classmethod + def __makeErrorDict(cls, err_type, err_value, err_tb): + if isinstance(err_type, type): + if err_type.__module__ == 'builtins': + typename = err_type.__name__ + else: + typename = f'{err_type.__module__}.{err_type.__name__}' + else: + typename = repr(err_type) + + msg = traceback.format_exception(err_type, err_value, None) + tb = traceback.format_exception(err_type, err_value, err_tb) + + return { + 'type': typename, + 'message': ''.join(msg), + '': ''.join(tb), + } + + def addError(self, test, err): + self._add_result(test, True, error=self.__makeErrorDict(*err)) + super().addError(test, err) + + def addExpectedFailure(self, test, err): + self._add_result(test, True, output=self.__makeErrorDict(*err)) + super().addExpectedFailure(test, err) + + def addFailure(self, test, err): + self._add_result(test, True, failure=self.__makeErrorDict(*err)) + super().addFailure(test, err) + + def addSkip(self, test, reason): + self._add_result(test, skipped=reason) + super().addSkip(test, reason) + + def addSuccess(self, test): + self._add_result(test) + super().addSuccess(test) + + def addUnexpectedSuccess(self, test): + self._add_result(test, outcome='UNEXPECTED_SUCCESS') + super().addUnexpectedSuccess(test) + + def get_xml_element(self): + if not self.USE_XML: + raise ValueError("USE_XML is false") + e = self.__suite + e.set('tests', str(self.testsRun)) + e.set('errors', str(len(self.errors))) + e.set('failures', str(len(self.failures))) + return e + +class QuietRegressionTestRunner: + def __init__(self, stream, buffer=False): + self.result = RegressionTestResult(stream, None, 0) + self.result.buffer = buffer + + def run(self, test): + test(self.result) + return self.result + +def get_test_runner_class(verbosity, buffer=False): + if verbosity: + return functools.partial(unittest.TextTestRunner, + resultclass=RegressionTestResult, + buffer=buffer, + verbosity=verbosity) + return functools.partial(QuietRegressionTestRunner, buffer=buffer) + +def get_test_runner(stream, verbosity, capture_output=False): + return get_test_runner_class(verbosity, capture_output)(stream) + +if __name__ == '__main__': + import xml.etree.ElementTree as ET + RegressionTestResult.USE_XML = True + + class TestTests(unittest.TestCase): + def test_pass(self): + pass + + def test_pass_slow(self): + time.sleep(1.0) + + def test_fail(self): + print('stdout', file=sys.stdout) + print('stderr', file=sys.stderr) + self.fail('failure message') + + def test_error(self): + print('stdout', file=sys.stdout) + print('stderr', file=sys.stderr) + raise RuntimeError('error message') + + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(TestTests)) + stream = io.StringIO() + runner_cls = get_test_runner_class(sum(a == '-v' for a in sys.argv)) + runner = runner_cls(sys.stdout) + result = runner.run(suite) + print('Output:', stream.getvalue()) + print('XML: ', end='') + for s in ET.tostringlist(result.get_xml_element()): + print(s.decode(), end='') + print() diff --git a/omnilmm/lib/python3.10/test/support/threading_helper.py b/omnilmm/lib/python3.10/test/support/threading_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..92a64e8354acbce5aa0762a2b84c6552103c7269 --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/threading_helper.py @@ -0,0 +1,209 @@ +import _thread +import contextlib +import functools +import sys +import threading +import time + +from test import support + + +#======================================================================= +# Threading support to prevent reporting refleaks when running regrtest.py -R + +# NOTE: we use thread._count() rather than threading.enumerate() (or the +# moral equivalent thereof) because a threading.Thread object is still alive +# until its __bootstrap() method has returned, even after it has been +# unregistered from the threading module. +# thread._count(), on the other hand, only gets decremented *after* the +# __bootstrap() method has returned, which gives us reliable reference counts +# at the end of a test run. + + +def threading_setup(): + return _thread._count(), threading._dangling.copy() + + +def threading_cleanup(*original_values): + _MAX_COUNT = 100 + + for count in range(_MAX_COUNT): + values = _thread._count(), threading._dangling + if values == original_values: + break + + if not count: + # Display a warning at the first iteration + support.environment_altered = True + dangling_threads = values[1] + support.print_warning(f"threading_cleanup() failed to cleanup " + f"{values[0] - original_values[0]} threads " + f"(count: {values[0]}, " + f"dangling: {len(dangling_threads)})") + for thread in dangling_threads: + support.print_warning(f"Dangling thread: {thread!r}") + + # Don't hold references to threads + dangling_threads = None + values = None + + time.sleep(0.01) + support.gc_collect() + + +def reap_threads(func): + """Use this function when threads are being used. This will + ensure that the threads are cleaned up even when the test fails. + """ + @functools.wraps(func) + def decorator(*args): + key = threading_setup() + try: + return func(*args) + finally: + threading_cleanup(*key) + return decorator + + +@contextlib.contextmanager +def wait_threads_exit(timeout=None): + """ + bpo-31234: Context manager to wait until all threads created in the with + statement exit. + + Use _thread.count() to check if threads exited. Indirectly, wait until + threads exit the internal t_bootstrap() C function of the _thread module. + + threading_setup() and threading_cleanup() are designed to emit a warning + if a test leaves running threads in the background. This context manager + is designed to cleanup threads started by the _thread.start_new_thread() + which doesn't allow to wait for thread exit, whereas thread.Thread has a + join() method. + """ + if timeout is None: + timeout = support.SHORT_TIMEOUT + old_count = _thread._count() + try: + yield + finally: + start_time = time.monotonic() + deadline = start_time + timeout + while True: + count = _thread._count() + if count <= old_count: + break + if time.monotonic() > deadline: + dt = time.monotonic() - start_time + msg = (f"wait_threads() failed to cleanup {count - old_count} " + f"threads after {dt:.1f} seconds " + f"(count: {count}, old count: {old_count})") + raise AssertionError(msg) + time.sleep(0.010) + support.gc_collect() + + +def join_thread(thread, timeout=None): + """Join a thread. Raise an AssertionError if the thread is still alive + after timeout seconds. + """ + if timeout is None: + timeout = support.SHORT_TIMEOUT + thread.join(timeout) + if thread.is_alive(): + msg = f"failed to join the thread in {timeout:.1f} seconds" + raise AssertionError(msg) + + +@contextlib.contextmanager +def start_threads(threads, unlock=None): + import faulthandler + threads = list(threads) + started = [] + try: + try: + for t in threads: + t.start() + started.append(t) + except: + if support.verbose: + print("Can't start %d threads, only %d threads started" % + (len(threads), len(started))) + raise + yield + finally: + try: + if unlock: + unlock() + endtime = time.monotonic() + for timeout in range(1, 16): + endtime += 60 + for t in started: + t.join(max(endtime - time.monotonic(), 0.01)) + started = [t for t in started if t.is_alive()] + if not started: + break + if support.verbose: + print('Unable to join %d threads during a period of ' + '%d minutes' % (len(started), timeout)) + finally: + started = [t for t in started if t.is_alive()] + if started: + faulthandler.dump_traceback(sys.stdout) + raise AssertionError('Unable to join %d threads' % len(started)) + + +class catch_threading_exception: + """ + Context manager catching threading.Thread exception using + threading.excepthook. + + Attributes set when an exception is caught: + + * exc_type + * exc_value + * exc_traceback + * thread + + See threading.excepthook() documentation for these attributes. + + These attributes are deleted at the context manager exit. + + Usage: + + with threading_helper.catch_threading_exception() as cm: + # code spawning a thread which raises an exception + ... + + # check the thread exception, use cm attributes: + # exc_type, exc_value, exc_traceback, thread + ... + + # exc_type, exc_value, exc_traceback, thread attributes of cm no longer + # exists at this point + # (to avoid reference cycles) + """ + + def __init__(self): + self.exc_type = None + self.exc_value = None + self.exc_traceback = None + self.thread = None + self._old_hook = None + + def _hook(self, args): + self.exc_type = args.exc_type + self.exc_value = args.exc_value + self.exc_traceback = args.exc_traceback + self.thread = args.thread + + def __enter__(self): + self._old_hook = threading.excepthook + threading.excepthook = self._hook + return self + + def __exit__(self, *exc_info): + threading.excepthook = self._old_hook + del self.exc_type + del self.exc_value + del self.exc_traceback + del self.thread diff --git a/omnilmm/lib/python3.10/test/support/warnings_helper.py b/omnilmm/lib/python3.10/test/support/warnings_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..93a91e6d99f955e20f679b0da0a90525938e32ef --- /dev/null +++ b/omnilmm/lib/python3.10/test/support/warnings_helper.py @@ -0,0 +1,199 @@ +import contextlib +import functools +import re +import sys +import warnings + + +def check_syntax_warning(testcase, statement, errtext='', + *, lineno=1, offset=None): + # Test also that a warning is emitted only once. + from test.support import check_syntax_error + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter('always', SyntaxWarning) + compile(statement, '', 'exec') + testcase.assertEqual(len(warns), 1, warns) + + warn, = warns + testcase.assertTrue(issubclass(warn.category, SyntaxWarning), + warn.category) + if errtext: + testcase.assertRegex(str(warn.message), errtext) + testcase.assertEqual(warn.filename, '') + testcase.assertIsNotNone(warn.lineno) + if lineno is not None: + testcase.assertEqual(warn.lineno, lineno) + + # SyntaxWarning should be converted to SyntaxError when raised, + # since the latter contains more information and provides better + # error report. + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter('error', SyntaxWarning) + check_syntax_error(testcase, statement, errtext, + lineno=lineno, offset=offset) + # No warnings are leaked when a SyntaxError is raised. + testcase.assertEqual(warns, []) + + +def ignore_warnings(*, category): + """Decorator to suppress warnings. + + Use of context managers to hide warnings make diffs + more noisy and tools like 'git blame' less useful. + """ + def decorator(test): + @functools.wraps(test) + def wrapper(self, *args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter('ignore', category=category) + return test(self, *args, **kwargs) + return wrapper + return decorator + + +class WarningsRecorder(object): + """Convenience wrapper for the warnings list returned on + entry to the warnings.catch_warnings() context manager. + """ + def __init__(self, warnings_list): + self._warnings = warnings_list + self._last = 0 + + def __getattr__(self, attr): + if len(self._warnings) > self._last: + return getattr(self._warnings[-1], attr) + elif attr in warnings.WarningMessage._WARNING_DETAILS: + return None + raise AttributeError("%r has no attribute %r" % (self, attr)) + + @property + def warnings(self): + return self._warnings[self._last:] + + def reset(self): + self._last = len(self._warnings) + + +@contextlib.contextmanager +def check_warnings(*filters, **kwargs): + """Context manager to silence warnings. + + Accept 2-tuples as positional arguments: + ("message regexp", WarningCategory) + + Optional argument: + - if 'quiet' is True, it does not fail if a filter catches nothing + (default True without argument, + default False if some filters are defined) + + Without argument, it defaults to: + check_warnings(("", Warning), quiet=True) + """ + quiet = kwargs.get('quiet') + if not filters: + filters = (("", Warning),) + # Preserve backward compatibility + if quiet is None: + quiet = True + return _filterwarnings(filters, quiet) + + +@contextlib.contextmanager +def check_no_warnings(testcase, message='', category=Warning, force_gc=False): + """Context manager to check that no warnings are emitted. + + This context manager enables a given warning within its scope + and checks that no warnings are emitted even with that warning + enabled. + + If force_gc is True, a garbage collection is attempted before checking + for warnings. This may help to catch warnings emitted when objects + are deleted, such as ResourceWarning. + + Other keyword arguments are passed to warnings.filterwarnings(). + """ + from test.support import gc_collect + with warnings.catch_warnings(record=True) as warns: + warnings.filterwarnings('always', + message=message, + category=category) + yield + if force_gc: + gc_collect() + testcase.assertEqual(warns, []) + + +@contextlib.contextmanager +def check_no_resource_warning(testcase): + """Context manager to check that no ResourceWarning is emitted. + + Usage: + + with check_no_resource_warning(self): + f = open(...) + ... + del f + + You must remove the object which may emit ResourceWarning before + the end of the context manager. + """ + with check_no_warnings(testcase, category=ResourceWarning, force_gc=True): + yield + + +def _filterwarnings(filters, quiet=False): + """Catch the warnings, then check if all the expected + warnings have been raised and re-raise unexpected warnings. + If 'quiet' is True, only re-raise the unexpected warnings. + """ + # Clear the warning registry of the calling module + # in order to re-raise the warnings. + frame = sys._getframe(2) + registry = frame.f_globals.get('__warningregistry__') + if registry: + registry.clear() + with warnings.catch_warnings(record=True) as w: + # Set filter "always" to record all warnings. Because + # test_warnings swap the module, we need to look up in + # the sys.modules dictionary. + sys.modules['warnings'].simplefilter("always") + yield WarningsRecorder(w) + # Filter the recorded warnings + reraise = list(w) + missing = [] + for msg, cat in filters: + seen = False + for w in reraise[:]: + warning = w.message + # Filter out the matching messages + if (re.match(msg, str(warning), re.I) and + issubclass(warning.__class__, cat)): + seen = True + reraise.remove(w) + if not seen and not quiet: + # This filter caught nothing + missing.append((msg, cat.__name__)) + if reraise: + raise AssertionError("unhandled warning %s" % reraise[0]) + if missing: + raise AssertionError("filter (%r, %s) did not catch any warning" % + missing[0]) + + +@contextlib.contextmanager +def save_restore_warnings_filters(): + old_filters = warnings.filters[:] + try: + yield + finally: + warnings.filters[:] = old_filters + + +def _warn_about_deprecation(): + warnings.warn( + "This is used in test_support test to ensure" + " support.ignore_deprecations_from() works as expected." + " You should not be seeing this.", + DeprecationWarning, + stacklevel=0, + ) diff --git a/omnilmm/lib/python3.10/test/test_script_helper.py b/omnilmm/lib/python3.10/test/test_script_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..4ade2cbc0d4b18467be012b511b7ee442d9828f1 --- /dev/null +++ b/omnilmm/lib/python3.10/test/test_script_helper.py @@ -0,0 +1,125 @@ +"""Unittests for test.support.script_helper. Who tests the test helper?""" + +import subprocess +import sys +import os +from test.support import script_helper +import unittest +from unittest import mock + + +class TestScriptHelper(unittest.TestCase): + + def test_assert_python_ok(self): + t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)') + self.assertEqual(0, t[0], 'return code was not 0') + + def test_assert_python_failure(self): + # I didn't import the sys module so this child will fail. + rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)') + self.assertNotEqual(0, rc, 'return code should not be 0') + + def test_assert_python_ok_raises(self): + # I didn't import the sys module so this child will fail. + with self.assertRaises(AssertionError) as error_context: + script_helper.assert_python_ok('-c', 'sys.exit(0)') + error_msg = str(error_context.exception) + self.assertIn('command line:', error_msg) + self.assertIn('sys.exit(0)', error_msg, msg='unexpected command line') + + def test_assert_python_failure_raises(self): + with self.assertRaises(AssertionError) as error_context: + script_helper.assert_python_failure('-c', 'import sys; sys.exit(0)') + error_msg = str(error_context.exception) + self.assertIn('Process return code is 0\n', error_msg) + self.assertIn('import sys; sys.exit(0)', error_msg, + msg='unexpected command line.') + + @mock.patch('subprocess.Popen') + def test_assert_python_isolated_when_env_not_required(self, mock_popen): + with mock.patch.object(script_helper, + 'interpreter_requires_environment', + return_value=False) as mock_ire_func: + mock_popen.side_effect = RuntimeError('bail out of unittest') + try: + script_helper._assert_python(True, '-c', 'None') + except RuntimeError as err: + self.assertEqual('bail out of unittest', err.args[0]) + self.assertEqual(1, mock_popen.call_count) + self.assertEqual(1, mock_ire_func.call_count) + popen_command = mock_popen.call_args[0][0] + self.assertEqual(sys.executable, popen_command[0]) + self.assertIn('None', popen_command) + self.assertIn('-I', popen_command) + self.assertNotIn('-E', popen_command) # -I overrides this + + @mock.patch('subprocess.Popen') + def test_assert_python_not_isolated_when_env_is_required(self, mock_popen): + """Ensure that -I is not passed when the environment is required.""" + with mock.patch.object(script_helper, + 'interpreter_requires_environment', + return_value=True) as mock_ire_func: + mock_popen.side_effect = RuntimeError('bail out of unittest') + try: + script_helper._assert_python(True, '-c', 'None') + except RuntimeError as err: + self.assertEqual('bail out of unittest', err.args[0]) + popen_command = mock_popen.call_args[0][0] + self.assertNotIn('-I', popen_command) + self.assertNotIn('-E', popen_command) + + +class TestScriptHelperEnvironment(unittest.TestCase): + """Code coverage for interpreter_requires_environment().""" + + def setUp(self): + self.assertTrue( + hasattr(script_helper, '__cached_interp_requires_environment')) + # Reset the private cached state. + script_helper.__dict__['__cached_interp_requires_environment'] = None + + def tearDown(self): + # Reset the private cached state. + script_helper.__dict__['__cached_interp_requires_environment'] = None + + @mock.patch('subprocess.check_call') + def test_interpreter_requires_environment_true(self, mock_check_call): + with mock.patch.dict(os.environ): + os.environ.pop('PYTHONHOME', None) + mock_check_call.side_effect = subprocess.CalledProcessError('', '') + self.assertTrue(script_helper.interpreter_requires_environment()) + self.assertTrue(script_helper.interpreter_requires_environment()) + self.assertEqual(1, mock_check_call.call_count) + + @mock.patch('subprocess.check_call') + def test_interpreter_requires_environment_false(self, mock_check_call): + with mock.patch.dict(os.environ): + os.environ.pop('PYTHONHOME', None) + # The mocked subprocess.check_call fakes a no-error process. + script_helper.interpreter_requires_environment() + self.assertFalse(script_helper.interpreter_requires_environment()) + self.assertEqual(1, mock_check_call.call_count) + + @mock.patch('subprocess.check_call') + def test_interpreter_requires_environment_details(self, mock_check_call): + with mock.patch.dict(os.environ): + os.environ.pop('PYTHONHOME', None) + script_helper.interpreter_requires_environment() + self.assertFalse(script_helper.interpreter_requires_environment()) + self.assertFalse(script_helper.interpreter_requires_environment()) + self.assertEqual(1, mock_check_call.call_count) + check_call_command = mock_check_call.call_args[0][0] + self.assertEqual(sys.executable, check_call_command[0]) + self.assertIn('-E', check_call_command) + + @mock.patch('subprocess.check_call') + def test_interpreter_requires_environment_with_pythonhome(self, mock_check_call): + with mock.patch.dict(os.environ): + os.environ['PYTHONHOME'] = 'MockedHome' + self.assertTrue(script_helper.interpreter_requires_environment()) + self.assertTrue(script_helper.interpreter_requires_environment()) + self.assertEqual(0, mock_check_call.call_count) + + +if __name__ == '__main__': + unittest.main() diff --git a/omnilmm/lib/python3.10/test/test_support.py b/omnilmm/lib/python3.10/test/test_support.py new file mode 100644 index 0000000000000000000000000000000000000000..79290986c494d500af1a86d8ad57efbd1b7cbb2b --- /dev/null +++ b/omnilmm/lib/python3.10/test/test_support.py @@ -0,0 +1,713 @@ +import errno +import importlib +import io +import os +import shutil +import socket +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import warnings + +from test import support +from test.support import import_helper +from test.support import os_helper +from test.support import script_helper +from test.support import socket_helper +from test.support import warnings_helper + +TESTFN = os_helper.TESTFN + + +class TestSupport(unittest.TestCase): + @classmethod + def setUpClass(cls): + orig_filter_len = len(warnings.filters) + cls._warnings_helper_token = support.ignore_deprecations_from( + "test.support.warnings_helper", like=".*used in test_support.*" + ) + cls._test_support_token = support.ignore_deprecations_from( + "test.test_support", like=".*You should NOT be seeing this.*" + ) + assert len(warnings.filters) == orig_filter_len + 2 + + @classmethod + def tearDownClass(cls): + orig_filter_len = len(warnings.filters) + support.clear_ignored_deprecations( + cls._warnings_helper_token, + cls._test_support_token, + ) + assert len(warnings.filters) == orig_filter_len - 2 + + def test_ignored_deprecations_are_silent(self): + """Test support.ignore_deprecations_from() silences warnings""" + with warnings.catch_warnings(record=True) as warning_objs: + warnings_helper._warn_about_deprecation() + warnings.warn("You should NOT be seeing this.", DeprecationWarning) + messages = [str(w.message) for w in warning_objs] + self.assertEqual(len(messages), 0, messages) + + def test_import_module(self): + import_helper.import_module("ftplib") + self.assertRaises(unittest.SkipTest, + import_helper.import_module, "foo") + + def test_import_fresh_module(self): + import_helper.import_fresh_module("ftplib") + + def test_get_attribute(self): + self.assertEqual(support.get_attribute(self, "test_get_attribute"), + self.test_get_attribute) + self.assertRaises(unittest.SkipTest, support.get_attribute, self, "foo") + + @unittest.skip("failing buildbots") + def test_get_original_stdout(self): + self.assertEqual(support.get_original_stdout(), sys.stdout) + + def test_unload(self): + import sched + self.assertIn("sched", sys.modules) + import_helper.unload("sched") + self.assertNotIn("sched", sys.modules) + + def test_unlink(self): + with open(TESTFN, "w", encoding="utf-8") as f: + pass + os_helper.unlink(TESTFN) + self.assertFalse(os.path.exists(TESTFN)) + os_helper.unlink(TESTFN) + + def test_rmtree(self): + dirpath = os_helper.TESTFN + 'd' + subdirpath = os.path.join(dirpath, 'subdir') + os.mkdir(dirpath) + os.mkdir(subdirpath) + os_helper.rmtree(dirpath) + self.assertFalse(os.path.exists(dirpath)) + with support.swap_attr(support, 'verbose', 0): + os_helper.rmtree(dirpath) + + os.mkdir(dirpath) + os.mkdir(subdirpath) + os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR) + with support.swap_attr(support, 'verbose', 0): + os_helper.rmtree(dirpath) + self.assertFalse(os.path.exists(dirpath)) + + os.mkdir(dirpath) + os.mkdir(subdirpath) + os.chmod(dirpath, 0) + with support.swap_attr(support, 'verbose', 0): + os_helper.rmtree(dirpath) + self.assertFalse(os.path.exists(dirpath)) + + def test_forget(self): + mod_filename = TESTFN + '.py' + with open(mod_filename, 'w', encoding="utf-8") as f: + print('foo = 1', file=f) + sys.path.insert(0, os.curdir) + importlib.invalidate_caches() + try: + mod = __import__(TESTFN) + self.assertIn(TESTFN, sys.modules) + + import_helper.forget(TESTFN) + self.assertNotIn(TESTFN, sys.modules) + finally: + del sys.path[0] + os_helper.unlink(mod_filename) + os_helper.rmtree('__pycache__') + + def test_HOST(self): + s = socket.create_server((socket_helper.HOST, 0)) + s.close() + + def test_find_unused_port(self): + port = socket_helper.find_unused_port() + s = socket.create_server((socket_helper.HOST, port)) + s.close() + + def test_bind_port(self): + s = socket.socket() + socket_helper.bind_port(s) + s.listen() + s.close() + + # Tests for temp_dir() + + def test_temp_dir(self): + """Test that temp_dir() creates and destroys its directory.""" + parent_dir = tempfile.mkdtemp() + parent_dir = os.path.realpath(parent_dir) + + try: + path = os.path.join(parent_dir, 'temp') + self.assertFalse(os.path.isdir(path)) + with os_helper.temp_dir(path) as temp_path: + self.assertEqual(temp_path, path) + self.assertTrue(os.path.isdir(path)) + self.assertFalse(os.path.isdir(path)) + finally: + os_helper.rmtree(parent_dir) + + def test_temp_dir__path_none(self): + """Test passing no path.""" + with os_helper.temp_dir() as temp_path: + self.assertTrue(os.path.isdir(temp_path)) + self.assertFalse(os.path.isdir(temp_path)) + + def test_temp_dir__existing_dir__quiet_default(self): + """Test passing a directory that already exists.""" + def call_temp_dir(path): + with os_helper.temp_dir(path) as temp_path: + raise Exception("should not get here") + + path = tempfile.mkdtemp() + path = os.path.realpath(path) + try: + self.assertTrue(os.path.isdir(path)) + self.assertRaises(FileExistsError, call_temp_dir, path) + # Make sure temp_dir did not delete the original directory. + self.assertTrue(os.path.isdir(path)) + finally: + shutil.rmtree(path) + + def test_temp_dir__existing_dir__quiet_true(self): + """Test passing a directory that already exists with quiet=True.""" + path = tempfile.mkdtemp() + path = os.path.realpath(path) + + try: + with warnings_helper.check_warnings() as recorder: + with os_helper.temp_dir(path, quiet=True) as temp_path: + self.assertEqual(path, temp_path) + warnings = [str(w.message) for w in recorder.warnings] + # Make sure temp_dir did not delete the original directory. + self.assertTrue(os.path.isdir(path)) + finally: + shutil.rmtree(path) + + self.assertEqual(len(warnings), 1, warnings) + warn = warnings[0] + self.assertTrue(warn.startswith(f'tests may fail, unable to create ' + f'temporary directory {path!r}: '), + warn) + + @unittest.skipUnless(hasattr(os, "fork"), "test requires os.fork") + def test_temp_dir__forked_child(self): + """Test that a forked child process does not remove the directory.""" + # See bpo-30028 for details. + # Run the test as an external script, because it uses fork. + script_helper.assert_python_ok("-c", textwrap.dedent(""" + import os + from test import support + from test.support import os_helper + with os_helper.temp_cwd() as temp_path: + pid = os.fork() + if pid != 0: + # parent process + + # wait for the child to terminate + support.wait_process(pid, exitcode=0) + + # Make sure that temp_path is still present. When the child + # process leaves the 'temp_cwd'-context, the __exit__()- + # method of the context must not remove the temporary + # directory. + if not os.path.isdir(temp_path): + raise AssertionError("Child removed temp_path.") + """)) + + # Tests for change_cwd() + + def test_change_cwd(self): + original_cwd = os.getcwd() + + with os_helper.temp_dir() as temp_path: + with os_helper.change_cwd(temp_path) as new_cwd: + self.assertEqual(new_cwd, temp_path) + self.assertEqual(os.getcwd(), new_cwd) + + self.assertEqual(os.getcwd(), original_cwd) + + def test_change_cwd__non_existent_dir(self): + """Test passing a non-existent directory.""" + original_cwd = os.getcwd() + + def call_change_cwd(path): + with os_helper.change_cwd(path) as new_cwd: + raise Exception("should not get here") + + with os_helper.temp_dir() as parent_dir: + non_existent_dir = os.path.join(parent_dir, 'does_not_exist') + self.assertRaises(FileNotFoundError, call_change_cwd, + non_existent_dir) + + self.assertEqual(os.getcwd(), original_cwd) + + def test_change_cwd__non_existent_dir__quiet_true(self): + """Test passing a non-existent directory with quiet=True.""" + original_cwd = os.getcwd() + + with os_helper.temp_dir() as parent_dir: + bad_dir = os.path.join(parent_dir, 'does_not_exist') + with warnings_helper.check_warnings() as recorder: + with os_helper.change_cwd(bad_dir, quiet=True) as new_cwd: + self.assertEqual(new_cwd, original_cwd) + self.assertEqual(os.getcwd(), new_cwd) + warnings = [str(w.message) for w in recorder.warnings] + + self.assertEqual(len(warnings), 1, warnings) + warn = warnings[0] + self.assertTrue(warn.startswith(f'tests may fail, unable to change ' + f'the current working directory ' + f'to {bad_dir!r}: '), + warn) + + # Tests for change_cwd() + + def test_change_cwd__chdir_warning(self): + """Check the warning message when os.chdir() fails.""" + path = TESTFN + '_does_not_exist' + with warnings_helper.check_warnings() as recorder: + with os_helper.change_cwd(path=path, quiet=True): + pass + messages = [str(w.message) for w in recorder.warnings] + + self.assertEqual(len(messages), 1, messages) + msg = messages[0] + self.assertTrue(msg.startswith(f'tests may fail, unable to change ' + f'the current working directory ' + f'to {path!r}: '), + msg) + + # Tests for temp_cwd() + + def test_temp_cwd(self): + here = os.getcwd() + with os_helper.temp_cwd(name=TESTFN): + self.assertEqual(os.path.basename(os.getcwd()), TESTFN) + self.assertFalse(os.path.exists(TESTFN)) + self.assertEqual(os.getcwd(), here) + + + def test_temp_cwd__name_none(self): + """Test passing None to temp_cwd().""" + original_cwd = os.getcwd() + with os_helper.temp_cwd(name=None) as new_cwd: + self.assertNotEqual(new_cwd, original_cwd) + self.assertTrue(os.path.isdir(new_cwd)) + self.assertEqual(os.getcwd(), new_cwd) + self.assertEqual(os.getcwd(), original_cwd) + + def test_sortdict(self): + self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}") + + def test_make_bad_fd(self): + fd = os_helper.make_bad_fd() + with self.assertRaises(OSError) as cm: + os.write(fd, b"foo") + self.assertEqual(cm.exception.errno, errno.EBADF) + + def test_check_syntax_error(self): + support.check_syntax_error(self, "def class", lineno=1, offset=5) + with self.assertRaises(AssertionError): + support.check_syntax_error(self, "x=1") + + def test_CleanImport(self): + import importlib + with import_helper.CleanImport("pprint"): + importlib.import_module("pprint") + + def test_DirsOnSysPath(self): + with import_helper.DirsOnSysPath('foo', 'bar'): + self.assertIn("foo", sys.path) + self.assertIn("bar", sys.path) + self.assertNotIn("foo", sys.path) + self.assertNotIn("bar", sys.path) + + def test_captured_stdout(self): + with support.captured_stdout() as stdout: + print("hello") + self.assertEqual(stdout.getvalue(), "hello\n") + + def test_captured_stderr(self): + with support.captured_stderr() as stderr: + print("hello", file=sys.stderr) + self.assertEqual(stderr.getvalue(), "hello\n") + + def test_captured_stdin(self): + with support.captured_stdin() as stdin: + stdin.write('hello\n') + stdin.seek(0) + # call test code that consumes from sys.stdin + captured = input() + self.assertEqual(captured, "hello") + + def test_gc_collect(self): + support.gc_collect() + + def test_python_is_optimized(self): + self.assertIsInstance(support.python_is_optimized(), bool) + + def test_swap_attr(self): + class Obj: + pass + obj = Obj() + obj.x = 1 + with support.swap_attr(obj, "x", 5) as x: + self.assertEqual(obj.x, 5) + self.assertEqual(x, 1) + self.assertEqual(obj.x, 1) + with support.swap_attr(obj, "y", 5) as y: + self.assertEqual(obj.y, 5) + self.assertIsNone(y) + self.assertFalse(hasattr(obj, 'y')) + with support.swap_attr(obj, "y", 5): + del obj.y + self.assertFalse(hasattr(obj, 'y')) + + def test_swap_item(self): + D = {"x":1} + with support.swap_item(D, "x", 5) as x: + self.assertEqual(D["x"], 5) + self.assertEqual(x, 1) + self.assertEqual(D["x"], 1) + with support.swap_item(D, "y", 5) as y: + self.assertEqual(D["y"], 5) + self.assertIsNone(y) + self.assertNotIn("y", D) + with support.swap_item(D, "y", 5): + del D["y"] + self.assertNotIn("y", D) + + class RefClass: + attribute1 = None + attribute2 = None + _hidden_attribute1 = None + __magic_1__ = None + + class OtherClass: + attribute2 = None + attribute3 = None + __magic_1__ = None + __magic_2__ = None + + def test_detect_api_mismatch(self): + missing_items = support.detect_api_mismatch(self.RefClass, + self.OtherClass) + self.assertEqual({'attribute1'}, missing_items) + + missing_items = support.detect_api_mismatch(self.OtherClass, + self.RefClass) + self.assertEqual({'attribute3', '__magic_2__'}, missing_items) + + def test_detect_api_mismatch__ignore(self): + ignore = ['attribute1', 'attribute3', '__magic_2__', 'not_in_either'] + + missing_items = support.detect_api_mismatch( + self.RefClass, self.OtherClass, ignore=ignore) + self.assertEqual(set(), missing_items) + + missing_items = support.detect_api_mismatch( + self.OtherClass, self.RefClass, ignore=ignore) + self.assertEqual(set(), missing_items) + + def test_check__all__(self): + extra = {'tempdir'} + not_exported = {'template'} + support.check__all__(self, + tempfile, + extra=extra, + not_exported=not_exported) + + extra = {'TextTestResult', 'installHandler'} + not_exported = {'load_tests', "TestProgram", "BaseTestSuite"} + + support.check__all__(self, + unittest, + ("unittest.result", "unittest.case", + "unittest.suite", "unittest.loader", + "unittest.main", "unittest.runner", + "unittest.signals", "unittest.async_case"), + extra=extra, + not_exported=not_exported) + + self.assertRaises(AssertionError, support.check__all__, self, unittest) + + @unittest.skipUnless(hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG'), + 'need os.waitpid() and os.WNOHANG') + def test_reap_children(self): + # Make sure that there is no other pending child process + support.reap_children() + + # Create a child process + pid = os.fork() + if pid == 0: + # child process: do nothing, just exit + os._exit(0) + + t0 = time.monotonic() + deadline = time.monotonic() + support.SHORT_TIMEOUT + + was_altered = support.environment_altered + try: + support.environment_altered = False + stderr = io.StringIO() + + while True: + if time.monotonic() > deadline: + self.fail("timeout") + + old_stderr = sys.__stderr__ + try: + sys.__stderr__ = stderr + support.reap_children() + finally: + sys.__stderr__ = old_stderr + + # Use environment_altered to check if reap_children() found + # the child process + if support.environment_altered: + break + + # loop until the child process completed + time.sleep(0.100) + + msg = "Warning -- reap_children() reaped child process %s" % pid + self.assertIn(msg, stderr.getvalue()) + self.assertTrue(support.environment_altered) + finally: + support.environment_altered = was_altered + + # Just in case, check again that there is no other + # pending child process + support.reap_children() + + def check_options(self, args, func, expected=None): + code = f'from test.support import {func}; print(repr({func}()))' + cmd = [sys.executable, *args, '-c', code] + env = {key: value for key, value in os.environ.items() + if not key.startswith('PYTHON')} + proc = subprocess.run(cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + universal_newlines=True, + env=env) + if expected is None: + expected = args + self.assertEqual(proc.stdout.rstrip(), repr(expected)) + self.assertEqual(proc.returncode, 0) + + def test_args_from_interpreter_flags(self): + # Test test.support.args_from_interpreter_flags() + for opts in ( + # no option + [], + # single option + ['-B'], + ['-s'], + ['-S'], + ['-E'], + ['-v'], + ['-b'], + ['-q'], + ['-I'], + # same option multiple times + ['-bb'], + ['-vvv'], + # -W options + ['-Wignore'], + # -X options + ['-X', 'dev'], + ['-Wignore', '-X', 'dev'], + ['-X', 'faulthandler'], + ['-X', 'importtime'], + ['-X', 'showrefcount'], + ['-X', 'tracemalloc'], + ['-X', 'tracemalloc=3'], + ): + with self.subTest(opts=opts): + self.check_options(opts, 'args_from_interpreter_flags') + + self.check_options(['-I', '-E', '-s'], 'args_from_interpreter_flags', + ['-I']) + + def test_optim_args_from_interpreter_flags(self): + # Test test.support.optim_args_from_interpreter_flags() + for opts in ( + # no option + [], + ['-O'], + ['-OO'], + ['-OOOO'], + ): + with self.subTest(opts=opts): + self.check_options(opts, 'optim_args_from_interpreter_flags') + + def test_match_test(self): + class Test: + def __init__(self, test_id): + self.test_id = test_id + + def id(self): + return self.test_id + + test_access = Test('test.test_os.FileTests.test_access') + test_chdir = Test('test.test_os.Win32ErrorTests.test_chdir') + + # Test acceptance + with support.swap_attr(support, '_match_test_func', None): + # match all + support.set_match_tests([]) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # match all using None + support.set_match_tests(None, None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # match the full test identifier + support.set_match_tests([test_access.id()], None) + self.assertTrue(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + # match the module name + support.set_match_tests(['test_os'], None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # Test '*' pattern + support.set_match_tests(['test_*'], None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # Test case sensitivity + support.set_match_tests(['filetests'], None) + self.assertFalse(support.match_test(test_access)) + support.set_match_tests(['FileTests'], None) + self.assertTrue(support.match_test(test_access)) + + # Test pattern containing '.' and a '*' metacharacter + support.set_match_tests(['*test_os.*.test_*'], None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # Multiple patterns + support.set_match_tests([test_access.id(), test_chdir.id()], None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + support.set_match_tests(['test_access', 'DONTMATCH'], None) + self.assertTrue(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + # Test rejection + with support.swap_attr(support, '_match_test_func', None): + # match all + support.set_match_tests(ignore_patterns=[]) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # match all using None + support.set_match_tests(None, None) + self.assertTrue(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # match the full test identifier + support.set_match_tests(None, [test_access.id()]) + self.assertFalse(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + # match the module name + support.set_match_tests(None, ['test_os']) + self.assertFalse(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + # Test '*' pattern + support.set_match_tests(None, ['test_*']) + self.assertFalse(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + # Test case sensitivity + support.set_match_tests(None, ['filetests']) + self.assertTrue(support.match_test(test_access)) + support.set_match_tests(None, ['FileTests']) + self.assertFalse(support.match_test(test_access)) + + # Test pattern containing '.' and a '*' metacharacter + support.set_match_tests(None, ['*test_os.*.test_*']) + self.assertFalse(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + # Multiple patterns + support.set_match_tests(None, [test_access.id(), test_chdir.id()]) + self.assertFalse(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + + support.set_match_tests(None, ['test_access', 'DONTMATCH']) + self.assertFalse(support.match_test(test_access)) + self.assertTrue(support.match_test(test_chdir)) + + def test_fd_count(self): + # We cannot test the absolute value of fd_count(): on old Linux + # kernel or glibc versions, os.urandom() keeps a FD open on + # /dev/urandom device and Python has 4 FD opens instead of 3. + start = os_helper.fd_count() + fd = os.open(__file__, os.O_RDONLY) + try: + more = os_helper.fd_count() + finally: + os.close(fd) + self.assertEqual(more - start, 1) + + def check_print_warning(self, msg, expected): + stderr = io.StringIO() + + old_stderr = sys.__stderr__ + try: + sys.__stderr__ = stderr + support.print_warning(msg) + finally: + sys.__stderr__ = old_stderr + + self.assertEqual(stderr.getvalue(), expected) + + def test_print_warning(self): + self.check_print_warning("msg", + "Warning -- msg\n") + self.check_print_warning("a\nb", + 'Warning -- a\nWarning -- b\n') + + # XXX -follows a list of untested API + # make_legacy_pyc + # is_resource_enabled + # requires + # fcmp + # umaks + # findfile + # check_warnings + # EnvironmentVarGuard + # transient_internet + # run_with_locale + # set_memlimit + # bigmemtest + # precisionbigmemtest + # bigaddrspacetest + # requires_resource + # run_doctest + # threading_cleanup + # reap_threads + # can_symlink + # skip_unless_symlink + # SuppressCrashReport + + +if __name__ == '__main__': + unittest.main() diff --git a/omnilmm/lib/python3.10/unittest/__pycache__/__init__.cpython-310.pyc b/omnilmm/lib/python3.10/unittest/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..961b8be75a7c3905bf27581d02d5412fe5d13bb2 Binary files /dev/null and b/omnilmm/lib/python3.10/unittest/__pycache__/__init__.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/unittest/__pycache__/main.cpython-310.pyc b/omnilmm/lib/python3.10/unittest/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f9a8d54c75c586fac726e8f955b60542c91fb5 Binary files /dev/null and b/omnilmm/lib/python3.10/unittest/__pycache__/main.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/unittest/__pycache__/util.cpython-310.pyc b/omnilmm/lib/python3.10/unittest/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf1c5fd016b6f764433a6f8d580a4d0f067d2bfa Binary files /dev/null and b/omnilmm/lib/python3.10/unittest/__pycache__/util.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/xmlrpc/__init__.py b/omnilmm/lib/python3.10/xmlrpc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..196d3788575993eb403588b01ac6b0a3fbba13da --- /dev/null +++ b/omnilmm/lib/python3.10/xmlrpc/__init__.py @@ -0,0 +1 @@ +# This directory is a Python package. diff --git a/omnilmm/lib/python3.10/xmlrpc/__pycache__/__init__.cpython-310.pyc b/omnilmm/lib/python3.10/xmlrpc/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eb458fa3d4dca086ebfd40874da037f694a59e3 Binary files /dev/null and b/omnilmm/lib/python3.10/xmlrpc/__pycache__/__init__.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/xmlrpc/__pycache__/client.cpython-310.pyc b/omnilmm/lib/python3.10/xmlrpc/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc25a8ea8e7a193805c199370b6ccbf1bf5a02c0 Binary files /dev/null and b/omnilmm/lib/python3.10/xmlrpc/__pycache__/client.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/xmlrpc/__pycache__/server.cpython-310.pyc b/omnilmm/lib/python3.10/xmlrpc/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4df39112f40d39ebca6c1864acf6d523db8b800d Binary files /dev/null and b/omnilmm/lib/python3.10/xmlrpc/__pycache__/server.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/xmlrpc/client.py b/omnilmm/lib/python3.10/xmlrpc/client.py new file mode 100644 index 0000000000000000000000000000000000000000..a614cef6ab2f1a52b3ece45f9a3c2e6920802e15 --- /dev/null +++ b/omnilmm/lib/python3.10/xmlrpc/client.py @@ -0,0 +1,1532 @@ +# +# XML-RPC CLIENT LIBRARY +# $Id$ +# +# an XML-RPC client interface for Python. +# +# the marshalling and response parser code can also be used to +# implement XML-RPC servers. +# +# Notes: +# this version is designed to work with Python 2.1 or newer. +# +# History: +# 1999-01-14 fl Created +# 1999-01-15 fl Changed dateTime to use localtime +# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service +# 1999-01-19 fl Fixed array data element (from Skip Montanaro) +# 1999-01-21 fl Fixed dateTime constructor, etc. +# 1999-02-02 fl Added fault handling, handle empty sequences, etc. +# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro) +# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8) +# 2000-11-28 fl Changed boolean to check the truth value of its argument +# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches +# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1) +# 2001-03-28 fl Make sure response tuple is a singleton +# 2001-03-29 fl Don't require empty params element (from Nicholas Riley) +# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2) +# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod) +# 2001-09-03 fl Allow Transport subclass to override getparser +# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup) +# 2001-10-01 fl Remove containers from memo cache when done with them +# 2001-10-01 fl Use faster escape method (80% dumps speedup) +# 2001-10-02 fl More dumps microtuning +# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum) +# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow +# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems) +# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix) +# 2002-03-17 fl Avoid buffered read when possible (from James Rucker) +# 2002-04-07 fl Added pythondoc comments +# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers +# 2002-05-15 fl Added error constants (from Andrew Kuchling) +# 2002-06-27 fl Merged with Python CVS version +# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby) +# 2003-01-22 sm Add support for the bool type +# 2003-02-27 gvr Remove apply calls +# 2003-04-24 sm Use cStringIO if available +# 2003-04-25 ak Add support for nil +# 2003-06-15 gn Add support for time.struct_time +# 2003-07-12 gp Correct marshalling of Faults +# 2003-10-31 mvl Add multicall support +# 2004-08-20 mvl Bump minimum supported Python version to 2.1 +# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability +# +# Copyright (c) 1999-2002 by Secret Labs AB. +# Copyright (c) 1999-2002 by Fredrik Lundh. +# +# info@pythonware.com +# http://www.pythonware.com +# +# -------------------------------------------------------------------- +# The XML-RPC client interface is +# +# Copyright (c) 1999-2002 by Secret Labs AB +# Copyright (c) 1999-2002 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +""" +An XML-RPC client interface for Python. + +The marshalling and response parser code can also be used to +implement XML-RPC servers. + +Exported exceptions: + + Error Base class for client errors + ProtocolError Indicates an HTTP protocol error + ResponseError Indicates a broken response package + Fault Indicates an XML-RPC fault package + +Exported classes: + + ServerProxy Represents a logical connection to an XML-RPC server + + MultiCall Executor of boxcared xmlrpc requests + DateTime dateTime wrapper for an ISO 8601 string or time tuple or + localtime integer value to generate a "dateTime.iso8601" + XML-RPC value + Binary binary data wrapper + + Marshaller Generate an XML-RPC params chunk from a Python data structure + Unmarshaller Unmarshal an XML-RPC response from incoming XML event message + Transport Handles an HTTP transaction to an XML-RPC server + SafeTransport Handles an HTTPS transaction to an XML-RPC server + +Exported constants: + + (none) + +Exported functions: + + getparser Create instance of the fastest available parser & attach + to an unmarshalling object + dumps Convert an argument tuple or a Fault instance to an XML-RPC + request (or response, if the methodresponse option is used). + loads Convert an XML-RPC packet to unmarshalled data plus a method + name (None if not present). +""" + +import base64 +import sys +import time +from datetime import datetime +from decimal import Decimal +import http.client +import urllib.parse +from xml.parsers import expat +import errno +from io import BytesIO +try: + import gzip +except ImportError: + gzip = None #python can be built without zlib/gzip support + +# -------------------------------------------------------------------- +# Internal stuff + +def escape(s): + s = s.replace("&", "&") + s = s.replace("<", "<") + return s.replace(">", ">",) + +# used in User-Agent header sent +__version__ = '%d.%d' % sys.version_info[:2] + +# xmlrpc integer limits +MAXINT = 2**31-1 +MININT = -2**31 + +# -------------------------------------------------------------------- +# Error constants (from Dan Libby's specification at +# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php) + +# Ranges of errors +PARSE_ERROR = -32700 +SERVER_ERROR = -32600 +APPLICATION_ERROR = -32500 +SYSTEM_ERROR = -32400 +TRANSPORT_ERROR = -32300 + +# Specific errors +NOT_WELLFORMED_ERROR = -32700 +UNSUPPORTED_ENCODING = -32701 +INVALID_ENCODING_CHAR = -32702 +INVALID_XMLRPC = -32600 +METHOD_NOT_FOUND = -32601 +INVALID_METHOD_PARAMS = -32602 +INTERNAL_ERROR = -32603 + +# -------------------------------------------------------------------- +# Exceptions + +## +# Base class for all kinds of client-side errors. + +class Error(Exception): + """Base class for client errors.""" + __str__ = object.__str__ + +## +# Indicates an HTTP-level protocol error. This is raised by the HTTP +# transport layer, if the server returns an error code other than 200 +# (OK). +# +# @param url The target URL. +# @param errcode The HTTP error code. +# @param errmsg The HTTP error message. +# @param headers The HTTP header dictionary. + +class ProtocolError(Error): + """Indicates an HTTP protocol error.""" + def __init__(self, url, errcode, errmsg, headers): + Error.__init__(self) + self.url = url + self.errcode = errcode + self.errmsg = errmsg + self.headers = headers + def __repr__(self): + return ( + "<%s for %s: %s %s>" % + (self.__class__.__name__, self.url, self.errcode, self.errmsg) + ) + +## +# Indicates a broken XML-RPC response package. This exception is +# raised by the unmarshalling layer, if the XML-RPC response is +# malformed. + +class ResponseError(Error): + """Indicates a broken response package.""" + pass + +## +# Indicates an XML-RPC fault response package. This exception is +# raised by the unmarshalling layer, if the XML-RPC response contains +# a fault string. This exception can also be used as a class, to +# generate a fault XML-RPC message. +# +# @param faultCode The XML-RPC fault code. +# @param faultString The XML-RPC fault string. + +class Fault(Error): + """Indicates an XML-RPC fault package.""" + def __init__(self, faultCode, faultString, **extra): + Error.__init__(self) + self.faultCode = faultCode + self.faultString = faultString + def __repr__(self): + return "<%s %s: %r>" % (self.__class__.__name__, + self.faultCode, self.faultString) + +# -------------------------------------------------------------------- +# Special values + +## +# Backwards compatibility + +boolean = Boolean = bool + +## +# Wrapper for XML-RPC DateTime values. This converts a time value to +# the format used by XML-RPC. +#

+# The value can be given as a datetime object, as a string in the +# format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by +# time.localtime()), or an integer value (as returned by time.time()). +# The wrapper uses time.localtime() to convert an integer to a time +# tuple. +# +# @param value The time, given as a datetime object, an ISO 8601 string, +# a time tuple, or an integer time value. + + +# Issue #13305: different format codes across platforms +_day0 = datetime(1, 1, 1) +def _try(fmt): + try: + return _day0.strftime(fmt) == '0001' + except ValueError: + return False +if _try('%Y'): # Mac OS X + def _iso8601_format(value): + return value.strftime("%Y%m%dT%H:%M:%S") +elif _try('%4Y'): # Linux + def _iso8601_format(value): + return value.strftime("%4Y%m%dT%H:%M:%S") +else: + def _iso8601_format(value): + return value.strftime("%Y%m%dT%H:%M:%S").zfill(17) +del _day0 +del _try + + +def _strftime(value): + if isinstance(value, datetime): + return _iso8601_format(value) + + if not isinstance(value, (tuple, time.struct_time)): + if value == 0: + value = time.time() + value = time.localtime(value) + + return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] + +class DateTime: + """DateTime wrapper for an ISO 8601 string or time tuple or + localtime integer value to generate 'dateTime.iso8601' XML-RPC + value. + """ + + def __init__(self, value=0): + if isinstance(value, str): + self.value = value + else: + self.value = _strftime(value) + + def make_comparable(self, other): + if isinstance(other, DateTime): + s = self.value + o = other.value + elif isinstance(other, datetime): + s = self.value + o = _iso8601_format(other) + elif isinstance(other, str): + s = self.value + o = other + elif hasattr(other, "timetuple"): + s = self.timetuple() + o = other.timetuple() + else: + s = self + o = NotImplemented + return s, o + + def __lt__(self, other): + s, o = self.make_comparable(other) + if o is NotImplemented: + return NotImplemented + return s < o + + def __le__(self, other): + s, o = self.make_comparable(other) + if o is NotImplemented: + return NotImplemented + return s <= o + + def __gt__(self, other): + s, o = self.make_comparable(other) + if o is NotImplemented: + return NotImplemented + return s > o + + def __ge__(self, other): + s, o = self.make_comparable(other) + if o is NotImplemented: + return NotImplemented + return s >= o + + def __eq__(self, other): + s, o = self.make_comparable(other) + if o is NotImplemented: + return NotImplemented + return s == o + + def timetuple(self): + return time.strptime(self.value, "%Y%m%dT%H:%M:%S") + + ## + # Get date/time value. + # + # @return Date/time value, as an ISO 8601 string. + + def __str__(self): + return self.value + + def __repr__(self): + return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self)) + + def decode(self, data): + self.value = str(data).strip() + + def encode(self, out): + out.write("") + out.write(self.value) + out.write("\n") + +def _datetime(data): + # decode xml element contents into a DateTime structure. + value = DateTime() + value.decode(data) + return value + +def _datetime_type(data): + return datetime.strptime(data, "%Y%m%dT%H:%M:%S") + +## +# Wrapper for binary data. This can be used to transport any kind +# of binary data over XML-RPC, using BASE64 encoding. +# +# @param data An 8-bit string containing arbitrary data. + +class Binary: + """Wrapper for binary data.""" + + def __init__(self, data=None): + if data is None: + data = b"" + else: + if not isinstance(data, (bytes, bytearray)): + raise TypeError("expected bytes or bytearray, not %s" % + data.__class__.__name__) + data = bytes(data) # Make a copy of the bytes! + self.data = data + + ## + # Get buffer contents. + # + # @return Buffer contents, as an 8-bit string. + + def __str__(self): + return str(self.data, "latin-1") # XXX encoding?! + + def __eq__(self, other): + if isinstance(other, Binary): + other = other.data + return self.data == other + + def decode(self, data): + self.data = base64.decodebytes(data) + + def encode(self, out): + out.write("\n") + encoded = base64.encodebytes(self.data) + out.write(encoded.decode('ascii')) + out.write("\n") + +def _binary(data): + # decode xml element contents into a Binary structure + value = Binary() + value.decode(data) + return value + +WRAPPERS = (DateTime, Binary) + +# -------------------------------------------------------------------- +# XML parsers + +class ExpatParser: + # fast expat parser for Python 2.0 and later. + def __init__(self, target): + self._parser = parser = expat.ParserCreate(None, None) + self._target = target + parser.StartElementHandler = target.start + parser.EndElementHandler = target.end + parser.CharacterDataHandler = target.data + encoding = None + target.xml(encoding, None) + + def feed(self, data): + self._parser.Parse(data, False) + + def close(self): + try: + parser = self._parser + except AttributeError: + pass + else: + del self._target, self._parser # get rid of circular references + parser.Parse(b"", True) # end of data + +# -------------------------------------------------------------------- +# XML-RPC marshalling and unmarshalling code + +## +# XML-RPC marshaller. +# +# @param encoding Default encoding for 8-bit strings. The default +# value is None (interpreted as UTF-8). +# @see dumps + +class Marshaller: + """Generate an XML-RPC params chunk from a Python data structure. + + Create a Marshaller instance for each set of parameters, and use + the "dumps" method to convert your data (represented as a tuple) + to an XML-RPC params chunk. To write a fault response, pass a + Fault instance instead. You may prefer to use the "dumps" module + function for this purpose. + """ + + # by the way, if you don't understand what's going on in here, + # that's perfectly ok. + + def __init__(self, encoding=None, allow_none=False): + self.memo = {} + self.data = None + self.encoding = encoding + self.allow_none = allow_none + + dispatch = {} + + def dumps(self, values): + out = [] + write = out.append + dump = self.__dump + if isinstance(values, Fault): + # fault instance + write("\n") + dump({'faultCode': values.faultCode, + 'faultString': values.faultString}, + write) + write("\n") + else: + # parameter block + # FIXME: the xml-rpc specification allows us to leave out + # the entire block if there are no parameters. + # however, changing this may break older code (including + # old versions of xmlrpclib.py), so this is better left as + # is for now. See @XMLRPC3 for more information. /F + write("\n") + for v in values: + write("\n") + dump(v, write) + write("\n") + write("\n") + result = "".join(out) + return result + + def __dump(self, value, write): + try: + f = self.dispatch[type(value)] + except KeyError: + # check if this object can be marshalled as a structure + if not hasattr(value, '__dict__'): + raise TypeError("cannot marshal %s objects" % type(value)) + # check if this class is a sub-class of a basic type, + # because we don't know how to marshal these types + # (e.g. a string sub-class) + for type_ in type(value).__mro__: + if type_ in self.dispatch.keys(): + raise TypeError("cannot marshal %s objects" % type(value)) + # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix + # for the p3yk merge, this should probably be fixed more neatly. + f = self.dispatch["_arbitrary_instance"] + f(self, value, write) + + def dump_nil (self, value, write): + if not self.allow_none: + raise TypeError("cannot marshal None unless allow_none is enabled") + write("") + dispatch[type(None)] = dump_nil + + def dump_bool(self, value, write): + write("") + write(value and "1" or "0") + write("\n") + dispatch[bool] = dump_bool + + def dump_long(self, value, write): + if value > MAXINT or value < MININT: + raise OverflowError("int exceeds XML-RPC limits") + write("") + write(str(int(value))) + write("\n") + dispatch[int] = dump_long + + # backward compatible + dump_int = dump_long + + def dump_double(self, value, write): + write("") + write(repr(value)) + write("\n") + dispatch[float] = dump_double + + def dump_unicode(self, value, write, escape=escape): + write("") + write(escape(value)) + write("\n") + dispatch[str] = dump_unicode + + def dump_bytes(self, value, write): + write("\n") + encoded = base64.encodebytes(value) + write(encoded.decode('ascii')) + write("\n") + dispatch[bytes] = dump_bytes + dispatch[bytearray] = dump_bytes + + def dump_array(self, value, write): + i = id(value) + if i in self.memo: + raise TypeError("cannot marshal recursive sequences") + self.memo[i] = None + dump = self.__dump + write("\n") + for v in value: + dump(v, write) + write("\n") + del self.memo[i] + dispatch[tuple] = dump_array + dispatch[list] = dump_array + + def dump_struct(self, value, write, escape=escape): + i = id(value) + if i in self.memo: + raise TypeError("cannot marshal recursive dictionaries") + self.memo[i] = None + dump = self.__dump + write("\n") + for k, v in value.items(): + write("\n") + if not isinstance(k, str): + raise TypeError("dictionary key must be string") + write("%s\n" % escape(k)) + dump(v, write) + write("\n") + write("\n") + del self.memo[i] + dispatch[dict] = dump_struct + + def dump_datetime(self, value, write): + write("") + write(_strftime(value)) + write("\n") + dispatch[datetime] = dump_datetime + + def dump_instance(self, value, write): + # check for special wrappers + if value.__class__ in WRAPPERS: + self.write = write + value.encode(self) + del self.write + else: + # store instance attributes as a struct (really?) + self.dump_struct(value.__dict__, write) + dispatch[DateTime] = dump_instance + dispatch[Binary] = dump_instance + # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix + # for the p3yk merge, this should probably be fixed more neatly. + dispatch["_arbitrary_instance"] = dump_instance + +## +# XML-RPC unmarshaller. +# +# @see loads + +class Unmarshaller: + """Unmarshal an XML-RPC response, based on incoming XML event + messages (start, data, end). Call close() to get the resulting + data structure. + + Note that this reader is fairly tolerant, and gladly accepts bogus + XML-RPC data without complaining (but not bogus XML). + """ + + # and again, if you don't understand what's going on in here, + # that's perfectly ok. + + def __init__(self, use_datetime=False, use_builtin_types=False): + self._type = None + self._stack = [] + self._marks = [] + self._data = [] + self._value = False + self._methodname = None + self._encoding = "utf-8" + self.append = self._stack.append + self._use_datetime = use_builtin_types or use_datetime + self._use_bytes = use_builtin_types + + def close(self): + # return response tuple and target method + if self._type is None or self._marks: + raise ResponseError() + if self._type == "fault": + raise Fault(**self._stack[0]) + return tuple(self._stack) + + def getmethodname(self): + return self._methodname + + # + # event handlers + + def xml(self, encoding, standalone): + self._encoding = encoding + # FIXME: assert standalone == 1 ??? + + def start(self, tag, attrs): + # prepare to handle this element + if ':' in tag: + tag = tag.split(':')[-1] + if tag == "array" or tag == "struct": + self._marks.append(len(self._stack)) + self._data = [] + if self._value and tag not in self.dispatch: + raise ResponseError("unknown tag %r" % tag) + self._value = (tag == "value") + + def data(self, text): + self._data.append(text) + + def end(self, tag): + # call the appropriate end tag handler + try: + f = self.dispatch[tag] + except KeyError: + if ':' not in tag: + return # unknown tag ? + try: + f = self.dispatch[tag.split(':')[-1]] + except KeyError: + return # unknown tag ? + return f(self, "".join(self._data)) + + # + # accelerator support + + def end_dispatch(self, tag, data): + # dispatch data + try: + f = self.dispatch[tag] + except KeyError: + if ':' not in tag: + return # unknown tag ? + try: + f = self.dispatch[tag.split(':')[-1]] + except KeyError: + return # unknown tag ? + return f(self, data) + + # + # element decoders + + dispatch = {} + + def end_nil (self, data): + self.append(None) + self._value = 0 + dispatch["nil"] = end_nil + + def end_boolean(self, data): + if data == "0": + self.append(False) + elif data == "1": + self.append(True) + else: + raise TypeError("bad boolean value") + self._value = 0 + dispatch["boolean"] = end_boolean + + def end_int(self, data): + self.append(int(data)) + self._value = 0 + dispatch["i1"] = end_int + dispatch["i2"] = end_int + dispatch["i4"] = end_int + dispatch["i8"] = end_int + dispatch["int"] = end_int + dispatch["biginteger"] = end_int + + def end_double(self, data): + self.append(float(data)) + self._value = 0 + dispatch["double"] = end_double + dispatch["float"] = end_double + + def end_bigdecimal(self, data): + self.append(Decimal(data)) + self._value = 0 + dispatch["bigdecimal"] = end_bigdecimal + + def end_string(self, data): + if self._encoding: + data = data.decode(self._encoding) + self.append(data) + self._value = 0 + dispatch["string"] = end_string + dispatch["name"] = end_string # struct keys are always strings + + def end_array(self, data): + mark = self._marks.pop() + # map arrays to Python lists + self._stack[mark:] = [self._stack[mark:]] + self._value = 0 + dispatch["array"] = end_array + + def end_struct(self, data): + mark = self._marks.pop() + # map structs to Python dictionaries + dict = {} + items = self._stack[mark:] + for i in range(0, len(items), 2): + dict[items[i]] = items[i+1] + self._stack[mark:] = [dict] + self._value = 0 + dispatch["struct"] = end_struct + + def end_base64(self, data): + value = Binary() + value.decode(data.encode("ascii")) + if self._use_bytes: + value = value.data + self.append(value) + self._value = 0 + dispatch["base64"] = end_base64 + + def end_dateTime(self, data): + value = DateTime() + value.decode(data) + if self._use_datetime: + value = _datetime_type(data) + self.append(value) + dispatch["dateTime.iso8601"] = end_dateTime + + def end_value(self, data): + # if we stumble upon a value element with no internal + # elements, treat it as a string element + if self._value: + self.end_string(data) + dispatch["value"] = end_value + + def end_params(self, data): + self._type = "params" + dispatch["params"] = end_params + + def end_fault(self, data): + self._type = "fault" + dispatch["fault"] = end_fault + + def end_methodName(self, data): + if self._encoding: + data = data.decode(self._encoding) + self._methodname = data + self._type = "methodName" # no params + dispatch["methodName"] = end_methodName + +## Multicall support +# + +class _MultiCallMethod: + # some lesser magic to store calls made to a MultiCall object + # for batch execution + def __init__(self, call_list, name): + self.__call_list = call_list + self.__name = name + def __getattr__(self, name): + return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name)) + def __call__(self, *args): + self.__call_list.append((self.__name, args)) + +class MultiCallIterator: + """Iterates over the results of a multicall. Exceptions are + raised in response to xmlrpc faults.""" + + def __init__(self, results): + self.results = results + + def __getitem__(self, i): + item = self.results[i] + if type(item) == type({}): + raise Fault(item['faultCode'], item['faultString']) + elif type(item) == type([]): + return item[0] + else: + raise ValueError("unexpected type in multicall result") + +class MultiCall: + """server -> an object used to boxcar method calls + + server should be a ServerProxy object. + + Methods can be added to the MultiCall using normal + method call syntax e.g.: + + multicall = MultiCall(server_proxy) + multicall.add(2,3) + multicall.get_address("Guido") + + To execute the multicall, call the MultiCall object e.g.: + + add_result, address = multicall() + """ + + def __init__(self, server): + self.__server = server + self.__call_list = [] + + def __repr__(self): + return "<%s at %#x>" % (self.__class__.__name__, id(self)) + + def __getattr__(self, name): + return _MultiCallMethod(self.__call_list, name) + + def __call__(self): + marshalled_list = [] + for name, args in self.__call_list: + marshalled_list.append({'methodName' : name, 'params' : args}) + + return MultiCallIterator(self.__server.system.multicall(marshalled_list)) + +# -------------------------------------------------------------------- +# convenience functions + +FastMarshaller = FastParser = FastUnmarshaller = None + +## +# Create a parser object, and connect it to an unmarshalling instance. +# This function picks the fastest available XML parser. +# +# return A (parser, unmarshaller) tuple. + +def getparser(use_datetime=False, use_builtin_types=False): + """getparser() -> parser, unmarshaller + + Create an instance of the fastest available parser, and attach it + to an unmarshalling object. Return both objects. + """ + if FastParser and FastUnmarshaller: + if use_builtin_types: + mkdatetime = _datetime_type + mkbytes = base64.decodebytes + elif use_datetime: + mkdatetime = _datetime_type + mkbytes = _binary + else: + mkdatetime = _datetime + mkbytes = _binary + target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault) + parser = FastParser(target) + else: + target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types) + if FastParser: + parser = FastParser(target) + else: + parser = ExpatParser(target) + return parser, target + +## +# Convert a Python tuple or a Fault instance to an XML-RPC packet. +# +# @def dumps(params, **options) +# @param params A tuple or Fault instance. +# @keyparam methodname If given, create a methodCall request for +# this method name. +# @keyparam methodresponse If given, create a methodResponse packet. +# If used with a tuple, the tuple must be a singleton (that is, +# it must contain exactly one element). +# @keyparam encoding The packet encoding. +# @return A string containing marshalled data. + +def dumps(params, methodname=None, methodresponse=None, encoding=None, + allow_none=False): + """data [,options] -> marshalled data + + Convert an argument tuple or a Fault instance to an XML-RPC + request (or response, if the methodresponse option is used). + + In addition to the data object, the following options can be given + as keyword arguments: + + methodname: the method name for a methodCall packet + + methodresponse: true to create a methodResponse packet. + If this option is used with a tuple, the tuple must be + a singleton (i.e. it can contain only one element). + + encoding: the packet encoding (default is UTF-8) + + All byte strings in the data structure are assumed to use the + packet encoding. Unicode strings are automatically converted, + where necessary. + """ + + assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance" + if isinstance(params, Fault): + methodresponse = 1 + elif methodresponse and isinstance(params, tuple): + assert len(params) == 1, "response tuple must be a singleton" + + if not encoding: + encoding = "utf-8" + + if FastMarshaller: + m = FastMarshaller(encoding) + else: + m = Marshaller(encoding, allow_none) + + data = m.dumps(params) + + if encoding != "utf-8": + xmlheader = "\n" % str(encoding) + else: + xmlheader = "\n" # utf-8 is default + + # standard XML-RPC wrappings + if methodname: + # a method call + data = ( + xmlheader, + "\n" + "", methodname, "\n", + data, + "\n" + ) + elif methodresponse: + # a method response, or a fault structure + data = ( + xmlheader, + "\n", + data, + "\n" + ) + else: + return data # return as is + return "".join(data) + +## +# Convert an XML-RPC packet to a Python object. If the XML-RPC packet +# represents a fault condition, this function raises a Fault exception. +# +# @param data An XML-RPC packet, given as an 8-bit string. +# @return A tuple containing the unpacked data, and the method name +# (None if not present). +# @see Fault + +def loads(data, use_datetime=False, use_builtin_types=False): + """data -> unmarshalled data, method name + + Convert an XML-RPC packet to unmarshalled data plus a method + name (None if not present). + + If the XML-RPC packet represents a fault condition, this function + raises a Fault exception. + """ + p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types) + p.feed(data) + p.close() + return u.close(), u.getmethodname() + +## +# Encode a string using the gzip content encoding such as specified by the +# Content-Encoding: gzip +# in the HTTP header, as described in RFC 1952 +# +# @param data the unencoded data +# @return the encoded data + +def gzip_encode(data): + """data -> gzip encoded data + + Encode data using the gzip content encoding as described in RFC 1952 + """ + if not gzip: + raise NotImplementedError + f = BytesIO() + with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf: + gzf.write(data) + return f.getvalue() + +## +# Decode a string using the gzip content encoding such as specified by the +# Content-Encoding: gzip +# in the HTTP header, as described in RFC 1952 +# +# @param data The encoded data +# @keyparam max_decode Maximum bytes to decode (20 MiB default), use negative +# values for unlimited decoding +# @return the unencoded data +# @raises ValueError if data is not correctly coded. +# @raises ValueError if max gzipped payload length exceeded + +def gzip_decode(data, max_decode=20971520): + """gzip encoded data -> unencoded data + + Decode data using the gzip content encoding as described in RFC 1952 + """ + if not gzip: + raise NotImplementedError + with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf: + try: + if max_decode < 0: # no limit + decoded = gzf.read() + else: + decoded = gzf.read(max_decode + 1) + except OSError: + raise ValueError("invalid data") + if max_decode >= 0 and len(decoded) > max_decode: + raise ValueError("max gzipped payload length exceeded") + return decoded + +## +# Return a decoded file-like object for the gzip encoding +# as described in RFC 1952. +# +# @param response A stream supporting a read() method +# @return a file-like object that the decoded data can be read() from + +class GzipDecodedResponse(gzip.GzipFile if gzip else object): + """a file-like object to decode a response encoded with the gzip + method, as described in RFC 1952. + """ + def __init__(self, response): + #response doesn't support tell() and read(), required by + #GzipFile + if not gzip: + raise NotImplementedError + self.io = BytesIO(response.read()) + gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io) + + def close(self): + try: + gzip.GzipFile.close(self) + finally: + self.io.close() + + +# -------------------------------------------------------------------- +# request dispatcher + +class _Method: + # some magic to bind an XML-RPC method to an RPC server. + # supports "nested" methods (e.g. examples.getStateName) + def __init__(self, send, name): + self.__send = send + self.__name = name + def __getattr__(self, name): + return _Method(self.__send, "%s.%s" % (self.__name, name)) + def __call__(self, *args): + return self.__send(self.__name, args) + +## +# Standard transport class for XML-RPC over HTTP. +#

+# You can create custom transports by subclassing this method, and +# overriding selected methods. + +class Transport: + """Handles an HTTP transaction to an XML-RPC server.""" + + # client identifier (may be overridden) + user_agent = "Python-xmlrpc/%s" % __version__ + + #if true, we'll request gzip encoding + accept_gzip_encoding = True + + # if positive, encode request using gzip if it exceeds this threshold + # note that many servers will get confused, so only use it if you know + # that they can decode such a request + encode_threshold = None #None = don't encode + + def __init__(self, use_datetime=False, use_builtin_types=False, + *, headers=()): + self._use_datetime = use_datetime + self._use_builtin_types = use_builtin_types + self._connection = (None, None) + self._headers = list(headers) + self._extra_headers = [] + + ## + # Send a complete request, and parse the response. + # Retry request if a cached connection has disconnected. + # + # @param host Target host. + # @param handler Target PRC handler. + # @param request_body XML-RPC request body. + # @param verbose Debugging flag. + # @return Parsed response. + + def request(self, host, handler, request_body, verbose=False): + #retry request once if cached connection has gone cold + for i in (0, 1): + try: + return self.single_request(host, handler, request_body, verbose) + except http.client.RemoteDisconnected: + if i: + raise + except OSError as e: + if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, + errno.EPIPE): + raise + + def single_request(self, host, handler, request_body, verbose=False): + # issue XML-RPC request + try: + http_conn = self.send_request(host, handler, request_body, verbose) + resp = http_conn.getresponse() + if resp.status == 200: + self.verbose = verbose + return self.parse_response(resp) + + except Fault: + raise + except Exception: + #All unexpected errors leave connection in + # a strange state, so we clear it. + self.close() + raise + + #We got an error response. + #Discard any response data and raise exception + if resp.getheader("content-length", ""): + resp.read() + raise ProtocolError( + host + handler, + resp.status, resp.reason, + dict(resp.getheaders()) + ) + + + ## + # Create parser. + # + # @return A 2-tuple containing a parser and an unmarshaller. + + def getparser(self): + # get parser and unmarshaller + return getparser(use_datetime=self._use_datetime, + use_builtin_types=self._use_builtin_types) + + ## + # Get authorization info from host parameter + # Host may be a string, or a (host, x509-dict) tuple; if a string, + # it is checked for a "user:pw@host" format, and a "Basic + # Authentication" header is added if appropriate. + # + # @param host Host descriptor (URL or (URL, x509 info) tuple). + # @return A 3-tuple containing (actual host, extra headers, + # x509 info). The header and x509 fields may be None. + + def get_host_info(self, host): + + x509 = {} + if isinstance(host, tuple): + host, x509 = host + + auth, host = urllib.parse._splituser(host) + + if auth: + auth = urllib.parse.unquote_to_bytes(auth) + auth = base64.encodebytes(auth).decode("utf-8") + auth = "".join(auth.split()) # get rid of whitespace + extra_headers = [ + ("Authorization", "Basic " + auth) + ] + else: + extra_headers = [] + + return host, extra_headers, x509 + + ## + # Connect to server. + # + # @param host Target host. + # @return An HTTPConnection object + + def make_connection(self, host): + #return an existing connection if possible. This allows + #HTTP/1.1 keep-alive. + if self._connection and host == self._connection[0]: + return self._connection[1] + # create a HTTP connection object from a host descriptor + chost, self._extra_headers, x509 = self.get_host_info(host) + self._connection = host, http.client.HTTPConnection(chost) + return self._connection[1] + + ## + # Clear any cached connection object. + # Used in the event of socket errors. + # + def close(self): + host, connection = self._connection + if connection: + self._connection = (None, None) + connection.close() + + ## + # Send HTTP request. + # + # @param host Host descriptor (URL or (URL, x509 info) tuple). + # @param handler Target RPC handler (a path relative to host) + # @param request_body The XML-RPC request body + # @param debug Enable debugging if debug is true. + # @return An HTTPConnection. + + def send_request(self, host, handler, request_body, debug): + connection = self.make_connection(host) + headers = self._headers + self._extra_headers + if debug: + connection.set_debuglevel(1) + if self.accept_gzip_encoding and gzip: + connection.putrequest("POST", handler, skip_accept_encoding=True) + headers.append(("Accept-Encoding", "gzip")) + else: + connection.putrequest("POST", handler) + headers.append(("Content-Type", "text/xml")) + headers.append(("User-Agent", self.user_agent)) + self.send_headers(connection, headers) + self.send_content(connection, request_body) + return connection + + ## + # Send request headers. + # This function provides a useful hook for subclassing + # + # @param connection httpConnection. + # @param headers list of key,value pairs for HTTP headers + + def send_headers(self, connection, headers): + for key, val in headers: + connection.putheader(key, val) + + ## + # Send request body. + # This function provides a useful hook for subclassing + # + # @param connection httpConnection. + # @param request_body XML-RPC request body. + + def send_content(self, connection, request_body): + #optionally encode the request + if (self.encode_threshold is not None and + self.encode_threshold < len(request_body) and + gzip): + connection.putheader("Content-Encoding", "gzip") + request_body = gzip_encode(request_body) + + connection.putheader("Content-Length", str(len(request_body))) + connection.endheaders(request_body) + + ## + # Parse response. + # + # @param file Stream. + # @return Response tuple and target method. + + def parse_response(self, response): + # read response data from httpresponse, and parse it + # Check for new http response object, otherwise it is a file object. + if hasattr(response, 'getheader'): + if response.getheader("Content-Encoding", "") == "gzip": + stream = GzipDecodedResponse(response) + else: + stream = response + else: + stream = response + + p, u = self.getparser() + + while 1: + data = stream.read(1024) + if not data: + break + if self.verbose: + print("body:", repr(data)) + p.feed(data) + + if stream is not response: + stream.close() + p.close() + + return u.close() + +## +# Standard transport class for XML-RPC over HTTPS. + +class SafeTransport(Transport): + """Handles an HTTPS transaction to an XML-RPC server.""" + + def __init__(self, use_datetime=False, use_builtin_types=False, + *, headers=(), context=None): + super().__init__(use_datetime=use_datetime, + use_builtin_types=use_builtin_types, + headers=headers) + self.context = context + + # FIXME: mostly untested + + def make_connection(self, host): + if self._connection and host == self._connection[0]: + return self._connection[1] + + if not hasattr(http.client, "HTTPSConnection"): + raise NotImplementedError( + "your version of http.client doesn't support HTTPS") + # create a HTTPS connection object from a host descriptor + # host may be a string, or a (host, x509-dict) tuple + chost, self._extra_headers, x509 = self.get_host_info(host) + self._connection = host, http.client.HTTPSConnection(chost, + None, context=self.context, **(x509 or {})) + return self._connection[1] + +## +# Standard server proxy. This class establishes a virtual connection +# to an XML-RPC server. +#

+# This class is available as ServerProxy and Server. New code should +# use ServerProxy, to avoid confusion. +# +# @def ServerProxy(uri, **options) +# @param uri The connection point on the server. +# @keyparam transport A transport factory, compatible with the +# standard transport class. +# @keyparam encoding The default encoding used for 8-bit strings +# (default is UTF-8). +# @keyparam verbose Use a true value to enable debugging output. +# (printed to standard output). +# @see Transport + +class ServerProxy: + """uri [,options] -> a logical connection to an XML-RPC server + + uri is the connection point on the server, given as + scheme://host/target. + + The standard implementation always supports the "http" scheme. If + SSL socket support is available (Python 2.0), it also supports + "https". + + If the target part and the slash preceding it are both omitted, + "/RPC2" is assumed. + + The following options can be given as keyword arguments: + + transport: a transport factory + encoding: the request encoding (default is UTF-8) + + All 8-bit strings passed to the server proxy are assumed to use + the given encoding. + """ + + def __init__(self, uri, transport=None, encoding=None, verbose=False, + allow_none=False, use_datetime=False, use_builtin_types=False, + *, headers=(), context=None): + # establish a "logical" server connection + + # get the url + p = urllib.parse.urlsplit(uri) + if p.scheme not in ("http", "https"): + raise OSError("unsupported XML-RPC protocol") + self.__host = p.netloc + self.__handler = urllib.parse.urlunsplit(["", "", *p[2:]]) + if not self.__handler: + self.__handler = "/RPC2" + + if transport is None: + if p.scheme == "https": + handler = SafeTransport + extra_kwargs = {"context": context} + else: + handler = Transport + extra_kwargs = {} + transport = handler(use_datetime=use_datetime, + use_builtin_types=use_builtin_types, + headers=headers, + **extra_kwargs) + self.__transport = transport + + self.__encoding = encoding or 'utf-8' + self.__verbose = verbose + self.__allow_none = allow_none + + def __close(self): + self.__transport.close() + + def __request(self, methodname, params): + # call a method on the remote server + + request = dumps(params, methodname, encoding=self.__encoding, + allow_none=self.__allow_none).encode(self.__encoding, 'xmlcharrefreplace') + + response = self.__transport.request( + self.__host, + self.__handler, + request, + verbose=self.__verbose + ) + + if len(response) == 1: + response = response[0] + + return response + + def __repr__(self): + return ( + "<%s for %s%s>" % + (self.__class__.__name__, self.__host, self.__handler) + ) + + def __getattr__(self, name): + # magic method dispatcher + return _Method(self.__request, name) + + # note: to call a remote object with a non-standard name, use + # result getattr(server, "strange-python-name")(args) + + def __call__(self, attr): + """A workaround to get special attributes on the ServerProxy + without interfering with the magic __getattr__ + """ + if attr == "close": + return self.__close + elif attr == "transport": + return self.__transport + raise AttributeError("Attribute %r not found" % (attr,)) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.__close() + +# compatibility + +Server = ServerProxy + +# -------------------------------------------------------------------- +# test code + +if __name__ == "__main__": + + # simple test program (from the XML-RPC specification) + + # local server, available from Lib/xmlrpc/server.py + server = ServerProxy("http://localhost:8000") + + try: + print(server.currentTime.getCurrentTime()) + except Error as v: + print("ERROR", v) + + multi = MultiCall(server) + multi.getData() + multi.pow(2,9) + multi.add(1,2) + try: + for response in multi(): + print(response) + except Error as v: + print("ERROR", v) diff --git a/omnilmm/lib/python3.10/xmlrpc/server.py b/omnilmm/lib/python3.10/xmlrpc/server.py new file mode 100644 index 0000000000000000000000000000000000000000..69a260f5b12c079813d9760d45e1dff689527861 --- /dev/null +++ b/omnilmm/lib/python3.10/xmlrpc/server.py @@ -0,0 +1,993 @@ +r"""XML-RPC Servers. + +This module can be used to create simple XML-RPC servers +by creating a server and either installing functions, a +class instance, or by extending the SimpleXMLRPCServer +class. + +It can also be used to handle XML-RPC requests in a CGI +environment using CGIXMLRPCRequestHandler. + +The Doc* classes can be used to create XML-RPC servers that +serve pydoc-style documentation in response to HTTP +GET requests. This documentation is dynamically generated +based on the functions and methods registered with the +server. + +A list of possible usage patterns follows: + +1. Install functions: + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_function(pow) +server.register_function(lambda x,y: x+y, 'add') +server.serve_forever() + +2. Install an instance: + +class MyFuncs: + def __init__(self): + # make all of the sys functions available through sys.func_name + import sys + self.sys = sys + def _listMethods(self): + # implement this method so that system.listMethods + # knows to advertise the sys methods + return list_public_methods(self) + \ + ['sys.' + method for method in list_public_methods(self.sys)] + def pow(self, x, y): return pow(x, y) + def add(self, x, y) : return x + y + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_introspection_functions() +server.register_instance(MyFuncs()) +server.serve_forever() + +3. Install an instance with custom dispatch method: + +class Math: + def _listMethods(self): + # this method must be present for system.listMethods + # to work + return ['add', 'pow'] + def _methodHelp(self, method): + # this method must be present for system.methodHelp + # to work + if method == 'add': + return "add(2,3) => 5" + elif method == 'pow': + return "pow(x, y[, z]) => number" + else: + # By convention, return empty + # string if no help is available + return "" + def _dispatch(self, method, params): + if method == 'pow': + return pow(*params) + elif method == 'add': + return params[0] + params[1] + else: + raise ValueError('bad method') + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_introspection_functions() +server.register_instance(Math()) +server.serve_forever() + +4. Subclass SimpleXMLRPCServer: + +class MathServer(SimpleXMLRPCServer): + def _dispatch(self, method, params): + try: + # We are forcing the 'export_' prefix on methods that are + # callable through XML-RPC to prevent potential security + # problems + func = getattr(self, 'export_' + method) + except AttributeError: + raise Exception('method "%s" is not supported' % method) + else: + return func(*params) + + def export_add(self, x, y): + return x + y + +server = MathServer(("localhost", 8000)) +server.serve_forever() + +5. CGI script: + +server = CGIXMLRPCRequestHandler() +server.register_function(pow) +server.handle_request() +""" + +# Written by Brian Quinlan (brian@sweetapp.com). +# Based on code written by Fredrik Lundh. + +from xmlrpc.client import Fault, dumps, loads, gzip_encode, gzip_decode +from http.server import BaseHTTPRequestHandler +from functools import partial +from inspect import signature +import html +import http.server +import socketserver +import sys +import os +import re +import pydoc +import traceback +try: + import fcntl +except ImportError: + fcntl = None + +def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): + """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d + + Resolves a dotted attribute name to an object. Raises + an AttributeError if any attribute in the chain starts with a '_'. + + If the optional allow_dotted_names argument is false, dots are not + supported and this function operates similar to getattr(obj, attr). + """ + + if allow_dotted_names: + attrs = attr.split('.') + else: + attrs = [attr] + + for i in attrs: + if i.startswith('_'): + raise AttributeError( + 'attempt to access private attribute "%s"' % i + ) + else: + obj = getattr(obj,i) + return obj + +def list_public_methods(obj): + """Returns a list of attribute strings, found in the specified + object, which represent callable attributes""" + + return [member for member in dir(obj) + if not member.startswith('_') and + callable(getattr(obj, member))] + +class SimpleXMLRPCDispatcher: + """Mix-in class that dispatches XML-RPC requests. + + This class is used to register XML-RPC method handlers + and then to dispatch them. This class doesn't need to be + instanced directly when used by SimpleXMLRPCServer but it + can be instanced when used by the MultiPathXMLRPCServer + """ + + def __init__(self, allow_none=False, encoding=None, + use_builtin_types=False): + self.funcs = {} + self.instance = None + self.allow_none = allow_none + self.encoding = encoding or 'utf-8' + self.use_builtin_types = use_builtin_types + + def register_instance(self, instance, allow_dotted_names=False): + """Registers an instance to respond to XML-RPC requests. + + Only one instance can be installed at a time. + + If the registered instance has a _dispatch method then that + method will be called with the name of the XML-RPC method and + its parameters as a tuple + e.g. instance._dispatch('add',(2,3)) + + If the registered instance does not have a _dispatch method + then the instance will be searched to find a matching method + and, if found, will be called. Methods beginning with an '_' + are considered private and will not be called by + SimpleXMLRPCServer. + + If a registered function matches an XML-RPC request, then it + will be called instead of the registered instance. + + If the optional allow_dotted_names argument is true and the + instance does not have a _dispatch method, method names + containing dots are supported and resolved, as long as none of + the name segments start with an '_'. + + *** SECURITY WARNING: *** + + Enabling the allow_dotted_names options allows intruders + to access your module's global variables and may allow + intruders to execute arbitrary code on your machine. Only + use this option on a secure, closed network. + + """ + + self.instance = instance + self.allow_dotted_names = allow_dotted_names + + def register_function(self, function=None, name=None): + """Registers a function to respond to XML-RPC requests. + + The optional name argument can be used to set a Unicode name + for the function. + """ + # decorator factory + if function is None: + return partial(self.register_function, name=name) + + if name is None: + name = function.__name__ + self.funcs[name] = function + + return function + + def register_introspection_functions(self): + """Registers the XML-RPC introspection methods in the system + namespace. + + see http://xmlrpc.usefulinc.com/doc/reserved.html + """ + + self.funcs.update({'system.listMethods' : self.system_listMethods, + 'system.methodSignature' : self.system_methodSignature, + 'system.methodHelp' : self.system_methodHelp}) + + def register_multicall_functions(self): + """Registers the XML-RPC multicall method in the system + namespace. + + see http://www.xmlrpc.com/discuss/msgReader$1208""" + + self.funcs.update({'system.multicall' : self.system_multicall}) + + def _marshaled_dispatch(self, data, dispatch_method = None, path = None): + """Dispatches an XML-RPC method from marshalled (XML) data. + + XML-RPC methods are dispatched from the marshalled (XML) data + using the _dispatch method and the result is returned as + marshalled data. For backwards compatibility, a dispatch + function can be provided as an argument (see comment in + SimpleXMLRPCRequestHandler.do_POST) but overriding the + existing method through subclassing is the preferred means + of changing method dispatch behavior. + """ + + try: + params, method = loads(data, use_builtin_types=self.use_builtin_types) + + # generate response + if dispatch_method is not None: + response = dispatch_method(method, params) + else: + response = self._dispatch(method, params) + # wrap response in a singleton tuple + response = (response,) + response = dumps(response, methodresponse=1, + allow_none=self.allow_none, encoding=self.encoding) + except Fault as fault: + response = dumps(fault, allow_none=self.allow_none, + encoding=self.encoding) + except: + # report exception back to server + exc_type, exc_value, exc_tb = sys.exc_info() + try: + response = dumps( + Fault(1, "%s:%s" % (exc_type, exc_value)), + encoding=self.encoding, allow_none=self.allow_none, + ) + finally: + # Break reference cycle + exc_type = exc_value = exc_tb = None + + return response.encode(self.encoding, 'xmlcharrefreplace') + + def system_listMethods(self): + """system.listMethods() => ['add', 'subtract', 'multiple'] + + Returns a list of the methods supported by the server.""" + + methods = set(self.funcs.keys()) + if self.instance is not None: + # Instance can implement _listMethod to return a list of + # methods + if hasattr(self.instance, '_listMethods'): + methods |= set(self.instance._listMethods()) + # if the instance has a _dispatch method then we + # don't have enough information to provide a list + # of methods + elif not hasattr(self.instance, '_dispatch'): + methods |= set(list_public_methods(self.instance)) + return sorted(methods) + + def system_methodSignature(self, method_name): + """system.methodSignature('add') => [double, int, int] + + Returns a list describing the signature of the method. In the + above example, the add method takes two integers as arguments + and returns a double result. + + This server does NOT support system.methodSignature.""" + + # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html + + return 'signatures not supported' + + def system_methodHelp(self, method_name): + """system.methodHelp('add') => "Adds two integers together" + + Returns a string containing documentation for the specified method.""" + + method = None + if method_name in self.funcs: + method = self.funcs[method_name] + elif self.instance is not None: + # Instance can implement _methodHelp to return help for a method + if hasattr(self.instance, '_methodHelp'): + return self.instance._methodHelp(method_name) + # if the instance has a _dispatch method then we + # don't have enough information to provide help + elif not hasattr(self.instance, '_dispatch'): + try: + method = resolve_dotted_attribute( + self.instance, + method_name, + self.allow_dotted_names + ) + except AttributeError: + pass + + # Note that we aren't checking that the method actually + # be a callable object of some kind + if method is None: + return "" + else: + return pydoc.getdoc(method) + + def system_multicall(self, call_list): + """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ +[[4], ...] + + Allows the caller to package multiple XML-RPC calls into a single + request. + + See http://www.xmlrpc.com/discuss/msgReader$1208 + """ + + results = [] + for call in call_list: + method_name = call['methodName'] + params = call['params'] + + try: + # XXX A marshalling error in any response will fail the entire + # multicall. If someone cares they should fix this. + results.append([self._dispatch(method_name, params)]) + except Fault as fault: + results.append( + {'faultCode' : fault.faultCode, + 'faultString' : fault.faultString} + ) + except: + exc_type, exc_value, exc_tb = sys.exc_info() + try: + results.append( + {'faultCode' : 1, + 'faultString' : "%s:%s" % (exc_type, exc_value)} + ) + finally: + # Break reference cycle + exc_type = exc_value = exc_tb = None + return results + + def _dispatch(self, method, params): + """Dispatches the XML-RPC method. + + XML-RPC calls are forwarded to a registered function that + matches the called XML-RPC method name. If no such function + exists then the call is forwarded to the registered instance, + if available. + + If the registered instance has a _dispatch method then that + method will be called with the name of the XML-RPC method and + its parameters as a tuple + e.g. instance._dispatch('add',(2,3)) + + If the registered instance does not have a _dispatch method + then the instance will be searched to find a matching method + and, if found, will be called. + + Methods beginning with an '_' are considered private and will + not be called. + """ + + try: + # call the matching registered function + func = self.funcs[method] + except KeyError: + pass + else: + if func is not None: + return func(*params) + raise Exception('method "%s" is not supported' % method) + + if self.instance is not None: + if hasattr(self.instance, '_dispatch'): + # call the `_dispatch` method on the instance + return self.instance._dispatch(method, params) + + # call the instance's method directly + try: + func = resolve_dotted_attribute( + self.instance, + method, + self.allow_dotted_names + ) + except AttributeError: + pass + else: + if func is not None: + return func(*params) + + raise Exception('method "%s" is not supported' % method) + +class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler): + """Simple XML-RPC request handler class. + + Handles all HTTP POST requests and attempts to decode them as + XML-RPC requests. + """ + + # Class attribute listing the accessible path components; + # paths not on this list will result in a 404 error. + rpc_paths = ('/', '/RPC2') + + #if not None, encode responses larger than this, if possible + encode_threshold = 1400 #a common MTU + + #Override form StreamRequestHandler: full buffering of output + #and no Nagle. + wbufsize = -1 + disable_nagle_algorithm = True + + # a re to match a gzip Accept-Encoding + aepattern = re.compile(r""" + \s* ([^\s;]+) \s* #content-coding + (;\s* q \s*=\s* ([0-9\.]+))? #q + """, re.VERBOSE | re.IGNORECASE) + + def accept_encodings(self): + r = {} + ae = self.headers.get("Accept-Encoding", "") + for e in ae.split(","): + match = self.aepattern.match(e) + if match: + v = match.group(3) + v = float(v) if v else 1.0 + r[match.group(1)] = v + return r + + def is_rpc_path_valid(self): + if self.rpc_paths: + return self.path in self.rpc_paths + else: + # If .rpc_paths is empty, just assume all paths are legal + return True + + def do_POST(self): + """Handles the HTTP POST request. + + Attempts to interpret all HTTP POST requests as XML-RPC calls, + which are forwarded to the server's _dispatch method for handling. + """ + + # Check that the path is legal + if not self.is_rpc_path_valid(): + self.report_404() + return + + try: + # Get arguments by reading body of request. + # We read this in chunks to avoid straining + # socket.read(); around the 10 or 15Mb mark, some platforms + # begin to have problems (bug #792570). + max_chunk_size = 10*1024*1024 + size_remaining = int(self.headers["content-length"]) + L = [] + while size_remaining: + chunk_size = min(size_remaining, max_chunk_size) + chunk = self.rfile.read(chunk_size) + if not chunk: + break + L.append(chunk) + size_remaining -= len(L[-1]) + data = b''.join(L) + + data = self.decode_request_content(data) + if data is None: + return #response has been sent + + # In previous versions of SimpleXMLRPCServer, _dispatch + # could be overridden in this class, instead of in + # SimpleXMLRPCDispatcher. To maintain backwards compatibility, + # check to see if a subclass implements _dispatch and dispatch + # using that method if present. + response = self.server._marshaled_dispatch( + data, getattr(self, '_dispatch', None), self.path + ) + except Exception as e: # This should only happen if the module is buggy + # internal error, report as HTTP server error + self.send_response(500) + + # Send information about the exception if requested + if hasattr(self.server, '_send_traceback_header') and \ + self.server._send_traceback_header: + self.send_header("X-exception", str(e)) + trace = traceback.format_exc() + trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII') + self.send_header("X-traceback", trace) + + self.send_header("Content-length", "0") + self.end_headers() + else: + self.send_response(200) + self.send_header("Content-type", "text/xml") + if self.encode_threshold is not None: + if len(response) > self.encode_threshold: + q = self.accept_encodings().get("gzip", 0) + if q: + try: + response = gzip_encode(response) + self.send_header("Content-Encoding", "gzip") + except NotImplementedError: + pass + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + def decode_request_content(self, data): + #support gzip encoding of request + encoding = self.headers.get("content-encoding", "identity").lower() + if encoding == "identity": + return data + if encoding == "gzip": + try: + return gzip_decode(data) + except NotImplementedError: + self.send_response(501, "encoding %r not supported" % encoding) + except ValueError: + self.send_response(400, "error decoding gzip content") + else: + self.send_response(501, "encoding %r not supported" % encoding) + self.send_header("Content-length", "0") + self.end_headers() + + def report_404 (self): + # Report a 404 error + self.send_response(404) + response = b'No such page' + self.send_header("Content-type", "text/plain") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + def log_request(self, code='-', size='-'): + """Selectively log an accepted request.""" + + if self.server.logRequests: + BaseHTTPRequestHandler.log_request(self, code, size) + +class SimpleXMLRPCServer(socketserver.TCPServer, + SimpleXMLRPCDispatcher): + """Simple XML-RPC server. + + Simple XML-RPC server that allows functions and a single instance + to be installed to handle requests. The default implementation + attempts to dispatch XML-RPC calls to the functions or instance + installed in the server. Override the _dispatch method inherited + from SimpleXMLRPCDispatcher to change this behavior. + """ + + allow_reuse_address = True + + # Warning: this is for debugging purposes only! Never set this to True in + # production code, as will be sending out sensitive information (exception + # and stack trace details) when exceptions are raised inside + # SimpleXMLRPCRequestHandler.do_POST + _send_traceback_header = False + + def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + self.logRequests = logRequests + + SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) + socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) + + +class MultiPathXMLRPCServer(SimpleXMLRPCServer): + """Multipath XML-RPC Server + This specialization of SimpleXMLRPCServer allows the user to create + multiple Dispatcher instances and assign them to different + HTTP request paths. This makes it possible to run two or more + 'virtual XML-RPC servers' at the same port. + Make sure that the requestHandler accepts the paths in question. + """ + def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + + SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none, + encoding, bind_and_activate, use_builtin_types) + self.dispatchers = {} + self.allow_none = allow_none + self.encoding = encoding or 'utf-8' + + def add_dispatcher(self, path, dispatcher): + self.dispatchers[path] = dispatcher + return dispatcher + + def get_dispatcher(self, path): + return self.dispatchers[path] + + def _marshaled_dispatch(self, data, dispatch_method = None, path = None): + try: + response = self.dispatchers[path]._marshaled_dispatch( + data, dispatch_method, path) + except: + # report low level exception back to server + # (each dispatcher should have handled their own + # exceptions) + exc_type, exc_value = sys.exc_info()[:2] + try: + response = dumps( + Fault(1, "%s:%s" % (exc_type, exc_value)), + encoding=self.encoding, allow_none=self.allow_none) + response = response.encode(self.encoding, 'xmlcharrefreplace') + finally: + # Break reference cycle + exc_type = exc_value = None + return response + +class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): + """Simple handler for XML-RPC data passed through CGI.""" + + def __init__(self, allow_none=False, encoding=None, use_builtin_types=False): + SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) + + def handle_xmlrpc(self, request_text): + """Handle a single XML-RPC request""" + + response = self._marshaled_dispatch(request_text) + + print('Content-Type: text/xml') + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def handle_get(self): + """Handle a single HTTP GET request. + + Default implementation indicates an error because + XML-RPC uses the POST method. + """ + + code = 400 + message, explain = BaseHTTPRequestHandler.responses[code] + + response = http.server.DEFAULT_ERROR_MESSAGE % \ + { + 'code' : code, + 'message' : message, + 'explain' : explain + } + response = response.encode('utf-8') + print('Status: %d %s' % (code, message)) + print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE) + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def handle_request(self, request_text=None): + """Handle a single XML-RPC request passed through a CGI post method. + + If no XML data is given then it is read from stdin. The resulting + XML-RPC response is printed to stdout along with the correct HTTP + headers. + """ + + if request_text is None and \ + os.environ.get('REQUEST_METHOD', None) == 'GET': + self.handle_get() + else: + # POST data is normally available through stdin + try: + length = int(os.environ.get('CONTENT_LENGTH', None)) + except (ValueError, TypeError): + length = -1 + if request_text is None: + request_text = sys.stdin.read(length) + + self.handle_xmlrpc(request_text) + + +# ----------------------------------------------------------------------------- +# Self documenting XML-RPC Server. + +class ServerHTMLDoc(pydoc.HTMLDoc): + """Class used to generate pydoc HTML document for a server""" + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + + # XXX Note that this regular expression does not allow for the + # hyperlinking of arbitrary strings being used as method + # names. Only methods with names consisting of word characters + # and '.'s are hyperlinked. + pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?((?:\w|\.)+))\b') + while 1: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('%s' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('%s' % (url, escape(all))) + elif pep: + url = 'https://www.python.org/dev/peps/pep-%04d/' % int(pep) + results.append('%s' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.%s' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return ''.join(results) + + def docroutine(self, object, name, mod=None, + funcs={}, classes={}, methods={}, cl=None): + """Produce HTML documentation for a function or method object.""" + + anchor = (cl and cl.__name__ or '') + '-' + name + note = '' + + title = '%s' % ( + self.escape(anchor), self.escape(name)) + + if callable(object): + argspec = str(signature(object)) + else: + argspec = '(...)' + + if isinstance(object, tuple): + argspec = object[0] or argspec + docstring = object[1] or "" + else: + docstring = pydoc.getdoc(object) + + decl = title + argspec + (note and self.grey( + '%s' % note)) + + doc = self.markup( + docstring, self.preformat, funcs, classes, methods) + doc = doc and '

%s
' % doc + return '
%s
%s
\n' % (decl, doc) + + def docserver(self, server_name, package_documentation, methods): + """Produce HTML documentation for an XML-RPC server.""" + + fdict = {} + for key, value in methods.items(): + fdict[key] = '#-' + key + fdict[value] = fdict[key] + + server_name = self.escape(server_name) + head = '%s' % server_name + result = self.heading(head, '#ffffff', '#7799ee') + + doc = self.markup(package_documentation, self.preformat, fdict) + doc = doc and '%s' % doc + result = result + '

%s

\n' % doc + + contents = [] + method_items = sorted(methods.items()) + for key, value in method_items: + contents.append(self.docroutine(value, key, funcs=fdict)) + result = result + self.bigsection( + 'Methods', '#ffffff', '#eeaa77', ''.join(contents)) + + return result + +class XMLRPCDocGenerator: + """Generates documentation for an XML-RPC server. + + This class is designed as mix-in and should not + be constructed directly. + """ + + def __init__(self): + # setup variables used for HTML documentation + self.server_name = 'XML-RPC Server Documentation' + self.server_documentation = \ + "This server exports the following methods through the XML-RPC "\ + "protocol." + self.server_title = 'XML-RPC Server Documentation' + + def set_server_title(self, server_title): + """Set the HTML title of the generated server documentation""" + + self.server_title = server_title + + def set_server_name(self, server_name): + """Set the name of the generated HTML server documentation""" + + self.server_name = server_name + + def set_server_documentation(self, server_documentation): + """Set the documentation string for the entire server.""" + + self.server_documentation = server_documentation + + def generate_html_documentation(self): + """generate_html_documentation() => html documentation for the server + + Generates HTML documentation for the server using introspection for + installed functions and instances that do not implement the + _dispatch method. Alternatively, instances can choose to implement + the _get_method_argstring(method_name) method to provide the + argument string used in the documentation and the + _methodHelp(method_name) method to provide the help text used + in the documentation.""" + + methods = {} + + for method_name in self.system_listMethods(): + if method_name in self.funcs: + method = self.funcs[method_name] + elif self.instance is not None: + method_info = [None, None] # argspec, documentation + if hasattr(self.instance, '_get_method_argstring'): + method_info[0] = self.instance._get_method_argstring(method_name) + if hasattr(self.instance, '_methodHelp'): + method_info[1] = self.instance._methodHelp(method_name) + + method_info = tuple(method_info) + if method_info != (None, None): + method = method_info + elif not hasattr(self.instance, '_dispatch'): + try: + method = resolve_dotted_attribute( + self.instance, + method_name + ) + except AttributeError: + method = method_info + else: + method = method_info + else: + assert 0, "Could not find method in self.functions and no "\ + "instance installed" + + methods[method_name] = method + + documenter = ServerHTMLDoc() + documentation = documenter.docserver( + self.server_name, + self.server_documentation, + methods + ) + + return documenter.page(html.escape(self.server_title), documentation) + +class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + """XML-RPC and documentation request handler class. + + Handles all HTTP POST requests and attempts to decode them as + XML-RPC requests. + + Handles all HTTP GET requests and interprets them as requests + for documentation. + """ + + def do_GET(self): + """Handles the HTTP GET request. + + Interpret all HTTP GET requests as requests for server + documentation. + """ + # Check that the path is legal + if not self.is_rpc_path_valid(): + self.report_404() + return + + response = self.server.generate_html_documentation().encode('utf-8') + self.send_response(200) + self.send_header("Content-type", "text/html") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + +class DocXMLRPCServer( SimpleXMLRPCServer, + XMLRPCDocGenerator): + """XML-RPC and HTML documentation server. + + Adds the ability to serve server documentation to the capabilities + of SimpleXMLRPCServer. + """ + + def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, + allow_none, encoding, bind_and_activate, + use_builtin_types) + XMLRPCDocGenerator.__init__(self) + +class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler, + XMLRPCDocGenerator): + """Handler for XML-RPC data and documentation requests passed through + CGI""" + + def handle_get(self): + """Handles the HTTP GET request. + + Interpret all HTTP GET requests as requests for server + documentation. + """ + + response = self.generate_html_documentation().encode('utf-8') + + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def __init__(self): + CGIXMLRPCRequestHandler.__init__(self) + XMLRPCDocGenerator.__init__(self) + + +if __name__ == '__main__': + import datetime + + class ExampleService: + def getData(self): + return '42' + + class currentTime: + @staticmethod + def getCurrentTime(): + return datetime.datetime.now() + + with SimpleXMLRPCServer(("localhost", 8000)) as server: + server.register_function(pow) + server.register_function(lambda x,y: x+y, 'add') + server.register_instance(ExampleService(), allow_dotted_names=True) + server.register_multicall_functions() + print('Serving XML-RPC on localhost port 8000') + print('It is advisable to run this example server within a secure, closed network.') + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nKeyboard interrupt received, exiting.") + sys.exit(0)