diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/AUTHORS b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..05892fb77ea973118f89bf36efcc360f24148a73 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/AUTHORS @@ -0,0 +1,62 @@ +Gevent is written and maintained by + + Denis Bilenko + Matt Iversen + Steffen Prince + Jason Madden + +and the contributors (ordered by the date of first contribution): + + Jason Toffaletti + Mike Barton + Ludvig Ericson + Marcus Cavanaugh + Matt Goodall + Ralf Schmitt + Daniele Varrazzo + Nicholas Piël + Örjan Persson + Uriel Katz + Ted Suzman + Randall Leeds + Erik Näslund + Alexey Borzenkov + David Hain + Dmitry Chechik + Ned Rockson + Tommie Gannert + Shaun Lindsay + Andreas Blixt + Nick Barkas + Galfy Pundee + Alexander Boudkar + Damien Churchill + Tom Lynn + Shaun Cutts + David LaBissoniere + Alexandre Kandalintsev + Geert Jansen + Vitaly Kruglikov + Saúl Ibarra Corretgé + Oliver Beattie + Bobby Powers + Anton Patrushev + Jan-Philip Gehrcke + Alex Gaynor + 陈小玉 + Philip Conrad + Heungsub Lee + Ron Rothman + + See https://github.com/gevent/gevent/graphs/contributors for more info. + +Gevent is inspired by and uses some code from eventlet which was written by + + Bob Ipollito + Donovan Preston + +The win32util module is taken from Twisted. The tblib module is taken from python-tblib by Ionel Cristian Mărieș. + +Some modules (local, ssl) contain code from the Python standard library. + +If your code is used in gevent and you are not mentioned above, please contact the maintainer. diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/INSTALLER b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/LICENSE b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b767c2450217ee321178d99fcdd48faad0eaeab7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Except when otherwise stated (look at the beginning of each file) the software +and the documentation in this project are copyrighted by: + + Denis Bilenko and the contributors, http://www.gevent.org + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/METADATA b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..62e6cfc1139a9a1bc96eeb1603b8eaefd898bc9f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/METADATA @@ -0,0 +1,349 @@ +Metadata-Version: 2.1 +Name: gevent +Version: 24.11.1 +Summary: Coroutine-based network library +Home-page: http://www.gevent.org/ +Author: Denis Bilenko +Author-email: denis.bilenko@gmail.com +Maintainer: Jason Madden +Maintainer-email: jason@nextthought.com +License: MIT +Project-URL: Bug Tracker, https://github.com/gevent/gevent/issues +Project-URL: Source Code, https://github.com/gevent/gevent/ +Project-URL: Documentation, http://www.gevent.org +Project-URL: Changes, https://www.gevent.org/changelog.html +Keywords: greenlet coroutine cooperative multitasking light threads monkey +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Intended Audience :: Developers +Classifier: Development Status :: 4 - Beta +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: NOTICE +License-File: AUTHORS +Requires-Dist: zope.event +Requires-Dist: zope.interface +Requires-Dist: greenlet>=3.1.1; platform_python_implementation == "CPython" +Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and sys_platform == "win32" +Provides-Extra: dnspython +Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "dnspython" +Requires-Dist: idna; python_version < "3.10" and extra == "dnspython" +Provides-Extra: docs +Requires-Dist: sphinx; extra == "docs" +Requires-Dist: furo; extra == "docs" +Requires-Dist: repoze.sphinx.autointerface; extra == "docs" +Requires-Dist: sphinxcontrib-programoutput; extra == "docs" +Requires-Dist: zope.schema; extra == "docs" +Provides-Extra: events +Provides-Extra: monitor +Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "monitor" +Provides-Extra: recommended +Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and extra == "recommended" +Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "recommended" +Requires-Dist: idna; python_version < "3.10" and extra == "recommended" +Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "recommended" +Provides-Extra: test +Requires-Dist: requests; extra == "test" +Requires-Dist: objgraph; extra == "test" +Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and extra == "test" +Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "test" +Requires-Dist: idna; python_version < "3.10" and extra == "test" +Requires-Dist: coverage>=5.0; sys_platform != "win32" and extra == "test" +Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "test" + +======== + gevent +======== + +.. image:: https://github.com/gevent/gevent/workflows/gevent%20testing/badge.svg + :target: https://github.com/gevent/gevent/actions + +.. image:: https://ci.appveyor.com/api/projects/status/bqxl88yhpho223jg?svg=true + :target: https://ci.appveyor.com/project/denik/gevent + +.. image:: https://coveralls.io/repos/gevent/gevent/badge.svg?branch=master&service=github + :target: https://coveralls.io/github/gevent/gevent?branch=master + +.. + This file is included in README.rst from the top-level + so it is limited to pure ReST markup, not Sphinx. + + + +gevent is a coroutine_ -based Python_ networking library that uses +`greenlet `_ to provide a high-level synchronous API on top of the `libev`_ +or `libuv`_ event loop. + +Features include: + + +* Fast event loop based on `libev`_ or `libuv`_. +* Lightweight execution units based on greenlets. +* API that re-uses concepts from the Python standard library (for + examples there are `events`_ and + `queues`_). +* `Cooperative sockets with SSL support `_ +* `Cooperative DNS queries `_ performed through a threadpool, + dnspython, or c-ares. +* `Monkey patching utility `_ to get 3rd party modules to become cooperative +* TCP/UDP/HTTP servers +* Subprocess support (through `gevent.subprocess`_) +* Thread pools + +gevent is `inspired by eventlet`_ but features a more consistent API, +simpler implementation and better performance. Read why others `use +gevent`_ and check out the list of the `open source projects based on +gevent`_. + +gevent was written by `Denis Bilenko `_. + +Since version 1.1, gevent is maintained by Jason Madden for +`NextThought `_ (through gevent 21) and +`Institutional Shareholder Services `_ +with help from the `contributors +`_ and is +licensed under the MIT license. + +See `what's new`_ in the latest major release. + +Check out the detailed changelog_ for this version. + +.. _events: http://www.gevent.org/api/gevent.event.html#gevent.event.Event +.. _queues: http://www.gevent.org/api/gevent.queue.html#gevent.queue.Queue +.. _gevent.subprocess: http://www.gevent.org/api/gevent.subprocess.html#module-gevent.subprocess + +.. _coroutine: https://en.wikipedia.org/wiki/Coroutine +.. _Python: http://python.org +.. _libev: http://software.schmorp.de/pkg/libev.html +.. _libuv: http://libuv.org +.. _inspired by eventlet: http://blog.gevent.org/2010/02/27/why-gevent/ +.. _use gevent: http://groups.google.com/group/gevent/browse_thread/thread/4de9703e5dca8271 +.. _open source projects based on gevent: https://github.com/gevent/gevent/wiki/Projects +.. _what's new: http://www.gevent.org/whatsnew_1_5.html +.. _changelog: http://www.gevent.org/changelog.html + + +Read the documentation online at http://www.gevent.org. + +Post issues on the `bug tracker`_, discuss and ask open ended +questions on the `mailing list`_, and find announcements and +information on the blog_ and `twitter (@gevent)`_. + +=============================== + Installation and Requirements +=============================== + +.. _installation: + +.. + This file is included in README.rst so it is limited to plain + ReST markup, not Sphinx. + +.. note:: + + If you are reading this document on the `Python Package Index`_ + (PyPI, https://pypi.org/), it is specific to the version of gevent that + you are viewing. If you are viewing this document on gevent.org, it + refers to the current state of gevent in source control (git + master). + +Supported Platforms +=================== + +This version of gevent runs on Python 3.8 and up, (for exact details +of tested versions, see the classifiers on the PyPI page or in +``setup.py``). gevent requires the `greenlet +`_ library and will install the +`cffi`_ library by default on Windows. The cffi library will become +the default on all platforms in a future release of gevent. + +This version of gevent is also tested on on PyPy 3.10 (7.3.12); it +should run on PyPy 3.9 and above. On PyPy, there are no external +dependencies. + +gevent is tested on Windows, macOS, and Linux, and should run on most +other Unix-like operating systems (e.g., FreeBSD, Solaris, etc.) + +.. note:: + + Windows is supported as a tier 2, "best effort," platform. It is + suitable for development, but not recommended for production. In + particular, PyPy3 on Windows may have issues, especially with + subprocesses. + + On Windows using the deprecated libev backend, gevent is + limited to a maximum of 1024 open sockets due to + `limitations in libev`_. This limitation should not exist + with the default libuv backend. + +Older Versions of Python +------------------------ + +Users of older versions of Python 2 or Python 3 may install an older +version of gevent. Note that these versions are generally not +supported. + ++-------+-------+ +|Python |Gevent | +|Version|Version| ++=======+=======+ +|2.5 |1.0.x | +| | | ++-------+-------+ +|2.6 |1.1.x | ++-------+-------+ +|<= |1.2.x | +|2.7.8 | | ++-------+-------+ +|3.3 |1.2.x | ++-------+-------+ +|3.4.0 -| 1.3.x | +|3.4.2 | | +| | | ++-------+-------+ +|3.4.3 | 1.4.x | +| | | +| | | ++-------+-------+ +|3.5.x | 20.9.0| +| | | +| | | ++-------+-------+ +|2.7.9 -| | +|2.7.18,| 22.10 | +|3.6, | | +|3.7 | | +| | | ++-------+-------+ + +Installation +============ + +.. note:: + + This section is about installing released versions of gevent as + distributed on the `Python Package Index`_. For building gevent + from source, including customizing the build and embedded + libraries, see `Installing From Source`_. + +.. _Python Package Index: http://pypi.org/project/gevent + +gevent and greenlet can both be installed with `pip`_, e.g., ``pip +install gevent``. Installation using `buildout +`_ is also supported. + +On Windows, macOS, and Linux, both gevent and greenlet are +distributed as binary `wheels`_. + +.. tip:: + + You need Pip 8.0 or later, or buildout 2.10.0 to install the binary + wheels on Windows or macOS. On Linux, you'll need `pip 19 + `_ to install the + manylinux2010 wheels. + +.. tip:: + + While the x86-64 binaries are considered production quality, they + are built with relatively low optimization levels and no hardware + specific optimizations. Serious production users are encouraged to + install from source with appropriate compiler flags. + +.. tip:: + + Beginning with gevent 20.12.0, 64-bit ARM binaries are distributed + on PyPI for aarch64 manylinux2014 compatible systems. Installing these + needs a very recent version of ``pip``. These wheels *do not* + contain the c-ares resolver, are not tested, and are built with + very low levels of optimizations. Serious production users of + gevent on 64-bit ARM systems are encouraged to build their own + binary wheels. + + Beginning with gevent 22.10.0, ppc64le binaries are distributed on + PyPI. The same caveats apply as for 64-bit ARM binaries. Using them + for anything other than local development is discouraged. + + Beginning with gevent 23, muslinux aarch64 and S390X binaries + are distributed on PyPI. The same caveats apply as for 64-bit ARM + binaries. Using them for anything other than local development is + discouraged. + + +Installing From Source +---------------------- + +If you are unable to use the binary wheels (for platforms where no +pre-built wheels are available or if wheel installation is disabled), +you can build gevent from source. A normal ``pip install`` will +fall back to doing this if no binary wheel is available. See +`Installing From Source`_ for more, including common installation issues. + +Extra Dependencies +================== + +There are a number +of additional libraries that extend gevent's functionality and will be +used if they are available. All of these may be installed using +`setuptools extras +`_, +as named below, e.g., ``pip install gevent[events]``. + +events + In versions of gevent up to and including 20.5.0, this provided configurable + event support using `zope.event + `_ and was highly + recommended. + + In versions after that, this extra is empty and does nothing. It + will be removed in gevent 21.0. + +dnspython + Enables a pure-Python resolver, backed by `dnspython + `_. On Python 2, this also + includes `idna `_. They can be + installed with the ``dnspython`` extra. + + .. note:: This is not compatible with Python 3.10+ or dnspython 2. + +monitor + Enhancements to gevent's self-monitoring capabilities. This + includes the `psutil `_ library + which is needed to monitor memory usage. (Note that this may not + build on all platforms.) + +recommended + A shortcut for installing suggested extras together. This includes + the non-test extras defined here, plus additions that improve + gevent's operation on certain platforms (for example, in the past, + it has included backports of newer APIs). + +test + Everything needed to run the complete gevent test suite. + + +.. _`pip`: https://pip.pypa.io/en/stable/installing/ +.. _`wheels`: http://pythonwheels.com +.. _`gevent 1.5`: whatsnew_1_5.html +.. _`Installing From Source`: https://www.gevent.org/development/installing_from_source.html + +.. _`cffi`: https://cffi.readthedocs.io +.. _`limitations in libev`: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#WIN32_PLATFORM_LIMITATIONS_AND_WORKA + + +.. _bug tracker: https://github.com/gevent/gevent/issues +.. _mailing list: http://groups.google.com/group/gevent +.. _blog: https://dev.nextthought.com/blog/categories/gevent.html +.. _twitter (@gevent): http://twitter.com/gevent diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/NOTICE b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..83573c08ea00b6d4beb7ea8e7561db855125db02 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/NOTICE @@ -0,0 +1,94 @@ +gevent is licensed under the MIT license. See the LICENSE file for the +complete license. + +Portions of this software may have other licenses. + +============================================= + +greentest/2.7 +greentest/2.7.8 +greentest/2.7pypy +greentest/3.3 +greentest/3.4 +greentest/3.5 +----------------- + +Copyright (c) 2001-2016 Python Software Foundation; All Rights Reserved + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001-2016 Python Software Foundation; All Rights +Reserved" are retained in Python alone or in any derivative version prepared +by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + +============================================ + +gevent/libuv/_corecffi_source.c +gevent/libuv/_corecffi_cdef.c + +Originally based on code from https://github.com/veegee/guv + +Copyright (c) 2014 V G + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + +=========================================== diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/RECORD b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7550202e89cbcc91e8a70fcc50410be3dd6e32c8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/RECORD @@ -0,0 +1,558 @@ +gevent-24.11.1.dist-info/AUTHORS,sha256=IS4ttuioANx5ucZqOXHiezC9ys2nkpxl1M_8f77Rleo,1303 +gevent-24.11.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +gevent-24.11.1.dist-info/LICENSE,sha256=TUa8EdGeOFPVQyWXO44sUwkPVjinvyf6H18SMseJAfc,1235 +gevent-24.11.1.dist-info/METADATA,sha256=WaZtQb7KccFebD8a5N-GXq2gXBzY6CzkOSA33IqGveA,13477 +gevent-24.11.1.dist-info/NOTICE,sha256=ZJOCR8qaV_7kwRZWQEuTwxMCkYfhPaeHySe2xkpoBYM,4004 +gevent-24.11.1.dist-info/RECORD,, +gevent-24.11.1.dist-info/WHEEL,sha256=-ffw4ErOrld3H5FyGb0-yfKd91A4S1balHz5KyTz-4c,151 +gevent-24.11.1.dist-info/entry_points.txt,sha256=g2MTL3KfdJVJ6CEp0d4f9x6HjLAp-MklXYlxlZQ9_u4,95 +gevent-24.11.1.dist-info/top_level.txt,sha256=fpElGiTe2fdw27vmNxdV5MQpyndjzWZMk5TB_NMYPSI,7 +gevent/__init__.py,sha256=CGttQxS3SceN70fIhe-oRee6AmT9RjtXKc02Aol6TNw,3407 +gevent/__pycache__/__init__.cpython-310.pyc,, +gevent/__pycache__/_abstract_linkable.cpython-310.pyc,, +gevent/__pycache__/_compat.cpython-310.pyc,, +gevent/__pycache__/_config.cpython-310.pyc,, +gevent/__pycache__/_fileobjectcommon.cpython-310.pyc,, +gevent/__pycache__/_fileobjectposix.cpython-310.pyc,, +gevent/__pycache__/_greenlet_primitives.cpython-310.pyc,, +gevent/__pycache__/_hub_local.cpython-310.pyc,, +gevent/__pycache__/_hub_primitives.cpython-310.pyc,, +gevent/__pycache__/_ident.cpython-310.pyc,, +gevent/__pycache__/_imap.cpython-310.pyc,, +gevent/__pycache__/_interfaces.cpython-310.pyc,, +gevent/__pycache__/_monitor.cpython-310.pyc,, +gevent/__pycache__/_patcher.cpython-310.pyc,, +gevent/__pycache__/_semaphore.cpython-310.pyc,, +gevent/__pycache__/_socket3.cpython-310.pyc,, +gevent/__pycache__/_socketcommon.cpython-310.pyc,, +gevent/__pycache__/_tblib.cpython-310.pyc,, +gevent/__pycache__/_threading.cpython-310.pyc,, +gevent/__pycache__/_tracer.cpython-310.pyc,, +gevent/__pycache__/_util.cpython-310.pyc,, +gevent/__pycache__/_waiter.cpython-310.pyc,, +gevent/__pycache__/ares.cpython-310.pyc,, +gevent/__pycache__/backdoor.cpython-310.pyc,, +gevent/__pycache__/baseserver.cpython-310.pyc,, +gevent/__pycache__/builtins.cpython-310.pyc,, +gevent/__pycache__/contextvars.cpython-310.pyc,, +gevent/__pycache__/core.cpython-310.pyc,, +gevent/__pycache__/event.cpython-310.pyc,, +gevent/__pycache__/events.cpython-310.pyc,, +gevent/__pycache__/exceptions.cpython-310.pyc,, +gevent/__pycache__/fileobject.cpython-310.pyc,, +gevent/__pycache__/greenlet.cpython-310.pyc,, +gevent/__pycache__/hub.cpython-310.pyc,, +gevent/__pycache__/local.cpython-310.pyc,, +gevent/__pycache__/lock.cpython-310.pyc,, +gevent/__pycache__/os.cpython-310.pyc,, +gevent/__pycache__/pool.cpython-310.pyc,, +gevent/__pycache__/pywsgi.cpython-310.pyc,, +gevent/__pycache__/queue.cpython-310.pyc,, +gevent/__pycache__/resolver_ares.cpython-310.pyc,, +gevent/__pycache__/resolver_thread.cpython-310.pyc,, +gevent/__pycache__/select.cpython-310.pyc,, +gevent/__pycache__/selectors.cpython-310.pyc,, +gevent/__pycache__/server.cpython-310.pyc,, +gevent/__pycache__/signal.cpython-310.pyc,, +gevent/__pycache__/socket.cpython-310.pyc,, +gevent/__pycache__/ssl.cpython-310.pyc,, +gevent/__pycache__/subprocess.cpython-310.pyc,, +gevent/__pycache__/thread.cpython-310.pyc,, +gevent/__pycache__/threading.cpython-310.pyc,, +gevent/__pycache__/threadpool.cpython-310.pyc,, +gevent/__pycache__/time.cpython-310.pyc,, +gevent/__pycache__/timeout.cpython-310.pyc,, +gevent/__pycache__/util.cpython-310.pyc,, +gevent/__pycache__/win32util.cpython-310.pyc,, +gevent/_abstract_linkable.py,sha256=vpHRKQF0qw4FMKYQMCCY70jzuWGUpL-VFeBshchG364,22722 +gevent/_compat.py,sha256=5J80cwYac8ns8sOWc719Lkw7O-pCSH7r3Y7Na4OsDYM,2806 +gevent/_config.py,sha256=Lx1isVwHjFutWHL2Oth1Y6lc9ynENucjhcZFOVFrxnc,21428 +gevent/_ffi/__init__.py,sha256=BTBgjjvO4ecQBPbReBhem-0zvy1Mq6jXf5dMrykGIhs,493 +gevent/_ffi/__pycache__/__init__.cpython-310.pyc,, +gevent/_ffi/__pycache__/callback.cpython-310.pyc,, +gevent/_ffi/__pycache__/loop.cpython-310.pyc,, +gevent/_ffi/__pycache__/watcher.cpython-310.pyc,, +gevent/_ffi/callback.py,sha256=JL2mvMVD7vVaatIdUxo9UfvUJvIwiHhZ7qLGgiBc8YA,1564 +gevent/_ffi/loop.py,sha256=gq5kGvEyhMknFEM58vXnN0QC5tbmN9sOOWOsHHR7NcY,31802 +gevent/_ffi/watcher.py,sha256=qUFXAHM56_GVyCrvv6VkA735ZvtvLB8Zv26I8iMKIgs,20954 +gevent/_fileobjectcommon.py,sha256=S-69DeitiPnvjbGfexTuD2yzPeI0-eDv_1DBIlV0sTg,24359 +gevent/_fileobjectposix.py,sha256=n4ziPoRoq3741XEHN-UTKdXihoq8TUyik6k9HD-UFI8,12840 +gevent/_gevent_c_abstract_linkable.cpython-310-x86_64-linux-gnu.so,sha256=biDM6csd8yxuD1ggOl_n69rZroxKaawS4qzExEPBLWo,1021000 +gevent/_gevent_c_greenlet_primitives.cpython-310-x86_64-linux-gnu.so,sha256=QkNhIn0oKA4PHk1XTCssDgz3CpjbTY3_y_EQwbupfd8,498944 +gevent/_gevent_c_hub_local.cpython-310-x86_64-linux-gnu.so,sha256=Gf2NVwg68xmwNzj04QQsXXCJlouk28J9_ilBC0BPZx0,398712 +gevent/_gevent_c_hub_primitives.cpython-310-x86_64-linux-gnu.so,sha256=8CR_u8d-3MO0YQKOZCT0xY7Zt-u4nkM6vJK2wVv0c-0,1086104 +gevent/_gevent_c_ident.cpython-310-x86_64-linux-gnu.so,sha256=3Lz-x4XoynIkpg8XwIvU3zk5dCMwjeHArldLReiUOwk,346704 +gevent/_gevent_c_imap.cpython-310-x86_64-linux-gnu.so,sha256=dyXcy00koo5ACsyQHdFNzF-dTeFHBOX2hV-R2BRheSY,623536 +gevent/_gevent_c_semaphore.cpython-310-x86_64-linux-gnu.so,sha256=Y3o7jHFE9r4bJwRmPSuXn-TH1lwgJO65Xl54Jl4IeD4,1062208 +gevent/_gevent_c_tracer.cpython-310-x86_64-linux-gnu.so,sha256=gnwW0AS7s4QFfWlCUAb7wFBMoQ5_Z3KUcoAaDgtXDeg,731368 +gevent/_gevent_c_waiter.cpython-310-x86_64-linux-gnu.so,sha256=8_ttuHOOOEcckQpbhtqUO9eECjHstd8K4wOh9T9bXAo,521608 +gevent/_gevent_cevent.cpython-310-x86_64-linux-gnu.so,sha256=spDqQyo89edL6qPh2TMk5YliCxnbMSiKhpsMhhloddA,776328 +gevent/_gevent_cgreenlet.cpython-310-x86_64-linux-gnu.so,sha256=ai4EL81Zy8Sq47-zwEjYSrvrT-wYd8qFD0vWtH6_pnE,2119856 +gevent/_gevent_clocal.cpython-310-x86_64-linux-gnu.so,sha256=9zjpFK2y2q99o-FyiY7mHkDfcPb18pi7crb4SmzkpSA,1009128 +gevent/_gevent_cqueue.cpython-310-x86_64-linux-gnu.so,sha256=hfPVeCsWlxgSv254bEWRmEFDUb8OhIEvc3CipIc3DuU,1923064 +gevent/_greenlet_primitives.py,sha256=i2b0bj5oYr5qzhRRQPhzbCMEg9zMRAx_zhiSOCHtTeY,4647 +gevent/_hub_local.py,sha256=OJPT7QZufzgEgV3SJvOVUWIqhYAKVgfn2mGx9ismIFo,4763 +gevent/_hub_primitives.py,sha256=aTCXhH1gJNdb1JONz7X0fBnNCu9Lv1U55sVF2dXpnUk,14026 +gevent/_ident.py,sha256=w7kjbyaNR4MVzRTjB0_3ZUZ-JYS6eukY55l-r_MdjM4,2249 +gevent/_imap.py,sha256=RtrIfyUPPMFxNX4gSVuJQLjn6oxIdI2t9ERVErIgtwg,7672 +gevent/_interfaces.py,sha256=D-ZJuGse_gtj8XOTRQyXgsj9FNLCr9Xtn_9U5Txk-Cc,9731 +gevent/_monitor.py,sha256=t-zK6iL6rxtGMuBcnNq0kpRIdNDmESWnTRf1y4j64vc,12006 +gevent/_patcher.py,sha256=e4dfPB9MhmnipVpwwEPcChMbiC2F0Rp_MdkwZ02ZF_c,9020 +gevent/_semaphore.py,sha256=BBjdqHfz8NFVD_XbKbiGxgMUvxYfGeBXA1qh26tgqb8,20887 +gevent/_socket3.py,sha256=w8mFOeD3gFyI2_zWOj1u0adxIKBeNc2Jumhy-CjmNUs,23013 +gevent/_socketcommon.py,sha256=tbdbfwoVh6lSBEYYKogVCRTH-uyUpKBvIbCc4TFkGwY,26066 +gevent/_tblib.py,sha256=szKF1dyK4ELE2_44vxyBPZatAtZe57w0Mseki4ld_IA,12219 +gevent/_threading.py,sha256=mYFPLhSlSWXTGDixNLm0JFfnh3jH1e51fyl5iSXaczM,8342 +gevent/_tracer.py,sha256=FX1B-6s7GWWKLvcdYKRZYCbHABy9i3c5p66cy95ijKM,6455 +gevent/_util.py,sha256=go3VuMYv1k9zpvNkGp0MbxZT4gn3xfutA9HjoY9G6nk,10964 +gevent/_waiter.py,sha256=fCVW5AxbqvIYROgHbC22kljXr6wHIr54fPePtTVMoW4,7387 +gevent/ares.py,sha256=2LLRXoWkyS5YwSpJ0b7R_e3M8ikwpsA53eUWizys8eM,383 +gevent/backdoor.py,sha256=Hn7dZXAzywWypJm2MENTWZLS4oUrSpriy_Apz2X-7f4,8642 +gevent/baseserver.py,sha256=x4zWdbE5JtOYCuvGQozCUgfpArhN0mPMXdLdPDRiYnI,16614 +gevent/builtins.py,sha256=0K7haEs0DhfIEhArBaxaRRx_i3Dws2ZqFWey6HOYjHo,4108 +gevent/contextvars.py,sha256=a0f8GxwQESkQM-zUNO-gdmDcW-2-kV321auE6KbSHGw,9838 +gevent/core.py,sha256=XgaVreHocvO9JCVby3JCo8ixbllJL08V9OrA7ETDaHs,479 +gevent/event.py,sha256=vOR3t77RyCzLH240f-DrypxLNgwsP4YkOaaeqZfYa64,15079 +gevent/events.py,sha256=olRj_SbHNW-I8Ifs6vNYWaRKV0bWtgEFnOYt6Uhihuk,17182 +gevent/exceptions.py,sha256=6JvoCgb4Recrl_kngtBe8Zx36uwc5qTakLJSJBQVr8I,3932 +gevent/fileobject.py,sha256=GNeYmbGSLWq8t311pVbgYsyDpzMmtQ8m2fHI15a0EpI,3020 +gevent/greenlet.py,sha256=gWxllLzY6SQanwBKO_nXxm7IEY7k02cv4Bq0V4gIm0Y,45203 +gevent/hub.py,sha256=_ZodHnESbnnj2qg8p-4aGhY4HH4u-7T7wJHI00JYJAM,34590 +gevent/libev/__init__.py,sha256=I6hpYFJCnbBBDrousKzZ7Ql--mnfAFwfM2q1BuxcMfI,169 +gevent/libev/__pycache__/__init__.cpython-310.pyc,, +gevent/libev/__pycache__/_corecffi_build.cpython-310.pyc,, +gevent/libev/__pycache__/corecffi.cpython-310.pyc,, +gevent/libev/__pycache__/watcher.cpython-310.pyc,, +gevent/libev/_corecffi.abi3.so,sha256=iivm2mzecVM_515ub_hbspW7nT1nRFlS4NC8TUWlumw,473480 +gevent/libev/_corecffi_build.py,sha256=ARUO9jiMqdfk80aSs4_CkBIIwcpUaF9enyj-AJVXVP8,4059 +gevent/libev/corecext.cpython-310-x86_64-linux-gnu.so,sha256=dVkXbVISohLQNrKUqHonyhh1BDzudif32NSryKk0aGU,2563472 +gevent/libev/corecffi.py,sha256=yxz0x6YzcQSFPSuba3JJpPJkkdU7KBwFPa299cGOGSw,13720 +gevent/libev/watcher.py,sha256=DGBi_JFksqLv4ifO5o-eIT8POn-om3EdiJhQDVx4pLs,7999 +gevent/libuv/__init__.py,sha256=I6hpYFJCnbBBDrousKzZ7Ql--mnfAFwfM2q1BuxcMfI,169 +gevent/libuv/__pycache__/__init__.cpython-310.pyc,, +gevent/libuv/__pycache__/_corecffi_build.cpython-310.pyc,, +gevent/libuv/__pycache__/loop.cpython-310.pyc,, +gevent/libuv/__pycache__/watcher.cpython-310.pyc,, +gevent/libuv/_corecffi.abi3.so,sha256=LsSrcAHjxBA-GEbOP7U-E3OuVX9T4yp4ZX_sncATvrQ,1307296 +gevent/libuv/_corecffi_build.py,sha256=uzAzrWhtl6yfjvBSR-1WkdPtsPSPo-oS_kqii1WAMnc,12349 +gevent/libuv/loop.py,sha256=q7es7RTne1wl2EEJ9AVHw5-mBvu92cmxQ5qh_QeKtlM,27626 +gevent/libuv/watcher.py,sha256=kuT3uqGc5XnAw1T_vgnseH2KpqAUqE5xjk65VXVoFxk,27664 +gevent/local.py,sha256=I12OWg8nWR5q7p3UZhJjSMfbyHuShVqYqQTkmPdF-8k,21457 +gevent/lock.py,sha256=Wsfkdv2By0C-7plcGmK5OWEX9EmVhvY1UpEdYkHUNYA,11398 +gevent/monkey/__init__.py,sha256=blTV4wtxZGjRAJLXA80cCSduobcUJE9KUdLvkibq2Xk,24869 +gevent/monkey/__main__.py,sha256=JPNIwI-Qb_VQERows-n4R2XzcY8rGCt5FR8kUiKD1J4,31 +gevent/monkey/__pycache__/__init__.cpython-310.pyc,, +gevent/monkey/__pycache__/__main__.cpython-310.pyc,, +gevent/monkey/__pycache__/_errors.cpython-310.pyc,, +gevent/monkey/__pycache__/_main.cpython-310.pyc,, +gevent/monkey/__pycache__/_patch_thread_common.cpython-310.pyc,, +gevent/monkey/__pycache__/_patch_thread_gte313.cpython-310.pyc,, +gevent/monkey/__pycache__/_patch_thread_lt313.cpython-310.pyc,, +gevent/monkey/__pycache__/_state.cpython-310.pyc,, +gevent/monkey/__pycache__/_util.cpython-310.pyc,, +gevent/monkey/__pycache__/api.cpython-310.pyc,, +gevent/monkey/_errors.py,sha256=cBctoXo4sAME97eaCdWGY1q1zEOtG8krDFyv-O5WOiQ,547 +gevent/monkey/_main.py,sha256=8zzhBLrRSBV0D_GbgwcY_iwsIR3ayrG9xX8TvyGAvH8,4411 +gevent/monkey/_patch_thread_common.py,sha256=n018JoqZ2zMZnKWzhDNOOkEOWJxskOOWjth-q_30b3A,13119 +gevent/monkey/_patch_thread_gte313.py,sha256=83Mix-vpJA2xGmmsxD4Glc4c-c8kyjrMMngxuB1zlPo,3490 +gevent/monkey/_patch_thread_lt313.py,sha256=3qLEpTt2L6CRJy2H1SFyVqtrfT8ItnHpUpOD45Mxdzc,3054 +gevent/monkey/_state.py,sha256=FGJFTDXFUwio1b-IwtlOmXCysVrqheM9j9JjRxOzrqI,1897 +gevent/monkey/_util.py,sha256=U-KBkLB9v5J7RedNHOfK7qaaonaKo5Z7oQ-5gwrYnAo,3689 +gevent/monkey/api.py,sha256=ZoRUk0e-wVXE6CnTI8BULQaDAIVqyEmTCwXhVzUrh5s,6760 +gevent/os.py,sha256=1sJXacYJZUDwgUii44K_D1AB6EwFTTHtYQEX7D6Vaho,20858 +gevent/pool.py,sha256=JSt0I106SQr3wYjc9z919ebcX3MUyM33gaAbohSXNCo,25634 +gevent/pywsgi.py,sha256=ZWZMKmn21k3K5NS6JLJ4UrPLTA3z2bn-jPjHRjm7fKc,69033 +gevent/queue.py,sha256=Vkq4L7xSTcYYOmw_EynWMas6OkWoXdSV47YOivlMnI0,25708 +gevent/resolver/__init__.py,sha256=lx0L8Up3DXkp61RQxceQbmj5AVFt9WGMhHi12-iy7GI,10760 +gevent/resolver/__pycache__/__init__.cpython-310.pyc,, +gevent/resolver/__pycache__/_addresses.cpython-310.pyc,, +gevent/resolver/__pycache__/_hostsfile.cpython-310.pyc,, +gevent/resolver/__pycache__/ares.cpython-310.pyc,, +gevent/resolver/__pycache__/blocking.cpython-310.pyc,, +gevent/resolver/__pycache__/dnspython.cpython-310.pyc,, +gevent/resolver/__pycache__/thread.cpython-310.pyc,, +gevent/resolver/_addresses.py,sha256=BvLXxwN1QTQ4Pajgk5UwvHRP6J8TDQ8n-_75AfIaOVo,4795 +gevent/resolver/_hostsfile.py,sha256=KY6q-aY5F1f3MV4SZioAcstBRvxm4647-JKlCtY47E0,4629 +gevent/resolver/ares.py,sha256=6Oed67PUah45MwMQz3KFIWNAnm7XkoRJXx9vz7voJEc,12965 +gevent/resolver/blocking.py,sha256=5ubBMewB7X-JouMKIlf_s2JNw4KJ_EqmNVUg4PrrSaA,1216 +gevent/resolver/cares.cpython-310-x86_64-linux-gnu.so,sha256=MRiOjNPMCvdmF0vwePyW9kFRz0mDbURipVbx1vXWCsM,2882264 +gevent/resolver/dnspython.py,sha256=cZ0mQyWluVz_h2YsyS_sSg0n7NEpuFPsZhp63WMyFeg,20706 +gevent/resolver/thread.py,sha256=DTSwSwBRsSJKjPjyAHS0qT07oDxmFOhR4wYLfSSaJCU,2487 +gevent/resolver_ares.py,sha256=s5Jo9Z0b-zKxSWcIvW5onaFE2OrfqLuNnTPlOoxFxEQ,486 +gevent/resolver_thread.py,sha256=jcKcEVCXwyRqcsDUZmryQ9hc-83yztgaM4kuTKHOvaw,504 +gevent/select.py,sha256=7-LNetKIlhpB3YifQ5momSLQXnt5q92g8EDJaC4qGEE,13257 +gevent/selectors.py,sha256=ffV2jG6m2etjqNIppHNCBY7JSDr4q0_zbf-tkA06gVI,11725 +gevent/server.py,sha256=7rrN3Ieujlo0vKddDyYIqgocslsW-3VNG-faOfOk7vE,10852 +gevent/signal.py,sha256=-Rx0_Ta7Zel8UWXmrrtzDWVnjUQZuGWINWhrNwHB9ic,5217 +gevent/socket.py,sha256=CUC-jiNIjbXghj_muCXyn9Ij7GUDa44kKxBb3F1-PMM,6503 +gevent/ssl.py,sha256=Q_etOyl2s9PcZRvOaf1_7joEIeo8d8u4N7XWhRxnFTs,34772 +gevent/subprocess.py,sha256=Q1mRVgRyAVigzjlLd0aXvhTb5IKk3TOhbLNcK6mVJX0,83510 +gevent/testing/__init__.py,sha256=my2P6ikG7OUO9hGXN54zZawh4LYtu825K9epAGUnoDc,5583 +gevent/testing/__pycache__/__init__.cpython-310.pyc,, +gevent/testing/__pycache__/errorhandler.cpython-310.pyc,, +gevent/testing/__pycache__/exception.cpython-310.pyc,, +gevent/testing/__pycache__/flaky.cpython-310.pyc,, +gevent/testing/__pycache__/hub.cpython-310.pyc,, +gevent/testing/__pycache__/leakcheck.cpython-310.pyc,, +gevent/testing/__pycache__/modules.cpython-310.pyc,, +gevent/testing/__pycache__/monkey_test.cpython-310.pyc,, +gevent/testing/__pycache__/openfiles.cpython-310.pyc,, +gevent/testing/__pycache__/params.cpython-310.pyc,, +gevent/testing/__pycache__/patched_tests_setup.cpython-310.pyc,, +gevent/testing/__pycache__/resources.cpython-310.pyc,, +gevent/testing/__pycache__/six.cpython-310.pyc,, +gevent/testing/__pycache__/skipping.cpython-310.pyc,, +gevent/testing/__pycache__/sockets.cpython-310.pyc,, +gevent/testing/__pycache__/support.cpython-310.pyc,, +gevent/testing/__pycache__/switching.cpython-310.pyc,, +gevent/testing/__pycache__/sysinfo.cpython-310.pyc,, +gevent/testing/__pycache__/testcase.cpython-310.pyc,, +gevent/testing/__pycache__/testrunner.cpython-310.pyc,, +gevent/testing/__pycache__/timing.cpython-310.pyc,, +gevent/testing/__pycache__/travis.cpython-310.pyc,, +gevent/testing/__pycache__/util.cpython-310.pyc,, +gevent/testing/coveragesite/__pycache__/sitecustomize.cpython-310.pyc,, +gevent/testing/coveragesite/sitecustomize.py,sha256=GSOkHhxLE_pjOHuUn4InKmmuLyIGSIumySFVVSmc4Vo,558 +gevent/testing/errorhandler.py,sha256=NzoItIrdz8t0YOFEAa6fn9WyFnubs_egnpV8yD7AcDQ,2329 +gevent/testing/exception.py,sha256=yQHF9Ebom2JAKUq70mLsdFk9p4eorpK36O-3iH1LL1Q,1265 +gevent/testing/flaky.py,sha256=x-IujIZGK_m2FYRyi4RxKMZhLfxq25p47En4DAlYhCs,4104 +gevent/testing/hub.py,sha256=Qmo7bcZPLIEOF7mncgV3vR-KrbHLUT_pORNQejrltig,3115 +gevent/testing/leakcheck.py,sha256=mHU-MoeEtHV319aTbDeMx-F0OwDWmf3rJI-sYJl9lmI,8227 +gevent/testing/modules.py,sha256=qGfvohEps4mo6_hqcRZHlEuxBx1wDNqRY_DZmJDM61o,4987 +gevent/testing/monkey_test.py,sha256=Y2WYnBEb5FQIuOnFpv42ETuvdKRbBhAtqywDDDoPowE,5730 +gevent/testing/openfiles.py,sha256=daybcm27dkOGOiloGj0GocHzPRX2q6NvW861WylWxFA,8739 +gevent/testing/params.py,sha256=B-5PoctZfrtii3rcjA68kmI0wvwg7_sHJ4pWFzRAcbw,2674 +gevent/testing/patched_tests_setup.py,sha256=ztdpf2o4DlhjaLSIMy1Ie5VJY78l843b7QpAFA_pwZ8,66439 +gevent/testing/resources.py,sha256=C3cxaDi56orLzs50vTCnGElxk-ChJBjFV3JX2f610_A,7481 +gevent/testing/six.py,sha256=4Gi0PTjZ9rKHn-DGy9WdRSxuYFmeoTonD_LL_TvyrcU,1035 +gevent/testing/skipping.py,sha256=z9S_gzsCaDeuAbw3E80gysE7CoVGrvc6a1OYXyDtTkY,6719 +gevent/testing/sockets.py,sha256=CvtRiCVxCXcv_Vv3OFQiEYEH-Mok32sY18JiATEbeI4,2285 +gevent/testing/support.py,sha256=hn2IghJcKYUcS7hcii9RdWBLy0gGOu2nRTlEEvaq06U,4631 +gevent/testing/switching.py,sha256=6idIaCiHKFZF8aibeHjxIdZi38cxXCKuhQRHUT1YWoo,2708 +gevent/testing/sysinfo.py,sha256=LP97FlKGdJXc-S1ejAkO-k8VHGX2ybIpk_Ozy_WNNIw,8211 +gevent/testing/testcase.py,sha256=-Xo56A1ZIX_PW7RMqn_YkPKauzUI5yxJXAjpd_dKjXI,18602 +gevent/testing/testrunner.py,sha256=ld43CGn3CbDjzOGW4lOlyOnubr2mWyd2ve-J8Pt58F4,36487 +gevent/testing/timing.py,sha256=Yy9dQ3KvJ9uEV6BwpgM3ZEnVYP1ic6jgVGqZF1uWLLc,4982 +gevent/testing/travis.py,sha256=yYJlIY2L4vMzSxaODPVhANFaB_svNmwhrw4CRotQXlc,877 +gevent/testing/util.py,sha256=Kky0x628NVhr9g_-yYjkeuhSQViBSRZ9YWt02WfWbG4,19302 +gevent/tests/2_7_keycert.pem,sha256=PuSO2qCmga4an7pkSs7ep1Fo16yrQKd9i84DnrqSYcI,5081 +gevent/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +gevent/tests/__main__.py,sha256=EMw-OppCjl-heu15mLg-cf400NS1Ikuy96OisvLoKLM,179 +gevent/tests/__pycache__/__init__.cpython-310.pyc,, +gevent/tests/__pycache__/__main__.cpython-310.pyc,, +gevent/tests/__pycache__/_blocks_at_top_level.cpython-310.pyc,, +gevent/tests/__pycache__/_import_import_patch.cpython-310.pyc,, +gevent/tests/__pycache__/_import_patch.cpython-310.pyc,, +gevent/tests/__pycache__/_import_wait.cpython-310.pyc,, +gevent/tests/__pycache__/_imports_at_top_level.cpython-310.pyc,, +gevent/tests/__pycache__/_imports_imports_at_top_level.cpython-310.pyc,, +gevent/tests/__pycache__/getaddrinfo_module.cpython-310.pyc,, +gevent/tests/__pycache__/known_failures.cpython-310.pyc,, +gevent/tests/__pycache__/lock_tests.cpython-310.pyc,, +gevent/tests/__pycache__/test__GreenletExit.cpython-310.pyc,, +gevent/tests/__pycache__/test___config.cpython-310.pyc,, +gevent/tests/__pycache__/test___ident.cpython-310.pyc,, +gevent/tests/__pycache__/test___monitor.cpython-310.pyc,, +gevent/tests/__pycache__/test___monkey_patching.cpython-310.pyc,, +gevent/tests/__pycache__/test__all__.cpython-310.pyc,, +gevent/tests/__pycache__/test__api.cpython-310.pyc,, +gevent/tests/__pycache__/test__api_timeout.cpython-310.pyc,, +gevent/tests/__pycache__/test__ares_host_result.cpython-310.pyc,, +gevent/tests/__pycache__/test__ares_timeout.cpython-310.pyc,, +gevent/tests/__pycache__/test__backdoor.cpython-310.pyc,, +gevent/tests/__pycache__/test__close_backend_fd.cpython-310.pyc,, +gevent/tests/__pycache__/test__compat.cpython-310.pyc,, +gevent/tests/__pycache__/test__contextvars.cpython-310.pyc,, +gevent/tests/__pycache__/test__core.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_async.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_callback.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_fork.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_loop_run.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_stat.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_timer.cpython-310.pyc,, +gevent/tests/__pycache__/test__core_watcher.cpython-310.pyc,, +gevent/tests/__pycache__/test__destroy.cpython-310.pyc,, +gevent/tests/__pycache__/test__destroy_default_loop.cpython-310.pyc,, +gevent/tests/__pycache__/test__doctests.cpython-310.pyc,, +gevent/tests/__pycache__/test__environ.cpython-310.pyc,, +gevent/tests/__pycache__/test__event.cpython-310.pyc,, +gevent/tests/__pycache__/test__events.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_echoserver.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_portforwarder.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_udp_client.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_udp_server.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_webproxy.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_wsgiserver.cpython-310.pyc,, +gevent/tests/__pycache__/test__example_wsgiserver_ssl.cpython-310.pyc,, +gevent/tests/__pycache__/test__examples.cpython-310.pyc,, +gevent/tests/__pycache__/test__exc_info.cpython-310.pyc,, +gevent/tests/__pycache__/test__execmodules.cpython-310.pyc,, +gevent/tests/__pycache__/test__fileobject.cpython-310.pyc,, +gevent/tests/__pycache__/test__getaddrinfo_import.cpython-310.pyc,, +gevent/tests/__pycache__/test__greenio.cpython-310.pyc,, +gevent/tests/__pycache__/test__greenlet.cpython-310.pyc,, +gevent/tests/__pycache__/test__greenletset.cpython-310.pyc,, +gevent/tests/__pycache__/test__greenness.cpython-310.pyc,, +gevent/tests/__pycache__/test__hub.cpython-310.pyc,, +gevent/tests/__pycache__/test__hub_join.cpython-310.pyc,, +gevent/tests/__pycache__/test__hub_join_timeout.cpython-310.pyc,, +gevent/tests/__pycache__/test__import_blocking_in_greenlet.cpython-310.pyc,, +gevent/tests/__pycache__/test__import_wait.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue112.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue1686.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue1864.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue230.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue330.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue467.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue6.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue600.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue607.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue639.cpython-310.pyc,, +gevent/tests/__pycache__/test__issue_728.cpython-310.pyc,, +gevent/tests/__pycache__/test__issues461_471.cpython-310.pyc,, +gevent/tests/__pycache__/test__iwait.cpython-310.pyc,, +gevent/tests/__pycache__/test__joinall.cpython-310.pyc,, +gevent/tests/__pycache__/test__local.cpython-310.pyc,, +gevent/tests/__pycache__/test__lock.cpython-310.pyc,, +gevent/tests/__pycache__/test__loop_callback.cpython-310.pyc,, +gevent/tests/__pycache__/test__makefile_ref.cpython-310.pyc,, +gevent/tests/__pycache__/test__memleak.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_builtins_future.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_hub_in_thread.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_logging.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_module_run.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_multiple_imports.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_queue.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_select.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_selectors.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_sigchld.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_sigchld_2.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_sigchld_3.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_ssl_warning.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_ssl_warning2.cpython-310.pyc,, +gevent/tests/__pycache__/test__monkey_ssl_warning3.cpython-310.pyc,, +gevent/tests/__pycache__/test__nondefaultloop.cpython-310.pyc,, +gevent/tests/__pycache__/test__order.cpython-310.pyc,, +gevent/tests/__pycache__/test__os.cpython-310.pyc,, +gevent/tests/__pycache__/test__pool.cpython-310.pyc,, +gevent/tests/__pycache__/test__pywsgi.cpython-310.pyc,, +gevent/tests/__pycache__/test__queue.cpython-310.pyc,, +gevent/tests/__pycache__/test__real_greenlet.cpython-310.pyc,, +gevent/tests/__pycache__/test__refcount.cpython-310.pyc,, +gevent/tests/__pycache__/test__refcount_core.cpython-310.pyc,, +gevent/tests/__pycache__/test__resolver_dnspython.cpython-310.pyc,, +gevent/tests/__pycache__/test__select.cpython-310.pyc,, +gevent/tests/__pycache__/test__selectors.cpython-310.pyc,, +gevent/tests/__pycache__/test__semaphore.cpython-310.pyc,, +gevent/tests/__pycache__/test__server.cpython-310.pyc,, +gevent/tests/__pycache__/test__server_pywsgi.cpython-310.pyc,, +gevent/tests/__pycache__/test__signal.cpython-310.pyc,, +gevent/tests/__pycache__/test__sleep0.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_close.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_dns.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_dns6.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_errors.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_ex.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_send_memoryview.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_ssl.cpython-310.pyc,, +gevent/tests/__pycache__/test__socket_timeout.cpython-310.pyc,, +gevent/tests/__pycache__/test__socketpair.cpython-310.pyc,, +gevent/tests/__pycache__/test__ssl.cpython-310.pyc,, +gevent/tests/__pycache__/test__subprocess.cpython-310.pyc,, +gevent/tests/__pycache__/test__subprocess_interrupted.cpython-310.pyc,, +gevent/tests/__pycache__/test__subprocess_poll.cpython-310.pyc,, +gevent/tests/__pycache__/test__systemerror.cpython-310.pyc,, +gevent/tests/__pycache__/test__thread.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_2.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_before_monkey.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_fork_from_dummy.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_holding_lock_while_monkey.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_monkey_in_thread.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_native_before_monkey.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_no_monkey.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_patched_local.cpython-310.pyc,, +gevent/tests/__pycache__/test__threading_vs_settrace.cpython-310.pyc,, +gevent/tests/__pycache__/test__threadpool.cpython-310.pyc,, +gevent/tests/__pycache__/test__threadpool_executor_patched.cpython-310.pyc,, +gevent/tests/__pycache__/test__timeout.cpython-310.pyc,, +gevent/tests/__pycache__/test__util.cpython-310.pyc,, +gevent/tests/_blocks_at_top_level.py,sha256=Hp36RFiC0djMSfvUHZsu8pVttpc7Hbmv_7VGq6xW630,48 +gevent/tests/_import_import_patch.py,sha256=IbgraY7KaPggcX1JNVkUQTTBSboegF_VWSDFJp38buI,28 +gevent/tests/_import_patch.py,sha256=_PWRiLjpsFyhT2CxTDIE9ZVS9gcCFqzQGFKel00zc2s,47 +gevent/tests/_import_wait.py,sha256=8353o30STWbRg53op9CWmTXfElU6VV4klLdqiq7Jmjg,570 +gevent/tests/_imports_at_top_level.py,sha256=9SCo81uRMT8xWbDFUBhbc_EwAoii9oygwOBSSNWfWWI,55 +gevent/tests/_imports_imports_at_top_level.py,sha256=VcIaDELcdgeEMqO_Cndy0XMjx05h5eG4_F_12giOSDs,345 +gevent/tests/badcert.pem,sha256=JioQeRZkHH8hGsWJjAF3U1zQvcWqhyzG6IOEJpTY9SE,1928 +gevent/tests/badkey.pem,sha256=gaBK9px_gG7DmrLKxfD6f6i-toAmARBTVfs-YGFRQF0,2162 +gevent/tests/getaddrinfo_module.py,sha256=oFyeNRywc3QO5HlpuV5DVcpUbml8hFn86pbWm_mGQX8,116 +gevent/tests/hosts_file.txt,sha256=07jEX3FicSKuiUJbQ_14H0MP8v7r35h_usGUmScPnSM,290909 +gevent/tests/https_svn_python_org_root.pem,sha256=wOB3Onnc62Iu9kEFd8GcHhd_suucYjpJNA3jyfHeJWA,2569 +gevent/tests/keycert.pem,sha256=r0KE1WH9eV6X4mUykpCY5Dm8_robBSi4zwMcGBPtMi4,1872 +gevent/tests/known_failures.py,sha256=y7BTq9dlR-At455-Q5YCJ5pnDaXOnmo5Ms317fcbbDo,17473 +gevent/tests/lock_tests.py,sha256=Oxi0uoEPVzA1NKP6t69fuezuHCZE0xQZbHBuMQtTwUs,21858 +gevent/tests/monkey_package/__init__.py,sha256=bvY5MXWih-w0IshrJmEKnPTI25R0eC_ma0Xa2bT3XCI,329 +gevent/tests/monkey_package/__main__.py,sha256=mJx6YRmYplQEY8Lb3hQOPrbIj2Z3mwrZY3wLL7p2zcM,363 +gevent/tests/monkey_package/__pycache__/__init__.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/__main__.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/issue1526_no_monkey.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/issue1526_with_monkey.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/issue302monkey.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/script.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/threadpool_monkey_patches.cpython-310.pyc,, +gevent/tests/monkey_package/__pycache__/threadpool_no_monkey.cpython-310.pyc,, +gevent/tests/monkey_package/issue1526_no_monkey.py,sha256=mDdY5_Y4IDBd8b-gjYNQKh8U4jb8Nn7eSEC_DM7lSxk,573 +gevent/tests/monkey_package/issue1526_with_monkey.py,sha256=5mbVockojXOZQZwQFaPrMVcg50T_vD1WRj07F6pOj_Y,666 +gevent/tests/monkey_package/issue302monkey.py,sha256=aitTDyrxJZI4EE_n6gg0o4AfHEQsFPfzQtVVmWMr6JQ,935 +gevent/tests/monkey_package/script.py,sha256=4q695hn_S3YA2aQh4TRyjVJ7QA9xlfqNTrezlUZkjVQ,427 +gevent/tests/monkey_package/threadpool_monkey_patches.py,sha256=0Glu2IugiK6rT6fYZbgqmGgciUjUX-6eannkqekzTi4,869 +gevent/tests/monkey_package/threadpool_no_monkey.py,sha256=c-bdOwTHjhBzlmcJMFyixL3Wjp-wXO4T1VZIGC3clGE,787 +gevent/tests/nullcert.pem,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +gevent/tests/server.crt,sha256=LOyJ1muRGaDZapZQ9x3BRNGIrC4jKiiIyNZJvMM5eQI,1809 +gevent/tests/server.key,sha256=CXI8bo8kvTo3I_o0kVPabuQ0oHBsoNbgFVT1bWNTwOI,3272 +gevent/tests/sha256.pem,sha256=trYsA7FY0hyVoV1AoGNwZ_s6T89eiiOIFexoNRv029s,2065 +gevent/tests/test__GreenletExit.py,sha256=qHtC7KnjCG039F_VGDXnsrhyWaQXvfcmgnVB2Rfa_Vk,127 +gevent/tests/test___config.py,sha256=mCJfAOG9DEAU5RtUg_UgHwsB6f0x-KWTjHX9aTaS7d8,4889 +gevent/tests/test___ident.py,sha256=15ucVXe5y4hE9F--Y8fhxN9-WcGhXt2ehHMLTzDuDKs,2109 +gevent/tests/test___monitor.py,sha256=-hp7xNRmS3dnqgdfea9228hOUQ_IuG26WXTk2gsVZgE,12624 +gevent/tests/test___monkey_patching.py,sha256=2W6ZF3gTCSh9SgUjJUuX2OP1ZZCq9Vjsv20UPqgrXnY,3502 +gevent/tests/test__all__.py,sha256=j_TqCJ3_iILFT3tDlH0RBGjYv70dqzncJ536ove_ZOs,11547 +gevent/tests/test__api.py,sha256=zJF6cfQKnPscZio9ErpkY2Mn2NNPOzNnzX4J8ujx4ww,4550 +gevent/tests/test__api_timeout.py,sha256=is-HOBSQiMKPc67r41FqamL3KOF5BnfmtV8kW01JId4,6323 +gevent/tests/test__ares_host_result.py,sha256=f-ZJubI1wyzJExMifQnRFNpNcxkZ0Ykyp2W75jLjrqY,908 +gevent/tests/test__ares_timeout.py,sha256=65MC4NdPYJzbLO90FRjwtPuz3E_Y0JJm2Ld5aDcYLcU,1015 +gevent/tests/test__backdoor.py,sha256=y6xN2JGBlo4EziEWp5C4Xh550RMe60EHyrgGm73VE4I,5580 +gevent/tests/test__close_backend_fd.py,sha256=6yssqISBW-rhKZx25iCDbE6gaLYAEBCTzPlchwzsB7Y,3865 +gevent/tests/test__compat.py,sha256=YBE4IJwtRozcCRqeZXY9dkxqjZ6m2xS0Pk1ceApjvnE,1439 +gevent/tests/test__contextvars.py,sha256=JUPQ3TzpSLTQkdRNr7g2OgEzmFIK5vd8ml2bF7BNTYc,31717 +gevent/tests/test__core.py,sha256=VDxOazcjEyhp4o094xQcKSupm-Qf0aDNN0o3Ja_UF7s,5618 +gevent/tests/test__core_async.py,sha256=X4CNU4Kroea9fyjlfd_l8HmMLKfvec-eE4qzqTPZNow,761 +gevent/tests/test__core_callback.py,sha256=occ-buOrq8DrbJ0GUzHeMVF-Qcuu5e4qnUPnrmqvq80,618 +gevent/tests/test__core_fork.py,sha256=i4WdiNIL_LWINMg38rnNakfCfVZiMkFgVo9wUsiXxH4,2738 +gevent/tests/test__core_loop_run.py,sha256=N6ZHGuVfrclHoKrL1R8T7BeObT9P28Ey2wfvyo_jGJs,494 +gevent/tests/test__core_stat.py,sha256=YvqLSe-9j5tIFC6MoPQhD5_0MdBtxrbVagp4o0jzpw8,3754 +gevent/tests/test__core_timer.py,sha256=e6VG-IHLiQ3OkrTOYGiLMX4VdU6RLG3UoA69uao2xG8,4330 +gevent/tests/test__core_watcher.py,sha256=ULftUAJqrMLYgzItmSzEosgeagKbI72m0oheKn14vYo,3573 +gevent/tests/test__destroy.py,sha256=fy9Gh1WH6URkLCTjVv2RzxljX6DDRZXmaCuUEHVCYf8,1765 +gevent/tests/test__destroy_default_loop.py,sha256=9KsDb5i7Nn4uFrNrfT_vMYLOG7VV6-hp46HGlFg06nc,2199 +gevent/tests/test__doctests.py,sha256=aZqNLQDOpyvFYkhmqgXyDRhtV3CnN50H4OnZkp0vC0E,3613 +gevent/tests/test__environ.py,sha256=i7sqbSsRVyM5ypN9obyVIMWKyATOs5FC3BrMNf_i5Sk,608 +gevent/tests/test__event.py,sha256=UVT1jc5lgWoTJnWSEThOhrV3kaXCk7oA6ai8d-JiYYQ,14176 +gevent/tests/test__events.py,sha256=wa8mZSnMCsZ_qX2ak0Lwy3RE0MqXfdaSevLv0PEzXFM,1465 +gevent/tests/test__example_echoserver.py,sha256=oHLko-fDrrhS-3YrSr86B599W1ww1-MlTomarszLuZM,1198 +gevent/tests/test__example_portforwarder.py,sha256=hIVFPP8CBapzR918PBlrZM_Zibt8OyzDdKD9V1vfgbw,2025 +gevent/tests/test__example_udp_client.py,sha256=VGDHP_cYMlxnDkqW1E1fs-WteLH_6O7euW3SYvA1Mvk,884 +gevent/tests/test__example_udp_server.py,sha256=ApnWzkhqlHXmELMwgviFr8jf2QU4obHYefWCq1t2zlY,513 +gevent/tests/test__example_webproxy.py,sha256=Tg4dVbS725yOQVoslPz3FpA6SFAoYKIPAhddwUvEvEs,807 +gevent/tests/test__example_wsgiserver.py,sha256=bavlc9OfdFdkyibxxGhBuhEFXOYcfyc_Jqg0P8gfQEo,3202 +gevent/tests/test__example_wsgiserver_ssl.py,sha256=Ztn83XeMTLENcZduhdE2hiGYitSvi0hEQLJaD1tLpdA,649 +gevent/tests/test__examples.py,sha256=F2tAzDtGDYz3mo9Y5u0UfgnXGUTSz6TbtxK_LzEJyFQ,3336 +gevent/tests/test__exc_info.py,sha256=qp4J_TJrPk3JakATBvyOBO_7UbEhpoXmqVShNRK3yvY,1377 +gevent/tests/test__execmodules.py,sha256=oUgXwnV9wD3PZSJD6RVzWj9DxDpnmzPE5pm0z8YgG_4,1628 +gevent/tests/test__fileobject.py,sha256=38RddEZk-TdK0adkLpZmrKQUkJwXifAFrcT2fvkViAI,18345 +gevent/tests/test__getaddrinfo_import.py,sha256=eGmX5zaq-x9Or3UGtIZL8yqNN97yVBQx9zlehM3ogE4,463 +gevent/tests/test__greenio.py,sha256=vYzw_tSAAZxD0TjbKt_9wy_2KM3727YjUEdmcJ6GNvc,5523 +gevent/tests/test__greenlet.py,sha256=_bm2-nbngzCtR1mjC7LuugvWX-BhHANrnwUpeEOaYDw,32010 +gevent/tests/test__greenletset.py,sha256=NaIikUvwC7FcHjZQ24P3blp3iW4VaLImJfqH_E6mVuo,5032 +gevent/tests/test__greenness.py,sha256=YztEj8cMW3XkbTtoRJPv8K5yKugRwhlWy6szMKRwk2o,2790 +gevent/tests/test__hub.py,sha256=kT1T7tzDAZ1zmU3EsYGhGBqyYRv7acMVgTA3_BE1Ok0,13728 +gevent/tests/test__hub_join.py,sha256=-V1LjhFtZOAvCTWJsqxsLKFGicoDbp3NpojlS1EOZKc,3217 +gevent/tests/test__hub_join_timeout.py,sha256=E6Ul1xhZ1Ro7_IMx9QZBpf1zzWl1yrYWS11K25JyLho,2913 +gevent/tests/test__import_blocking_in_greenlet.py,sha256=BEEB6WrcXqFscxQxEIdMzlLVQ-KFvDlQ52yNlQWxIKs,1134 +gevent/tests/test__import_wait.py,sha256=-m2mg2urO-nNDTj3Ov0QNXuDmgr7rOCa7MKD-LT5cyA,252 +gevent/tests/test__issue112.py,sha256=OxamNgJF1QlKuirw_jJNYzpE84PgjYP2z1x27n61JQc,338 +gevent/tests/test__issue1686.py,sha256=5CIooK1MteQPtSWaWPpvyzMil_OLcvIYeHjIcZHlpxE,2878 +gevent/tests/test__issue1864.py,sha256=Xb3CcArxYDox-lCDpHOpwTkE5XXM3jK5zqUk3zyKGzk,1291 +gevent/tests/test__issue230.py,sha256=3zEzP5fLwLaHUeX0xNntV29AhhtHr_9t0cG1SPSa24c,500 +gevent/tests/test__issue330.py,sha256=qDbqSKfvZ4IdR_r7PwDAuCfTQuZEjLELSK1IvTowoaI,2333 +gevent/tests/test__issue467.py,sha256=PrqSlERQf8XttyiNB5NRZqEo8D0cmNTiO8qIdamRgPg,1205 +gevent/tests/test__issue6.py,sha256=OOBbWEwmA4zKxpF8jZ_5fm4E7uHKbqxP63FiE0ktU9w,1530 +gevent/tests/test__issue600.py,sha256=dKW-RzdzaJhVl8dClpBzLzgRjMn7BlqeTIiIB97R9cw,1386 +gevent/tests/test__issue607.py,sha256=-lQuJxVfIPDhrrf1G-2BpIbQqwDMygDeuRMh7vANGPM,1354 +gevent/tests/test__issue639.py,sha256=ExWDeXqUDqGTXF1rx6t1SQjac4GWKqZ2opusTpxgi1g,214 +gevent/tests/test__issue_728.py,sha256=1u6WSToRxMYe70aLU5vMhrWSZ_OHtwN9oP6L4UXXywg,212 +gevent/tests/test__issues461_471.py,sha256=_Xwj-ImGgYuTcWGxITACba3FGnRHmlXZxTDkkChriVg,3889 +gevent/tests/test__iwait.py,sha256=uzef1gKSo8dDbciyjZobklIXNDdc-B0ehEKb3iIn2Bg,1205 +gevent/tests/test__joinall.py,sha256=UAV56-NMPLhs8TBYJ-qcNAC8gT_ZoUAcOq22_qYEQZM,296 +gevent/tests/test__local.py,sha256=1iThKxhRmbTG5aH91kVNOEdU84CnsT3YMqjX3zY5WXU,11741 +gevent/tests/test__lock.py,sha256=9QBouc6_S4xVwbxraJNpTPN12S7R9c4yj_4mwF28KuA,1100 +gevent/tests/test__loop_callback.py,sha256=SUKmuaQh4sSC1fTyGv3zaTG1NkJN7T4EaJt-ezd_wT4,356 +gevent/tests/test__makefile_ref.py,sha256=OVdy8i-zQDzL_wnF9_M_WL_3cT1S_k-VAAKQQ8Rh-MA,19150 +gevent/tests/test__memleak.py,sha256=Yq3tfWmbpgI5hYopozWEHSbP8Xs4lDqBBQ76in2mFxc,1466 +gevent/tests/test__monkey.py,sha256=DNAhYP27e9l3t_wFATd99SHlPKhbSzzYPF6mKh3WGdM,6722 +gevent/tests/test__monkey_builtins_future.py,sha256=ZUJj7wWz9jEa9vDPSdEPrjqewiUwBspmtgh7RN8LymA,521 +gevent/tests/test__monkey_hub_in_thread.py,sha256=iMWv4a8Agy_llZypYxXo62kSB7LLTdNG5u9N_eHKIg8,520 +gevent/tests/test__monkey_logging.py,sha256=ZBbUvAqOam0Twekv_Mint1dWiWBt_ce9Y7L3JRCrqGU,1564 +gevent/tests/test__monkey_module_run.py,sha256=G-bHCowrKt4dDUgotEeB5rX8yVlDrfppIRGKYJIOdA8,4368 +gevent/tests/test__monkey_multiple_imports.py,sha256=QwmJJ4r3RXOQhti_5vj3Let0zllXzq4GwDY8NqzJUuQ,296 +gevent/tests/test__monkey_queue.py,sha256=d9m4mfBPMFa5bhuyNOOEMHEoBLc7bvlCz7Q3jbODULk,12337 +gevent/tests/test__monkey_select.py,sha256=U77pqLIX-2wCtdY7CxigfT0wgSTBqHs3e53eajJV45A,741 +gevent/tests/test__monkey_selectors.py,sha256=gootPuj6Hp_ZuT_ChQmjkR75TY9xNmTXNq0nTbRxEMU,2580 +gevent/tests/test__monkey_sigchld.py,sha256=U4L8AciJ-1-ivwMZlfIMkgpmoWFVxxlZri0bsJ_1vvo,2939 +gevent/tests/test__monkey_sigchld_2.py,sha256=zV1WsDX8dTQiW6XBOs0GQejZsq2obE2LA9Dil1eo_9Y,1774 +gevent/tests/test__monkey_sigchld_3.py,sha256=dlaDG9t4kPRfhT6anZRRCkltvQSKWNeKPOBd7doAgGo,1755 +gevent/tests/test__monkey_ssl_warning.py,sha256=vvfhrq-1zurv3ERAaeiIotk1LARVAGeUy4UDdrde7Zk,1250 +gevent/tests/test__monkey_ssl_warning2.py,sha256=NRlZ8-s-doOC6xNkQbaiVPIaqOtFBfEmQzyrKsUukww,1255 +gevent/tests/test__monkey_ssl_warning3.py,sha256=WZEOHQoewYAuYJu0f8UMjpmRzaR0B-sf0wBhvaRKTEQ,1330 +gevent/tests/test__nondefaultloop.py,sha256=Y3IrgT8SF3SmO3A1IlvC0nF4GCqxzvKES0KqvO72crE,204 +gevent/tests/test__order.py,sha256=iI8wh316sNia20IkHx7wSnE_LKdCsse6Q89xVkQev1U,1125 +gevent/tests/test__os.py,sha256=FywENBJyzocpTd2dK_3VfqVWFBK2lPNhPm-8qkMZDog,5963 +gevent/tests/test__pool.py,sha256=oOf38RQcEVd8AQQuynwebNWLnQ2CRoXHV9hJWskmhrc,18351 +gevent/tests/test__pywsgi.py,sha256=qOp0J-IbtKy9EXZBXBG-EBE6j2a6Zp8E8Av11j_wSTQ,73786 +gevent/tests/test__queue.py,sha256=GZTa2XcuseEqJKNOa04Clk4ipPGPCgsARGo09nDjwxk,13107 +gevent/tests/test__real_greenlet.py,sha256=SoZQ8cY1wQFJnVmTFxuYvXo08KVyb99ZUqGDBUbo1C4,693 +gevent/tests/test__refcount.py,sha256=rqdMK4QiCLWTIblXbxvGJ2AWQimV91KDFmawHV-X5ik,5866 +gevent/tests/test__refcount_core.py,sha256=XiTmU2kYH-JkVINch2jpA1vGVKOc6ufdPW28DMNpo9c,600 +gevent/tests/test__resolver_dnspython.py,sha256=aA7rtaB273IaTG9whMwvtGwG8c42xTPtb4iH9gTR4DE,1117 +gevent/tests/test__select.py,sha256=q7wFNosgYq2T6BBekZ-DKZifNQVnbzXr-nfv4eewpVM,4069 +gevent/tests/test__selectors.py,sha256=SB2A581GN0ZDl_qk5LdQIeGI2q6Kbiwv7NGas238M6c,3789 +gevent/tests/test__semaphore.py,sha256=m-CHrKE_S5yyKd6O78b6j8AvmTFpgTVJtGT-b91nDvA,13756 +gevent/tests/test__server.py,sha256=VmpoHCkPW6baDlfzhfg9Jg8LIKefsOkXaP0KEUYKtU4,19882 +gevent/tests/test__server_pywsgi.py,sha256=0Fquqy69Xylu3UXATvd__Y9wTBXnohP9fdvEoUhGysI,3074 +gevent/tests/test__signal.py,sha256=3vN7T6bNTQchXHs6THkRm9QNROisO_40lGk1jgiO41I,3813 +gevent/tests/test__sleep0.py,sha256=uoruOPjsaPk1m0thN_4UppH4kW4k9fHQXDuLXnc3u5k,139 +gevent/tests/test__socket.py,sha256=GbN3AZC6eup3G8w_bpnBf7jcAWL2oCTYG9Zzd-KC8FU,23490 +gevent/tests/test__socket_close.py,sha256=_lidh6C8SSup3avpXKUdv0Kkok1GiLbaC_5Dn6hkiRQ,1862 +gevent/tests/test__socket_dns.py,sha256=n_KUI-C2x15cfoj_3N7XlOevQAsMI721zdWm4ToyZJo,36681 +gevent/tests/test__socket_dns6.py,sha256=zCqRfupQLxCNNQFaHVat5pzO_UMWiBORnmxWeax_K9U,3716 +gevent/tests/test__socket_errors.py,sha256=L6ZZymYkkYGq6V_S7lzdC2D1J-0jQkKF9_xytAldQN8,1869 +gevent/tests/test__socket_ex.py,sha256=RYT56ubUxD-e13wL1rG5NS9afx0gaqYfKcqzL0uS0T0,1110 +gevent/tests/test__socket_send_memoryview.py,sha256=xhNyL7y_TriGrMbJvKmbwEReUBMR_M6LKL0l0IarBbE,960 +gevent/tests/test__socket_ssl.py,sha256=X7iDcOwBbtX7e0B_JBXoSFI_dRzpQzVMGYpMQTswtf4,865 +gevent/tests/test__socket_timeout.py,sha256=_TqCsWOPrKNMJ8OFvKGjLIbiToDm7X1Y1wJxR39rJME,1351 +gevent/tests/test__socketpair.py,sha256=VKi94yATBBTzKsN7S7D1rpx-GropJf0qXRpw9GT43c0,951 +gevent/tests/test__ssl.py,sha256=mTvZ6r9hJxh_9siwPgQDwaG7c4WTjDDIPr4JsfY7JpA,5597 +gevent/tests/test__subprocess.py,sha256=7hByz0Yh4_BG93BwDhnGyZPvMnPlW11RLSmp6Hy3daQ,20208 +gevent/tests/test__subprocess_interrupted.py,sha256=qNr4GCwg-xhLrZLGHnprQILnj0g08-GozvYClSR_uE0,1922 +gevent/tests/test__subprocess_poll.py,sha256=AFlQJZcNCfDKP5zwefoGmSFvPe_1cT5HpUu_VDbp4Lk,346 +gevent/tests/test__systemerror.py,sha256=lgUg-grJQ6VTNXjOTkQQGds6m7PmtoPgddG-tYURYsU,3295 +gevent/tests/test__thread.py,sha256=xhyh6Z_HQzh2kqSjdoPoEdUURzj8A2B2l1dbXpuv1yc,780 +gevent/tests/test__threading.py,sha256=R6eAMnNIMQE757HL6JdwKaCFQq21HD4uPCen5iRCghc,2586 +gevent/tests/test__threading_2.py,sha256=Z23N_WRNT6h2wDGuK-qQY6UWi7NKxB5Vy6dW8og-4EM,23535 +gevent/tests/test__threading_before_monkey.py,sha256=DhdEFVUY6LTb-74I3KgiFExW-aFvSn_B8jTvMS_NjWo,714 +gevent/tests/test__threading_fork_from_dummy.py,sha256=Ds0y3KgYqLzQnjUuAeu2WmpBtabpMF9qA4n6weoirwQ,2181 +gevent/tests/test__threading_holding_lock_while_monkey.py,sha256=5IWkIjTs1eRlphtDF0cCINz16M6tUi9hZMB-R_eVMIw,411 +gevent/tests/test__threading_monkey_in_thread.py,sha256=rnxzlmcUahqg4pWEIdh-5bmIMdGn5ed-V7hjt-WxXDo,2366 +gevent/tests/test__threading_native_before_monkey.py,sha256=KvQaAWQe78cGVYT-T2MAh6T4s7YUZdza8-vqxS4YJp0,2157 +gevent/tests/test__threading_no_monkey.py,sha256=FkY93eRfkpZjsbEzLbJLvtI9-POMbAGYd3IpJE8peHw,806 +gevent/tests/test__threading_patched_local.py,sha256=0EaAtlORHJjfxkUZzGKL1lOh-OY9hZa1R6MoUE0eSHo,675 +gevent/tests/test__threading_vs_settrace.py,sha256=vsRpAqYimfePGGqyTj-8M-SpGmwVN01JQ6yROkKBjl8,5023 +gevent/tests/test__threadpool.py,sha256=FhfeW0JZ5U_e84B8Q3JIb6KBxXKFkGSD6RsYVNHMMoM,24825 +gevent/tests/test__threadpool_executor_patched.py,sha256=KihwMAZ_hQfZBhnxv_CCx8HJnvdQaKxxaMuuJkV9IiM,386 +gevent/tests/test__timeout.py,sha256=uRjOchrp6NVrjkxrCW9UMd6r5iheRe8EjzpW5XDD7Bg,5243 +gevent/tests/test__util.py,sha256=8T3EPIPWlOQtAylapMTLjz32ZQyCudhRlchXx-EGSGQ,10705 +gevent/tests/test_server.crt,sha256=QIKfCQ-jpwWvzwJLO-eOSqT2TTSEVE-HLcC1wzs-YNw,1809 +gevent/tests/test_server.key,sha256=5yU4QY75gVWwTt4TE5EKkiOhENEwO0eP9oG3WTB0dtk,3268 +gevent/tests/tests_that_dont_do_leakchecks.txt,sha256=dzRXEFB_7uZlFI5ANA1VCfYCd9HTINqDTi1BcIkzxOY,223 +gevent/tests/tests_that_dont_monkeypatch.txt,sha256=PH8kQY8hpSlwzXJkJQpTsczkNZ13uUxkWM-Hl4Cz-wQ,647 +gevent/tests/tests_that_dont_use_resolver.txt,sha256=nhsAcj2CwFEsEtmfROY3NFiIe7Xqpb3AK1I-nQK6f2A,3184 +gevent/tests/wrongcert.pem,sha256=6n4u7wcalNKCtnMsq7J3Y7uOiez901ZLiH38oE0jGUM,1880 +gevent/thread.py,sha256=H6weO4bwie9U0DciiDjC1rDLMvkGgSKDO1xDT2pXaKE,10586 +gevent/threading.py,sha256=yIo2tlqfrlgutwKM9Bw1uIsbYQquMdGICBnXbsZHE6Q,16808 +gevent/threadpool.py,sha256=iQ90WLeFsm1XUM_cI_WehtKGLh9BJ-r-fgubPvsyTEo,30975 +gevent/time.py,sha256=C0eRlHq0rBxy9tC_SsIywkYaBNlwO1bc04qFi2OceB4,491 +gevent/timeout.py,sha256=TWuPBaYcXZMzX4vUEKtGVBCsLj3QClL6TWTCZq5Zcng,13678 +gevent/util.py,sha256=lZoYCZDZdkBQYd8wSCbbwdkVW0VTVx_cikkX1lxMDmg,22571 +gevent/win32util.py,sha256=WBk_YNf_kk3QF3PMUdScqgM_PreF4OBhfXq2W5264n0,3637 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/WHEEL b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7f736e9a4d9f982b35f055c3019059d4bae0e480 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/entry_points.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5fe662856e05c2f73d5f31044385f4f5052fa8d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[gevent.plugins.monkey.will_patch_all] +signal_os_incompat = gevent.monkey:_subscribe_signal_os diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/top_level.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a63abe68f639ef8b5d1e25ca733ecaeca39cbc8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/top_level.txt @@ -0,0 +1 @@ +gevent diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..56f1e9656e401f49a5cf5953a0976c470e9de957 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/__init__.py @@ -0,0 +1,27 @@ +""" +Internal helpers for FFI implementations. +""" +from __future__ import print_function, absolute_import + +import os +import sys + +def _dbg(*args, **kwargs): + # pylint:disable=unused-argument + pass + +#_dbg = print + +def _pid_dbg(*args, **kwargs): + kwargs['file'] = sys.stderr + print(os.getpid(), *args, **kwargs) + +CRITICAL = 1 +ERROR = 3 +DEBUG = 5 +TRACE = 9 + +GEVENT_DEBUG_LEVEL = vars()[os.getenv("GEVENT_DEBUG", 'CRITICAL').upper()] + +if GEVENT_DEBUG_LEVEL >= TRACE: + _dbg = _pid_dbg diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/callback.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..38ddda13418cf7c776bb7493dbeadd202fec3f20 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/callback.py @@ -0,0 +1,57 @@ +from __future__ import absolute_import +from __future__ import print_function + +from zope.interface import implementer + +from gevent._interfaces import ICallback + +__all__ = [ + 'callback', +] + + +@implementer(ICallback) +class callback(object): + + __slots__ = ('callback', 'args') + + def __init__(self, cb, args): + self.callback = cb + self.args = args + + def stop(self): + self.callback = None + self.args = None + + close = stop + + # Note that __nonzero__ and pending are different + # bool() is used in contexts where we need to know whether to schedule another callback, + # so it's true if it's pending or currently running + # 'pending' has the same meaning as libev watchers: it is cleared before actually + # running the callback + + def __bool__(self): + # it's nonzero if it's pending or currently executing + # NOTE: This depends on loop._run_callbacks setting the args property + # to None. + return self.args is not None + + @property + def pending(self): + return self.callback is not None + + def _format(self): + return '' + + def __repr__(self): + result = "<%s at 0x%x" % (self.__class__.__name__, id(self)) + if self.pending: + result += " pending" + if self.callback is not None: + result += " callback=%r" % (self.callback, ) + if self.args is not None: + result += " args=%r" % (self.args, ) + if self.callback is None and self.args is None: + result += " stopped" + return result + ">" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/loop.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/loop.py new file mode 100644 index 0000000000000000000000000000000000000000..6b25b2a77b600b8c31cadcbf3881249864191355 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/loop.py @@ -0,0 +1,789 @@ +""" +Basic loop implementation for ffi-based cores. +""" +# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable +from __future__ import absolute_import, print_function + +from collections import deque +import sys +import os +import traceback + +from gevent._ffi import _dbg +from gevent._ffi import GEVENT_DEBUG_LEVEL +from gevent._ffi import TRACE +from gevent._ffi.callback import callback +from gevent._compat import PYPY +from gevent.exceptions import HubDestroyed + +from gevent import getswitchinterval + +__all__ = [ + 'AbstractLoop', + 'assign_standard_callbacks', +] + + +class _EVENTSType(object): + def __repr__(self): + return 'gevent.core.EVENTS' + +EVENTS = GEVENT_CORE_EVENTS = _EVENTSType() + + +class _DiscardedSet(frozenset): + __slots__ = () + + def discard(self, o): + "Does nothing." + +##### +## Note on CFFI objects, callbacks and the lifecycle of watcher objects +# +# Each subclass of `watcher` allocates a C structure of the +# appropriate type e.g., struct gevent_ev_io and holds this pointer in +# its `_gwatcher` attribute. When that watcher instance is garbage +# collected, then the C structure is also freed. The C structure is +# passed to libev from the watcher's start() method and then to the +# appropriate C callback function, e.g., _gevent_ev_io_callback, which +# passes it back to python's _python_callback where we need the +# watcher instance. Therefore, as long as that callback is active (the +# watcher is started), the watcher instance must not be allowed to get +# GC'd---any access at the C level or even the FFI level to the freed +# memory could crash the process. +# +# However, the typical idiom calls for writing something like this: +# loop.io(fd, python_cb).start() +# thus forgetting the newly created watcher subclass and allowing it to be immediately +# GC'd. To combat this, when the watcher is started, it places itself into the loop's +# `_keepaliveset`, and it only removes itself when the watcher's `stop()` method is called. +# Often, this is the *only* reference keeping the watcher object, and hence its C structure, +# alive. +# +# This is slightly complicated by the fact that the python-level +# callback, called from the C callback, could choose to manually stop +# the watcher. When we return to the C level callback, we now have an +# invalid pointer, and attempting to pass it back to Python (e.g., to +# handle an error) could crash. Hence, _python_callback, +# _gevent_io_callback, and _python_handle_error cooperate to make sure +# that the watcher instance stays in the loops `_keepaliveset` while +# the C code could be running---and if it gets removed, to not call back +# to Python again. +# See also https://github.com/gevent/gevent/issues/676 +#### +class AbstractCallbacks(object): + + + def __init__(self, ffi): + self.ffi = ffi + self.callbacks = [] + if GEVENT_DEBUG_LEVEL < TRACE: + self.from_handle = ffi.from_handle + + def from_handle(self, handle): # pylint:disable=method-hidden + x = self.ffi.from_handle(handle) + return x + + def python_callback(self, handle, revents): + """ + Returns an integer having one of three values: + + - -1 + An exception occurred during the callback and you must call + :func:`_python_handle_error` to deal with it. The Python watcher + object will have the exception tuple saved in ``_exc_info``. + - 1 + Everything went according to plan. You should check to see if the native + watcher is still active, and call :func:`python_stop` if it is not. This will + clean up the memory. Finding the watcher still active at the event loop level, + but not having stopped itself at the gevent level is a buggy scenario and + shouldn't happen. + - 2 + Everything went according to plan, but the watcher has already + been stopped. Its memory may no longer be valid. + + This function should never return 0, as that's the default value that + Python exceptions will produce. + """ + #_dbg("Running callback", handle) + orig_ffi_watcher = None + orig_loop = None + try: + # Even dereferencing the handle needs to be inside the try/except; + # if we don't return normally (e.g., a signal) then we wind up going + # to the 'onerror' handler (unhandled_onerror), which + # is not what we want; that can permanently wedge the loop depending + # on which callback was executing. + # XXX: See comments in that function. We may be able to restart and do better? + if not handle: + # Hmm, a NULL handle. That's not supposed to happen. + # We can easily get into a loop if we deref it and allow that + # to raise. + _dbg("python_callback got null handle") + return 1 + the_watcher = self.from_handle(handle) + orig_ffi_watcher = the_watcher._watcher + orig_loop = the_watcher.loop + args = the_watcher.args + if args is None: + # Legacy behaviour from corecext: convert None into () + # See test__core_watcher.py + args = _NOARGS + if args and args[0] == GEVENT_CORE_EVENTS: + args = (revents, ) + args[1:] + the_watcher.callback(*args) # None here means we weren't started + except: # pylint:disable=bare-except + # It's possible for ``the_watcher`` to be undefined (UnboundLocalError) + # if we threw an exception (signal) on the line that created that variable. + # This is typically the case with a signal under libuv + try: + the_watcher + except UnboundLocalError: + the_watcher = self.from_handle(handle) + + # It may not be safe to do anything with `handle` or `orig_ffi_watcher` + # anymore. If the watcher closed or stopped itself *before* throwing the exception, + # then the `handle` and `orig_ffi_watcher` may no longer be valid. Attempting to + # e.g., dereference the handle is likely to crash the process. + the_watcher._exc_info = sys.exc_info() + + + # If it hasn't been stopped, we need to make sure its + # memory stays valid so we can stop it at the native level if needed. + # If its loop is gone, it has already been stopped, + # see https://github.com/gevent/gevent/issues/1295 for a case where + # that happened, as well as issue #1482 + if ( + # The last thing it does. Full successful close. + the_watcher.loop is None + # Only a partial close. We could leak memory and even crash later. + or the_watcher._handle is None + ): + # Prevent unhandled_onerror from using the invalid handle + handle = None + exc_info = the_watcher._exc_info + del the_watcher._exc_info + try: + if orig_loop is not None: + orig_loop.handle_error(the_watcher, *exc_info) + else: + self.unhandled_onerror(*exc_info) + except: + print("WARNING: gevent: Error when handling error", + file=sys.stderr) + traceback.print_exc() + # Signal that we're closed, no need to do more. + return 2 + + # Keep it around so we can close it later. + the_watcher.loop._keepaliveset.add(the_watcher) + return -1 + + if (the_watcher.loop is not None + and the_watcher in the_watcher.loop._keepaliveset + and the_watcher._watcher is orig_ffi_watcher): + # It didn't stop itself, *and* it didn't stop itself, reset + # its watcher, and start itself again. libuv's io watchers + # multiplex and may do this. + + # The normal, expected scenario when we find the watcher still + # in the keepaliveset is that it is still active at the event loop + # level, so we don't expect that python_stop gets called. + #_dbg("The watcher has not stopped itself, possibly still active", the_watcher) + return 1 + return 2 # it stopped itself + + def python_handle_error(self, handle, _revents): + _dbg("Handling error for handle", handle) + if not handle: + return + try: + watcher = self.from_handle(handle) + exc_info = watcher._exc_info + del watcher._exc_info + # In the past, we passed the ``watcher`` itself as the context, + # which typically meant that the Hub would just print + # the exception. This is a problem because sometimes we can't + # detect signals until late in ``python_callback``; specifically, + # test_selectors.py:DefaultSelectorTest.test_select_interrupt_exc + # installs a SIGALRM handler that raises an exception. That exception can happen + # before we enter ``python_callback`` or at any point within it because of the way + # libuv swallows signals. By passing None, we get the exception prapagated into + # the main greenlet (which is probably *also* not what we always want, but + # I see no way to distinguish the cases). + watcher.loop.handle_error(None, *exc_info) + finally: + # XXX Since we're here on an error condition, and we + # made sure that the watcher object was put in loop._keepaliveset, + # what about not stopping the watcher? Looks like a possible + # memory leak? + # XXX: This used to do "if revents & (libev.EV_READ | libev.EV_WRITE)" + # before stopping. Why? + try: + watcher.stop() + except: # pylint:disable=bare-except + watcher.loop.handle_error(watcher, *sys.exc_info()) + return # pylint:disable=lost-exception,return-in-finally + + def unhandled_onerror(self, t, v, tb): + # This is supposed to be called for signals, etc. + # This is the onerror= value for CFFI. + # If we return None, C will get a value of 0/NULL; + # if we raise, CFFI will print the exception and then + # return 0/NULL; (unless error= was configured) + # If things go as planned, we return the value that asks + # C to call back and check on if the watcher needs to be closed or + # not. + + # XXX: TODO: Could this cause events to be lost? Maybe we need to return + # a value that causes the C loop to try the callback again? + # at least for signals under libuv, which are delivered at very odd times. + # Hopefully the event still shows up when we poll the next time. + watcher = None + handle = tb.tb_frame.f_locals.get('handle') if tb is not None else None + if handle: # handle could be NULL + watcher = self.from_handle(handle) + if watcher is not None: + watcher.loop.handle_error(None, t, v, tb) + return 1 + + # Raising it causes a lot of noise from CFFI + print("WARNING: gevent: Unhandled error with no watcher", + file=sys.stderr) + traceback.print_exception(t, v, tb) + + def python_stop(self, handle): + if not handle: # pragma: no cover + print( + "WARNING: gevent: Unable to dereference handle; not stopping watcher. " + "Native resources may leak. This is most likely a bug in gevent.", + file=sys.stderr) + # The alternative is to crash with no helpful information + # NOTE: Raising exceptions here does nothing, they're swallowed by CFFI. + # Since the C level passed in a null pointer, even dereferencing the handle + # will just produce some exceptions. + return + watcher = self.from_handle(handle) + watcher.stop() + + if not PYPY: + def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument + # If we have the onerror callback, this is a no-op; all the real + # work to rethrow the exception is done by the onerror callback + + # NOTE: Unlike the rest of the functions, this is called with a pointer + # to the C level structure, *not* a pointer to the void* that represents a + # for the Python Watcher object. + pass + else: # PyPy + # On PyPy, we need the function to have some sort of body, otherwise + # the signal exceptions don't always get caught, *especially* with + # libuv (however, there's no reason to expect this to only be a libuv + # issue; it's just that we don't depend on the periodic signal timer + # under libev, so the issue is much more pronounced under libuv) + # test_socket's test_sendall_interrupted can hang. + # See https://github.com/gevent/gevent/issues/1112 + + def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument + # Things we've tried that *don't* work: + # greenlet.getcurrent() + # 1 + 1 + try: + raise MemoryError() + except MemoryError: + pass + + def python_prepare_callback(self, watcher_ptr): + loop = self._find_loop_from_c_watcher(watcher_ptr) + if loop is None: # pragma: no cover + print("WARNING: gevent: running prepare callbacks from a destroyed handle: ", + watcher_ptr) + return + loop._run_callbacks() + + def check_callback_onerror(self, t, v, tb): + loop = None + watcher_ptr = self._find_watcher_ptr_in_traceback(tb) + if watcher_ptr: + loop = self._find_loop_from_c_watcher(watcher_ptr) + if loop is not None: + # None as the context argument causes the exception to be raised + # in the main greenlet. + loop.handle_error(None, t, v, tb) + return None + raise v # Let CFFI print + + def _find_loop_from_c_watcher(self, watcher_ptr): + raise NotImplementedError() + + def _find_watcher_ptr_in_traceback(self, tb): + return tb.tb_frame.f_locals['watcher_ptr'] if tb is not None else None + + +def assign_standard_callbacks(ffi, lib, callbacks_class, extras=()): # pylint:disable=unused-argument + """ + Given the typical *ffi* and *lib* arguments, and a subclass of :class:`AbstractCallbacks` + in *callbacks_class*, set up the ``def_extern`` Python callbacks from C + into an instance of *callbacks_class*. + + :param tuple extras: If given, this is a sequence of ``(name, error_function)`` + additional callbacks to register. Each *name* is an attribute of + the *callbacks_class* instance. (Each element cas also be just a *name*.) + :return: The *callbacks_class* instance. This object must be kept alive, + typically at module scope. + """ + # callbacks keeps these cdata objects alive at the python level + callbacks = callbacks_class(ffi) + extras = [extra if len(extra) == 2 else (extra, None) for extra in extras] + extras = tuple((getattr(callbacks, name), error) for name, error in extras) + for (func, error_func) in ( + (callbacks.python_callback, None), + (callbacks.python_handle_error, None), + (callbacks.python_stop, None), + (callbacks.python_check_callback, callbacks.check_callback_onerror), + (callbacks.python_prepare_callback, callbacks.check_callback_onerror) + ) + extras: + # The name of the callback function matches the 'extern Python' declaration. + error_func = error_func or callbacks.unhandled_onerror + callback = ffi.def_extern(onerror=error_func)(func) + # keep alive the cdata + # (def_extern returns the original function, and it requests that + # the function be "global", so maybe it keeps a hard reference to it somewhere now + # unlike ffi.callback(), and we don't need to do this?) + callbacks.callbacks.append(callback) + + # At this point, the library C variable (static function, actually) + # is filled in. + + return callbacks + + + +basestring = (bytes, str) +integer_types = (int,) + + +_NOARGS = () + + +class AbstractLoop(object): + # pylint:disable=too-many-public-methods,too-many-instance-attributes + + # How many callbacks we should run between checking against the + # switch interval. + CALLBACK_CHECK_COUNT = 50 + + error_handler = None + + _CHECK_POINTER = None + + _TIMER_POINTER = None + _TIMER_CALLBACK_SIG = None + + _PREPARE_POINTER = None + + starting_timer_may_update_loop_time = False + + # Subclasses should set this in __init__ to reflect + # whether they were the default loop. + _default = None + + _keepaliveset = _DiscardedSet() + _threadsafe_async = None + + def __init__(self, ffi, lib, watchers, flags=None, default=None): + self._ffi = ffi + self._lib = lib + self._ptr = None + self._handle_to_self = self._ffi.new_handle(self) # XXX: Reference cycle? + self._watchers = watchers + self._in_callback = False + self._callbacks = deque() + # Stores python watcher objects while they are started + self._keepaliveset = set() + self._init_loop_and_aux_watchers(flags, default) + + def _init_loop_and_aux_watchers(self, flags=None, default=None): + self._ptr = self._init_loop(flags, default) + + # self._check is a watcher that runs in each iteration of the + # mainloop, just after the blocking call. It's point is to handle + # signals. It doesn't run watchers or callbacks, it just exists to give + # CFFI a chance to raise signal exceptions so we can handle them. + self._check = self._ffi.new(self._CHECK_POINTER) + self._check.data = self._handle_to_self + self._init_and_start_check() + + # self._prepare is a watcher that runs in each iteration of the mainloop, + # just before the blocking call. It's where we run deferred callbacks + # from self.run_callback. This cooperates with _setup_for_run_callback() + # to schedule self._timer0 if needed. + self._prepare = self._ffi.new(self._PREPARE_POINTER) + self._prepare.data = self._handle_to_self + self._init_and_start_prepare() + + # A timer we start and stop on demand. If we have callbacks, + # too many to run in one iteration of _run_callbacks, we turn this + # on so as to have the next iteration of the run loop return to us + # as quickly as possible. + # TODO: There may be a more efficient way to do this using ev_timer_again; + # see the "ev_timer" section of the ev manpage (http://linux.die.net/man/3/ev) + # Alternatively, setting the ev maximum block time may also work. + self._timer0 = self._ffi.new(self._TIMER_POINTER) + self._timer0.data = self._handle_to_self + self._init_callback_timer() + + self._threadsafe_async = self.async_(ref=False) + # No need to do anything with this on ``fork()``, both libev and libuv + # take care of creating a new pipe in their respective ``loop_fork()`` methods. + self._threadsafe_async.start(lambda: None) + # TODO: We may be able to do something nicer and use the existing python_callback + # combined with onerror and the class check/timer/prepare to simplify things + # and unify our handling + + def _init_loop(self, flags, default): + """ + Called by __init__ to create or find the loop. The return value + is assigned to self._ptr. + """ + raise NotImplementedError() + + def _init_and_start_check(self): + raise NotImplementedError() + + def _init_and_start_prepare(self): + raise NotImplementedError() + + def _init_callback_timer(self): + raise NotImplementedError() + + def _stop_callback_timer(self): + raise NotImplementedError() + + def _start_callback_timer(self): + raise NotImplementedError() + + def _check_callback_handle_error(self, t, v, tb): + self.handle_error(None, t, v, tb) + + def _run_callbacks(self): # pylint:disable=too-many-branches + # When we're running callbacks, its safe for timers to + # update the notion of the current time (because if we're here, + # we're not running in a timer callback that may let other timers + # run; this is mostly an issue for libuv). + + # That's actually a bit of a lie: on libev, self._timer0 really is + # a timer, and so sometimes this is running in a timer callback, not + # a prepare callback. But that's OK, libev doesn't suffer from cascading + # timer expiration and its safe to update the loop time at any + # moment there. + self.starting_timer_may_update_loop_time = True + try: + count = self.CALLBACK_CHECK_COUNT + now = self.now() + expiration = now + getswitchinterval() + self._stop_callback_timer() + while self._callbacks: + cb = self._callbacks.popleft() # pylint:disable=assignment-from-no-return + count -= 1 + self.unref() # XXX: libuv doesn't have a global ref count! + callback = cb.callback + cb.callback = None + args = cb.args + if callback is None or args is None: + # it's been stopped + continue + + try: + callback(*args) + except: # pylint:disable=bare-except + # If we allow an exception to escape this method (while we are running the ev callback), + # then CFFI will print the error and libev will continue executing. + # There are two problems with this. The first is that the code after + # the loop won't run. The second is that any remaining callbacks scheduled + # for this loop iteration will be silently dropped; they won't run, but they'll + # also not be *stopped* (which is not a huge deal unless you're looking for + # consistency or checking the boolean/pending status; the loop doesn't keep + # a reference to them like it does to watchers...*UNLESS* the callback itself had + # a reference to a watcher; then I don't know what would happen, it depends on + # the state of the watcher---a leak or crash is not totally inconceivable). + # The Cython implementation in core.ppyx uses gevent_call from callbacks.c + # to run the callback, which uses gevent_handle_error to handle any errors the + # Python callback raises...it unconditionally simply prints any error raised + # by loop.handle_error and clears it, so callback handling continues. + # We take a similar approach (but are extra careful about printing) + try: + self.handle_error(cb, *sys.exc_info()) + except: # pylint:disable=bare-except + try: + print("Exception while handling another error", file=sys.stderr) + traceback.print_exc() + except: # pylint:disable=bare-except + pass # Nothing we can do here + finally: + # NOTE: this must be reset here, because cb.args is used as a flag in + # the callback class so that bool(cb) of a callback that has been run + # becomes False + cb.args = None + + # We've finished running one group of callbacks + # but we may have more, so before looping check our + # switch interval. + if count == 0 and self._callbacks: + count = self.CALLBACK_CHECK_COUNT + self.update_now() + if self.now() >= expiration: + now = 0 + break + + # Update the time before we start going again, if we didn't + # just do so. + if now != 0: + self.update_now() + + if self._callbacks: + self._start_callback_timer() + finally: + self.starting_timer_may_update_loop_time = False + + def _stop_aux_watchers(self): + if self._threadsafe_async is not None: + self._threadsafe_async.close() + self._threadsafe_async = None + + def destroy(self): + ptr = self.ptr + if ptr: + try: + if not self._can_destroy_loop(ptr): + return False + self._stop_aux_watchers() + self._destroy_loop(ptr) + finally: + # not ffi.NULL, we don't want something that can be + # passed to C and crash later. This will create nice friendly + # TypeError from CFFI. + self._ptr = None + del self._handle_to_self + del self._callbacks + del self._keepaliveset + + return True + + def _can_destroy_loop(self, ptr): + raise NotImplementedError() + + def _destroy_loop(self, ptr): + raise NotImplementedError() + + @property + def ptr(self): + # Use this when you need to be sure the pointer is valid. + return self._ptr + + @property + def WatcherType(self): + return self._watchers.watcher + + @property + def MAXPRI(self): + return 1 + + @property + def MINPRI(self): + return 1 + + def _handle_syserr(self, message, errno): + try: + errno = os.strerror(errno) + except: # pylint:disable=bare-except + traceback.print_exc() + try: + message = '%s: %s' % (message, errno) + except: # pylint:disable=bare-except + traceback.print_exc() + self.handle_error(None, SystemError, SystemError(message), None) + + def handle_error(self, context, type, value, tb): + if type is HubDestroyed: + self._callbacks.clear() + self.break_() + return + + handle_error = None + error_handler = self.error_handler + if error_handler is not None: + # we do want to do getattr every time so that setting Hub.handle_error property just works + handle_error = getattr(error_handler, 'handle_error', error_handler) + handle_error(context, type, value, tb) + else: + self._default_handle_error(context, type, value, tb) + + def _default_handle_error(self, context, type, value, tb): # pylint:disable=unused-argument + # note: Hub sets its own error handler so this is not used by gevent + # this is here to make core.loop usable without the rest of gevent + # Should cause the loop to stop running. + traceback.print_exception(type, value, tb) + + + def run(self, nowait=False, once=False): + raise NotImplementedError() + + def reinit(self): + raise NotImplementedError() + + def ref(self): + # XXX: libuv doesn't do it this way + raise NotImplementedError() + + def unref(self): + raise NotImplementedError() + + def break_(self, how=None): + raise NotImplementedError() + + def verify(self): + pass + + def now(self): + raise NotImplementedError() + + def update_now(self): + raise NotImplementedError() + + def update(self): + import warnings + warnings.warn("'update' is deprecated; use 'update_now'", + DeprecationWarning, + stacklevel=2) + self.update_now() + + def __repr__(self): + return '<%s.%s at 0x%x %s>' % ( + self.__class__.__module__, + self.__class__.__name__, + id(self), + self._format() + ) + + @property + def default(self): + return self._default if self.ptr else False + + @property + def iteration(self): + return -1 + + @property + def depth(self): + return -1 + + @property + def backend_int(self): + return 0 + + @property + def backend(self): + return "default" + + @property + def pendingcnt(self): + return 0 + + def io(self, fd, events, ref=True, priority=None): + return self._watchers.io(self, fd, events, ref, priority) + + def closing_fd(self, fd): # pylint:disable=unused-argument + return False + + def timer(self, after, repeat=0.0, ref=True, priority=None): + return self._watchers.timer(self, after, repeat, ref, priority) + + def signal(self, signum, ref=True, priority=None): + return self._watchers.signal(self, signum, ref, priority) + + def idle(self, ref=True, priority=None): + return self._watchers.idle(self, ref, priority) + + def prepare(self, ref=True, priority=None): + return self._watchers.prepare(self, ref, priority) + + def check(self, ref=True, priority=None): + return self._watchers.check(self, ref, priority) + + def fork(self, ref=True, priority=None): + return self._watchers.fork(self, ref, priority) + + def async_(self, ref=True, priority=None): + return self._watchers.async_(self, ref, priority) + + # Provide BWC for those that can use 'async' as is + locals()['async'] = async_ + + if sys.platform != "win32": + + def child(self, pid, trace=0, ref=True): + return self._watchers.child(self, pid, trace, ref) + + def install_sigchld(self): + pass + + def stat(self, path, interval=0.0, ref=True, priority=None): + return self._watchers.stat(self, path, interval, ref, priority) + + def callback(self, priority=None): + return callback(self, priority) + + def _setup_for_run_callback(self): + raise NotImplementedError() + + def run_callback(self, func, *args): + # If we happen to already be running callbacks (inside + # _run_callbacks), this could happen almost immediately, + # without the loop cycling. + cb = callback(func, args) + self._callbacks.append(cb) # Relying on the GIL for this to be threadsafe + self._setup_for_run_callback() # XXX: This may not be threadsafe. + return cb + + def run_callback_threadsafe(self, func, *args): + cb = self.run_callback(func, *args) + self._threadsafe_async.send() + return cb + + def _format(self): + ptr = self.ptr + if not ptr: + return 'destroyed' + msg = "backend=" + self.backend + msg += ' ptr=' + str(ptr) + if self.default: + msg += ' default' + msg += ' pending=%s' % self.pendingcnt + msg += self._format_details() + return msg + + def _format_details(self): + msg = '' + fileno = self.fileno() # pylint:disable=assignment-from-none + try: + activecnt = self.activecnt + except AttributeError: + activecnt = None + if activecnt is not None: + msg += ' ref=' + repr(activecnt) + if fileno is not None: + msg += ' fileno=' + repr(fileno) + #if sigfd is not None and sigfd != -1: + # msg += ' sigfd=' + repr(sigfd) + msg += ' callbacks=' + str(len(self._callbacks)) + return msg + + def fileno(self): + return None + + @property + def activecnt(self): + if not self.ptr: + raise ValueError('operation on destroyed loop') + return 0 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/watcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c723925818245d2b2fab596af22e78443ef752 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/watcher.py @@ -0,0 +1,644 @@ +""" +Useful base classes for watchers. The available +watchers will depend on the specific event loop. +""" +# pylint:disable=not-callable +from __future__ import absolute_import, print_function + +import signal as signalmodule +import functools +import warnings + +from gevent._config import config +from gevent._util import LazyOnClass + +try: + from tracemalloc import get_object_traceback + + def tracemalloc(init): + # PYTHONTRACEMALLOC env var controls this on Python 3. + return init +except ImportError: # Python < 3.4 + + if config.trace_malloc: + # Use the same env var to turn this on for Python 2 + import traceback + + class _TB(object): + __slots__ = ('lines',) + + def __init__(self, lines): + # These end in newlines, which we don't want for consistency + self.lines = [x.rstrip() for x in lines] + + def format(self): + return self.lines + + def tracemalloc(init): + @functools.wraps(init) + def traces(self, *args, **kwargs): + init(self, *args, **kwargs) + self._captured_malloc = _TB(traceback.format_stack()) + return traces + + def get_object_traceback(obj): + return obj._captured_malloc + + else: + def get_object_traceback(_obj): + return None + + def tracemalloc(init): + return init + +from gevent._compat import fsencode + +from gevent._ffi import _dbg # pylint:disable=unused-import +from gevent._ffi import GEVENT_DEBUG_LEVEL +from gevent._ffi import DEBUG +from gevent._ffi.loop import GEVENT_CORE_EVENTS +from gevent._ffi.loop import _NOARGS + +ALLOW_WATCHER_DEL = GEVENT_DEBUG_LEVEL >= DEBUG + +__all__ = [ + +] + +try: + ResourceWarning # pylint:disable=used-before-assignment +except NameError: + class ResourceWarning(Warning): + "Python 2 fallback" + +class _NoWatcherResult(int): + + def __repr__(self): + return "" + +_NoWatcherResult = _NoWatcherResult(0) + +def events_to_str(event_field, all_events): + result = [] + for (flag, string) in all_events: + c_flag = flag + if event_field & c_flag: + result.append(string) + event_field &= (~c_flag) + if not event_field: + break + if event_field: + result.append(hex(event_field)) + return '|'.join(result) + + +def not_while_active(func): + @functools.wraps(func) + def nw(self, *args, **kwargs): + if self.active: + raise ValueError("not while active") + func(self, *args, **kwargs) + return nw + +def only_if_watcher(func): + @functools.wraps(func) + def if_w(self): + if self._watcher: + return func(self) + return _NoWatcherResult + return if_w + + +class AbstractWatcherType(type): + """ + Base metaclass for watchers. + + To use, you will: + + - subclass the watcher class defined from this type. + - optionally subclass this type + """ + # pylint:disable=bad-mcs-classmethod-argument + + _FFI = None + _LIB = None + + def __new__(cls, name, bases, cls_dict): + if name != 'watcher' and not cls_dict.get('_watcher_skip_ffi'): + cls._fill_watcher(name, bases, cls_dict) + if '__del__' in cls_dict and not ALLOW_WATCHER_DEL: # pragma: no cover + raise TypeError("CFFI watchers are not allowed to have __del__") + return type.__new__(cls, name, bases, cls_dict) + + @classmethod + def _fill_watcher(cls, name, bases, cls_dict): + # TODO: refactor smaller + # pylint:disable=too-many-locals + if name.endswith('_'): + # Strip trailing _ added to avoid keyword duplications + # e.g., async_ + name = name[:-1] + + def _mro_get(attr, bases, error=True): + for b in bases: + try: + return getattr(b, attr) + except AttributeError: + continue + if error: # pragma: no cover + raise AttributeError(attr) + _watcher_prefix = cls_dict.get('_watcher_prefix') or _mro_get('_watcher_prefix', bases) + + if '_watcher_type' not in cls_dict: + watcher_type = _watcher_prefix + '_' + name + cls_dict['_watcher_type'] = watcher_type + elif not cls_dict['_watcher_type'].startswith(_watcher_prefix): + watcher_type = _watcher_prefix + '_' + cls_dict['_watcher_type'] + cls_dict['_watcher_type'] = watcher_type + + active_name = _watcher_prefix + '_is_active' + + def _watcher_is_active(self): + return getattr(self._LIB, active_name) + + LazyOnClass.lazy(cls_dict, _watcher_is_active) + + watcher_struct_name = cls_dict.get('_watcher_struct_name') + if not watcher_struct_name: + watcher_struct_pattern = (cls_dict.get('_watcher_struct_pattern') + or _mro_get('_watcher_struct_pattern', bases, False) + or 'struct %s') + watcher_struct_name = watcher_struct_pattern % (watcher_type,) + + def _watcher_struct_pointer_type(self): + return self._FFI.typeof(watcher_struct_name + ' *') + + LazyOnClass.lazy(cls_dict, _watcher_struct_pointer_type) + + callback_name = (cls_dict.get('_watcher_callback_name') + or _mro_get('_watcher_callback_name', bases, False) + or '_gevent_generic_callback') + + def _watcher_callback(self): + return self._FFI.addressof(self._LIB, callback_name) + + LazyOnClass.lazy(cls_dict, _watcher_callback) + + def _make_meth(name, watcher_name): + def meth(self): + lib_name = self._watcher_type + '_' + name + return getattr(self._LIB, lib_name) + meth.__name__ = watcher_name + return meth + + for meth_name in 'start', 'stop', 'init': + watcher_name = '_watcher' + '_' + meth_name + if watcher_name not in cls_dict: + LazyOnClass.lazy(cls_dict, _make_meth(meth_name, watcher_name)) + + def new_handle(cls, obj): + return cls._FFI.new_handle(obj) + + def new(cls, kind): + return cls._FFI.new(kind) + +class watcher(object): + + _callback = None + _args = None + _watcher = None + # self._handle has a reference to self, keeping it alive. + # We must keep self._handle alive for ffi.from_handle() to be + # able to work. We only fill this in when we are started, + # and when we are stopped we destroy it. + # NOTE: This is a GC cycle, so we keep it around for as short + # as possible. + _handle = None + + @tracemalloc + def __init__(self, _loop, ref=True, priority=None, args=_NOARGS): + self.loop = _loop + self.__init_priority = priority + self.__init_args = args + self.__init_ref = ref + self._watcher_full_init() + + + def _watcher_full_init(self): + priority = self.__init_priority + ref = self.__init_ref + args = self.__init_args + + self._watcher_create(ref) + + if priority is not None: + self._watcher_ffi_set_priority(priority) + + try: + self._watcher_ffi_init(args) + except: + # Let these be GC'd immediately. + # If we keep them around to when *we* are gc'd, + # they're probably invalid, meaning any native calls + # we do then to close() them are likely to fail + self._watcher = None + raise + self._watcher_ffi_set_init_ref(ref) + + @classmethod + def _watcher_ffi_close(cls, ffi_watcher): + pass + + def _watcher_create(self, ref): # pylint:disable=unused-argument + self._watcher = self._watcher_new() + + def _watcher_new(self): + return type(self).new(self._watcher_struct_pointer_type) # pylint:disable=no-member + + def _watcher_ffi_set_init_ref(self, ref): + pass + + def _watcher_ffi_set_priority(self, priority): + pass + + def _watcher_ffi_init(self, args): + raise NotImplementedError() + + def _watcher_ffi_start(self): + raise NotImplementedError() + + def _watcher_ffi_stop(self): + self._watcher_stop(self.loop.ptr, self._watcher) + + def _watcher_ffi_ref(self): + raise NotImplementedError() + + def _watcher_ffi_unref(self): + raise NotImplementedError() + + def _watcher_ffi_start_unref(self): + # While a watcher is active, we don't keep it + # referenced. This allows a timer, for example, to be started, + # and still allow the loop to end if there is nothing + # else to do. see test__order.TestSleep0 for one example. + self._watcher_ffi_unref() + + def _watcher_ffi_stop_ref(self): + self._watcher_ffi_ref() + + # A string identifying the type of libev object we watch, e.g., 'ev_io' + # This should be a class attribute. + _watcher_type = None + # A class attribute that is the callback on the libev object that init's the C struct, + # e.g., libev.ev_io_init. If None, will be set by _init_subclasses. + _watcher_init = None + # A class attribute that is the callback on the libev object that starts the C watcher, + # e.g., libev.ev_io_start. If None, will be set by _init_subclasses. + _watcher_start = None + # A class attribute that is the callback on the libev object that stops the C watcher, + # e.g., libev.ev_io_stop. If None, will be set by _init_subclasses. + _watcher_stop = None + # A cffi ctype object identifying the struct pointer we create. + # This is a class attribute set based on the _watcher_type + _watcher_struct_pointer_type = None + # The attribute of the libev object identifying the custom + # callback function for this type of watcher. This is a class + # attribute set based on the _watcher_type in _init_subclasses. + _watcher_callback = None + _watcher_is_active = None + + def close(self): + if self._watcher is None: + return + + self.stop() + _watcher = self._watcher + self._watcher = None + self._watcher_set_data(_watcher, self._FFI.NULL) # pylint: disable=no-member + self._watcher_ffi_close(_watcher) + self.loop = None + + def _watcher_set_data(self, the_watcher, data): + # This abstraction exists for the sole benefit of + # libuv.watcher.stat, which "subclasses" uv_handle_t. + # Can we do something to avoid this extra function call? + the_watcher.data = data + return data + + def __enter__(self): + return self + + def __exit__(self, t, v, tb): + self.close() + + if ALLOW_WATCHER_DEL: + def __del__(self): + if self._watcher: + tb = get_object_traceback(self) + tb_msg = '' + if tb is not None: + tb_msg = '\n'.join(tb.format()) + tb_msg = '\nTraceback:\n' + tb_msg + warnings.warn("Failed to close watcher %r%s" % (self, tb_msg), + ResourceWarning) + + # may fail if __init__ did; will be harmlessly printed + self.close() + + __in_repr = False + + def __repr__(self): + basic = "<%s at 0x%x" % (self.__class__.__name__, id(self)) + if self.__in_repr: + return basic + '>' + # Running child watchers have been seen to have a + # recursive repr in ``self.args``, thanks to ``gevent.os.fork_and_watch`` + # passing the watcher as an argument to its callback. + self.__in_repr = True + try: + result = '%s%s' % (basic, self._format()) + if self.pending: + result += " pending" + if self.callback is not None: + fself = getattr(self.callback, '__self__', None) + if fself is self: + result += " callback=" % (self.callback.__name__) + else: + result += " callback=%r" % (self.callback, ) + if self.args is not None: + result += " args=%r" % (self.args, ) + if self.callback is None and self.args is None: + result += " stopped" + result += " watcher=%s" % (self._watcher) + result += " handle=%s" % (self._watcher_handle) + result += " ref=%s" % (self.ref) + return result + ">" + finally: + self.__in_repr = False + + @property + def _watcher_handle(self): + if self._watcher: + return self._watcher.data + + def _format(self): + return '' + + @property + def ref(self): + raise NotImplementedError() + + def _get_callback(self): + return self._callback if '_callback' in self.__dict__ else None + + def _set_callback(self, cb): + if not callable(cb) and cb is not None: + raise TypeError("Expected callable, not %r" % (cb, )) + if cb is None: + if '_callback' in self.__dict__: + del self._callback + else: + self._callback = cb + callback = property(_get_callback, _set_callback) + + def _get_args(self): + return self._args + + def _set_args(self, args): + if not isinstance(args, tuple) and args is not None: + raise TypeError("args must be a tuple or None") + if args is None: + if '_args' in self.__dict__: + del self._args + else: + self._args = args + + args = property(_get_args, _set_args) + + def start(self, callback, *args): + if callback is None: + raise TypeError('callback must be callable, not None') + self.callback = callback + self.args = args or _NOARGS + self.loop._keepaliveset.add(self) + self._handle = self._watcher_set_data(self._watcher, type(self).new_handle(self)) # pylint:disable=no-member + self._watcher_ffi_start() + self._watcher_ffi_start_unref() + + def stop(self): + if self.callback is None: + assert self.loop is None or self not in self.loop._keepaliveset + return + self.callback = None + # Only after setting the signal to make this idempotent do + # we move ahead. + self._watcher_ffi_stop_ref() + self._watcher_ffi_stop() + self.loop._keepaliveset.discard(self) + self._handle = None + self._watcher_set_data(self._watcher, self._FFI.NULL) # pylint:disable=no-member + + self.args = None + + def _get_priority(self): + return None + + @not_while_active + def _set_priority(self, priority): + pass + + priority = property(_get_priority, _set_priority) + + + @property + def active(self): + if self._watcher is not None and self._watcher_is_active(self._watcher): + return True + return False + + @property + def pending(self): + return False + +watcher = AbstractWatcherType('watcher', (object,), dict(watcher.__dict__)) + +class IoMixin(object): + + EVENT_MASK = 0 + + def __init__(self, loop, fd, events, ref=True, priority=None, _args=None): + # Win32 only works with sockets, and only when we use libuv, because + # we don't use _open_osfhandle. See libuv/watchers.py:io for a description. + if fd < 0: + raise ValueError('fd must be non-negative: %r' % fd) + if events & ~self.EVENT_MASK: + raise ValueError('illegal event mask: %r' % events) + self._fd = fd + super(IoMixin, self).__init__(loop, ref=ref, priority=priority, + args=_args or (fd, events)) + + def start(self, callback, *args, **kwargs): + args = args or _NOARGS + if kwargs.get('pass_events'): + args = (GEVENT_CORE_EVENTS, ) + args + super(IoMixin, self).start(callback, *args) + + def _format(self): + return ' fd=%d' % self._fd + +class TimerMixin(object): + _watcher_type = 'timer' + + def __init__(self, loop, after=0.0, repeat=0.0, ref=True, priority=None): + if repeat < 0.0: + raise ValueError("repeat must be positive or zero: %r" % repeat) + self._after = after + self._repeat = repeat + super(TimerMixin, self).__init__(loop, ref=ref, priority=priority, args=(after, repeat)) + + def start(self, callback, *args, **kw): + update = kw.get("update", self.loop.starting_timer_may_update_loop_time) + if update: + # Quoth the libev doc: "This is a costly operation and is + # usually done automatically within ev_run(). This + # function is rarely useful, but when some event callback + # runs for a very long time without entering the event + # loop, updating libev's idea of the current time is a + # good idea." + + # 1.3 changed the default for this to False *unless* the loop is + # running a callback; see libuv for details. Note that + # starting Timeout objects still sets this to true. + + self.loop.update_now() + super(TimerMixin, self).start(callback, *args) + + def again(self, callback, *args, **kw): + raise NotImplementedError() + + +class SignalMixin(object): + _watcher_type = 'signal' + + def __init__(self, loop, signalnum, ref=True, priority=None): + if signalnum < 1 or signalnum >= signalmodule.NSIG: + raise ValueError('illegal signal number: %r' % signalnum) + # still possible to crash on one of libev's asserts: + # 1) "libev: ev_signal_start called with illegal signal number" + # EV_NSIG might be different from signal.NSIG on some platforms + # 2) "libev: a signal must not be attached to two different loops" + # we probably could check that in LIBEV_EMBED mode, but not in general + self._signalnum = signalnum + super(SignalMixin, self).__init__(loop, ref=ref, priority=priority, args=(signalnum, )) + + +class IdleMixin(object): + _watcher_type = 'idle' + + +class PrepareMixin(object): + _watcher_type = 'prepare' + + +class CheckMixin(object): + _watcher_type = 'check' + + +class ForkMixin(object): + _watcher_type = 'fork' + + +class AsyncMixin(object): + _watcher_type = 'async' + + def send(self): + raise NotImplementedError() + + def send_ignoring_arg(self, _ignored): + """ + Calling compatibility with ``greenlet.switch(arg)`` + as used by waiters that have ``rawlink``. + + This is an advanced method, not usually needed. + """ + return self.send() + + @property + def pending(self): + raise NotImplementedError() + + +class ChildMixin(object): + + # hack for libuv which doesn't extend watcher + _CALL_SUPER_INIT = True + + def __init__(self, loop, pid, trace=0, ref=True): + if not loop.default: + raise TypeError('child watchers are only available on the default loop') + loop.install_sigchld() + self._pid = pid + if self._CALL_SUPER_INIT: + super(ChildMixin, self).__init__(loop, ref=ref, args=(pid, trace)) + + def _format(self): + return ' pid=%r rstatus=%r' % (self.pid, self.rstatus) + + @property + def pid(self): + return self._pid + + @property + def rpid(self): + # The received pid, the result of the waitpid() call. + return self._rpid + + _rpid = None + _rstatus = 0 + + @property + def rstatus(self): + return self._rstatus + +class StatMixin(object): + + @staticmethod + def _encode_path(path): + return fsencode(path) + + def __init__(self, _loop, path, interval=0.0, ref=True, priority=None): + # Store the encoded path in the same attribute that corecext does + self._paths = self._encode_path(path) + + # Keep the original path to avoid re-encoding, especially on Python 3 + self._path = path + + # Although CFFI would automatically convert a bytes object into a char* when + # calling ev_stat_init(..., char*, ...), on PyPy the char* pointer is not + # guaranteed to live past the function call. On CPython, only with a constant/interned + # bytes object is the pointer guaranteed to last path the function call. (And since + # Python 3 is pretty much guaranteed to produce a newly-encoded bytes object above, thats + # rarely the case). Therefore, we must keep a reference to the produced cdata object + # so that the struct ev_stat_watcher's `path` pointer doesn't become invalid/deallocated + self._cpath = self._FFI.new('char[]', self._paths) + + self._interval = interval + super(StatMixin, self).__init__(_loop, ref=ref, priority=priority, + args=(self._cpath, + interval)) + + @property + def path(self): + return self._path + + @property + def attr(self): + raise NotImplementedError + + @property + def prev(self): + raise NotImplementedError + + @property + def interval(self): + return self._interval diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/core.py new file mode 100644 index 0000000000000000000000000000000000000000..906e739e5553ed46f515dc7b28e59ce73904d2c6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/core.py @@ -0,0 +1,20 @@ +# Copyright (c) 2009-2015 Denis Bilenko and gevent contributors. See LICENSE for details. +""" +Deprecated; this does not reflect all the possible options +and its interface varies. + +.. versionchanged:: 1.3a2 + Deprecated. +""" +from __future__ import absolute_import + +import sys + +from gevent._config import config +from gevent._util import copy_globals + +_core = sys.modules[config.loop.__module__] + +copy_globals(_core, globals()) + +__all__ = _core.__all__ # pylint:disable=no-member diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/event.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/event.py new file mode 100644 index 0000000000000000000000000000000000000000..2831815903cfe7038cf5d03db62cec6d22803688 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/event.py @@ -0,0 +1,427 @@ +# Copyright (c) 2009-2016 Denis Bilenko, gevent contributors. See LICENSE for details. +# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False,infer_types=True + +"""Basic synchronization primitives: Event and AsyncResult""" +from __future__ import print_function + +from gevent._util import _NONE +from gevent._compat import reraise +from gevent._tblib import dump_traceback, load_traceback + +from gevent.timeout import Timeout + + +__all__ = [ + 'Event', + 'AsyncResult', +] + +def _get_linkable(): + x = __import__('gevent._abstract_linkable') + return x._abstract_linkable.AbstractLinkable +locals()['AbstractLinkable'] = _get_linkable() +del _get_linkable + + +class Event(AbstractLinkable): # pylint:disable=undefined-variable + """ + A synchronization primitive that allows one greenlet to wake up + one or more others. It has the same interface as + :class:`threading.Event` but works across greenlets. + + .. important:: + This object is for communicating among greenlets within the + same thread *only*! Do not try to use it to communicate across threads. + + An event object manages an internal flag that can be set to true + with the :meth:`set` method and reset to false with the + :meth:`clear` method. The :meth:`wait` method blocks until the + flag is true; as soon as the flag is set to true, all greenlets + that are currently blocked in a call to :meth:`wait` will be scheduled + to awaken. + + Note that the flag may be cleared and set many times before + any individual greenlet runs; all the greenlet can know for sure is that the + flag was set *at least once* while it was waiting. + If the greenlet cares whether the flag is still + set, it must check with :meth:`ready` and possibly call back into + :meth:`wait` again. + + .. note:: + + The exact order and timing in which waiting greenlets are awakened is not determined. + + Once the event is set, other greenlets may run before any waiting greenlets + are awakened. + + While the code here will awaken greenlets in the order in which they + waited, each such greenlet that runs may in turn cause other greenlets + to run. + + These details may change in the future. + + .. versionchanged:: 1.5a3 + + Waiting greenlets are now awakened in + the order in which they waited. + + .. versionchanged:: 1.5a3 + + The low-level ``rawlink`` method (most users won't use this) now + automatically unlinks waiters before calling them. + + .. versionchanged:: 20.5.1 + + Callers to ``wait`` that find the event already set will now run + after any other waiters that had to block. See :issue:`1520`. + """ + + __slots__ = ('_flag',) + + def __init__(self): + super(Event, self).__init__() + self._flag = False + + def __str__(self): + return '<%s.%s %s _links[%s]>' % ( + self.__class__.__module__, + self.__class__.__name__, + 'set' if self._flag else 'clear', + self.linkcount() + ) + + def is_set(self): + """Return true if and only if the internal flag is true.""" + return self._flag + + def isSet(self): + # makes it a better drop-in replacement for threading.Event + return self._flag + + def ready(self): + # makes it compatible with AsyncResult and Greenlet (for + # example in wait()) + return self._flag + + def set(self): + """ + Set the internal flag to true. + + All greenlets waiting for it to become true are awakened in + some order at some time in the future. Greenlets that call + :meth:`wait` once the flag is true will not block at all + (until :meth:`clear` is called). + """ + self._flag = True + self._check_and_notify() + + def clear(self): + """ + Reset the internal flag to false. + + Subsequently, threads calling :meth:`wait` will block until + :meth:`set` is called to set the internal flag to true again. + """ + self._flag = False + + def _wait_return_value(self, waited, wait_success): + # To avoid the race condition outlined in http://bugs.python.org/issue13502, + # if we had to wait, then we need to return whether or not + # the condition got changed. Otherwise we simply echo + # the current state of the flag (which should be true) + if not waited: + flag = self._flag + assert flag, "if we didn't wait we should already be set" + return flag + + return wait_success + + def wait(self, timeout=None): + """ + Block until this object is :meth:`ready`. + + If the internal flag is true on entry, return immediately. Otherwise, + block until another thread (greenlet) calls :meth:`set` to set the flag to true, + or until the optional *timeout* expires. + + When the *timeout* argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + :return: This method returns true if and only if the internal flag has been set to + true, either before the wait call or after the wait starts, so it will + always return ``True`` except if a timeout is given and the operation + times out. + + .. versionchanged:: 1.1 + The return value represents the flag during the elapsed wait, not + just after it elapses. This solves a race condition if one greenlet + sets and then clears the flag without switching, while other greenlets + are waiting. When the waiters wake up, this will return True; previously, + they would still wake up, but the return value would be False. This is most + noticeable when the *timeout* is present. + """ + return self._wait(timeout) + + def _reset_internal_locks(self): # pragma: no cover + # for compatibility with threading.Event + # Exception AttributeError: AttributeError("'Event' object has no attribute '_reset_internal_locks'",) + # in ignored + pass + + +class AsyncResult(AbstractLinkable): # pylint:disable=undefined-variable + """ + A one-time event that stores a value or an exception. + + Like :class:`Event` it wakes up all the waiters when :meth:`set` + or :meth:`set_exception` is called. Waiters may receive the passed + value or exception by calling :meth:`get` instead of :meth:`wait`. + An :class:`AsyncResult` instance cannot be reset. + + .. important:: + This object is for communicating among greenlets within the + same thread *only*! Do not try to use it to communicate across threads. + + To pass a value call :meth:`set`. Calls to :meth:`get` (those that + are currently blocking as well as those made in the future) will + return the value:: + + >>> from gevent.event import AsyncResult + >>> result = AsyncResult() + >>> result.set(100) + >>> result.get() + 100 + + To pass an exception call :meth:`set_exception`. This will cause + :meth:`get` to raise that exception:: + + >>> result = AsyncResult() + >>> result.set_exception(RuntimeError('failure')) + >>> result.get() + Traceback (most recent call last): + ... + RuntimeError: failure + + :class:`AsyncResult` implements :meth:`__call__` and thus can be + used as :meth:`link` target:: + + >>> import gevent + >>> result = AsyncResult() + >>> gevent.spawn(lambda : 1/0).link(result) + >>> try: + ... result.get() + ... except ZeroDivisionError: + ... print('ZeroDivisionError') + ZeroDivisionError + + .. note:: + + The order and timing in which waiting greenlets are awakened is not determined. + As an implementation note, in gevent 1.1 and 1.0, waiting greenlets are awakened in a + undetermined order sometime *after* the current greenlet yields to the event loop. Other greenlets + (those not waiting to be awakened) may run between the current greenlet yielding and + the waiting greenlets being awakened. These details may change in the future. + + .. versionchanged:: 1.1 + + The exact order in which waiting greenlets + are awakened is not the same as in 1.0. + + .. versionchanged:: 1.1 + + Callbacks :meth:`linked ` to this object are required to + be hashable, and duplicates are merged. + + .. versionchanged:: 1.5a3 + + Waiting greenlets are now awakened in the order in which they + waited. + + .. versionchanged:: 1.5a3 + + The low-level ``rawlink`` method + (most users won't use this) now automatically unlinks waiters + before calling them. + """ + + __slots__ = ('_value', '_exc_info', '_imap_task_index') + + def __init__(self): + super(AsyncResult, self).__init__() + self._value = _NONE + self._exc_info = () + + @property + def _exception(self): + return self._exc_info[1] if self._exc_info else _NONE + + @property + def value(self): + """ + Holds the value passed to :meth:`set` if :meth:`set` was called. Otherwise, + ``None`` + """ + return self._value if self._value is not _NONE else None + + @property + def exc_info(self): + """ + The three-tuple of exception information if :meth:`set_exception` was called. + """ + if self._exc_info: + return (self._exc_info[0], self._exc_info[1], load_traceback(self._exc_info[2])) + return () + + def __str__(self): + result = '<%s ' % (self.__class__.__name__, ) + if self.value is not None or self._exception is not _NONE: + result += 'value=%r ' % self.value + if self._exception is not None and self._exception is not _NONE: + result += 'exception=%r ' % self._exception + if self._exception is _NONE: + result += 'unset ' + return result + ' _links[%s]>' % self.linkcount() + + def ready(self): + """Return true if and only if it holds a value or an exception""" + return self._exc_info or self._value is not _NONE + + def successful(self): + """Return true if and only if it is ready and holds a value""" + return self._value is not _NONE + + @property + def exception(self): + """Holds the exception instance passed to :meth:`set_exception` if :meth:`set_exception` was called. + Otherwise ``None``.""" + if self._exc_info: + return self._exc_info[1] + + def set(self, value=None): + """Store the value and wake up any waiters. + + All greenlets blocking on :meth:`get` or :meth:`wait` are awakened. + Subsequent calls to :meth:`wait` and :meth:`get` will not block at all. + """ + self._value = value + self._check_and_notify() + + def set_exception(self, exception, exc_info=None): + """Store the exception and wake up any waiters. + + All greenlets blocking on :meth:`get` or :meth:`wait` are awakened. + Subsequent calls to :meth:`wait` and :meth:`get` will not block at all. + + :keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback` + as returned by :func:`sys.exc_info`. This will be used when the exception + is re-raised to propagate the correct traceback. + """ + if exc_info: + self._exc_info = (exc_info[0], exc_info[1], dump_traceback(exc_info[2])) + else: + self._exc_info = (type(exception), exception, dump_traceback(None)) + + self._check_and_notify() + + def _raise_exception(self): + reraise(*self.exc_info) + + def get(self, block=True, timeout=None): + """Return the stored value or raise the exception. + + If this instance already holds a value or an exception, return or raise it immediately. + Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or + until the optional timeout occurs. + + When the *timeout* argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). If the *timeout* elapses, the *Timeout* exception will + be raised. + + :keyword bool block: If set to ``False`` and this instance is not ready, + immediately raise a :class:`Timeout` exception. + """ + if self._value is not _NONE: + return self._value + if self._exc_info: + return self._raise_exception() + + if not block: + # Not ready and not blocking, so immediately timeout + raise Timeout() + + self._capture_hub(True) + + # Wait, raising a timeout that elapses + self._wait_core(timeout, ()) + + # by definition we are now ready + return self.get(block=False) + + def get_nowait(self): + """ + Return the value or raise the exception without blocking. + + If this object is not yet :meth:`ready `, raise + :class:`gevent.Timeout` immediately. + """ + return self.get(block=False) + + def _wait_return_value(self, waited, wait_success): + # pylint:disable=unused-argument + # Always return the value. Since this is a one-shot event, + # no race condition should reset it. + return self.value + + def wait(self, timeout=None): + """Block until the instance is ready. + + If this instance already holds a value, it is returned immediately. If this + instance already holds an exception, ``None`` is returned immediately. + + Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` + (at which point either the value or ``None`` will be returned, respectively), + or until the optional timeout expires (at which point ``None`` will also be + returned). + + When the *timeout* argument is present and not ``None``, it should be a + floating point number specifying a timeout for the operation in seconds + (or fractions thereof). + + .. note:: If a timeout is given and expires, ``None`` will be returned + (no timeout exception will be raised). + + """ + return self._wait(timeout) + + # link protocol + def __call__(self, source): + if source.successful(): + self.set(source.value) + else: + self.set_exception(source.exception, getattr(source, 'exc_info', None)) + + # Methods to make us more like concurrent.futures.Future + + def result(self, timeout=None): + return self.get(timeout=timeout) + + set_result = set + + def done(self): + return self.ready() + + # we don't support cancelling + + def cancel(self): + return False + + def cancelled(self): + return False + + # exception is a method, we use it as a property + + +from gevent._util import import_c_accel +import_c_accel(globals(), 'gevent._event') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/events.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/events.py new file mode 100644 index 0000000000000000000000000000000000000000..c14c9fdc4ab206ba866a6a64eafca947f450f32d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/events.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2018 gevent. See LICENSE for details. +""" +Publish/subscribe event infrastructure. + +When certain "interesting" things happen during the lifetime of the +process, gevent will "publish" an event (an object). That event is +delivered to interested "subscribers" (functions that take one +parameter, the event object). + +Higher level frameworks may take this foundation and build richer +models on it. + +:mod:`zope.event` will be used to provide the functionality of +`notify` and `subscribers`. See :mod:`zope.event.classhandler` for a +simple class-based approach to subscribing to a filtered list of +events, and see `zope.component +`_ for a +much higher-level, flexible system. If you are using one of these +systems, you generally will not want to directly modify `subscribers`. + +.. versionadded:: 1.3b1 + +.. versionchanged:: 23.7.0 + Now uses :mod:`importlib.metadata` instead of :mod:`pkg_resources` + to locate entry points. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +__all__ = [ + 'subscribers', + + # monitor thread + 'IEventLoopBlocked', + 'EventLoopBlocked', + 'IMemoryUsageThresholdExceeded', + 'MemoryUsageThresholdExceeded', + 'IMemoryUsageUnderThreshold', + 'MemoryUsageUnderThreshold', + + # Hub + 'IPeriodicMonitorThread', + 'IPeriodicMonitorThreadStartedEvent', + 'PeriodicMonitorThreadStartedEvent', + + # monkey + 'IGeventPatchEvent', + 'GeventPatchEvent', + 'IGeventWillPatchEvent', + 'DoNotPatch', + 'GeventWillPatchEvent', + 'IGeventDidPatchEvent', + 'IGeventWillPatchModuleEvent', + 'GeventWillPatchModuleEvent', + 'IGeventDidPatchModuleEvent', + 'GeventDidPatchModuleEvent', + 'IGeventWillPatchAllEvent', + 'GeventWillPatchAllEvent', + 'IGeventDidPatchBuiltinModulesEvent', + 'GeventDidPatchBuiltinModulesEvent', + 'IGeventDidPatchAllEvent', + 'GeventDidPatchAllEvent', +] + +# pylint:disable=no-self-argument,inherit-non-class +import platform + +from zope.interface import Interface +from zope.interface import Attribute +from zope.interface import implementer + +from zope.event import subscribers +from zope.event import notify + + + +#: Applications may register for notification of events by appending a +#: callable to the ``subscribers`` list. +#: +#: Each subscriber takes a single argument, which is the event object +#: being published. +#: +#: Exceptions raised by subscribers will be propagated *without* running +#: any remaining subscribers. +#: +#: This is an alias for `zope.event.subscribers`; prefer to use +#: that attribute directly. +subscribers = subscribers + +try: + # Cache the platform info. pkg_resources uses + # platform.machine() for environment markers, and + # platform.machine() wants to call os.popen('uname'), which is + # broken on Py2 when the gevent child signal handler is + # installed. (see test__monkey_sigchild_2.py) + platform.uname() +except: # pylint:disable=bare-except + pass +finally: + del platform + +def notify_and_call_entry_points(event): + notify(event) + from importlib import metadata + import sys + # This used to use the old ``pkg_resources.iter_entry_points(group,name=None)`` + # API, passing it just the first argument, ``group=event.ENTRY_POINT_NAME``. + # In other words, we don't care about the ``name``. + if sys.version_info[:2] >= (3, 10): + # pylint:disable-next=unexpected-keyword-arg + # The only thing you can do with this is iterate it to get + # EntryPoint objects. (e.g., accessing by index raises a warning) + entry_points = metadata.entry_points(group=event.ENTRY_POINT_NAME) + else: + # Prior to 3.10, we have to do this all manually (keyword selection + # was introduced in 3.10; in 3.9 and before, entry_points returns a plain + # ``dict``). Using it like this is deprecated in 3.10, so to avoid warnings + # we have to write it twice. + # + # Prior to 3.9, there is no ``.module`` attribute, so if we + # needed that we'd have to look at the complete ``.value`` + # attribute. + ep_dict = metadata.entry_points() + __traceback_info__ = ep_dict + # On Python 3.8, we can get duplicate EntryPoint objects; it is unclear + # why. Drop them into a set to make sure we only get one. + # + # Running a more recent pylint flags the non-existence of ``get`` + # pylint:disable=no-member + entry_points = set( + ep + for ep + in ep_dict.get(event.ENTRY_POINT_NAME, ()) + ) + + for plugin in entry_points: + subscriber = plugin.load() + subscriber(event) + + +class IPeriodicMonitorThread(Interface): + """ + The contract for the periodic monitoring thread that is started + by the hub. + """ + + def add_monitoring_function(function, period): + """ + Schedule the *function* to be called approximately every *period* fractional seconds. + + The *function* receives one argument, the hub being monitored. It is called + in the monitoring thread, *not* the hub thread. It **must not** attempt to + use the gevent asynchronous API. + + If the *function* is already a monitoring function, then its *period* + will be updated for future runs. + + If the *period* is ``None``, then the function will be removed. + + A *period* less than or equal to zero is not allowed. + """ + +class IPeriodicMonitorThreadStartedEvent(Interface): + """ + The event emitted when a hub starts a periodic monitoring thread. + + You can use this event to add additional monitoring functions. + """ + + monitor = Attribute("The instance of `IPeriodicMonitorThread` that was started.") + +@implementer(IPeriodicMonitorThreadStartedEvent) +class PeriodicMonitorThreadStartedEvent(object): + """ + The implementation of :class:`IPeriodicMonitorThreadStartedEvent`. + + .. versionchanged:: 24.11.1 + Now actually implements the promised interface. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.hub.periodic_monitor_thread_started' + + def __init__(self, monitor): + self.monitor = monitor + +class IEventLoopBlocked(Interface): + """ + The event emitted when the event loop is blocked. + + This event is emitted in the monitor thread. + + .. versionchanged:: 24.11.1 + Add the *hub* attribute. + """ + + greenlet = Attribute("The greenlet that appeared to be blocking the loop.") + blocking_time = Attribute("The approximate time in seconds the loop has been blocked.") + info = Attribute("A list of string lines providing extra info. You may modify this list.") + hub = Attribute("""If not None, the hub being blocked.""") + +@implementer(IEventLoopBlocked) +class EventLoopBlocked(object): + """ + The event emitted when the event loop is blocked. + + Implements `IEventLoopBlocked`. + """ + + def __init__(self, greenlet, blocking_time, info, *, hub=None): + self.greenlet = greenlet + self.blocking_time = blocking_time + self.info = info + self.hub = hub + +class IMemoryUsageThresholdExceeded(Interface): + """ + The event emitted when the memory usage threshold is exceeded. + + This event is emitted only while memory continues to grow + above the threshold. Only if the condition or stabilized is corrected (memory + usage drops) will the event be emitted in the future. + + This event is emitted in the monitor thread. + """ + + mem_usage = Attribute("The current process memory usage, in bytes.") + max_allowed = Attribute("The maximum allowed memory usage, in bytes.") + memory_info = Attribute("The tuple of memory usage stats return by psutil.") + +class _AbstractMemoryEvent(object): + + def __init__(self, mem_usage, max_allowed, memory_info): + self.mem_usage = mem_usage + self.max_allowed = max_allowed + self.memory_info = memory_info + + def __repr__(self): + return "<%s used=%d max=%d details=%r>" % ( + self.__class__.__name__, + self.mem_usage, + self.max_allowed, + self.memory_info, + ) + +@implementer(IMemoryUsageThresholdExceeded) +class MemoryUsageThresholdExceeded(_AbstractMemoryEvent): + """ + Implementation of `IMemoryUsageThresholdExceeded`. + """ + + +class IMemoryUsageUnderThreshold(Interface): + """ + The event emitted when the memory usage drops below the + threshold after having previously been above it. + + This event is emitted only the first time memory usage is detected + to be below the threshold after having previously been above it. + If memory usage climbs again, a `IMemoryUsageThresholdExceeded` + event will be broadcast, and then this event could be broadcast again. + + This event is emitted in the monitor thread. + """ + + mem_usage = Attribute("The current process memory usage, in bytes.") + max_allowed = Attribute("The maximum allowed memory usage, in bytes.") + max_memory_usage = Attribute("The memory usage that caused the previous " + "IMemoryUsageThresholdExceeded event.") + memory_info = Attribute("The tuple of memory usage stats return by psutil.") + + +@implementer(IMemoryUsageUnderThreshold) +class MemoryUsageUnderThreshold(_AbstractMemoryEvent): + """ + Implementation of `IMemoryUsageUnderThreshold`. + """ + + def __init__(self, mem_usage, max_allowed, memory_info, max_usage): + super(MemoryUsageUnderThreshold, self).__init__(mem_usage, max_allowed, memory_info) + self.max_memory_usage = max_usage + + +class IGeventPatchEvent(Interface): + """ + The root for all monkey-patch events gevent emits. + """ + + source = Attribute("The source object containing the patches.") + target = Attribute("The destination object to be patched.") + +@implementer(IGeventPatchEvent) +class GeventPatchEvent(object): + """ + Implementation of `IGeventPatchEvent`. + """ + + def __init__(self, source, target): + self.source = source + self.target = target + + def __repr__(self): + return '<%s source=%r target=%r at %x>' % (self.__class__.__name__, + self.source, + self.target, + id(self)) + +class IGeventWillPatchEvent(IGeventPatchEvent): + """ + An event emitted *before* gevent monkey-patches something. + + If a subscriber raises `DoNotPatch`, then patching this particular + item will not take place. + """ + + +class DoNotPatch(BaseException): + """ + Subscribers to will-patch events can raise instances + of this class to tell gevent not to patch that particular item. + """ + + +@implementer(IGeventWillPatchEvent) +class GeventWillPatchEvent(GeventPatchEvent): + """ + Implementation of `IGeventWillPatchEvent`. + """ + +class IGeventDidPatchEvent(IGeventPatchEvent): + """ + An event emitted *after* gevent has patched something. + """ + +@implementer(IGeventDidPatchEvent) +class GeventDidPatchEvent(GeventPatchEvent): + """ + Implementation of `IGeventDidPatchEvent`. + """ + +class IGeventWillPatchModuleEvent(IGeventWillPatchEvent): + """ + An event emitted *before* gevent begins patching a specific module. + + Both *source* and *target* attributes are module objects. + """ + + module_name = Attribute("The name of the module being patched. " + "This is the same as ``target.__name__``.") + + target_item_names = Attribute("The list of item names to patch. " + "This can be modified in place with caution.") + +@implementer(IGeventWillPatchModuleEvent) +class GeventWillPatchModuleEvent(GeventWillPatchEvent): + """ + Implementation of `IGeventWillPatchModuleEvent`. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.monkey.will_patch_module' + + def __init__(self, module_name, source, target, items): + super(GeventWillPatchModuleEvent, self).__init__(source, target) + self.module_name = module_name + self.target_item_names = items + + +class IGeventDidPatchModuleEvent(IGeventDidPatchEvent): + """ + An event emitted *after* gevent has completed patching a specific + module. + """ + + module_name = Attribute("The name of the module being patched. " + "This is the same as ``target.__name__``.") + + +@implementer(IGeventDidPatchModuleEvent) +class GeventDidPatchModuleEvent(GeventDidPatchEvent): + """ + Implementation of `IGeventDidPatchModuleEvent`. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_module' + + def __init__(self, module_name, source, target): + super(GeventDidPatchModuleEvent, self).__init__(source, target) + self.module_name = module_name + +# TODO: Maybe it would be useful for the the module patch events +# to have an attribute telling if they're being done during patch_all? + +class IGeventWillPatchAllEvent(IGeventWillPatchEvent): + """ + An event emitted *before* gevent begins patching the system. + + Following this event will be a series of + `IGeventWillPatchModuleEvent` and `IGeventDidPatchModuleEvent` for + each patched module. + + Once the gevent builtin modules have been processed, + `IGeventDidPatchBuiltinModulesEvent` will be emitted. Processing + this event is an ideal time for third-party modules to be imported + and patched (which may trigger its own will/did patch module + events). + + Finally, a `IGeventDidPatchAllEvent` will be sent. + + If a subscriber to this event raises `DoNotPatch`, no patching + will be done. + + The *source* and *target* attributes have undefined values. + """ + + patch_all_arguments = Attribute( + "A dictionary of all the arguments to `gevent.monkey.patch_all`. " + "This dictionary should not be modified. " + ) + + patch_all_kwargs = Attribute( + "A dictionary of the extra arguments to `gevent.monkey.patch_all`. " + "This dictionary should not be modified. " + ) + + def will_patch_module(module_name): + """ + Return whether the module named *module_name* will be patched. + """ + +class _PatchAllMixin(object): + def __init__(self, patch_all_arguments, patch_all_kwargs): + super(_PatchAllMixin, self).__init__(None, None) + self._patch_all_arguments = patch_all_arguments + self._patch_all_kwargs = patch_all_kwargs + + @property + def patch_all_arguments(self): + return self._patch_all_arguments.copy() + + @property + def patch_all_kwargs(self): + return self._patch_all_kwargs.copy() + + def __repr__(self): + return '<%s %r at %x>' % (self.__class__.__name__, + self._patch_all_arguments, + id(self)) + +@implementer(IGeventWillPatchAllEvent) +class GeventWillPatchAllEvent(_PatchAllMixin, GeventWillPatchEvent): + """ + Implementation of `IGeventWillPatchAllEvent`. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.monkey.will_patch_all' + + def will_patch_module(self, module_name): + return self.patch_all_arguments.get(module_name) + +class IGeventDidPatchBuiltinModulesEvent(IGeventDidPatchEvent): + """ + Event emitted *after* the builtin modules have been patched. + + If you're going to monkey-patch a third-party library, this is + usually the event to listen for. + + The values of the *source* and *target* attributes are undefined. + """ + + patch_all_arguments = Attribute( + "A dictionary of all the arguments to `gevent.monkey.patch_all`. " + "This dictionary should not be modified. " + ) + + patch_all_kwargs = Attribute( + "A dictionary of the extra arguments to `gevent.monkey.patch_all`. " + "This dictionary should not be modified. " + ) + +@implementer(IGeventDidPatchBuiltinModulesEvent) +class GeventDidPatchBuiltinModulesEvent(_PatchAllMixin, GeventDidPatchEvent): + """ + Implementation of `IGeventDidPatchBuiltinModulesEvent`. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_builtins' + +class IGeventDidPatchAllEvent(IGeventDidPatchEvent): + """ + Event emitted after gevent has patched all modules, both builtin + and those provided by plugins/subscribers. + + The values of the *source* and *target* attributes are undefined. + """ + +@implementer(IGeventDidPatchAllEvent) +class GeventDidPatchAllEvent(_PatchAllMixin, GeventDidPatchEvent): + """ + Implementation of `IGeventDidPatchAllEvent`. + """ + + #: The name of the setuptools entry point that is called when this + #: event is emitted. + ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_all' diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/exceptions.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c599c7162eed29f544510c4b77c31431ec7c0115 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/exceptions.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# copyright 2018 gevent +""" +Exceptions. + +.. versionadded:: 1.3b1 + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from greenlet import GreenletExit + +__all__ = [ + 'LoopExit', +] + + +class LoopExit(Exception): + """ + Exception thrown when the hub finishes running (`gevent.hub.Hub.run` + would return). + + In a normal application, this is never thrown or caught + explicitly. The internal implementation of functions like + :meth:`gevent.hub.Hub.join` and :func:`gevent.joinall` may catch it, but user code + generally should not. + + .. caution:: + Errors in application programming can also lead to this exception being + raised. Some examples include (but are not limited too): + + - greenlets deadlocking on a lock; + - using a socket or other gevent object with native thread + affinity from a different thread + + """ + + @property + def hub(self): + """ + The (optional) hub that raised the error. + + .. versionadded:: 20.12.0 + """ + # XXX: Note that semaphore.py does this manually. + if len(self.args) == 3: # From the hub + return self.args[1] + + def __repr__(self): + # pylint:disable=unsubscriptable-object + if len(self.args) == 3: # From the hub + import pprint + return ( + "%s\n" + "\tHub: %s\n" + "\tHandles:\n%s" + ) % ( + self.args[0], + self.args[1], + pprint.pformat(self.args[2]) + ) + return Exception.__repr__(self) + + def __str__(self): + return repr(self) + +class BlockingSwitchOutError(AssertionError): + """ + Raised when a gevent synchronous function is called from a + low-level event loop callback. + + This is usually a programming error. + """ + + +class InvalidSwitchError(AssertionError): + """ + Raised when the event loop returns control to a greenlet in an + unexpected way. + + This is usually a bug in gevent, greenlet, or the event loop. + """ + +class ConcurrentObjectUseError(AssertionError): + """ + Raised when an object is used (waited on) by two greenlets + independently, meaning the object was entered into a blocking + state by one greenlet and then another while still blocking in the + first one. + + This is usually a programming error. + + .. seealso:: `gevent.socket.wait` + """ + +class InvalidThreadUseError(RuntimeError): + """ + Raised when an object is used from a different thread than + the one it is bound to. + + Some objects, such as gevent sockets, semaphores, and threadpools, + are tightly bound to their hub and its loop. The hub and loop + are not thread safe, with a few exceptions. Attempting to use + such objects from a different thread is an error, and may cause + problems ranging from incorrect results to memory corruption + and a crashed process. + + In some cases, gevent catches this "accidentally", and the result is + a `LoopExit`. In some cases, gevent doesn't catch this at all. + + In other cases (typically when the consequences are suspected to + be more on the more severe end of the scale, and when the operation in + question is already relatively heavyweight), gevent explicitly checks + for this usage and will raise this exception when it is detected. + + .. versionadded:: 1.5a3 + """ + + +class HubDestroyed(GreenletExit): + """ + Internal exception, raised when we're trying to destroy the + hub and we want the loop to stop running callbacks now. + + This must not be subclassed; the type is tested by identity. + + Clients outside of gevent must not raise this exception. + + .. versionadded:: 20.12.0 + """ + + def __init__(self, destroy_loop): + GreenletExit.__init__(self, destroy_loop) + self.destroy_loop = destroy_loop diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/fileobject.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/fileobject.py new file mode 100644 index 0000000000000000000000000000000000000000..68e438d34bd6aa99b117f8b49157526040a96ca7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/fileobject.py @@ -0,0 +1,85 @@ +""" +Wrappers to make file-like objects cooperative. + +.. class:: FileObject(fobj, mode='r', buffering=-1, closefd=True, encoding=None, errors=None, newline=None) + + The main entry point to the file-like gevent-compatible behaviour. It + will be defined to be the best available implementation. + + All the parameters are as for :func:`io.open`. + + :param fobj: Usually a file descriptor of a socket. Can also be + another object with a ``fileno()`` method, or an object that can + be passed to ``io.open()`` (e.g., a file system path). If the object + is not a socket, the results will vary based on the platform and the + type of object being opened. + + All supported versions of Python allow :class:`os.PathLike` objects. + + .. versionchanged:: 1.5 + Accept str and ``PathLike`` objects for *fobj* on all versions of Python. + .. versionchanged:: 1.5 + Add *encoding*, *errors* and *newline* arguments. + .. versionchanged:: 1.5 + Accept *closefd* and *buffering* instead of *close* and *bufsize* arguments. + The latter remain for backwards compatibility. + +There are two main implementations of ``FileObject``. On all systems, +there is :class:`FileObjectThread` which uses the built-in native +threadpool to avoid blocking the entire interpreter. On UNIX systems +(those that support the :mod:`fcntl` module), there is also +:class:`FileObjectPosix` which uses native non-blocking semantics. + +A third class, :class:`FileObjectBlock`, is simply a wrapper that +executes everything synchronously (and so is not gevent-compatible). +It is provided for testing and debugging purposes. + +All classes have the same signature; some may accept extra keyword arguments. + +Configuration +============= + +You may change the default value for ``FileObject`` using the +``GEVENT_FILE`` environment variable. Set it to ``posix``, ``thread``, +or ``block`` to choose from :class:`FileObjectPosix`, +:class:`FileObjectThread` and :class:`FileObjectBlock`, respectively. +You may also set it to the fully qualified class name of another +object that implements the file interface to use one of your own +objects. + +.. note:: + + The environment variable must be set at the time this module + is first imported. + +Classes +======= +""" +from __future__ import absolute_import + +from gevent._config import config + +__all__ = [ + 'FileObjectPosix', + 'FileObjectThread', + 'FileObjectBlock', + 'FileObject', +] + +try: + from fcntl import fcntl +except ImportError: + __all__.remove("FileObjectPosix") +else: + del fcntl + from gevent._fileobjectposix import FileObjectPosix + +from gevent._fileobjectcommon import FileObjectThread +from gevent._fileobjectcommon import FileObjectBlock + + +# None of the possible objects can live in this module because +# we would get an import cycle and the config couldn't be set from code. +# TODO: zope.hookable would be great for allowing this to be imported +# without requiring configuration but still being very fast. +FileObject = config.fileobject diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/greenlet.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/greenlet.py new file mode 100644 index 0000000000000000000000000000000000000000..e18cfeac829f5347d641835b14ffbb303d8d67da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/greenlet.py @@ -0,0 +1,1186 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False +# pylint:disable=too-many-lines +from __future__ import absolute_import, print_function, division + +from sys import _getframe as sys_getframe +from sys import exc_info as sys_exc_info +from weakref import ref as wref + +# XXX: How to get cython to let us rename this as RawGreenlet +# like we prefer? +from greenlet import greenlet +from greenlet import GreenletExit + +from gevent._compat import reraise +from gevent._compat import PYPY as _PYPY +from gevent._tblib import dump_traceback +from gevent._tblib import load_traceback + +from gevent.exceptions import InvalidSwitchError + +from gevent._hub_primitives import iwait_on_objects as iwait +from gevent._hub_primitives import wait_on_objects as wait + +from gevent.timeout import Timeout + +from gevent._config import config as GEVENT_CONFIG +from gevent._util import readproperty +from gevent._hub_local import get_hub_noargs as get_hub +from gevent import _waiter + + +__all__ = [ + 'Greenlet', + 'joinall', + 'killall', +] + + +# In Cython, we define these as 'cdef inline' functions. The +# compilation unit cannot have a direct assignment to them (import +# is assignment) without generating a 'lvalue is not valid target' +# error. +locals()['getcurrent'] = __import__('greenlet').getcurrent +locals()['greenlet_init'] = lambda: None +locals()['Waiter'] = _waiter.Waiter +# With Cython, this raises a TypeError if the parent is *not* +# the hub (SwitchOutGreenletWithLoop); in pure-Python, we will +# very likely get an AttributeError immediately after when we access `loop`; +# The TypeError message is more informative on Python 2. +# This must ONLY be called when we know that `s` is not None and is in fact a greenlet +# object (e.g., when called on `self`) +locals()['get_my_hub'] = lambda s: s.parent +# This must also ONLY be called when we know that S is not None and is in fact a greenlet +# object (including the result of getcurrent()) +locals()['get_generic_parent'] = lambda s: s.parent + +# Frame access +locals()['Gevent_PyFrame_GetCode'] = lambda frame: frame.f_code +locals()['Gevent_PyFrame_GetLineNumber'] = lambda frame: frame.f_lineno +locals()['Gevent_PyFrame_GetBack'] = lambda frame: frame.f_back + + +if _PYPY: + import _continuation # pylint:disable=import-error + _continulet = _continuation.continulet + + +class SpawnedLink(object): + """ + A wrapper around link that calls it in another greenlet. + + Can be called only from main loop. + """ + __slots__ = ['callback'] + + def __init__(self, callback): + if not callable(callback): + raise TypeError("Expected callable: %r" % (callback, )) + self.callback = callback + + def __call__(self, source): + g = greenlet(self.callback, get_hub()) + g.switch(source) + + def __hash__(self): + return hash(self.callback) + + def __eq__(self, other): + return self.callback == getattr(other, 'callback', other) + + def __str__(self): + return str(self.callback) + + def __repr__(self): + return repr(self.callback) + + def __getattr__(self, item): + assert item != 'callback' + return getattr(self.callback, item) + + +class SuccessSpawnedLink(SpawnedLink): + """A wrapper around link that calls it in another greenlet only if source succeed. + + Can be called only from main loop. + """ + __slots__ = [] + + def __call__(self, source): + if source.successful(): + return SpawnedLink.__call__(self, source) + + +class FailureSpawnedLink(SpawnedLink): + """A wrapper around link that calls it in another greenlet only if source failed. + + Can be called only from main loop. + """ + __slots__ = [] + + def __call__(self, source): + if not source.successful(): + return SpawnedLink.__call__(self, source) + +class _Frame(object): + + __slots__ = ('f_code', 'f_lineno', 'f_back') + + def __init__(self): + self.f_code = None + self.f_back = None + self.f_lineno = 0 + + @property + def f_globals(self): + return None + + +def _extract_stack(limit): + try: + frame = sys_getframe() + except ValueError: + # In certain embedded cases that directly use the Python C api + # to call Greenlet.spawn (e.g., uwsgi) this can raise + # `ValueError: call stack is not deep enough`. This is because + # the Cython stack frames for Greenlet.spawn -> + # Greenlet.__init__ -> _extract_stack are all on the C level, + # not the Python level. + # See https://github.com/gevent/gevent/issues/1212 + frame = None + + newest_Frame = None + newer_Frame = None + + while limit and frame is not None: + limit -= 1 + older_Frame = _Frame() + # Arguments are always passed to the constructor as Python objects, + # meaning we wind up boxing the f_lineno just to unbox it if we pass it. + # It's faster to simply assign once the object is created. + older_Frame.f_code = Gevent_PyFrame_GetCode(frame) # pylint:disable=undefined-variable + older_Frame.f_lineno = Gevent_PyFrame_GetLineNumber(frame) # pylint:disable=undefined-variable + if newer_Frame is not None: + newer_Frame.f_back = older_Frame + newer_Frame = older_Frame + if newest_Frame is None: + newest_Frame = newer_Frame + + frame = Gevent_PyFrame_GetBack(frame) # pylint:disable=undefined-variable + + return newest_Frame + + +_greenlet__init__ = greenlet.__init__ + +class Greenlet(greenlet): + """ + A light-weight cooperatively-scheduled execution unit. + """ + # pylint:disable=too-many-public-methods,too-many-instance-attributes + + spawning_stack_limit = 10 + + # pylint:disable=keyword-arg-before-vararg,super-init-not-called + def __init__(self, run=None, *args, **kwargs): + """ + :param args: The arguments passed to the ``run`` function. + :param kwargs: The keyword arguments passed to the ``run`` function. + :keyword callable run: The callable object to run. If not given, this object's + `_run` method will be invoked (typically defined by subclasses). + + .. versionchanged:: 1.1b1 + The ``run`` argument to the constructor is now verified to be a callable + object. Previously, passing a non-callable object would fail after the greenlet + was spawned. + + .. versionchanged:: 1.3b1 + The ``GEVENT_TRACK_GREENLET_TREE`` configuration value may be set to + a false value to disable ``spawn_tree_locals``, ``spawning_greenlet``, + and ``spawning_stack``. The first two will be None in that case, and the + latter will be empty. + + .. versionchanged:: 1.5 + Greenlet objects are now more careful to verify that their ``parent`` is really + a gevent hub, raising a ``TypeError`` earlier instead of an ``AttributeError`` later. + + .. versionchanged:: 20.12.1 + Greenlet objects now function as context managers. Exiting the ``with`` suite + ensures that the greenlet has completed by :meth:`joining ` + the greenlet (blocking, with + no timeout). If the body of the suite raises an exception, the greenlet is + :meth:`killed ` with the default arguments and not joined in that case. + """ + # The attributes are documented in the .rst file + + # greenlet.greenlet(run=None, parent=None) + # Calling it with both positional arguments instead of a keyword + # argument (parent=get_hub()) speeds up creation of this object ~30%: + # python -m timeit -s 'import gevent' 'gevent.Greenlet()' + # Python 3.5: 2.70usec with keywords vs 1.94usec with positional + # Python 3.4: 2.32usec with keywords vs 1.74usec with positional + # Python 3.3: 2.55usec with keywords vs 1.92usec with positional + # Python 2.7: 1.73usec with keywords vs 1.40usec with positional + + # Timings taken Feb 21 2018 prior to integration of #755 + # python -m perf timeit -s 'import gevent' 'gevent.Greenlet()' + # 3.6.4 : Mean +- std dev: 1.08 us +- 0.05 us + # 2.7.14 : Mean +- std dev: 1.44 us +- 0.06 us + # PyPy2 5.10.0: Mean +- std dev: 2.14 ns +- 0.08 ns + + # After the integration of spawning_stack, spawning_greenlet, + # and spawn_tree_locals on that same date: + # 3.6.4 : Mean +- std dev: 8.92 us +- 0.36 us -> 8.2x + # 2.7.14 : Mean +- std dev: 14.8 us +- 0.5 us -> 10.2x + # PyPy2 5.10.0: Mean +- std dev: 3.24 us +- 0.17 us -> 1.5x + + # Compiling with Cython gets us to these numbers: + # 3.6.4 : Mean +- std dev: 3.63 us +- 0.14 us + # 2.7.14 : Mean +- std dev: 3.37 us +- 0.20 us + # PyPy2 5.10.0 : Mean +- std dev: 4.44 us +- 0.28 us + + # Switching to reified frames and some more tuning gets us here: + # 3.7.2 : Mean +- std dev: 2.53 us +- 0.15 us + # 2.7.16 : Mean +- std dev: 2.35 us +- 0.12 us + # PyPy2 7.1 : Mean +- std dev: 11.6 us +- 0.4 us + + # Compared to the released 1.4 (tested at the same time): + # 3.7.2 : Mean +- std dev: 3.21 us +- 0.32 us + # 2.7.16 : Mean +- std dev: 3.11 us +- 0.19 us + # PyPy2 7.1 : Mean +- std dev: 12.3 us +- 0.8 us + + _greenlet__init__(self, None, get_hub()) + + if run is not None: + self._run = run + + # If they didn't pass a callable at all, then they must + # already have one. Note that subclassing to override the run() method + # itself has never been documented or supported. + if not callable(self._run): + raise TypeError("The run argument or self._run must be callable") + + self.args = args + self.kwargs = kwargs + self.value = None + + #: An event, such as a timer or a callback that fires. It is established in + #: start() and start_later() as those two objects, respectively. + #: Once this becomes non-None, the Greenlet cannot be started again. Conversely, + #: kill() and throw() check for non-None to determine if this object has ever been + #: scheduled for starting. A placeholder _cancelled_start_event is assigned by them to prevent + #: the greenlet from being started in the future, if necessary. + #: In the usual case, this transitions as follows: None -> event -> _start_completed_event. + #: A value of None means we've never been started. + self._start_event = None + + self._notifier = None + self._formatted_info = None + self._links = [] + self._ident = None + + # Initial state: None. + # Completed successfully: (None, None, None) + # Failed with exception: (t, v, dump_traceback(tb))) + self._exc_info = None + + if GEVENT_CONFIG.track_greenlet_tree: + spawner = getcurrent() # pylint:disable=undefined-variable + self.spawning_greenlet = wref(spawner) + try: + self.spawn_tree_locals = spawner.spawn_tree_locals + except AttributeError: + self.spawn_tree_locals = {} + if get_generic_parent(spawner) is not None: # pylint:disable=undefined-variable + # The main greenlet has no parent. + # Its children get separate locals. + spawner.spawn_tree_locals = self.spawn_tree_locals + + self.spawning_stack = _extract_stack(self.spawning_stack_limit) + # Don't copy the spawning greenlet's + # '_spawning_stack_frames' into ours. That's somewhat + # confusing, and, if we're not careful, a deep spawn tree + # can lead to excessive memory usage (an infinite spawning + # tree could lead to unbounded memory usage without care + # --- see https://github.com/gevent/gevent/issues/1371) + # The _spawning_stack_frames may be cleared out later if we access spawning_stack + else: + # None is the default for all of these in Cython, but we + # need to declare them for pure-Python mode. + self.spawning_greenlet = None + self.spawn_tree_locals = None + self.spawning_stack = None + + def _get_minimal_ident(self): + # Helper function for cython, to allow typing `reg` and making a + # C call to get_ident. + + # If we're being accessed from a hub different than the one running + # us, aka get_hub() is not self.parent, then calling hub.ident_registry.get_ident() + # may be quietly broken: it's not thread safe. + # If our parent is no longer the hub for whatever reason, this will raise a + # AttributeError or TypeError. + hub = get_my_hub(self) # pylint:disable=undefined-variable + + reg = hub.ident_registry + return reg.get_ident(self) + + @property + def minimal_ident(self): + """ + A small, unique non-negative integer that identifies this object. + + This is similar to :attr:`threading.Thread.ident` (and `id`) + in that as long as this object is alive, no other greenlet *in + this hub* will have the same id, but it makes a stronger + guarantee that the assigned values will be small and + sequential. Sometime after this object has died, the value + will be available for reuse. + + To get ids that are unique across all hubs, combine this with + the hub's (``self.parent``) ``minimal_ident``. + + Accessing this property from threads other than the thread running + this greenlet is not defined. + + .. versionadded:: 1.3a2 + + """ + # Not @Lazy, implemented manually because _ident is in the structure + # of the greenlet for fast access + if self._ident is None: + self._ident = self._get_minimal_ident() + return self._ident + + @readproperty + def name(self): + """ + The greenlet name. By default, a unique name is constructed using + the :attr:`minimal_ident`. You can assign a string to this + value to change it. It is shown in the `repr` of this object if it + has been assigned to or if the `minimal_ident` has already been generated. + + .. versionadded:: 1.3a2 + .. versionchanged:: 1.4 + Stop showing generated names in the `repr` when the ``minimal_ident`` + hasn't been requested. This reduces overhead and may be less confusing, + since ``minimal_ident`` can get reused. + """ + return 'Greenlet-%d' % (self.minimal_ident,) + + def _raise_exception(self): + reraise(*self.exc_info) + + @property + def loop(self): + # needed by killall + hub = get_my_hub(self) # pylint:disable=undefined-variable + return hub.loop + + def __bool__(self): + return self._start_event is not None and self._exc_info is None + + ### Lifecycle + + if _PYPY: + # oops - pypy's .dead relies on __nonzero__ which we overriden above + @property + def dead(self): + "Boolean indicating that the greenlet is dead and will not run again." + # pylint:disable=no-member + if self._greenlet__main: + return False + if self.__start_cancelled_by_kill() or self.__started_but_aborted(): + return True + + return self._greenlet__started and not _continulet.is_pending(self) + else: + @property + def dead(self): + """ + Boolean indicating that the greenlet is dead and will not run again. + + This is true if: + + 1. We were never started, but were :meth:`killed ` + immediately after creation (not possible with :meth:`spawn`); OR + 2. We were started, but were killed before running; OR + 3. We have run and terminated (by raising an exception out of the + started function or by reaching the end of the started function). + """ + return ( + self.__start_cancelled_by_kill() + or self.__started_but_aborted() + or greenlet.dead.__get__(self) + ) + + def __never_started_or_killed(self): + return self._start_event is None + + def __start_pending(self): + return ( + self._start_event is not None + and (self._start_event.pending or getattr(self._start_event, 'active', False)) + ) + + def __start_cancelled_by_kill(self): + return self._start_event is _cancelled_start_event + + def __start_completed(self): + return self._start_event is _start_completed_event + + def __started_but_aborted(self): + return ( + not self.__never_started_or_killed() # we have been started or killed + and not self.__start_cancelled_by_kill() # we weren't killed, so we must have been started + and not self.__start_completed() # the start never completed + and not self.__start_pending() # and we're not pending, so we must have been aborted + ) + + def __cancel_start(self): + if self._start_event is None: + # prevent self from ever being started in the future + self._start_event = _cancelled_start_event + # cancel any pending start event + # NOTE: If this was a real pending start event, this will leave a + # "dangling" callback/timer object in the hub.loop.callbacks list; + # depending on where we are in the event loop, it may even be in a local + # variable copy of that list (in _run_callbacks). This isn't a problem, + # except for the leak-tests. + self._start_event.stop() + self._start_event.close() + + def __handle_death_before_start(self, args): + # args is (t, v, tb) or simply t or v. + # The last two cases are transformed into (t, v, None); + # if the single argument is an exception type, a new instance + # is created; if the single argument is not an exception type and also + # not an exception, it is wrapped in a BaseException (this is not + # documented, but should result in better behaviour in the event of a + # user error---instead of silently printing something to stderr, we still + # kill the greenlet). + if self._exc_info is None and self.dead: + # the greenlet was never switched to before and it will + # never be; _report_error was not called, the result was + # not set, and the links weren't notified. Let's do it + # here. + # + # checking that self.dead is true is essential, because + # throw() does not necessarily kill the greenlet (if the + # exception raised by throw() is caught somewhere inside + # the greenlet). + if len(args) == 1: + arg = args[0] + if isinstance(arg, type) and issubclass(arg, BaseException): + args = (arg, arg(), None) + else: + args = (type(arg), arg, None) + elif not args: + args = (GreenletExit, GreenletExit(), None) + if not issubclass(args[0], BaseException): + # Random non-type, non-exception arguments. + args = (BaseException, BaseException(args), None) + assert issubclass(args[0], BaseException) + self.__report_error(args) + + @property + def started(self): + # DEPRECATED + return bool(self) + + def ready(self): + """ + Return a true value if and only if the greenlet has finished + execution. + + .. versionchanged:: 1.1 + This function is only guaranteed to return true or false *values*, not + necessarily the literal constants ``True`` or ``False``. + """ + return self.dead or self._exc_info is not None + + def successful(self): + """ + Return a true value if and only if the greenlet has finished execution + successfully, that is, without raising an error. + + .. tip:: A greenlet that has been killed with the default + :class:`GreenletExit` exception is considered successful. + That is, ``GreenletExit`` is not considered an error. + + .. note:: This function is only guaranteed to return true or false *values*, + not necessarily the literal constants ``True`` or ``False``. + """ + return self._exc_info is not None and self._exc_info[1] is None + + def __repr__(self): + classname = self.__class__.__name__ + # If no name has been assigned, don't generate one, including a minimal_ident, + # if not necessary. This reduces the use of weak references and associated + # overhead. + if 'name' not in self.__dict__ and self._ident is None: + name = ' ' + else: + name = ' "%s" ' % (self.name,) + result = '<%s%sat %s' % (classname, name, hex(id(self))) + formatted = self._formatinfo() + if formatted: + result += ': ' + formatted + return result + '>' + + + def _formatinfo(self): + info = self._formatted_info + if info is not None: + return info + + # Are we running an arbitrary function provided to the constructor, + # or did a subclass override _run? + func = self._run + im_self = getattr(func, '__self__', None) + if im_self is self: + funcname = '_run' + elif im_self is not None: + funcname = repr(func) + else: + funcname = getattr(func, '__name__', '') or repr(func) + + result = funcname + args = [] + if self.args: + args = [repr(x)[:50] for x in self.args] + if self.kwargs: + args.extend(['%s=%s' % (key, repr(value)[:50]) for (key, value) in self.kwargs.items()]) + if args: + result += '(' + ', '.join(args) + ')' + # it is important to save the result here, because once the greenlet exits '_run' attribute will be removed + self._formatted_info = result + return result + + @property + def exception(self): + """ + Holds the exception instance raised by the function if the + greenlet has finished with an error. Otherwise ``None``. + """ + return self._exc_info[1] if self._exc_info is not None else None + + @property + def exc_info(self): + """ + Holds the exc_info three-tuple raised by the function if the + greenlet finished with an error. Otherwise a false value. + + .. note:: This is a provisional API and may change. + + .. versionadded:: 1.1 + """ + ei = self._exc_info + if ei is not None and ei[0] is not None: + return ( + ei[0], + ei[1], + # The pickled traceback may be None if we couldn't pickle it. + load_traceback(ei[2]) if ei[2] else None + ) + + def throw(self, *args): + """Immediately switch into the greenlet and raise an exception in it. + + Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever. + To raise an exception in a safe manner from any greenlet, use :meth:`kill`. + + If a greenlet was started but never switched to yet, then also + a) cancel the event that will start it + b) fire the notifications as if an exception was raised in a greenlet + """ + self.__cancel_start() + + try: + if not self.dead: + # Prevent switching into a greenlet *at all* if we had never + # started it. Usually this is the same thing that happens by throwing, + # but if this is done from the hub with nothing else running, prevents a + # LoopExit. + greenlet.throw(self, *args) + finally: + self.__handle_death_before_start(args) + + def start(self): + """Schedule the greenlet to run in this loop iteration""" + if self._start_event is None: + _call_spawn_callbacks(self) + hub = get_my_hub(self) # pylint:disable=undefined-variable + self._start_event = hub.loop.run_callback(self.switch) + + def start_later(self, seconds): + """ + start_later(seconds) -> None + + Schedule the greenlet to run in the future loop iteration + *seconds* later + """ + if self._start_event is None: + _call_spawn_callbacks(self) + hub = get_my_hub(self) # pylint:disable=undefined-variable + self._start_event = hub.loop.timer(seconds) + self._start_event.start(self.switch) + + @staticmethod + def add_spawn_callback(callback): + """ + add_spawn_callback(callback) -> None + + Set up a *callback* to be invoked when :class:`Greenlet` objects + are started. + + The invocation order of spawn callbacks is unspecified. Adding the + same callback more than one time will not cause it to be called more + than once. + + .. versionadded:: 1.4.0 + """ + global _spawn_callbacks + if _spawn_callbacks is None: # pylint:disable=used-before-assignment + _spawn_callbacks = set() + _spawn_callbacks.add(callback) + + @staticmethod + def remove_spawn_callback(callback): + """ + remove_spawn_callback(callback) -> None + + Remove *callback* function added with :meth:`Greenlet.add_spawn_callback`. + This function will not fail if *callback* has been already removed or + if *callback* was never added. + + .. versionadded:: 1.4.0 + """ + global _spawn_callbacks + if _spawn_callbacks is not None: + _spawn_callbacks.discard(callback) + if not _spawn_callbacks: + _spawn_callbacks = None + + @classmethod + def spawn(cls, *args, **kwargs): + """ + spawn(function, *args, **kwargs) -> Greenlet + + Create a new :class:`Greenlet` object and schedule it to run ``function(*args, **kwargs)``. + This can be used as ``gevent.spawn`` or ``Greenlet.spawn``. + + The arguments are passed to :meth:`Greenlet.__init__`. + + .. versionchanged:: 1.1b1 + If a *function* is given that is not callable, immediately raise a :exc:`TypeError` + instead of spawning a greenlet that will raise an uncaught TypeError. + """ + g = cls(*args, **kwargs) + g.start() + return g + + @classmethod + def spawn_later(cls, seconds, *args, **kwargs): + """ + spawn_later(seconds, function, *args, **kwargs) -> Greenlet + + Create and return a new `Greenlet` object scheduled to run ``function(*args, **kwargs)`` + in a future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later`` + or ``gevent.spawn_later``. + + The arguments are passed to :meth:`Greenlet.__init__`. + + .. versionchanged:: 1.1b1 + If an argument that's meant to be a function (the first argument in *args*, or the ``run`` keyword ) + is given to this classmethod (and not a classmethod of a subclass), + it is verified to be callable. Previously, the spawned greenlet would have failed + when it started running. + """ + if cls is Greenlet and not args and 'run' not in kwargs: + raise TypeError("") + g = cls(*args, **kwargs) + g.start_later(seconds) + return g + + def _maybe_kill_before_start(self, exception): + # Helper for Greenlet.kill(), and also for killall() + self.__cancel_start() + self.__free() + dead = self.dead + if dead: + if isinstance(exception, tuple) and len(exception) == 3: + args = exception + else: + args = (exception,) + self.__handle_death_before_start(args) + return dead + + def kill(self, exception=GreenletExit, block=True, timeout=None): + """ + Raise the ``exception`` in the greenlet. + + If ``block`` is ``True`` (the default), wait until the greenlet + dies or the optional timeout expires; this may require switching + greenlets. + If block is ``False``, the current greenlet is not unscheduled. + + This function always returns ``None`` and never raises an error. It + may be called multpile times on the same greenlet object, and may be + called on an unstarted or dead greenlet. + + .. note:: + + Depending on what this greenlet is executing and the state + of the event loop, the exception may or may not be raised + immediately when this greenlet resumes execution. It may + be raised on a subsequent green call, or, if this greenlet + exits before making such a call, it may not be raised at + all. As of 1.1, an example where the exception is raised + later is if this greenlet had called :func:`sleep(0) + `; an example where the exception is raised + immediately is if this greenlet had called + :func:`sleep(0.1) `. + + .. caution:: + + Use care when killing greenlets. If the code executing is not + exception safe (e.g., makes proper use of ``finally``) then an + unexpected exception could result in corrupted state. Using + a :meth:`link` or :meth:`rawlink` (cheaper) may be a safer way to + clean up resources. + + See also :func:`gevent.kill` and :func:`gevent.killall`. + + :keyword type exception: The type of exception to raise in the greenlet. The default + is :class:`GreenletExit`, which indicates a :meth:`successful` completion + of the greenlet. + + .. versionchanged:: 0.13.0 + *block* is now ``True`` by default. + .. versionchanged:: 1.1a2 + If this greenlet had never been switched to, killing it will + prevent it from *ever* being switched to. Links (:meth:`rawlink`) + will still be executed, though. + .. versionchanged:: 20.12.1 + If this greenlet is :meth:`ready`, immediately return instead of + requiring a trip around the event loop. + """ + if not self._maybe_kill_before_start(exception): + if self.ready(): + return + + waiter = Waiter() if block else None # pylint:disable=undefined-variable + hub = get_my_hub(self) # pylint:disable=undefined-variable + hub.loop.run_callback(_kill, self, exception, waiter) + if waiter is not None: + waiter.get() + self.join(timeout) + + def get(self, block=True, timeout=None): + """ + get(block=True, timeout=None) -> object + + Return the result the greenlet has returned or re-raise the + exception it has raised. + + If block is ``False``, raise :class:`gevent.Timeout` if the + greenlet is still alive. If block is ``True``, unschedule the + current greenlet until the result is available or the timeout + expires. In the latter case, :class:`gevent.Timeout` is + raised. + """ + if self.ready(): + if self.successful(): + return self.value + self._raise_exception() + if not block: + raise Timeout() + + switch = getcurrent().switch # pylint:disable=undefined-variable + self.rawlink(switch) + try: + t = Timeout._start_new_or_dummy(timeout) + try: + result = get_my_hub(self).switch() # pylint:disable=undefined-variable + if result is not self: + raise InvalidSwitchError('Invalid switch into Greenlet.get(): %r' % (result, )) + finally: + t.cancel() + except: + # unlinking in 'except' instead of finally is an optimization: + # if switch occurred normally then link was already removed in _notify_links + # and there's no need to touch the links set. + # Note, however, that if "Invalid switch" assert was removed and invalid switch + # did happen, the link would remain, causing another invalid switch later in this greenlet. + self.unlink(switch) + raise + + if self.ready(): + if self.successful(): + return self.value + self._raise_exception() + + def join(self, timeout=None): + """ + join(timeout=None) -> None + + Wait until the greenlet finishes or *timeout* expires. Return + ``None`` regardless. + """ + if self.ready(): + return + + switch = getcurrent().switch # pylint:disable=undefined-variable + self.rawlink(switch) + try: + t = Timeout._start_new_or_dummy(timeout) + try: + result = get_my_hub(self).switch() # pylint:disable=undefined-variable + if result is not self: + raise InvalidSwitchError('Invalid switch into Greenlet.join(): %r' % (result, )) + finally: + t.cancel() + except Timeout as ex: + self.unlink(switch) + if ex is not t: + raise + except: + self.unlink(switch) + raise + + def __enter__(self): + return self + + def __exit__(self, t, v, tb): + if t is None: + try: + self.join() + finally: + self.kill() + else: + self.kill((t, v, tb)) + + def __report_result(self, result): + self._exc_info = (None, None, None) + self.value = result + if self._links and not self._notifier: + hub = get_my_hub(self) # pylint:disable=undefined-variable + self._notifier = hub.loop.run_callback(self._notify_links) + + def __report_error(self, exc_info): + if isinstance(exc_info[1], GreenletExit): + self.__report_result(exc_info[1]) + return + + # Depending on the error, we may not be able to pickle it. + # In particular, RecursionError can be a problem. + try: + tb = dump_traceback(exc_info[2]) + except: # pylint:disable=bare-except + tb = None + self._exc_info = exc_info[0], exc_info[1], tb + + hub = get_my_hub(self) # pylint:disable=undefined-variable + if self._links and not self._notifier: + self._notifier = hub.loop.run_callback(self._notify_links) + + try: + hub.handle_error(self, *exc_info) + finally: + del exc_info + + def run(self): + try: + self.__cancel_start() + self._start_event = _start_completed_event + + try: + result = self._run(*self.args, **self.kwargs) + except: # pylint:disable=bare-except + self.__report_error(sys_exc_info()) + else: + self.__report_result(result) + finally: + self.__free() + + def __free(self): + try: + # It seems that Cython 0.29.13 sometimes miscompiles + # self.__dict__.pop('_run', None) ? When we moved this out of the + # inline finally: block in run(), we started getting strange + # exceptions from places that subclassed Greenlet. + del self._run + except AttributeError: + pass + self.args = () + self.kwargs.clear() + + def _run(self): + """ + Subclasses may override this method to take any number of + arguments and keyword arguments. + + .. versionadded:: 1.1a3 + Previously, if no callable object was + passed to the constructor, the spawned greenlet would later + fail with an AttributeError. + """ + # We usually override this in __init__ + # pylint: disable=method-hidden + return + + def has_links(self): + return len(self._links) + + def rawlink(self, callback): + """ + Register a callable to be executed when the greenlet finishes + execution. + + The *callback* will be called with this instance as an + argument. + + The *callback* will be called even if linked after the greenlet + is already ready(). + + .. caution:: + The *callback* will be called in the hub and + **MUST NOT** raise an exception. + """ + if not callable(callback): + raise TypeError('Expected callable: %r' % (callback, )) + self._links.append(callback) # pylint:disable=no-member + if self.ready() and self._links and not self._notifier: + hub = get_my_hub(self) # pylint:disable=undefined-variable + self._notifier = hub.loop.run_callback(self._notify_links) + + def link(self, callback, SpawnedLink=SpawnedLink): + """ + Link greenlet's completion to a callable. + + The *callback* will be called with this instance as an + argument once this greenlet is dead. A callable is called in + its own :class:`greenlet.greenlet` (*not* a + :class:`Greenlet`). + + The *callback* will be called even if linked after the greenlet + is already ready(). + """ + # XXX: Is the redefinition of SpawnedLink supposed to just be an + # optimization, or do people use it? It's not documented + # pylint:disable=redefined-outer-name + self.rawlink(SpawnedLink(callback)) + + def unlink(self, callback): + """Remove the callback set by :meth:`link` or :meth:`rawlink`""" + try: + self._links.remove(callback) # pylint:disable=no-member + except ValueError: + pass + + def unlink_all(self): + """ + Remove all the callbacks. + + .. versionadded:: 1.3a2 + """ + del self._links[:] + + def link_value(self, callback, SpawnedLink=SuccessSpawnedLink): + """ + Like :meth:`link` but *callback* is only notified when the greenlet + has completed successfully. + """ + # pylint:disable=redefined-outer-name + self.link(callback, SpawnedLink=SpawnedLink) + + def link_exception(self, callback, SpawnedLink=FailureSpawnedLink): + """ + Like :meth:`link` but *callback* is only notified when the + greenlet dies because of an unhandled exception. + """ + # pylint:disable=redefined-outer-name + self.link(callback, SpawnedLink=SpawnedLink) + + def _notify_links(self): + while self._links: + # Early links are allowed to remove later links + # before we get to them, and they're also allowed to + # add new links, so we have to be careful about iterating. + + # We don't expect this list to be very large, so the time spent + # manipulating it should be small. a deque is probably not justified. + # Cython has optimizations to transform this into a memmove anyway. + link = self._links.pop(0) + try: + link(self) + except: # pylint:disable=bare-except, undefined-variable + get_my_hub(self).handle_error((link, self), *sys_exc_info()) + + +class _dummy_event(object): + __slots__ = ('pending', 'active') + + def __init__(self): + self.pending = self.active = False + + def stop(self): + pass + + def start(self, cb): # pylint:disable=unused-argument + raise AssertionError("Cannot start the dummy event") + + def close(self): + pass + +_cancelled_start_event = _dummy_event() +_start_completed_event = _dummy_event() + + +# This is *only* called as a callback from the hub via Greenlet.kill(), +# and its first argument is the Greenlet. So we can be sure about the types. +def _kill(glet, exception, waiter): + try: + if isinstance(exception, tuple) and len(exception) == 3: + glet.throw(*exception) + else: + glet.throw(exception) + except: # pylint:disable=bare-except, undefined-variable + # XXX do we need this here? + get_my_hub(glet).handle_error(glet, *sys_exc_info()) + if waiter is not None: + waiter.switch(None) + + +def joinall(greenlets, timeout=None, raise_error=False, count=None): + """ + Wait for the ``greenlets`` to finish. + + :param greenlets: A sequence (supporting :func:`len`) of greenlets to wait for. + :keyword float timeout: If given, the maximum number of seconds to wait. + :return: A sequence of the greenlets that finished before the timeout (if any) + expired. + """ + if not raise_error: + return wait(greenlets, timeout=timeout, count=count) + + done = [] + for obj in iwait(greenlets, timeout=timeout, count=count): + if getattr(obj, 'exception', None) is not None: + if hasattr(obj, '_raise_exception'): + obj._raise_exception() + else: + raise obj.exception + done.append(obj) + return done + + +def _killall3(greenlets, exception, waiter): + diehards = [] + for g in greenlets: + if not g.dead: + try: + g.throw(exception) + except: # pylint:disable=bare-except, undefined-variable + get_my_hub(g).handle_error(g, *sys_exc_info()) + if not g.dead: + diehards.append(g) + waiter.switch(diehards) + + +def _killall(greenlets, exception): + for g in greenlets: + if not g.dead: + try: + g.throw(exception) + except: # pylint:disable=bare-except, undefined-variable + get_my_hub(g).handle_error(g, *sys_exc_info()) + + +def _call_spawn_callbacks(gr): + if _spawn_callbacks is not None: + for cb in _spawn_callbacks: + cb(gr) + + +_spawn_callbacks = None + + +def killall(greenlets, exception=GreenletExit, block=True, timeout=None): + """ + Forceably terminate all the *greenlets* by causing them to raise *exception*. + + .. caution:: Use care when killing greenlets. If they are not prepared for exceptions, + this could result in corrupted state. + + :param greenlets: A **bounded** iterable of the non-None greenlets to terminate. + *All* the items in this iterable must be greenlets that belong to the same hub, + which should be the hub for this current thread. If this is a generator or iterator + that switches greenlets, the results are undefined. + :keyword exception: The type of exception to raise in the greenlets. By default this is + :class:`GreenletExit`. + :keyword bool block: If True (the default) then this function only returns when all the + greenlets are dead; the current greenlet is unscheduled during that process. + If greenlets ignore the initial exception raised in them, + then they will be joined (with :func:`gevent.joinall`) and allowed to die naturally. + If False, this function returns immediately and greenlets will raise + the exception asynchronously. + :keyword float timeout: A time in seconds to wait for greenlets to die. If given, it is + only honored when ``block`` is True. + :raise Timeout: If blocking and a timeout is given that elapses before + all the greenlets are dead. + + .. versionchanged:: 1.1a2 + *greenlets* can be any iterable of greenlets, like an iterator or a set. + Previously it had to be a list or tuple. + .. versionchanged:: 1.5a3 + Any :class:`Greenlet` in the *greenlets* list that hadn't been switched to before + calling this method will never be switched to. This makes this function + behave like :meth:`Greenlet.kill`. This does not apply to raw greenlets. + .. versionchanged:: 1.5a3 + Now accepts raw greenlets created by :func:`gevent.spawn_raw`. + """ + + need_killed = [] + for glet in greenlets: + # Quick pass through to prevent any greenlet from + # actually being switched to if it hasn't already. + # (Previously we called ``list(greenlets)`` so we're still + # linear.) + # + # We don't use glet.kill() here because we don't want to schedule + # any callbacks in the loop; we're about to handle that more directly. + try: + cancel = glet._maybe_kill_before_start + except AttributeError: + need_killed.append(glet) + else: + if not cancel(exception): + need_killed.append(glet) + + if not need_killed: + return + + loop = glet.loop # pylint:disable=undefined-loop-variable + if block: + waiter = Waiter() # pylint:disable=undefined-variable + loop.run_callback(_killall3, need_killed, exception, waiter) + t = Timeout._start_new_or_dummy(timeout) + try: + alive = waiter.get() + if alive: + joinall(alive, raise_error=False) + finally: + t.cancel() + else: + loop.run_callback(_killall, need_killed, exception) + +def _init(): + greenlet_init() # pylint:disable=undefined-variable + +_init() + +from gevent._util import import_c_accel +import_c_accel(globals(), 'gevent._greenlet') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/hub.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6726b216f8b4755a58f174b180da4a214fb9d7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/hub.py @@ -0,0 +1,909 @@ +# Copyright (c) 2009-2015 Denis Bilenko. See LICENSE for details. +""" +Event-loop hub. +""" +from __future__ import absolute_import, print_function +# XXX: FIXME: Refactor to make this smaller +# pylint:disable=too-many-lines +from functools import partial as _functools_partial + +import sys +import traceback + + +from greenlet import greenlet as RawGreenlet +from greenlet import getcurrent +from greenlet import GreenletExit +from greenlet import error as GreenletError + +__all__ = [ + 'getcurrent', + 'GreenletExit', + 'spawn_raw', + 'sleep', + 'kill', + 'signal', + 'reinit', + 'get_hub', + 'Hub', + 'Waiter', +] + +from gevent._config import config as GEVENT_CONFIG +from gevent._compat import thread_mod_name +from gevent._compat import reraise +from gevent._util import readproperty +from gevent._util import Lazy +from gevent._util import gmctime +from gevent._ident import IdentRegistry + +from gevent._hub_local import get_hub +from gevent._hub_local import get_loop +from gevent._hub_local import set_hub +from gevent._hub_local import set_loop +from gevent._hub_local import get_hub_if_exists as _get_hub +from gevent._hub_local import get_hub_noargs as _get_hub_noargs +from gevent._hub_local import set_default_hub_class + +from gevent._greenlet_primitives import TrackedRawGreenlet +from gevent._hub_primitives import WaitOperationsGreenlet + +# Export +from gevent import _hub_primitives +wait = _hub_primitives.wait_on_objects +iwait = _hub_primitives.iwait_on_objects + + +from gevent.exceptions import LoopExit +from gevent.exceptions import HubDestroyed + +from gevent._waiter import Waiter + + +# Need the real get_ident. We're imported early enough (by gevent/__init__.py) +# that we can be sure nothing is monkey patched yet. +get_thread_ident = __import__(thread_mod_name).get_ident +MAIN_THREAD_IDENT = get_thread_ident() # XXX: Assuming import is done on the main thread. + + + +def spawn_raw(function, *args, **kwargs): + """ + Create a new :class:`greenlet.greenlet` object and schedule it to + run ``function(*args, **kwargs)``. + + This returns a raw :class:`~greenlet.greenlet` which does not have all the useful + methods that :class:`gevent.Greenlet` has. Typically, applications + should prefer :func:`~gevent.spawn`, but this method may + occasionally be useful as an optimization if there are many + greenlets involved. + + .. versionchanged:: 1.1a3 + Verify that ``function`` is callable, raising a TypeError if not. Previously, + the spawned greenlet would have failed the first time it was switched to. + + .. versionchanged:: 1.1b1 + If *function* is not callable, immediately raise a :exc:`TypeError` + instead of spawning a greenlet that will raise an uncaught TypeError. + + .. versionchanged:: 1.1rc2 + Accept keyword arguments for ``function`` as previously (incorrectly) + documented. Note that this may incur an additional expense. + + .. versionchanged:: 1.3a2 + Populate the ``spawning_greenlet`` and ``spawn_tree_locals`` + attributes of the returned greenlet. + + .. versionchanged:: 1.3b1 + *Only* populate ``spawning_greenlet`` and ``spawn_tree_locals`` + if ``GEVENT_TRACK_GREENLET_TREE`` is enabled (the default). If not enabled, + those attributes will not be set. + + .. versionchanged:: 1.5a3 + The returned greenlet always has a *loop* attribute matching the + current hub's loop. This helps it work better with more gevent APIs. + """ + if not callable(function): + raise TypeError("function must be callable") + + # The hub is always the parent. + hub = _get_hub_noargs() + loop = hub.loop + + factory = TrackedRawGreenlet if GEVENT_CONFIG.track_greenlet_tree else RawGreenlet + + # The callback class object that we use to run this doesn't + # accept kwargs (and those objects are heavily used, as well as being + # implemented twice in core.ppyx and corecffi.py) so do it with a partial + if kwargs: + function = _functools_partial(function, *args, **kwargs) + g = factory(function, hub) + loop.run_callback(g.switch) + else: + g = factory(function, hub) + loop.run_callback(g.switch, *args) + g.loop = hub.loop + return g + + +def sleep(seconds=0, ref=True): + """ + Put the current greenlet to sleep for at least *seconds*. + + *seconds* may be specified as an integer, or a float if fractional + seconds are desired. + + .. tip:: In the current implementation, a value of 0 (the default) + means to yield execution to any other runnable greenlets, but + this greenlet may be scheduled again before the event loop + cycles (in an extreme case, a greenlet that repeatedly sleeps + with 0 can prevent greenlets that are ready to do I/O from + being scheduled for some (small) period of time); a value greater than + 0, on the other hand, will delay running this greenlet until + the next iteration of the loop. + + If *ref* is False, the greenlet running ``sleep()`` will not prevent :func:`gevent.wait` + from exiting. + + .. versionchanged:: 1.3a1 + Sleeping with a value of 0 will now be bounded to approximately block the + loop for no longer than :func:`gevent.getswitchinterval`. + + .. seealso:: :func:`idle` + """ + hub = _get_hub_noargs() + loop = hub.loop + if seconds <= 0: + waiter = Waiter(hub) + loop.run_callback(waiter.switch, None) + waiter.get() + else: + with loop.timer(seconds, ref=ref) as t: + # Sleeping is expected to be an "absolute" measure with + # respect to time.time(), not a relative measure, so it's + # important to update the loop's notion of now before we start + loop.update_now() + hub.wait(t) + + +def idle(priority=0): + """ + Cause the calling greenlet to wait until the event loop is idle. + + Idle is defined as having no other events of the same or higher + *priority* pending. That is, as long as sockets, timeouts or even + signals of the same or higher priority are being processed, the loop + is not idle. + + .. seealso:: :func:`sleep` + """ + hub = _get_hub_noargs() + with hub.loop.idle() as watcher: + if priority: + watcher.priority = priority + hub.wait(watcher) + + +def kill(greenlet, exception=GreenletExit): + """ + Kill greenlet asynchronously. The current greenlet is not unscheduled. + + .. note:: + + The method :meth:`Greenlet.kill` method does the same and + more (and the same caveats listed there apply here). However, the MAIN + greenlet - the one that exists initially - does not have a + ``kill()`` method, and neither do any created with :func:`spawn_raw`, + so you have to use this function. + + .. caution:: Use care when killing greenlets. If they are not prepared for + exceptions, this could result in corrupted state. + + .. versionchanged:: 1.1a2 + If the ``greenlet`` has a :meth:`kill ` method, calls it. This prevents a + greenlet from being switched to for the first time after it's been + killed but not yet executed. + """ + if not greenlet.dead: + if hasattr(greenlet, 'kill'): + # dealing with gevent.greenlet.Greenlet. Use it, especially + # to avoid allowing one to be switched to for the first time + # after it's been killed + greenlet.kill(exception=exception, block=False) + else: + _get_hub_noargs().loop.run_callback(greenlet.throw, exception) + + +class signal(object): + """ + signal_handler(signalnum, handler, *args, **kwargs) -> object + + Call the *handler* with the *args* and *kwargs* when the process + receives the signal *signalnum*. + + The *handler* will be run in a new greenlet when the signal is + delivered. + + This returns an object with the useful method ``cancel``, which, + when called, will prevent future deliveries of *signalnum* from + calling *handler*. It's best to keep the returned object alive + until you call ``cancel``. + + .. note:: + + This may not operate correctly with ``SIGCHLD`` if libev child + watchers are used (as they are by default with + `gevent.os.fork`). See :mod:`gevent.signal` for a more + general purpose solution. + + .. versionchanged:: 1.2a1 + + The ``handler`` argument is required to + be callable at construction time. + + .. versionchanged:: 20.5.1 + The ``cancel`` method now properly cleans up all native resources, + and drops references to all the arguments of this function. + """ + # This is documented as a function, not a class, + # so we're free to change implementation details. + + greenlet_class = None + + def __init__(self, signalnum, handler, *args, **kwargs): + if not callable(handler): + raise TypeError("signal handler must be callable.") + + self.hub = _get_hub_noargs() + self.watcher = self.hub.loop.signal(signalnum, ref=False) + self.handler = handler + self.args = args + self.kwargs = kwargs + if self.greenlet_class is None: + from gevent import Greenlet + type(self).greenlet_class = Greenlet + self.greenlet_class = Greenlet + + self.watcher.start(self._start) + + ref = property( + lambda self: self.watcher.ref, + lambda self, nv: setattr(self.watcher, 'ref', nv) + ) + + def cancel(self): + if self.watcher is not None: + self.watcher.stop() + # Must close the watcher at a deterministic time, otherwise + # when CFFI reclaims the memory, the native loop might still + # have some reference to it; if anything tries to touch it + # we can wind up writing to memory that is no longer valid, + # leading to a wide variety of crashes. + self.watcher.close() + self.watcher = None + self.handler = None + self.args = None + self.kwargs = None + self.hub = None + self.greenlet_class = None + + def _start(self): + # TODO: Maybe this should just be Greenlet.spawn()? + try: + greenlet = self.greenlet_class(self.handle) + greenlet.switch() + except: # pylint:disable=bare-except + self.hub.handle_error(None, *sys._exc_info()) # pylint:disable=no-member + + def handle(self): + try: + self.handler(*self.args, **self.kwargs) + except: # pylint:disable=bare-except + self.hub.handle_error(None, *sys.exc_info()) + + +def reinit(hub=None): + """ + reinit() -> None + + Prepare the gevent hub to run in a new (forked) process. + + This should be called *immediately* after :func:`os.fork` in the + child process. This is done automatically by + :func:`gevent.os.fork` or if the :mod:`os` module has been + monkey-patched. If this function is not called in a forked + process, symptoms may include hanging of functions like + :func:`socket.getaddrinfo`, and the hub's threadpool is unlikely + to work. + + .. note:: Registered fork watchers may or may not run before + this function (and thus ``gevent.os.fork``) return. If they have + not run, they will run "soon", after an iteration of the event loop. + You can force this by inserting a few small (but non-zero) calls to :func:`sleep` + after fork returns. (As of gevent 1.1 and before, fork watchers will + not have run, but this may change in the future.) + + .. note:: This function may be removed in a future major release + if the fork process can be more smoothly managed. + + .. warning:: See remarks in :func:`gevent.os.fork` about greenlets + and event loop watchers in the child process. + """ + # Note the signature line in the docstring: hub is not a public param. + + # The loop reinit function in turn calls libev's ev_loop_fork + # function. + hub = _get_hub() if hub is None else hub + if hub is None: + return + + # Note that we reinit the existing loop, not destroy it. + # See https://github.com/gevent/gevent/issues/200. + hub.loop.reinit() + # libev's fork watchers are slow to fire because the only fire + # at the beginning of a loop; due to our use of callbacks that + # run at the end of the loop, that may be too late. The + # threadpool and resolvers depend on the fork handlers being + # run (specifically, the threadpool will fail in the forked + # child if there were any threads in it, which there will be + # if the resolver_thread was in use (the default) before the + # fork.) + # + # If the forked process wants to use the threadpool or + # resolver immediately (in a queued callback), it would hang. + # + # The below is a workaround. Fortunately, all of these + # methods are idempotent and can be called multiple times + # following a fork if the suddenly started working, or were + # already working on some platforms. Other threadpools and fork handlers + # will be called at an arbitrary time later ('soon') + for obj in (hub._threadpool, hub._resolver, hub.periodic_monitoring_thread): + getattr(obj, '_on_fork', lambda: None)() + + # TODO: We'd like to sleep for a non-zero amount of time to force the loop to make a + # pass around before returning to this greenlet. That will allow any + # user-provided fork watchers to run. (Two calls are necessary.) HOWEVER, if + # we do this, certain tests that heavily mix threads and forking, + # like 2.7/test_threading:test_reinit_tls_after_fork, fail. It's not immediately clear + # why. + #sleep(0.00001) + #sleep(0.00001) + + +class Hub(WaitOperationsGreenlet): + """ + A greenlet that runs the event loop. + + It is created automatically by :func:`get_hub`. + + .. rubric:: Switching + + Every time this greenlet (i.e., the event loop) is switched *to*, + if the current greenlet has a ``switch_out`` method, it will be + called. This allows a greenlet to take some cleanup actions before + yielding control. This method should not call any gevent blocking + functions. + """ + + #: If instances of these classes are raised into the event loop, + #: they will be propagated out to the main greenlet (where they will + #: usually be caught by Python itself) + SYSTEM_ERROR = (KeyboardInterrupt, SystemExit, SystemError) + + #: Instances of these classes are not considered to be errors and + #: do not get logged/printed when raised by the event loop. + NOT_ERROR = (GreenletExit, SystemExit) + + #: The size we use for our threadpool. Either use a subclass + #: for this, or change it immediately after creating the hub. + threadpool_size = 10 + + # An instance of PeriodicMonitoringThread, if started. + periodic_monitoring_thread = None + + # The ident of the thread we were created in, which should be the + # thread that we run in. + thread_ident = None + + #: A string giving the name of this hub. Useful for associating hubs + #: with particular threads. Printed as part of the default repr. + #: + #: .. versionadded:: 1.3b1 + name = '' + + # NOTE: We cannot define a class-level 'loop' attribute + # because that conflicts with the slot we inherit from the + # Cythonized-bases. + + # This is the source for our 'minimal_ident' property. We don't use a + # IdentRegistry because we've seen some crashes having to do with + # clearing weak references on shutdown in Windows (see known_failures.py). + # This gives us slightly different semantics than a greenlet's minimal_ident + # (notably, there can be holes) but we never documented this object's minimal_ident, + # and there should be few enough hub's over the lifetime of a process so as not + # to matter much. + _hub_counter = 0 + + def __init__(self, loop=None, default=None): + WaitOperationsGreenlet.__init__(self, None, None) + self.thread_ident = get_thread_ident() + if hasattr(loop, 'run'): + if default is not None: + raise TypeError("Unexpected argument: default") + self.loop = loop + elif get_loop() is not None: + # Reuse a loop instance previously set by + # destroying a hub without destroying the associated + # loop. See #237 and #238. + self.loop = get_loop() + else: + if default is None and self.thread_ident != MAIN_THREAD_IDENT: + default = False + + if loop is None: + loop = self.backend + self.loop = self.loop_class(flags=loop, default=default) # pylint:disable=not-callable + self._resolver = None + self._threadpool = None + self.format_context = GEVENT_CONFIG.format_context + + Hub._hub_counter += 1 + self.minimal_ident = Hub._hub_counter + + @Lazy + def ident_registry(self): + return IdentRegistry() + + @property + def loop_class(self): + return GEVENT_CONFIG.loop + + @property + def backend(self): + return GEVENT_CONFIG.libev_backend + + @property + def main_hub(self): + """ + Is this the hub for the main thread? + + .. versionadded:: 1.3b1 + """ + return self.thread_ident == MAIN_THREAD_IDENT + + def __repr__(self): + if self.loop is None: + info = 'destroyed' + else: + try: + info = self.loop._format() + except Exception as ex: # pylint:disable=broad-except + info = str(ex) or repr(ex) or 'error' + result = '<%s %r at 0x%x %s' % ( + self.__class__.__name__, + self.name, + id(self), + info) + if self._resolver is not None: + result += ' resolver=%r' % self._resolver + if self._threadpool is not None: + result += ' threadpool=%r' % self._threadpool + result += ' thread_ident=%s' % (hex(self.thread_ident), ) + return result + '>' + + def _normalize_exception(self, t, v, tb): + # Allow passing in all None if the caller doesn't have + # easy access to sys.exc_info() + if (t, v, tb) == (None, None, None): + t, v, tb = sys.exc_info() + + if isinstance(v, str): + # Cython can raise errors where the value is a plain string + # e.g., AttributeError, "_semaphore.Semaphore has no attr", + v = t(v) + + return t, v, tb + + def handle_error(self, context, type, value, tb): + """ + Called by the event loop when an error occurs. The default + action is to print the exception to the :attr:`exception + stream `. + + The arguments ``type``, ``value``, and ``tb`` are the standard + tuple as returned by :func:`sys.exc_info`. (Note that when + this is called, it may not be safe to call + :func:`sys.exc_info`.) + + Errors that are :attr:`not errors ` are not + printed. + + Errors that are :attr:`system errors ` are + passed to :meth:`handle_system_error` after being printed. + + Applications can set a property on the hub instance with this + same signature to override the error handling provided by this + class. This is an advanced usage and requires great care. This + function *must not* raise any exceptions. + + :param context: If this is ``None``, indicates a system error + that should generally result in exiting the loop and being + thrown to the parent greenlet. + """ + type, value, tb = self._normalize_exception(type, value, tb) + + if type is HubDestroyed: + # We must continue propagating this for it to properly + # exit. + reraise(type, value, tb) + + if not issubclass(type, self.NOT_ERROR): + self.print_exception(context, type, value, tb) + if context is None or issubclass(type, self.SYSTEM_ERROR): + self.handle_system_error(type, value, tb) + + def handle_system_error(self, type, value, tb=None): + """ + Called from `handle_error` when the exception type is determined + to be a :attr:`system error `. + + System errors cause the exception to be raised in the main + greenlet (the parent of this hub). + + .. versionchanged:: 20.5.1 + Allow passing the traceback to associate with the + exception if it is rethrown into the main greenlet. + """ + current = getcurrent() + if current is self or current is self.parent or self.loop is None: + self.parent.throw(type, value, tb) + else: + # in case system error was handled and life goes on + # switch back to this greenlet as well + cb = None + try: + cb = self.loop.run_callback(current.switch) + except: # pylint:disable=bare-except + traceback.print_exc(file=self.exception_stream) + try: + self.parent.throw(type, value, tb) + finally: + if cb is not None: + cb.stop() + + @readproperty + def exception_stream(self): + """ + The stream to which exceptions will be written. + Defaults to ``sys.stderr`` unless assigned. Assigning a + false (None) value disables printing exceptions. + + .. versionadded:: 1.2a1 + """ + # Unwrap any FileObjectThread we have thrown around sys.stderr + # (because it can't be used in the hub). Tricky because we are + # called in error situations when it's not safe to import. + # Be careful not to access sys if we're in the process of interpreter + # shutdown. + stderr = sys.stderr if sys else None # pylint:disable=using-constant-test + if type(stderr).__name__ == 'FileObjectThread': + stderr = stderr.io # pylint:disable=no-member + return stderr + + def print_exception(self, context, t, v, tb): + # Python 3 does not gracefully handle None value or tb in + # traceback.print_exception() as previous versions did. + # pylint:disable=no-member + errstream = self.exception_stream + if not errstream: # pragma: no cover + # If the error stream is gone, such as when the sys dict + # gets cleared during interpreter shutdown, + # don't cause follow-on errors. + # See https://github.com/gevent/gevent/issues/1295 + return + + t, v, tb = self._normalize_exception(t, v, tb) + + if v is None: + errstream.write('%s\n' % t.__name__) + else: + traceback.print_exception(t, v, tb, file=errstream) + del tb + + try: + errstream.write(gmctime()) + errstream.write(' ' if context is not None else '\n') + except: # pylint:disable=bare-except + # Possible not safe to import under certain + # error conditions in Python 2 + pass + + if context is not None: + if not isinstance(context, str): + try: + context = self.format_context(context) + except: # pylint:disable=bare-except + traceback.print_exc(file=self.exception_stream) + context = repr(context) + errstream.write('%s failed with %s\n\n' % (context, getattr(t, '__name__', 'exception'), )) + + + def run(self): + """ + Entry-point to running the loop. This method is called automatically + when the hub greenlet is scheduled; do not call it directly. + + :raises gevent.exceptions.LoopExit: If the loop finishes running. This means + that there are no other scheduled greenlets, and no active + watchers or servers. In some situations, this indicates a + programming error. + """ + assert self is getcurrent(), 'Do not call Hub.run() directly' + self.start_periodic_monitoring_thread() + while 1: + loop = self.loop + loop.error_handler = self + try: + loop.run() + finally: + loop.error_handler = None # break the refcount cycle + + # This function must never return, as it will cause + # switch() in the parent greenlet to return an unexpected + # value. This can show up as unexpected failures e.g., + # from Waiters raising AssertionError or MulitpleWaiter + # raising invalid IndexError. + # + # It is still possible to kill this greenlet with throw. + # However, in that case switching to it is no longer safe, + # as switch will return immediately. + # + # Note that there's a problem with simply doing + # ``self.parent.throw()`` and never actually exiting this + # greenlet: The greenlet tends to stay alive. This is + # because throwing the exception captures stack frames + # (regardless of what we do with the argument) and those + # get saved. In addition to this object having + # ``gr_frame`` pointing to this method, which contains + # ``self``, which points to the parent, and both of which point to + # an internal thread state dict that points back to the current greenlet for the thread, + # which is likely to be the parent: a cycle. + # + # We can't have ``join()`` tell us to finish, because we + # need to be able to resume after this throw. The only way + # to dispose of the greenlet is to use ``self.destroy()``. + + debug = [] + if hasattr(loop, 'debug'): + debug = loop.debug() + loop = None + + self.parent.throw(LoopExit('This operation would block forever', + self, + debug)) + # Execution could resume here if another blocking API call is made + # in the same thread and the hub hasn't been destroyed, so clean + # up anything left. + debug = None + + def start_periodic_monitoring_thread(self): + if self.periodic_monitoring_thread is None and GEVENT_CONFIG.monitor_thread: + # Note that it is possible for one real thread to + # (temporarily) wind up with multiple monitoring threads, + # if hubs are started and stopped within the thread. This shows up + # in the threadpool tests. The monitoring threads will eventually notice their + # hub object is gone. + from gevent._monitor import PeriodicMonitoringThread + from gevent.events import PeriodicMonitorThreadStartedEvent + from gevent.events import notify_and_call_entry_points + self.periodic_monitoring_thread = PeriodicMonitoringThread(self) + + if self.main_hub: + self.periodic_monitoring_thread.install_monitor_memory_usage() + + notify_and_call_entry_points(PeriodicMonitorThreadStartedEvent( + self.periodic_monitoring_thread)) + + return self.periodic_monitoring_thread + + def join(self, timeout=None): + """ + Wait for the event loop to finish. Exits only when there + are no more spawned greenlets, started servers, active + timeouts or watchers. + + .. caution:: This doesn't clean up all resources associated + with the hub. For that, see :meth:`destroy`. + + :param float timeout: If *timeout* is provided, wait no longer + than the specified number of seconds. + + :return: `True` if this method returns because the loop + finished execution. Or `False` if the timeout + expired. + """ + assert getcurrent() is self.parent, "only possible from the MAIN greenlet" + if self.dead: + return True + + waiter = Waiter(self) + + if timeout is not None: + timeout = self.loop.timer(timeout, ref=False) + timeout.start(waiter.switch, None) + + try: + try: + # Switch to the hub greenlet and let it continue. + # Since we're the parent greenlet of the hub, when it exits + # by `parent.throw(LoopExit)`, control will resume here. + # If the timer elapses, however, ``waiter.switch()`` is called and + # again control resumes here, but without an exception. + waiter.get() + except LoopExit: + # Control will immediately be returned to this greenlet. + return True + finally: + # Clean up as much junk as we can. There is a small cycle in the frames, + # and it won't be GC'd. + # this greenlet -> this frame + # this greenlet -> the exception that was thrown + # the exception that was thrown -> a bunch of other frames, including this frame. + # some frame calling self.run() -> self + del waiter # this frame -> waiter -> self + del self # this frame -> self + if timeout is not None: + timeout.stop() + timeout.close() + del timeout + return False + + def destroy(self, destroy_loop=None): + """ + Destroy this hub and clean up its resources. + + If you manually create hubs, or you use a hub or the gevent + blocking API from multiple native threads, you *should* call this + method before disposing of the hub object reference. Ideally, + this should be called from the same thread running the hub, but + it can be called from other threads after that thread has exited. + + Once this is done, it is impossible to continue running the + hub. Attempts to use the blocking gevent API with pre-existing + objects from this native thread and bound to this hub will fail. + + .. versionchanged:: 20.5.1 + Attempt to ensure that Python stack frames and greenlets referenced by this + hub are cleaned up. This guarantees that switching to the hub again + is not safe after this. (It was never safe, but it's even less safe.) + + Note that this only works if the hub is destroyed in the same thread it + is running in. If the hub is destroyed by a different thread + after a ``fork()``, for example, expect some garbage to leak. + """ + if destroy_loop is None: + destroy_loop = not self.loop.default + + if self.periodic_monitoring_thread is not None: + self.periodic_monitoring_thread.kill() + self.periodic_monitoring_thread = None + if self._resolver is not None: + self._resolver.close() + del self._resolver + if self._threadpool is not None: + self._threadpool.kill() + del self._threadpool + + # Let the frame be cleaned up by causing the run() function to + # exit. This is the only way to guarantee that the hub itself + # and the main greenlet, if this was a secondary thread, get + # cleaned up. Otherwise there are likely to be reference + # cycles still around. We MUST do this before we destroy the + # loop; if we destroy the loop and then switch into the hub, + # things will go VERY, VERY wrong (because we will have destroyed + # the C datastructures in the middle of the C function that's + # using them; the best we can hope for is a segfault). + try: + self.throw(HubDestroyed(destroy_loop)) + except LoopExit: + # Expected. + pass + except GreenletError: + # Must be coming from a different thread. + # Note that python stack frames are likely to leak + # in this case. + pass + + if destroy_loop: + if get_loop() is self.loop: + # Don't let anyone try to reuse this + set_loop(None) + self.loop.destroy() + else: + # Store in case another hub is created for this + # thread. + set_loop(self.loop) + + self.loop = None + if _get_hub() is self: + set_hub(None) + + + + # XXX: We can probably simplify the resolver and threadpool properties. + + @property + def resolver_class(self): + return GEVENT_CONFIG.resolver + + def _get_resolver(self): + if self._resolver is None: + self._resolver = self.resolver_class(hub=self) # pylint:disable=not-callable + return self._resolver + + def _set_resolver(self, value): + self._resolver = value + + def _del_resolver(self): + self._resolver = None + + resolver = property(_get_resolver, _set_resolver, _del_resolver, + """ + The DNS resolver that the socket functions will use. + + .. seealso:: :doc:`/dns` + """) + + + @property + def threadpool_class(self): + return GEVENT_CONFIG.threadpool + + def _get_threadpool(self): + if self._threadpool is None: + # pylint:disable=not-callable + self._threadpool = self.threadpool_class( + self.threadpool_size, + hub=self, + idle_task_timeout=GEVENT_CONFIG.threadpool_idle_task_timeout + ) + return self._threadpool + + def _set_threadpool(self, value): + self._threadpool = value + + def _del_threadpool(self): + self._threadpool = None + + threadpool = property(_get_threadpool, _set_threadpool, _del_threadpool, + """ + The threadpool associated with this hub. + + Usually this is a + :class:`gevent.threadpool.ThreadPool`, but + you :attr:`can customize that + `. + + Use this object to schedule blocking + (non-cooperative) operations in a different + thread to prevent them from halting the event loop. + """) + + +set_default_hub_class(Hub) + + + +class linkproxy(object): + __slots__ = ['callback', 'obj'] + + def __init__(self, callback, obj): + self.callback = callback + self.obj = obj + + def __call__(self, *args): + callback = self.callback + obj = self.obj + self.callback = None + self.obj = None + callback(obj) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..412d64cec15683ec32f540afb1827789a8837bf7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# Nothing public here +__all__ = [] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/_corecffi_build.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/_corecffi_build.py new file mode 100644 index 0000000000000000000000000000000000000000..5c400fcbc2573fd9825feb5a56684090b23bf066 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/_corecffi_build.py @@ -0,0 +1,126 @@ +# pylint: disable=no-member + +# This module is only used to create and compile the gevent._corecffi module; +# nothing should be directly imported from it except `ffi`, which should only be +# used for `ffi.compile()`; programs should import gevent._corecfffi. +# However, because we are using "out-of-line" mode, it is necessary to examine +# this file to know what functions are created and available on the generated +# module. +from __future__ import absolute_import, print_function +import sys +import os +import os.path # pylint:disable=no-name-in-module +from cffi import FFI + +sys.path.append(".") +try: + import _setuplibev + import _setuputils +except ImportError: + print("This file must be imported with setup.py in the current working dir.") + raise + +thisdir = os.path.dirname(os.path.abspath(__file__)) +parentdir = os.path.abspath(os.path.join(thisdir, '..')) +setup_dir = os.path.abspath(os.path.join(thisdir, '..', '..', '..')) + + +__all__ = [] + + +ffi = FFI() +distutils_ext = _setuplibev.build_extension() + +def read_source(name): + # pylint:disable=unspecified-encoding + with open(os.path.join(thisdir, name), 'r') as f: + return f.read() + +# cdef goes to the cffi library and determines what can be used in +# Python. +_cdef = read_source('_corecffi_cdef.c') + +# These defines and uses help keep the C file readable and lintable by +# C tools. +_cdef = _cdef.replace('#define GEVENT_STRUCT_DONE int', '') +_cdef = _cdef.replace("GEVENT_STRUCT_DONE _;", '...;') + +_cdef = _cdef.replace('#define GEVENT_ST_NLINK_T int', + 'typedef int... nlink_t;') +_cdef = _cdef.replace('GEVENT_ST_NLINK_T', 'nlink_t') + +if _setuplibev.LIBEV_EMBED: + # Arrange access to the loop internals + _cdef += """ +struct ev_loop { + int backend_fd; + int activecnt; + ...; +}; + """ + +# arrange to be configured. +_setuputils.ConfiguringBuildExt.gevent_add_pre_run_action(distutils_ext.configure) + + +if sys.platform.startswith('win'): + # We must have the vfd_open, etc, functions on + # Windows. But on other platforms, going through + # CFFI to just return the file-descriptor is slower + # than just doing it in Python, so we check for and + # workaround their absence in corecffi.py + _cdef += """ +typedef int... vfd_socket_t; +int vfd_open(vfd_socket_t); +vfd_socket_t vfd_get(int); +void vfd_free(int); +""" + +# source goes to the C compiler +_source = read_source('_corecffi_source.c') + +macros = list(distutils_ext.define_macros) +try: + # We need the data pointer. + macros.remove(('EV_COMMON', '')) +except ValueError: + pass + +ffi.cdef(_cdef) +ffi.set_source( + 'gevent.libev._corecffi', + _source, + include_dirs=distutils_ext.include_dirs + [ + thisdir, # "libev.h" + parentdir, # _ffi/alloc.c + ], + define_macros=macros, + undef_macros=distutils_ext.undef_macros, + libraries=distutils_ext.libraries, +) + +if __name__ == '__main__': + # XXX: Note, on Windows, we would need to specify the external libraries + # that should be linked in, such as ws2_32 and (because libev_vfd.h makes + # Python.h calls) the proper Python library---at least for PyPy. I never got + # that to work though, and calling python functions is strongly discouraged + # from CFFI code. + + # On macOS to make the non-embedded case work correctly, against + # our local copy of libev: + # + # 1) configure and make libev + # 2) CPPFLAGS=-Ideps/libev/ LDFLAGS=-Ldeps/libev/.libs GEVENTSETUP_EMBED_LIBEV=0 \ + # python setup.py build_ext -i + # 3) export DYLD_LIBRARY_PATH=`pwd`/deps/libev/.libs + # + # The DYLD_LIBRARY_PATH is because the linker hard-codes + # /usr/local/lib/libev.4.dylib in the corecffi.so dylib, because + # that's the "install name" of the libev dylib that was built. + # Adding a -rpath to the LDFLAGS doesn't change things. + # This can be fixed with `install_name_tool`: + # + # 3) install_name_tool -change /usr/local/lib/libev.4.dylib \ + # `pwd`/deps/libev/.libs/libev.4.dylib \ + # src/gevent/libev/_corecffi.abi3.so + ffi.compile(verbose=True) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/corecffi.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/corecffi.py new file mode 100644 index 0000000000000000000000000000000000000000..1abd68f1d867cad79609dae8ab623959cad2d51c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/corecffi.py @@ -0,0 +1,470 @@ +# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable +# pylint: disable=no-member +from __future__ import absolute_import, print_function +import sys + +# pylint: disable=undefined-all-variable +__all__ = [ + 'get_version', + 'get_header_version', + 'supported_backends', + 'recommended_backends', + 'embeddable_backends', + 'time', + 'loop', +] + +from zope.interface import implementer + +from gevent._interfaces import ILoop + +from gevent.libev import _corecffi # pylint:disable=no-name-in-module,import-error + +ffi = _corecffi.ffi # pylint:disable=no-member +libev = _corecffi.lib # pylint:disable=no-member + +if hasattr(libev, 'vfd_open'): + # Must be on windows + # pylint:disable=c-extension-no-member + assert sys.platform.startswith("win"), "vfd functions only needed on windows" + vfd_open = libev.vfd_open + vfd_free = libev.vfd_free + vfd_get = libev.vfd_get +else: + vfd_open = vfd_free = vfd_get = lambda fd: fd + +libev.gevent_set_ev_alloc() + +##### +## NOTE on Windows: +# The C implementation does several things specially for Windows; +# a possibly incomplete list is: +# +# - the loop runs a periodic signal checker; +# - the io watcher constructor is different and it has a destructor; +# - the child watcher is not defined +# +# The CFFI implementation does none of these things, and so +# is possibly NOT FUNCTIONALLY CORRECT on Win32 +##### + + +from gevent._ffi.loop import AbstractCallbacks +from gevent._ffi.loop import assign_standard_callbacks + +class _Callbacks(AbstractCallbacks): + # pylint:disable=arguments-differ,arguments-renamed + + def python_check_callback(self, *args): + # There's a pylint bug (pylint 2.9.3, astroid 2.6.2) that causes pylint to crash + # with an AttributeError on certain types of arguments-differ errors + # But code in _ffi/loop depends on being able to find the watcher_ptr + # argument is the local frame. BUT it gets invoked before the function body runs. + # Hence the override of _find_watcher_ptr_in_traceback. + # pylint:disable=unused-variable + _loop, watcher_ptr, _events = args + AbstractCallbacks.python_check_callback(self, watcher_ptr) + + def _find_watcher_ptr_in_traceback(self, tb): + if tb is not None: + l = tb.tb_frame.f_locals + if 'watcher_ptr' in l: + return l['watcher_ptr'] + if 'args' in l and len(l['args']) == 3: + return l['args'][1] + return AbstractCallbacks._find_watcher_ptr_in_traceback(self, tb) + + def python_prepare_callback(self, _loop_ptr, watcher_ptr, _events): + AbstractCallbacks.python_prepare_callback(self, watcher_ptr) + + def _find_loop_from_c_watcher(self, watcher_ptr): + loop_handle = ffi.cast('struct ev_watcher*', watcher_ptr).data + return self.from_handle(loop_handle) + +_callbacks = assign_standard_callbacks(ffi, libev, _Callbacks) + + +UNDEF = libev.EV_UNDEF +NONE = libev.EV_NONE +READ = libev.EV_READ +WRITE = libev.EV_WRITE +TIMER = libev.EV_TIMER +PERIODIC = libev.EV_PERIODIC +SIGNAL = libev.EV_SIGNAL +CHILD = libev.EV_CHILD +STAT = libev.EV_STAT +IDLE = libev.EV_IDLE +PREPARE = libev.EV_PREPARE +CHECK = libev.EV_CHECK +EMBED = libev.EV_EMBED +FORK = libev.EV_FORK +CLEANUP = libev.EV_CLEANUP +ASYNC = libev.EV_ASYNC +CUSTOM = libev.EV_CUSTOM +ERROR = libev.EV_ERROR + +READWRITE = libev.EV_READ | libev.EV_WRITE + +MINPRI = libev.EV_MINPRI +MAXPRI = libev.EV_MAXPRI + +BACKEND_PORT = libev.EVBACKEND_PORT +BACKEND_KQUEUE = libev.EVBACKEND_KQUEUE +BACKEND_EPOLL = libev.EVBACKEND_EPOLL +BACKEND_POLL = libev.EVBACKEND_POLL +BACKEND_SELECT = libev.EVBACKEND_SELECT +FORKCHECK = libev.EVFLAG_FORKCHECK +NOINOTIFY = libev.EVFLAG_NOINOTIFY +SIGNALFD = libev.EVFLAG_SIGNALFD +NOSIGMASK = libev.EVFLAG_NOSIGMASK + + +from gevent._ffi.loop import EVENTS +GEVENT_CORE_EVENTS = EVENTS + + +def get_version(): + return 'libev-%d.%02d' % (libev.ev_version_major(), libev.ev_version_minor()) + + +def get_header_version(): + return 'libev-%d.%02d' % (libev.EV_VERSION_MAJOR, libev.EV_VERSION_MINOR) + +# This list backends in the order they are actually tried by libev, +# as defined in loop_init. The names must be lower case. +_flags = [ + # IOCP --- not supported/used. + (libev.EVBACKEND_PORT, 'port'), + (libev.EVBACKEND_KQUEUE, 'kqueue'), + (libev.EVBACKEND_IOURING, 'linux_iouring'), + (libev.EVBACKEND_LINUXAIO, "linux_aio"), + (libev.EVBACKEND_EPOLL, 'epoll'), + (libev.EVBACKEND_POLL, 'poll'), + (libev.EVBACKEND_SELECT, 'select'), + + (libev.EVFLAG_NOENV, 'noenv'), + (libev.EVFLAG_FORKCHECK, 'forkcheck'), + (libev.EVFLAG_SIGNALFD, 'signalfd'), + (libev.EVFLAG_NOSIGMASK, 'nosigmask') +] + +_flags_str2int = dict((string, flag) for (flag, string) in _flags) + + + +def _flags_to_list(flags): + result = [] + for code, value in _flags: + if flags & code: + result.append(value) + flags &= ~code + if not flags: + break + if flags: + result.append(flags) + return result + +if sys.version_info[0] >= 3: + basestring = (bytes, str) + integer_types = (int,) +else: + import __builtin__ # pylint:disable=import-error + basestring = (__builtin__.basestring,) + integer_types = (int, __builtin__.long) + + +def _flags_to_int(flags): + # Note, that order does not matter, libev has its own predefined order + if not flags: + return 0 + if isinstance(flags, integer_types): + return flags + result = 0 + try: + if isinstance(flags, basestring): + flags = flags.split(',') + for value in flags: + value = value.strip().lower() + if value: + result |= _flags_str2int[value] + except KeyError as ex: + raise ValueError('Invalid backend or flag: %s\nPossible values: %s' % (ex, ', '.join(sorted(_flags_str2int.keys())))) + return result + + +def _str_hex(flag): + if isinstance(flag, integer_types): + return hex(flag) + return str(flag) + + +def _check_flags(flags): + as_list = [] + flags &= libev.EVBACKEND_MASK + if not flags: + return + if not flags & libev.EVBACKEND_ALL: + raise ValueError('Invalid value for backend: 0x%x' % flags) + if not flags & libev.ev_supported_backends(): + as_list = [_str_hex(x) for x in _flags_to_list(flags)] + raise ValueError('Unsupported backend: %s' % '|'.join(as_list)) + + +def supported_backends(): + return _flags_to_list(libev.ev_supported_backends()) + + +def recommended_backends(): + return _flags_to_list(libev.ev_recommended_backends()) + + +def embeddable_backends(): + return _flags_to_list(libev.ev_embeddable_backends()) + + +def time(): + return libev.ev_time() + +from gevent._ffi.loop import AbstractLoop + + +from gevent.libev import watcher as _watchers +_events_to_str = _watchers._events_to_str # exported + + +@implementer(ILoop) +class loop(AbstractLoop): + # pylint:disable=too-many-public-methods + + # libuv parameters simply won't accept anything lower than 1ms + # (0.001s), but libev takes fractional seconds. In practice, on + # one machine, libev can sleep for very small periods of time: + # + # sleep(0.00001) -> 0.000024 + # sleep(0.0001) -> 0.000156 + # sleep(0.001) -> 0.00136 (which is comparable to libuv) + + approx_timer_resolution = 0.00001 + + error_handler = None + + _CHECK_POINTER = 'struct ev_check *' + + _PREPARE_POINTER = 'struct ev_prepare *' + + _TIMER_POINTER = 'struct ev_timer *' + + def __init__(self, flags=None, default=None): + AbstractLoop.__init__(self, ffi, libev, _watchers, flags, default) + self._default = bool(libev.ev_is_default_loop(self._ptr)) + + def _init_loop(self, flags, default): + c_flags = _flags_to_int(flags) + _check_flags(c_flags) + c_flags |= libev.EVFLAG_NOENV + c_flags |= libev.EVFLAG_FORKCHECK + if default is None: + default = True + if default: + ptr = libev.gevent_ev_default_loop(c_flags) + if not ptr: + raise SystemError("ev_default_loop(%s) failed" % (c_flags, )) + else: + ptr = libev.ev_loop_new(c_flags) + if not ptr: + raise SystemError("ev_loop_new(%s) failed" % (c_flags, )) + if default or SYSERR_CALLBACK is None: + set_syserr_cb(self._handle_syserr) + + # Mark this loop as being used. + libev.ev_set_userdata(ptr, ptr) + return ptr + + def _init_and_start_check(self): + libev.ev_check_init(self._check, libev.python_check_callback) + self._check.data = self._handle_to_self + libev.ev_check_start(self._ptr, self._check) + self.unref() + + def _init_and_start_prepare(self): + libev.ev_prepare_init(self._prepare, libev.python_prepare_callback) + libev.ev_prepare_start(self._ptr, self._prepare) + self.unref() + + def _init_callback_timer(self): + libev.ev_timer_init(self._timer0, libev.gevent_noop, 0.0, 0.0) + + def _stop_callback_timer(self): + libev.ev_timer_stop(self._ptr, self._timer0) + + def _start_callback_timer(self): + libev.ev_timer_start(self._ptr, self._timer0) + + def _stop_aux_watchers(self): + super(loop, self)._stop_aux_watchers() + if libev.ev_is_active(self._prepare): + self.ref() + libev.ev_prepare_stop(self._ptr, self._prepare) + if libev.ev_is_active(self._check): + self.ref() + libev.ev_check_stop(self._ptr, self._check) + if libev.ev_is_active(self._timer0): + libev.ev_timer_stop(self._timer0) + + def _setup_for_run_callback(self): + # XXX: libuv needs to start the callback timer to be sure + # that the loop wakes up and calls this. Our C version doesn't + # do this. + # self._start_callback_timer() + self.ref() # we should go through the loop now + + def destroy(self): + if self._ptr: + super(loop, self).destroy() + # pylint:disable=comparison-with-callable + if globals()["SYSERR_CALLBACK"] == self._handle_syserr: + set_syserr_cb(None) + + + def _can_destroy_loop(self, ptr): + # Is it marked as destroyed? + return libev.ev_userdata(ptr) + + def _destroy_loop(self, ptr): + # Mark as destroyed. + libev.ev_set_userdata(ptr, ffi.NULL) + libev.ev_loop_destroy(ptr) + + libev.gevent_zero_prepare(self._prepare) + libev.gevent_zero_check(self._check) + libev.gevent_zero_timer(self._timer0) + + del self._prepare + del self._check + del self._timer0 + + + @property + def MAXPRI(self): + return libev.EV_MAXPRI + + @property + def MINPRI(self): + return libev.EV_MINPRI + + def _default_handle_error(self, context, type, value, tb): # pylint:disable=unused-argument + super(loop, self)._default_handle_error(context, type, value, tb) + libev.ev_break(self._ptr, libev.EVBREAK_ONE) + + def run(self, nowait=False, once=False): + flags = 0 + if nowait: + flags |= libev.EVRUN_NOWAIT + if once: + flags |= libev.EVRUN_ONCE + + libev.ev_run(self._ptr, flags) + + def reinit(self): + libev.ev_loop_fork(self._ptr) + + def ref(self): + libev.ev_ref(self._ptr) + + def unref(self): + libev.ev_unref(self._ptr) + + def break_(self, how=libev.EVBREAK_ONE): + libev.ev_break(self._ptr, how) + + def verify(self): + libev.ev_verify(self._ptr) + + def now(self): + return libev.ev_now(self._ptr) + + def update_now(self): + libev.ev_now_update(self._ptr) + + def __repr__(self): + return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self._format()) + + @property + def iteration(self): + return libev.ev_iteration(self._ptr) + + @property + def depth(self): + return libev.ev_depth(self._ptr) + + @property + def backend_int(self): + return libev.ev_backend(self._ptr) + + @property + def backend(self): + backend = libev.ev_backend(self._ptr) + for key, value in _flags: + if key == backend: + return value + return backend + + @property + def pendingcnt(self): + return libev.ev_pending_count(self._ptr) + + def closing_fd(self, fd): + pending_before = libev.ev_pending_count(self._ptr) + libev.ev_feed_fd_event(self._ptr, fd, 0xFFFF) + pending_after = libev.ev_pending_count(self._ptr) + return pending_after > pending_before + + if sys.platform != "win32": + + def install_sigchld(self): + libev.gevent_install_sigchld_handler() + + def reset_sigchld(self): + libev.gevent_reset_sigchld_handler() + + def fileno(self): + if self._ptr and LIBEV_EMBED: + # If we don't embed, we can't access these fields, + # the type is opaque + fd = self._ptr.backend_fd + if fd >= 0: + return fd + + @property + def activecnt(self): + if not self._ptr: + raise ValueError('operation on destroyed loop') + if LIBEV_EMBED: + return self._ptr.activecnt + return -1 + + +@ffi.def_extern() +def _syserr_cb(msg): + try: + msg = ffi.string(msg) + SYSERR_CALLBACK(msg, ffi.errno) + except: + set_syserr_cb(None) + raise # let cffi print the traceback + + +def set_syserr_cb(callback): + global SYSERR_CALLBACK + if callback is None: + libev.ev_set_syserr_cb(ffi.NULL) + SYSERR_CALLBACK = None + elif callable(callback): + libev.ev_set_syserr_cb(libev._syserr_cb) + SYSERR_CALLBACK = callback + else: + raise TypeError('Expected callable or None, got %r' % (callback, )) + +SYSERR_CALLBACK = None + +LIBEV_EMBED = libev.LIBEV_EMBED diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/watcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae8d1debc06d25497ce1ec00899b2cd7e8b5853 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/watcher.py @@ -0,0 +1,287 @@ +# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable +# pylint: disable=no-member +from __future__ import absolute_import, print_function +import sys + +from gevent.libev import _corecffi # pylint:disable=no-name-in-module,import-error + +# Nothing public here +__all__ = [] + + +ffi = _corecffi.ffi # pylint:disable=no-member +libev = _corecffi.lib # pylint:disable=no-member + +if hasattr(libev, 'vfd_open'): + # Must be on windows + # pylint:disable=c-extension-no-member + assert sys.platform.startswith("win"), "vfd functions only needed on windows" + vfd_open = libev.vfd_open + vfd_free = libev.vfd_free + vfd_get = libev.vfd_get +else: + vfd_open = vfd_free = vfd_get = lambda fd: fd + +##### +## NOTE on Windows: +# The C implementation does several things specially for Windows; +# a possibly incomplete list is: +# +# - the loop runs a periodic signal checker; +# - the io watcher constructor is different and it has a destructor; +# - the child watcher is not defined +# +# The CFFI implementation does none of these things, and so +# is possibly NOT FUNCTIONALLY CORRECT on Win32 +##### +_NOARGS = () +_events = [(libev.EV_READ, 'READ'), + (libev.EV_WRITE, 'WRITE'), + (libev.EV__IOFDSET, '_IOFDSET'), + (libev.EV_PERIODIC, 'PERIODIC'), + (libev.EV_SIGNAL, 'SIGNAL'), + (libev.EV_CHILD, 'CHILD'), + (libev.EV_STAT, 'STAT'), + (libev.EV_IDLE, 'IDLE'), + (libev.EV_PREPARE, 'PREPARE'), + (libev.EV_CHECK, 'CHECK'), + (libev.EV_EMBED, 'EMBED'), + (libev.EV_FORK, 'FORK'), + (libev.EV_CLEANUP, 'CLEANUP'), + (libev.EV_ASYNC, 'ASYNC'), + (libev.EV_CUSTOM, 'CUSTOM'), + (libev.EV_ERROR, 'ERROR')] + +from gevent._ffi import watcher as _base + +def _events_to_str(events): + return _base.events_to_str(events, _events) + + + +class watcher(_base.watcher): + _FFI = ffi + _LIB = libev + _watcher_prefix = 'ev' + + # Flags is a bitfield with the following meaning: + # 0000 -> default, referenced (when active) + # 0010 -> ev_unref has been called + # 0100 -> not referenced; independent of 0010 + _flags = 0 + + def __init__(self, _loop, ref=True, priority=None, args=_base._NOARGS): + if ref: + self._flags = 0 + else: + self._flags = 4 + + super(watcher, self).__init__(_loop, ref=ref, priority=priority, args=args) + + def _watcher_ffi_set_priority(self, priority): + libev.ev_set_priority(self._watcher, priority) + + def _watcher_ffi_init(self, args): + self._watcher_init(self._watcher, + self._watcher_callback, + *args) + + def _watcher_ffi_start(self): + self._watcher_start(self.loop._ptr, self._watcher) + + def _watcher_ffi_ref(self): + if self._flags & 2: # we've told libev we're not referenced + self.loop.ref() + self._flags &= ~2 + + def _watcher_ffi_unref(self): + if self._flags & 6 == 4: + # We're not referenced, but we haven't told libev that + self.loop.unref() + self._flags |= 2 # now we've told libev + + def _get_ref(self): + return not self._flags & 4 + + def _set_ref(self, value): + if value: + if not self._flags & 4: + return # ref is already True + if self._flags & 2: # ev_unref was called, undo + self.loop.ref() + self._flags &= ~6 # do not want unref, no outstanding unref + else: + if self._flags & 4: + return # ref is already False + self._flags |= 4 # we're not referenced + if not self._flags & 2 and libev.ev_is_active(self._watcher): + # we haven't told libev we're not referenced, but it thinks we're + # active so we need to undo that + self.loop.unref() + self._flags |= 2 # libev knows we're not referenced + + ref = property(_get_ref, _set_ref) + + + def _get_priority(self): + return libev.ev_priority(self._watcher) + + @_base.not_while_active + def _set_priority(self, priority): + libev.ev_set_priority(self._watcher, priority) + + priority = property(_get_priority, _set_priority) + + def feed(self, revents, callback, *args): + self.callback = callback + self.args = args or _NOARGS + if self._flags & 6 == 4: + self.loop.unref() + self._flags |= 2 + libev.ev_feed_event(self.loop._ptr, self._watcher, revents) + if not self._flags & 1: + # Py_INCREF(self) + self._flags |= 1 + + @property + def pending(self): + return bool(self._watcher and libev.ev_is_pending(self._watcher)) + + +class io(_base.IoMixin, watcher): + + EVENT_MASK = libev.EV__IOFDSET | libev.EV_READ | libev.EV_WRITE + + def _get_fd(self): + return vfd_get(self._watcher.fd) + + @_base.not_while_active + def _set_fd(self, fd): + vfd = vfd_open(fd) + vfd_free(self._watcher.fd) + self._watcher_init(self._watcher, self._watcher_callback, vfd, self._watcher.events) + + fd = property(_get_fd, _set_fd) + + def _get_events(self): + return self._watcher.events + + @_base.not_while_active + def _set_events(self, events): + self._watcher_init(self._watcher, self._watcher_callback, self._watcher.fd, events) + + events = property(_get_events, _set_events) + + @property + def events_str(self): + return _events_to_str(self._watcher.events) + + def _format(self): + return ' fd=%s events=%s' % (self.fd, self.events_str) + + +class timer(_base.TimerMixin, watcher): + + @property + def at(self): + return self._watcher.at + + def again(self, callback, *args, **kw): + # Exactly the same as start(), just with a different initializer + # function + self._watcher_start = libev.ev_timer_again + try: + self.start(callback, *args, **kw) + finally: + del self._watcher_start + + +class signal(_base.SignalMixin, watcher): + pass + +class idle(_base.IdleMixin, watcher): + pass + +class prepare(_base.PrepareMixin, watcher): + pass + +class check(_base.CheckMixin, watcher): + pass + +class fork(_base.ForkMixin, watcher): + pass + + +class async_(_base.AsyncMixin, watcher): + + def send(self): + libev.ev_async_send(self.loop._ptr, self._watcher) + + @property + def pending(self): + return self._watcher is not None and bool(libev.ev_async_pending(self._watcher)) + +# Provide BWC for those that have async +locals()['async'] = async_ + +class _ClosedWatcher(object): + __slots__ = ('pid', 'rpid', 'rstatus') + + def __init__(self, other): + self.pid = other.pid + self.rpid = other.rpid + self.rstatus = other.rstatus + + def __bool__(self): + return False + __nonzero__ = __bool__ + +class child(_base.ChildMixin, watcher): + _watcher_type = 'child' + + def close(self): + # Capture the properties we defer to our _watcher, because + # we're about to discard it. + closed_watcher = _ClosedWatcher(self._watcher) + super(child, self).close() + self._watcher = closed_watcher + + @property + def pid(self): + return self._watcher.pid + + @property + def rpid(self): + return self._watcher.rpid + + @rpid.setter + def rpid(self, value): + self._watcher.rpid = value + + @property + def rstatus(self): + return self._watcher.rstatus + + @rstatus.setter + def rstatus(self, value): + self._watcher.rstatus = value + + +class stat(_base.StatMixin, watcher): + _watcher_type = 'stat' + + @property + def attr(self): + if not self._watcher.attr.st_nlink: + return + return self._watcher.attr + + @property + def prev(self): + if not self._watcher.prev.st_nlink: + return + return self._watcher.prev + + @property + def interval(self): + return self._watcher.interval diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..412d64cec15683ec32f540afb1827789a8837bf7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +# Nothing public here +__all__ = [] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/_corecffi_build.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/_corecffi_build.py new file mode 100644 index 0000000000000000000000000000000000000000..dba3a67b00f3abf318f443025b1fa7b1a9a08df5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/_corecffi_build.py @@ -0,0 +1,345 @@ +# pylint: disable=no-member + +# This module is only used to create and compile the gevent.libuv._corecffi module; +# nothing should be directly imported from it except `ffi`, which should only be +# used for `ffi.compile()`; programs should import gevent._corecfffi. +# However, because we are using "out-of-line" mode, it is necessary to examine +# this file to know what functions are created and available on the generated +# module. +from __future__ import absolute_import, print_function +import os +import os.path # pylint:disable=no-name-in-module +import platform +import sys + +from cffi import FFI + +sys.path.append(".") + +try: + import _setuputils +except ImportError: + print("This file must be imported with setup.py in the current working dir.") + raise + + +__all__ = [] + +WIN = sys.platform.startswith('win32') +LIBUV_EMBED = _setuputils.should_embed('libuv') +PY2 = sys.version_info[0] == 2 + + +ffi = FFI() + +thisdir = os.path.dirname(os.path.abspath(__file__)) +parentdir = os.path.abspath(os.path.join(thisdir, '..')) +setup_py_dir = os.path.abspath(os.path.join(thisdir, '..', '..', '..')) +libuv_dir = os.path.abspath(os.path.join(setup_py_dir, 'deps', 'libuv')) + +def read_source(name): + # pylint:disable=unspecified-encoding + with open(os.path.join(thisdir, name), 'r') as f: + return f.read() + +_cdef = read_source('_corecffi_cdef.c') +_source = read_source('_corecffi_source.c') + +# These defines and uses help keep the C file readable and lintable by +# C tools. +_cdef = _cdef.replace('#define GEVENT_STRUCT_DONE int', '') +_cdef = _cdef.replace("GEVENT_STRUCT_DONE _;", '...;') + +# nlink_t is not used in libuv. +_cdef = _cdef.replace('#define GEVENT_ST_NLINK_T int', + '') +_cdef = _cdef.replace('GEVENT_ST_NLINK_T', 'nlink_t') + + +_cdef = _cdef.replace('#define GEVENT_UV_OS_SOCK_T int', '') +# uv_os_sock_t is int on POSIX and SOCKET on Win32, but socket is +# just another name for handle, which is just another name for 'void*' +# which we will treat as an 'unsigned long' or 'unsigned long long' +# since it comes through 'fileno()' where it has been cast as an int. +# See class watcher.io +_void_pointer_as_integer = 'intptr_t' +_cdef = _cdef.replace("GEVENT_UV_OS_SOCK_T", 'int' if not WIN else _void_pointer_as_integer) + + + + +LIBUV_INCLUDE_DIRS = [ + os.path.join(libuv_dir, 'include'), + os.path.join(libuv_dir, 'src'), +] + +# Initially based on https://github.com/saghul/pyuv/blob/v1.x/setup_libuv.py + +def _libuv_source(rel_path): + # Certain versions of setuptools, notably on windows, are *very* + # picky about what we feed to sources= "setup() arguments must + # *always* be /-separated paths relative to the setup.py + # directory, *never* absolute paths." POSIX doesn't have that issue. + path = os.path.join('deps', 'libuv', 'src', rel_path) + return path + +LIBUV_SOURCES = [ + _libuv_source('fs-poll.c'), + _libuv_source('inet.c'), + _libuv_source('threadpool.c'), + _libuv_source('uv-common.c'), + _libuv_source('version.c'), + _libuv_source('uv-data-getter-setters.c'), + _libuv_source('timer.c'), + _libuv_source('idna.c'), + _libuv_source('strscpy.c'), + # Added between 1.42.0 and 1.44.2; only used + # on unix in that release, but generic + _libuv_source('strtok.c'), +] + +if WIN: + LIBUV_SOURCES += [ + _libuv_source('win/async.c'), + _libuv_source('win/core.c'), + _libuv_source('win/detect-wakeup.c'), + _libuv_source('win/dl.c'), + _libuv_source('win/error.c'), + _libuv_source('win/fs-event.c'), + _libuv_source('win/fs.c'), + # getaddrinfo.c refers to ConvertInterfaceIndexToLuid + # and ConvertInterfaceLuidToNameA, which are supposedly in iphlpapi.h + # and iphlpapi.lib/dll. But on Windows 10 with Python 3.5 and VC 14 (Visual Studio 2015), + # I get an undefined warning from the compiler for those functions and + # a link error from the linker, so this file can't be included. + # This is possibly because the functions are defined for Windows Vista, and + # Python 3.5 builds with at earlier SDK? + # Fortunately we don't use those functions. + #_libuv_source('win/getaddrinfo.c'), + # getnameinfo.c refers to uv__getaddrinfo_translate_error from + # getaddrinfo.c, which we don't have. + #_libuv_source('win/getnameinfo.c'), + _libuv_source('win/handle.c'), + _libuv_source('win/loop-watcher.c'), + _libuv_source('win/pipe.c'), + _libuv_source('win/poll.c'), + _libuv_source('win/process-stdio.c'), + _libuv_source('win/process.c'), + _libuv_source('win/signal.c'), + _libuv_source('win/snprintf.c'), + _libuv_source('win/stream.c'), + _libuv_source('win/tcp.c'), + _libuv_source('win/thread.c'), + _libuv_source('win/tty.c'), + _libuv_source('win/udp.c'), + _libuv_source('win/util.c'), + _libuv_source('win/winapi.c'), + _libuv_source('win/winsock.c'), + ] +else: + LIBUV_SOURCES += [ + _libuv_source('unix/async.c'), + _libuv_source('unix/core.c'), + _libuv_source('unix/dl.c'), + _libuv_source('unix/fs.c'), + _libuv_source('unix/getaddrinfo.c'), + _libuv_source('unix/getnameinfo.c'), + _libuv_source('unix/loop-watcher.c'), + _libuv_source('unix/loop.c'), + _libuv_source('unix/pipe.c'), + _libuv_source('unix/poll.c'), + _libuv_source('unix/process.c'), + _libuv_source('unix/signal.c'), + _libuv_source('unix/stream.c'), + _libuv_source('unix/tcp.c'), + _libuv_source('unix/thread.c'), + _libuv_source('unix/tty.c'), + _libuv_source('unix/udp.c'), + ] + + +if sys.platform.startswith('linux'): + LIBUV_SOURCES += [ + _libuv_source('unix/linux-core.c'), + _libuv_source('unix/linux-inotify.c'), + _libuv_source('unix/linux-syscalls.c'), + _libuv_source('unix/procfs-exepath.c'), + _libuv_source('unix/proctitle.c'), + _libuv_source('unix/random-sysctl-linux.c'), + _libuv_source('unix/epoll.c'), + ] +elif sys.platform == 'darwin': + LIBUV_SOURCES += [ + _libuv_source('unix/bsd-ifaddrs.c'), + _libuv_source('unix/darwin.c'), + _libuv_source('unix/darwin-proctitle.c'), + _libuv_source('unix/fsevents.c'), + _libuv_source('unix/kqueue.c'), + _libuv_source('unix/proctitle.c'), + ] +elif sys.platform.startswith(('freebsd', 'dragonfly')): # pragma: no cover + # Not tested + LIBUV_SOURCES += [ + _libuv_source('unix/bsd-ifaddrs.c'), + _libuv_source('unix/freebsd.c'), + _libuv_source('unix/kqueue.c'), + _libuv_source('unix/posix-hrtime.c'), + _libuv_source('unix/bsd-proctitle.c'), + ] +elif sys.platform.startswith('openbsd'): # pragma: no cover + # Not tested + LIBUV_SOURCES += [ + _libuv_source('unix/bsd-ifaddrs.c'), + _libuv_source('unix/kqueue.c'), + _libuv_source('unix/openbsd.c'), + _libuv_source('unix/posix-hrtime.c'), + _libuv_source('unix/bsd-proctitle.c'), + ] +elif sys.platform.startswith('netbsd'): # pragma: no cover + # Not tested + LIBUV_SOURCES += [ + _libuv_source('unix/bsd-ifaddrs.c'), + _libuv_source('unix/kqueue.c'), + _libuv_source('unix/netbsd.c'), + _libuv_source('unix/posix-hrtime.c'), + _libuv_source('unix/bsd-proctitle.c'), + ] +elif sys.platform.startswith('sunos'): # pragma: no cover + # Not tested. + LIBUV_SOURCES += [ + _libuv_source('unix/no-proctitle.c'), + _libuv_source('unix/sunos.c'), + ] +elif sys.platform.startswith('aix'): # pragma: no cover + # Not tested. + LIBUV_SOURCES += [ + _libuv_source('unix/aix.c'), + _libuv_source('unix/aix-common.c'), + ] +elif sys.platform.startswith('haiku'): # pragma: no cover + # Not tested + LIBUV_SOURCES += [ + _libuv_source('unix/haiku.c') + ] +elif sys.platform.startswith('cygwin'): # pragma: no cover + # Not tested. + + # Based on Cygwin package sources /usr/src/libuv-1.32.0-1.src/libuv-1.32.0/Makefile.am + # Apparently the same upstream at https://github.com/libuv/libuv/blob/v1.x/Makefile.am + LIBUV_SOURCES += [ + _libuv_source('unix/cygwin.c'), + _libuv_source('unix/bsd-ifaddrs.c'), + _libuv_source('unix/no-fsevents.c'), + _libuv_source('unix/no-proctitle.c'), + _libuv_source('unix/posix-hrtime.c'), + _libuv_source('unix/posix-poll.c'), + _libuv_source('unix/procfs-exepath.c'), + _libuv_source('unix/sysinfo-loadavg.c'), + _libuv_source('unix/sysinfo-memory.c'), + ] + + +LIBUV_MACROS = [ + ('LIBUV_EMBED', int(LIBUV_EMBED)), +] + +def _define_macro(name, value): + LIBUV_MACROS.append((name, value)) + +LIBUV_LIBRARIES = [] + +def _add_library(name): + LIBUV_LIBRARIES.append(name) + +if sys.platform != 'win32': + _define_macro('_LARGEFILE_SOURCE', 1) + _define_macro('_FILE_OFFSET_BITS', 64) + +if sys.platform.startswith('linux'): + _add_library('dl') + _add_library('rt') + _define_macro('_GNU_SOURCE', 1) + _define_macro('_POSIX_C_SOURCE', '200112') +elif sys.platform == 'darwin': + _define_macro('_DARWIN_USE_64_BIT_INODE', 1) + _define_macro('_DARWIN_UNLIMITED_SELECT', 1) +elif sys.platform.startswith('netbsd'): # pragma: no cover + _add_library('kvm') +elif sys.platform.startswith('sunos'): # pragma: no cover + _define_macro('__EXTENSIONS__', 1) + _define_macro('_XOPEN_SOURCE', 500) + _define_macro('_REENTRANT', 1) + _add_library('kstat') + _add_library('nsl') + _add_library('sendfile') + _add_library('socket') + if platform.release() == '5.10': + # https://github.com/libuv/libuv/issues/1458 + # https://github.com/giampaolo/psutil/blob/4d6a086411c77b7909cce8f4f141bbdecfc0d354/setup.py#L298-L300 + _define_macro('SUNOS_NO_IFADDRS', '') +elif sys.platform.startswith('aix'): # pragma: no cover + _define_macro('_LINUX_SOURCE_COMPAT', 1) + if os.uname().sysname != 'OS400': + _add_library('perfstat') +elif WIN: + # All other gevent .pyd files link to the specific minor-version Python + # DLL, so we should do the same here. In virtual environments that don't + # contain the major-version python?.dll stub, _corecffi.pyd would otherwise + # cause the Windows DLL loader to search the entire PATH for a DLL with + # that name. This might end up bringing a second, ABI-incompatible Python + # version into the process, which can easily lead to crashes. + # See https://github.com/gevent/gevent/pull/1814/files + _define_macro('_CFFI_NO_LIMITED_API', 1) + + _define_macro('_GNU_SOURCE', 1) + _define_macro('WIN32', 1) + _define_macro('_CRT_SECURE_NO_DEPRECATE', 1) + _define_macro('_CRT_NONSTDC_NO_DEPRECATE', 1) + _define_macro('_CRT_SECURE_NO_WARNINGS', 1) + _define_macro('_WIN32_WINNT', '0x0602') + _define_macro('WIN32_LEAN_AND_MEAN', 1) + # This value isn't available on the platform that we build and + # test Python 2.7 on. It's used for getting power management + # suspend/resume notifications, maybe for keeping timers accurate? + # + # TODO: This should be a more targeted check based on the platform + # version, but that's complicated because it depends on having a + # particular patch installed to the OS, and I don't know how to + # check for that...but we're dropping Python 2 support soon, so + # I suspect it really doesn't matter. + if PY2: + _define_macro('LOAD_LIBRARY_SEARCH_SYSTEM32', 0) + _add_library('advapi32') + _add_library('iphlpapi') + _add_library('psapi') + _add_library('shell32') + _add_library('user32') + _add_library('userenv') + _add_library('ws2_32') + +if not LIBUV_EMBED: + del LIBUV_SOURCES[:] + del LIBUV_INCLUDE_DIRS[:] + _add_library('uv') + +LIBUV_INCLUDE_DIRS.append(parentdir) + +ffi.cdef(_cdef) +ffi.set_source( + 'gevent.libuv._corecffi', + _source, + sources=LIBUV_SOURCES, + depends=LIBUV_SOURCES, + include_dirs=LIBUV_INCLUDE_DIRS, + libraries=list(LIBUV_LIBRARIES), + define_macros=list(LIBUV_MACROS), + extra_compile_args=list(_setuputils.IGNORE_THIRD_PARTY_WARNINGS), +) + +if __name__ == '__main__': + # See notes in libev/_corecffi_build.py for how to test this. + # + # Other than the obvious directory changes, the changes are: + # + # CPPFLAGS=-Ideps/libuv/include/ -Isrc/gevent/ + ffi.compile(verbose=True) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/loop.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/loop.py new file mode 100644 index 0000000000000000000000000000000000000000..8b717b7cb88006f8444d4000903f389e1852df74 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/loop.py @@ -0,0 +1,690 @@ +""" +libuv loop implementation +""" +# pylint: disable=no-member +from __future__ import absolute_import, print_function + +import os +from collections import defaultdict +from collections import namedtuple +from operator import delitem +import signal + +from zope.interface import implementer + +from gevent import getcurrent +from gevent.exceptions import LoopExit + +from gevent._ffi import _dbg # pylint: disable=unused-import +from gevent._ffi.loop import AbstractLoop +from gevent._ffi.loop import assign_standard_callbacks +from gevent._ffi.loop import AbstractCallbacks +from gevent._interfaces import ILoop +from gevent.libuv import _corecffi # pylint:disable=no-name-in-module,import-error + +ffi = _corecffi.ffi +libuv = _corecffi.lib + +__all__ = [ +] + + +class _Callbacks(AbstractCallbacks): + + def _find_loop_from_c_watcher(self, watcher_ptr): + loop_handle = ffi.cast('uv_handle_t*', watcher_ptr).data + return self.from_handle(loop_handle) if loop_handle else None + + def python_sigchld_callback(self, watcher_ptr, _signum): + self.from_handle(ffi.cast('uv_handle_t*', watcher_ptr).data)._sigchld_callback() + + def python_timer0_callback(self, watcher_ptr): + return self.python_prepare_callback(watcher_ptr) + + def python_queue_callback(self, watcher_ptr, revents): + watcher_handle = watcher_ptr.data + the_watcher = self.from_handle(watcher_handle) + + the_watcher.loop._queue_callback(watcher_ptr, revents) + + +_callbacks = assign_standard_callbacks( + ffi, libuv, _Callbacks, + [ + 'python_sigchld_callback', + 'python_timer0_callback', + 'python_queue_callback', + ] +) + +from gevent._ffi.loop import EVENTS +GEVENT_CORE_EVENTS = EVENTS # export + +from gevent.libuv import watcher as _watchers # pylint:disable=no-name-in-module + +_events_to_str = _watchers._events_to_str # export + +READ = libuv.UV_READABLE +WRITE = libuv.UV_WRITABLE + +def get_version(): + uv_bytes = ffi.string(libuv.uv_version_string()) + if not isinstance(uv_bytes, str): + # Py3 + uv_str = uv_bytes.decode("ascii") + else: + uv_str = uv_bytes + + return 'libuv-' + uv_str + +def get_header_version(): + return 'libuv-%d.%d.%d' % (libuv.UV_VERSION_MAJOR, libuv.UV_VERSION_MINOR, libuv.UV_VERSION_PATCH) + +def supported_backends(): + return ['default'] + +libuv.gevent_set_uv_alloc() + +@implementer(ILoop) +class loop(AbstractLoop): + + # libuv parameters simply won't accept anything lower than 1ms. In + # practice, looping on gevent.sleep(0.001) takes about 0.00138 s + # (+- 0.000036s) + approx_timer_resolution = 0.001 # 1ms + + # It's relatively more expensive to break from the callback loop + # because we don't do it "inline" from C, we're looping in Python + CALLBACK_CHECK_COUNT = max(AbstractLoop.CALLBACK_CHECK_COUNT, 100) + + # Defines the maximum amount of time the loop will sleep waiting for IO, + # which is also the interval at which signals are checked and handled. + SIGNAL_CHECK_INTERVAL_MS = 300 + + error_handler = None + + _CHECK_POINTER = 'uv_check_t *' + + _PREPARE_POINTER = 'uv_prepare_t *' + _PREPARE_CALLBACK_SIG = "void(*)(void*)" + + _TIMER_POINTER = _CHECK_POINTER # This is poorly named. It's for the callback "timer" + + def __init__(self, flags=None, default=None): + AbstractLoop.__init__(self, ffi, libuv, _watchers, flags, default) + self._child_watchers = defaultdict(list) + self._io_watchers = {} + self._fork_watchers = set() + self._pid = os.getpid() + # pylint:disable-next=superfluous-parens + self._default = (self._ptr == libuv.uv_default_loop()) + self._queued_callbacks = [] + + def _queue_callback(self, watcher_ptr, revents): + self._queued_callbacks.append((watcher_ptr, revents)) + + def _init_loop(self, flags, default): + if default is None: + default = True + # Unlike libev, libuv creates a new default + # loop automatically if the old default loop was + # closed. + + if default: + # XXX: If the default loop had been destroyed, this + # will create a new one, but we won't destroy it + ptr = libuv.uv_default_loop() + else: + ptr = libuv.uv_loop_new() + + + if not ptr: + raise SystemError("Failed to get loop") + + # Track whether or not any object has destroyed + # this loop. See _can_destroy_default_loop + ptr.data = self._handle_to_self + return ptr + + _signal_idle = None + + @property + def ptr(self): + if not self._ptr: + return None + if self._ptr and not self._ptr.data: + # Another instance of the Python loop destroyed + # the C loop. It was probably the default. + self._ptr = None + return self._ptr + + def _init_and_start_check(self): + libuv.uv_check_init(self.ptr, self._check) + libuv.uv_check_start(self._check, libuv.python_check_callback) + libuv.uv_unref(self._check) + + # We also have to have an idle watcher to be able to handle + # signals in a timely manner. Without them, libuv won't loop again + # and call into its check and prepare handlers. + # Note that this basically forces us into a busy-loop + # XXX: As predicted, using an idle watcher causes our process + # to eat 100% CPU time. We instead use a timer with a max of a .3 second + # delay to notice signals. Note that this timeout also implements fork + # watchers, effectively. + + # XXX: Perhaps we could optimize this to notice when there are other + # timers in the loop and start/stop it then. When we have a callback + # scheduled, this should also be the same and unnecessary? + # libev does takes this basic approach on Windows. + self._signal_idle = ffi.new("uv_timer_t*") + libuv.uv_timer_init(self.ptr, self._signal_idle) + self._signal_idle.data = self._handle_to_self + sig_cb = ffi.cast('void(*)(uv_timer_t*)', libuv.python_check_callback) + libuv.uv_timer_start(self._signal_idle, + sig_cb, + self.SIGNAL_CHECK_INTERVAL_MS, + self.SIGNAL_CHECK_INTERVAL_MS) + libuv.uv_unref(self._signal_idle) + + def __check_and_die(self): + if not self.ptr: + # We've been destroyed during the middle of self.run(). + # This method is being called into from C, and it's not + # safe to go back to C (Windows in particular can abort + # the process with "GetQueuedCompletionStatusEx: (6) The + # handle is invalid.") So switch to the parent greenlet. + getcurrent().parent.throw(LoopExit('Destroyed during run')) + + def _run_callbacks(self): + self.__check_and_die() + # Manually handle fork watchers. + curpid = os.getpid() + if curpid != self._pid: + self._pid = curpid + for watcher in self._fork_watchers: + watcher._on_fork() + + + # The contents of queued_callbacks at this point should be timers + # that expired when the loop began along with any idle watchers. + # We need to run them so that any manual callbacks they want to schedule + # get added to the list and ran next before we go on to poll for IO. + # This is critical for libuv on linux: closing a socket schedules some manual + # callbacks to actually stop the watcher; if those don't run before + # we poll for IO, then libuv can abort the process for the closed file descriptor. + + # XXX: There's still a race condition here because we may not run *all* the manual + # callbacks. We need a way to prioritize those. + + # Running these before the manual callbacks lead to some + # random test failures. In test__event.TestEvent_SetThenClear + # we would get a LoopExit sometimes. The problem occurred when + # a timer expired on entering the first loop; we would process + # it there, and then process the callback that it created + # below, leaving nothing for the loop to do. Having the + # self.run() manually process manual callbacks before + # continuing solves the problem. (But we must still run callbacks + # here again.) + self._prepare_ran_callbacks = self.__run_queued_callbacks() + + super(loop, self)._run_callbacks() + + def _init_and_start_prepare(self): + libuv.uv_prepare_init(self.ptr, self._prepare) + libuv.uv_prepare_start(self._prepare, libuv.python_prepare_callback) + libuv.uv_unref(self._prepare) + + def _init_callback_timer(self): + libuv.uv_check_init(self.ptr, self._timer0) + + def _stop_callback_timer(self): + libuv.uv_check_stop(self._timer0) + + def _start_callback_timer(self): + # The purpose of the callback timer is to ensure that we run + # callbacks as soon as possible on the next iteration of the event loop. + + # In libev, we set a 0 duration timer with a no-op callback. + # This executes immediately *after* the IO poll is done (it + # actually determines the time that the IO poll will block + # for), so having the timer present simply spins the loop, and + # our normal prepare watcher kicks in to run the callbacks. + + # In libuv, however, timers are run *first*, before prepare + # callbacks and before polling for IO. So a no-op 0 duration + # timer actually does *nothing*. (Also note that libev queues all + # watchers found during IO poll to run at the end (I think), while libuv + # runs them in uv__io_poll itself.) + + # From the loop inside uv_run: + # while True: + # uv__update_time(loop); + # uv__run_timers(loop); + # # we don't use pending watchers. They are how libuv + # # implements the pipe/udp/tcp streams. + # ran_pending = uv__run_pending(loop); + # uv__run_idle(loop); + # uv__run_prepare(loop); + # ... + # uv__io_poll(loop, timeout); # <--- IO watchers run here! + # uv__run_check(loop); + + # libev looks something like this (pseudo code because the real code is + # hard to read): + # + # do { + # run_fork_callbacks(); + # run_prepare_callbacks(); + # timeout = min(time of all timers or normal block time) + # io_poll() # <--- Only queues IO callbacks + # update_now(); calculate_expired_timers(); + # run callbacks in this order: (although specificying priorities changes it) + # check + # stat + # child + # signal + # timer + # io + # } + + # So instead of running a no-op and letting the side-effect of spinning + # the loop run the callbacks, we must explicitly run them here. + + # If we don't, test__systemerror:TestCallback will be flaky, failing + # one time out of ~20, depending on timing. + + # To get them to run immediately after this current loop, + # we use a check watcher, instead of a 0 duration timer entirely. + # If we use a 0 duration timer, we can get stuck in a timer loop. + # Python 3.6 fails in test_ftplib.py + + # As a final note, if we have not yet entered the loop *at + # all*, and a timer was created with a duration shorter than + # the amount of time it took for us to enter the loop in the + # first place, it may expire and get called before our callback + # does. This could also lead to test__systemerror:TestCallback + # appearing to be flaky. + + # As yet another final note, if we are currently running a + # timer callback, meaning we're inside uv__run_timers() in C, + # and the Python starts a new timer, if the Python code then + # update's the loop's time, it's possible that timer will + # expire *and be run in the same iteration of the loop*. This + # is trivial to do: In sequential code, anything after + # `gevent.sleep(0.1)` is running in a timer callback. Starting + # a new timer---e.g., another gevent.sleep() call---will + # update the time, *before* uv__run_timers exits, meaning + # other timers get a chance to run before our check or prepare + # watcher callbacks do. Therefore, we do indeed have to have a 0 + # timer to run callbacks---it gets inserted before any other user + # timers---ideally, this should be especially careful about how much time + # it runs for. + + # AND YET: We can't actually do that. We get timeouts that I haven't fully + # investigated if we do. Probably stuck in a timer loop. + + # As a partial remedy to this, unlike libev, our timer watcher + # class doesn't update the loop time by default. + + libuv.uv_check_start(self._timer0, libuv.python_timer0_callback) + + + def _stop_aux_watchers(self): + super(loop, self)._stop_aux_watchers() + assert self._prepare + assert self._check + assert self._signal_idle + libuv.uv_prepare_stop(self._prepare) + libuv.uv_ref(self._prepare) # Why are we doing this? + + libuv.uv_check_stop(self._check) + libuv.uv_ref(self._check) + + libuv.uv_timer_stop(self._signal_idle) + libuv.uv_ref(self._signal_idle) + + libuv.uv_check_stop(self._timer0) + + def _setup_for_run_callback(self): + self._start_callback_timer() + libuv.uv_ref(self._timer0) + + def _can_destroy_loop(self, ptr): + return ptr + + def __close_loop(self, ptr): + closed_failed = 1 + + while closed_failed: + closed_failed = libuv.uv_loop_close(ptr) + if not closed_failed: + break + + if closed_failed != libuv.UV_EBUSY: + raise SystemError("Unknown close failure reason", closed_failed) + # We already closed all the handles. Run the loop + # once to let them be cut off from the loop. + ran_has_more_callbacks = libuv.uv_run(ptr, libuv.UV_RUN_ONCE) + if ran_has_more_callbacks: + libuv.uv_run(ptr, libuv.UV_RUN_NOWAIT) + + + def _destroy_loop(self, ptr): + # We're being asked to destroy a loop that's, potentially, at + # the time it was constructed, was the default loop. If loop + # objects were constructed more than once, it may have already + # been destroyed, though. We track this in the data member. + data = ptr.data + ptr.data = ffi.NULL + try: + if data: + libuv.uv_stop(ptr) + libuv.gevent_close_all_handles(ptr) + finally: + ptr.data = ffi.NULL + + try: + if data: + self.__close_loop(ptr) + finally: + # Destroy the native resources *after* we have closed + # the loop. If we do it before, walking the handles + # attached to the loop is likely to segfault. + # Note that these may have been closed already if the default loop was shared. + if data: + libuv.gevent_zero_check(self._check) + libuv.gevent_zero_check(self._timer0) + libuv.gevent_zero_prepare(self._prepare) + libuv.gevent_zero_timer(self._signal_idle) + libuv.gevent_zero_loop(ptr) + + del self._check + del self._prepare + del self._signal_idle + del self._timer0 + + # Destroy any watchers we're still holding on to. + del self._io_watchers + del self._fork_watchers + del self._child_watchers + + _HandleState = namedtuple("HandleState", + ['handle', + 'type', + 'watcher', + 'ref', + 'active', + 'closing']) + def debug(self): + """ + Return all the handles that are open and their ref status. + """ + if not self.ptr: + return ["Loop has been destroyed"] + + handle_state = self._HandleState + handles = [] + + # XXX: Convert this to a modern callback. + def walk(handle, _arg): + data = handle.data + if data: + watcher = ffi.from_handle(data) + else: + watcher = None + handles.append(handle_state(handle, + ffi.string(libuv.uv_handle_type_name(handle.type)), + watcher, + libuv.uv_has_ref(handle), + libuv.uv_is_active(handle), + libuv.uv_is_closing(handle))) + + libuv.uv_walk(self.ptr, + ffi.callback("void(*)(uv_handle_t*,void*)", + walk), + ffi.NULL) + return handles + + def ref(self): + pass + + def unref(self): + # XXX: Called by _run_callbacks. + pass + + def break_(self, how=None): + if self.ptr: + libuv.uv_stop(self.ptr) + + def reinit(self): + # TODO: How to implement? We probably have to simply + # re-__init__ this whole class? Does it matter? + # OR maybe we need to uv_walk() and close all the handles? + + # XXX: libuv < 1.12 simply CANNOT handle a fork unless you immediately + # exec() in the child. There are multiple calls to abort() that + # will kill the child process: + # - The OS X poll implementation (kqueue) aborts on an error return + # value; since kqueue FDs can't be inherited, then the next call + # to kqueue in the child will fail and get aborted; fork() is likely + # to be called during the gevent loop, meaning we're deep inside the + # runloop already, so we can't even close the loop that we're in: + # it's too late, the next call to kqueue is already scheduled. + # - The threadpool, should it be in use, also aborts + # (https://github.com/joyent/libuv/pull/1136) + # - There global shared state that breaks signal handling + # and leads to an abort() in the child, EVEN IF the loop in the parent + # had already been closed + # (https://github.com/joyent/libuv/issues/1405) + + # In 1.12, the uv_loop_fork function was added (by gevent!) + libuv.uv_loop_fork(self.ptr) + + _prepare_ran_callbacks = False + + def __run_queued_callbacks(self): + if not self._queued_callbacks: + return False + + cbs = self._queued_callbacks[:] + del self._queued_callbacks[:] + + for watcher_ptr, arg in cbs: + handle = watcher_ptr.data + if not handle: + # It's been stopped and possibly closed + assert not libuv.uv_is_active(watcher_ptr) + continue + val = _callbacks.python_callback(handle, arg) + if val == -1: # Failure. + _callbacks.python_handle_error(handle, arg) + elif val == 1: # Success, and we may need to close the Python watcher. + if not libuv.uv_is_active(watcher_ptr): + # The callback closed the native watcher resources. Good. + # It's *supposed* to also reset the .data handle to NULL at + # that same time. If it resets it to something else, we're + # re-using the same watcher object, and that's not correct either. + # On Windows in particular, if the .data handle is changed because + # the IO multiplexer is being restarted, trying to dereference the + # *old* handle can crash with an FFI error. + handle_after_callback = watcher_ptr.data + try: + if handle_after_callback and handle_after_callback == handle: + _callbacks.python_stop(handle_after_callback) + finally: + watcher_ptr.data = ffi.NULL + return True + + + def run(self, nowait=False, once=False): + # we can only respect one flag or the other. + # nowait takes precedence because it can't block + mode = libuv.UV_RUN_DEFAULT + if once: + mode = libuv.UV_RUN_ONCE + if nowait: + mode = libuv.UV_RUN_NOWAIT + + if mode == libuv.UV_RUN_DEFAULT: + while self._ptr and self._ptr.data: + # This is here to better preserve order guarantees. + # See _run_callbacks for details. + + # It may get run again from the prepare watcher, so + # potentially we could take twice as long as the + # switch interval. + # If we have *lots* of callbacks to run, we may not actually + # get through them all before we're requested to poll for IO; + # so in that case, just spin the loop once (UV_RUN_NOWAIT) and + # go again. + self._run_callbacks() + self._prepare_ran_callbacks = False + + # UV_RUN_ONCE will poll for IO, blocking for up to the time needed + # for the next timer to expire. Worst case, that's our _signal_idle + # timer, about 1/3 second. UV_RUN_ONCE guarantees that some forward progress + # is made, either by an IO watcher or a timer. + # + # In contrast, UV_RUN_NOWAIT makes no such guarantee, it only polls for IO once and + # immediately returns; it does not update the loop time or timers after + # polling for IO. + run_mode = ( + libuv.UV_RUN_ONCE + if not self._callbacks and not self._queued_callbacks + else libuv.UV_RUN_NOWAIT + ) + + ran_status = libuv.uv_run(self._ptr, run_mode) + # Note that we run queued callbacks when the prepare watcher runs, + # thus accounting for timers that expired before polling for IO, + # and idle watchers. This next call should get IO callbacks and + # callbacks from timers that expired *after* polling for IO. + ran_callbacks = self.__run_queued_callbacks() + + if not ran_status and not ran_callbacks and not self._prepare_ran_callbacks: + # A return of 0 means there are no referenced and + # active handles. The loop is over. + # If we didn't run any callbacks, then we couldn't schedule + # anything to switch in the future, so there's no point + # running again. + return ran_status + return 0 # Somebody closed the loop + + result = libuv.uv_run(self._ptr, mode) + self.__run_queued_callbacks() + return result + + def now(self): + self.__check_and_die() + # libuv's now is expressed as an integer number of + # milliseconds, so to get it compatible with time.time units + # that this method is supposed to return, we have to divide by 1000.0 + now = libuv.uv_now(self.ptr) + return now / 1000.0 + + def update_now(self): + self.__check_and_die() + libuv.uv_update_time(self.ptr) + + def fileno(self): + if self.ptr: + fd = libuv.uv_backend_fd(self._ptr) + if fd >= 0: + return fd + + _sigchld_watcher = None + _sigchld_callback_ffi = None + + def install_sigchld(self): + if not self.default: + return + + if self._sigchld_watcher: + return + + self._sigchld_watcher = ffi.new('uv_signal_t*') + libuv.uv_signal_init(self.ptr, self._sigchld_watcher) + self._sigchld_watcher.data = self._handle_to_self + # Don't let this keep the loop alive + libuv.uv_unref(self._sigchld_watcher) + + libuv.uv_signal_start(self._sigchld_watcher, + libuv.python_sigchld_callback, + signal.SIGCHLD) + + def reset_sigchld(self): + if not self.default or not self._sigchld_watcher: + return + + libuv.uv_signal_stop(self._sigchld_watcher) + # Must go through this to manage the memory lifetime + # correctly. Alternately, we could just stop it and restart + # it in install_sigchld? + _watchers.watcher._watcher_ffi_close(self._sigchld_watcher) + del self._sigchld_watcher + + + def _sigchld_callback(self): + # Signals can arrive at (relatively) any time. To eliminate + # race conditions, and behave more like libev, we "queue" + # sigchld to run when we run callbacks. + while True: + try: + pid, status, _usage = os.wait3(os.WNOHANG) + except OSError: + # Python 3 raises ChildProcessError + break + + if pid == 0: + break + children_watchers = self._child_watchers.get(pid, []) + self._child_watchers.get(0, []) + for watcher in children_watchers: + self.run_callback(watcher._set_waitpid_status, pid, status) + + # Don't invoke child watchers for 0 more than once + self._child_watchers[0] = [] + + def _register_child_watcher(self, watcher): + self._child_watchers[watcher._pid].append(watcher) + + def _unregister_child_watcher(self, watcher): + try: + # stop() should be idempotent + self._child_watchers[watcher._pid].remove(watcher) + except ValueError: + pass + + # Now's a good time to clean up any dead watchers we don't need + # anymore + for pid in list(self._child_watchers): + if not self._child_watchers[pid]: + del self._child_watchers[pid] + + def io(self, fd, events, ref=True, priority=None): + # We rely on hard references here and explicit calls to + # close() on the returned object to correctly manage + # the watcher lifetimes. + + io_watchers = self._io_watchers + try: + io_watcher = io_watchers[fd] + assert io_watcher._multiplex_watchers, ("IO Watcher %s unclosed but should be dead" % io_watcher) + except KeyError: + # Start the watcher with just the events that we're interested in. + # as multiplexers are added, the real event mask will be updated to keep in sync. + # If we watch for too much, we get spurious wakeups and busy loops. + io_watcher = self._watchers.io(self, fd, 0) + io_watchers[fd] = io_watcher + io_watcher._no_more_watchers = lambda: delitem(io_watchers, fd) + + return io_watcher.multiplex(events) + + def prepare(self, ref=True, priority=None): + # We run arbitrary code in python_prepare_callback. That could switch + # greenlets. If it does that while also manipulating the active prepare + # watchers, we could corrupt the process state, since the prepare watcher + # queue is iterated on the stack (on unix). We could workaround this by implementing + # prepare watchers in pure Python. + # See https://github.com/gevent/gevent/issues/1126 + raise TypeError("prepare watchers are not currently supported in libuv. " + "If you need them, please contact the maintainers.") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/watcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..c0191a641465f439792641e66ac9fc161c49ddb6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/watcher.py @@ -0,0 +1,762 @@ +# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable +# pylint: disable=no-member +from __future__ import absolute_import, print_function + +import functools +import sys + +from gevent.libuv import _corecffi # pylint:disable=no-name-in-module,import-error + +# Nothing public here +__all__ = [] + +ffi = _corecffi.ffi +libuv = _corecffi.lib + +from gevent._ffi import watcher as _base +from gevent._ffi import _dbg + +# A set of uv_handle_t* CFFI objects. Kept around +# to keep the memory alive until libuv is done with them. +class _ClosingWatchers(dict): + __slots__ = () + + def remove(self, obj): + try: + del self[obj] + except KeyError: # pragma: no cover + # This has been seen to happen if the module is executed twice + # and so the callback doesn't match the storage seen by watcher objects. + print( + 'gevent error: Unable to remove closing watcher from keepaliveset. ' + 'Has the module state been corrupted or executed more than once?', + file=sys.stderr + ) + +_closing_watchers = _ClosingWatchers() + + +# In debug mode, it would be nice to be able to clear the memory of +# the watcher (its size determined by +# libuv.uv_handle_size(ffi_watcher.type)) using memset so that if we +# are using it after it's supposedly been closed and deleted, we'd +# catch it sooner. BUT doing so breaks test__threadpool. We get errors +# about `pthread_mutex_lock[3]: Invalid argument` (and sometimes we +# crash) suggesting either that we're writing on memory that doesn't +# belong to us, somehow, or that we haven't actually lost all +# references... +_uv_close_callback = ffi.def_extern(name='_uv_close_callback')( + _closing_watchers.remove +) + + +_events = [(libuv.UV_READABLE, "READ"), + (libuv.UV_WRITABLE, "WRITE")] + +def _events_to_str(events): # export + return _base.events_to_str(events, _events) + +class UVFuncallError(ValueError): + pass + +class libuv_error_wrapper(object): + # Makes sure that everything stored as a function + # on the wrapper instances (classes, actually, + # because this is used by the metaclass) + # checks its return value and raises an error. + # This expects that everything we call has an int + # or void return value and follows the conventions + # of error handling (that negative values are errors) + def __init__(self, uv): + self._libuv = uv + + def __getattr__(self, name): + libuv_func = getattr(self._libuv, name) + + @functools.wraps(libuv_func) + def wrap(*args, **kwargs): + if args and isinstance(args[0], watcher): + args = args[1:] + res = libuv_func(*args, **kwargs) + if res is not None and res < 0: + raise UVFuncallError( + str(ffi.string(libuv.uv_err_name(res)).decode('ascii') + + ' ' + + ffi.string(libuv.uv_strerror(res)).decode('ascii')) + + " Args: " + repr(args) + " KWARGS: " + repr(kwargs) + ) + return res + + setattr(self, name, wrap) + + return wrap + + +class ffi_unwrapper(object): + # undoes the wrapping of libuv_error_wrapper for + # the methods used by the metaclass that care + + def __init__(self, ff): + self._ffi = ff + + def __getattr__(self, name): + return getattr(self._ffi, name) + + def addressof(self, lib, name): + assert isinstance(lib, libuv_error_wrapper) + return self._ffi.addressof(libuv, name) + + +class watcher(_base.watcher): + _FFI = ffi_unwrapper(ffi) + _LIB = libuv_error_wrapper(libuv) + + _watcher_prefix = 'uv' + _watcher_struct_pattern = '%s_t' + + @classmethod + def _watcher_ffi_close(cls, ffi_watcher): + # Managing the lifetime of _watcher is tricky. + # They have to be uv_close()'d, but that only + # queues them to be closed in the *next* loop iteration. + # The memory must stay valid for at least that long, + # or assert errors are triggered. We can't use a ffi.gc() + # pointer to queue the uv_close, because by the time the + # destructor is called, there's no way to keep the memory alive + # and it could be re-used. + # So here we resort to resurrecting the pointer object out + # of our scope, keeping it alive past this object's lifetime. + # We then use the uv_close callback to handle removing that + # reference. There's no context passed to the close callback, + # so we have to do this globally. + + # Sadly, doing this causes crashes if there were multiple + # watchers for a given FD, so we have to take special care + # about that. See https://github.com/gevent/gevent/issues/790#issuecomment-208076604 + + # Note that this cannot be a __del__ method, because we store + # the CFFI handle to self on self, which is a cycle, and + # objects with a __del__ method cannot be collected on CPython < 3.4 + + # Instead, this is arranged as a callback to GC when the + # watcher class dies. Obviously it's important to keep the ffi + # watcher alive. + # We can pass in "subclasses" of uv_handle_t that line up at the C level, + # but that don't in CFFI without a cast. But be careful what we use the cast + # for, don't pass it back to C. + ffi_handle_watcher = cls._FFI.cast('uv_handle_t*', ffi_watcher) + ffi_handle_watcher.data = ffi.NULL + + if ffi_handle_watcher.type and not libuv.uv_is_closing(ffi_watcher): + # If the type isn't set, we were never properly initialized, + # and trying to close it results in libuv terminating the process. + # Sigh. Same thing if it's already in the process of being + # closed. + _closing_watchers[ffi_handle_watcher] = ffi_watcher + libuv.uv_close(ffi_watcher, libuv._uv_close_callback) + + def _watcher_ffi_set_init_ref(self, ref): + self.ref = ref + + def _watcher_ffi_init(self, args): + # TODO: we could do a better job chokepointing this + return self._watcher_init(self.loop.ptr, + self._watcher, + *args) + + def _watcher_ffi_start(self): + self._watcher_start(self._watcher, self._watcher_callback) + + def _watcher_ffi_stop(self): + if self._watcher: + # The multiplexed io watcher deletes self._watcher + # when it closes down. If that's in the process of + # an error handler, AbstractCallbacks.unhandled_onerror + # will try to close us again. + self._watcher_stop(self._watcher) + + @_base.only_if_watcher + def _watcher_ffi_ref(self): + libuv.uv_ref(self._watcher) + + @_base.only_if_watcher + def _watcher_ffi_unref(self): + libuv.uv_unref(self._watcher) + + def _watcher_ffi_start_unref(self): + pass + + def _watcher_ffi_stop_ref(self): + pass + + def _get_ref(self): + # Convert 1/0 to True/False + if self._watcher is None: + return None + return bool(libuv.uv_has_ref(self._watcher)) + + def _set_ref(self, value): + if value: + self._watcher_ffi_ref() + else: + self._watcher_ffi_unref() + + ref = property(_get_ref, _set_ref) + + def feed(self, _revents, _callback, *_args): + # pylint:disable-next=broad-exception-raised + raise Exception("Not implemented") + +class io(_base.IoMixin, watcher): + _watcher_type = 'poll' + _watcher_callback_name = '_gevent_poll_callback2' + + # On Windows is critical to be able to garbage collect these + # objects in a timely fashion so that they don't get reused + # for multiplexing completely different sockets. This is because + # uv_poll_init_socket does a lot of setup for the socket to make + # polling work. If get reused for another socket that has the same + # fileno, things break badly. (In theory this could be a problem + # on posix too, but in practice it isn't). + + # TODO: We should probably generalize this to all + # ffi watchers. Avoiding GC cycles as much as possible + # is a good thing, and potentially allocating new handles + # as needed gets us better memory locality. + + # Especially on Windows, we must also account for the case that a + # reference to this object has leaked (e.g., the socket object is + # still around), but the fileno has been closed and a new one + # opened. We must still get a new native watcher at that point. We + # handle this case by simply making sure that we don't even have + # a native watcher until the object is started, and we shut it down + # when the object is stopped. + + # XXX: I was able to solve at least Windows test_ftplib.py issues + # with more of a careful use of io objects in socket.py, so + # delaying this entirely is at least temporarily on hold. Instead + # sticking with the _watcher_create function override for the + # moment. + + # XXX: Note 2: Moving to a deterministic close model, which was necessary + # for PyPy, also seems to solve the Windows issues. So we're completely taking + # this object out of the loop's registration; we don't want GC callbacks and + # uv_close anywhere *near* this object. + + _watcher_registers_with_loop_on_create = False + + EVENT_MASK = libuv.UV_READABLE | libuv.UV_WRITABLE | libuv.UV_DISCONNECT + + _multiplex_watchers = () + + def __init__(self, loop, fd, events, ref=True, priority=None): + super(io, self).__init__(loop, fd, events, ref=ref, priority=priority, _args=(fd,)) + self._fd = fd + self._events = events + self._multiplex_watchers = [] + + def _get_fd(self): + return self._fd + + @_base.not_while_active + def _set_fd(self, fd): + self._fd = fd + self._watcher_ffi_init((fd,)) + + def _get_events(self): + return self._events + + def _set_events(self, events): + if events == self._events: + return + self._events = events + if self.active: + # We're running but libuv specifically says we can + # call start again to change our event mask. + assert self._handle is not None + self._watcher_start(self._watcher, self._events, self._watcher_callback) + + events = property(_get_events, _set_events) + + def _watcher_ffi_start(self): + self._watcher_start(self._watcher, self._events, self._watcher_callback) + + if sys.platform.startswith('win32'): + # uv_poll can only handle sockets on Windows, but the plain + # uv_poll_init we call on POSIX assumes that the fileno + # argument is already a C fileno, as created by + # _get_osfhandle. C filenos are limited resources, must be + # closed with _close. So there are lifetime issues with that: + # calling the C function _close to dispose of the fileno + # *also* closes the underlying win32 handle, possibly + # prematurely. (XXX: Maybe could do something with weak + # references? But to what?) + + # All libuv wants to do with the fileno in uv_poll_init is + # turn it back into a Win32 SOCKET handle. + + # Now, libuv provides uv_poll_init_socket, which instead of + # taking a C fileno takes the SOCKET, avoiding the need to dance with + # the C runtime. + + # It turns out that SOCKET (win32 handles in general) can be + # represented with `intptr_t`. It further turns out that + # CPython *directly* exposes the SOCKET handle as the value of + # fileno (32-bit PyPy does some munging on it, which should + # rarely matter). So we can pass socket.fileno() through + # to uv_poll_init_socket. + + # See _corecffi_build. + _watcher_init = watcher._LIB.uv_poll_init_socket + + + class _multiplexwatcher(object): + + callback = None + args = () + pass_events = False + ref = True + + def __init__(self, events, watcher): + self._events = events + + # References: + # These objects must keep the original IO object alive; + # the IO object SHOULD NOT keep these alive to avoid cycles + # We MUST NOT rely on GC to clean up the IO objects, but the explicit + # calls to close(); see _multiplex_closed. + self._watcher_ref = watcher + + events = property( + lambda self: self._events, + _base.not_while_active(lambda self, nv: setattr(self, '_events', nv))) + + def start(self, callback, *args, **kwargs): + self.pass_events = kwargs.get("pass_events") + self.callback = callback + self.args = args + + watcher = self._watcher_ref + if watcher is not None: + if not watcher.active: + watcher._io_start() + else: + # Make sure we're in the event mask + watcher._calc_and_update_events() + + def stop(self): + self.callback = None + self.pass_events = None + self.args = None + watcher = self._watcher_ref + if watcher is not None: + watcher._io_maybe_stop() + + def close(self): + if self._watcher_ref is not None: + self._watcher_ref._multiplex_closed(self) + self._watcher_ref = None + + @property + def active(self): + return self.callback is not None + + @property + def _watcher(self): + # For testing. + return self._watcher_ref._watcher + + # ares.pyx depends on this property, + # and test__core uses it too + fd = property(lambda self: getattr(self._watcher_ref, '_fd', -1), + lambda self, nv: self._watcher_ref._set_fd(nv)) + + def _io_maybe_stop(self): + self._calc_and_update_events() + for w in self._multiplex_watchers: + if w.callback is not None: + # There's still a reference to it, and it's started, + # so we can't stop. + return + # If we get here, nothing was started + # so we can take ourself out of the polling set + self.stop() + + def _io_start(self): + self._calc_and_update_events() + self.start(self._io_callback, pass_events=True) + + def _calc_and_update_events(self): + events = 0 + for watcher in self._multiplex_watchers: + if watcher.callback is not None: + # Only ask for events that are active. + events |= watcher.events + self._set_events(events) + + + def multiplex(self, events): + watcher = self._multiplexwatcher(events, self) + self._multiplex_watchers.append(watcher) + self._calc_and_update_events() + return watcher + + def close(self): + super(io, self).close() + del self._multiplex_watchers + + def _multiplex_closed(self, watcher): + self._multiplex_watchers.remove(watcher) + if not self._multiplex_watchers: + self.stop() # should already be stopped + self._no_more_watchers() + # It is absolutely critical that we control when the call + # to uv_close() gets made. uv_close() of a uv_poll_t + # handle winds up calling uv__platform_invalidate_fd, + # which, as the name implies, destroys any outstanding + # events for the *fd* that haven't been delivered yet, and also removes + # the *fd* from the poll set. So if this happens later, at some + # non-deterministic time when (cyclic or otherwise) GC runs, + # *and* we've opened a new watcher for the fd, that watcher will + # suddenly and mysteriously stop seeing events. So we do this now; + # this method is smart enough not to close the handle twice. + self.close() + else: + self._calc_and_update_events() + + def _no_more_watchers(self): + # The loop sets this on an individual watcher to delete it from + # the active list where it keeps hard references. + pass + + def _io_callback(self, events): + if events < 0: + # actually a status error code + _dbg("Callback error on", self._fd, + ffi.string(libuv.uv_err_name(events)), + ffi.string(libuv.uv_strerror(events))) + # XXX: We've seen one half of a FileObjectPosix pair + # (the read side of a pipe) report errno 11 'bad file descriptor' + # after the write side was closed and its watcher removed. But + # we still need to attempt to read from it to clear out what's in + # its buffers--if we return with the watcher inactive before proceeding to wake up + # the reader, we get a LoopExit. So we can't return here and arguably shouldn't print it + # either. The negative events mask will match the watcher's mask. + # See test__fileobject.py:Test.test_newlines for an example. + + # On Windows (at least with PyPy), we can get ENOTSOCK (socket operation on non-socket) + # if a socket gets closed. If we don't pass the events on, we hang. + # See test__makefile_ref.TestSSL for examples. + # return + + for watcher in self._multiplex_watchers: + if not watcher.callback: + # Stopped + continue + assert watcher._watcher_ref is self, (self, watcher._watcher_ref) + + send_event = (events & watcher.events) or events < 0 + if send_event: + if not watcher.pass_events: + watcher.callback(*watcher.args) + else: + watcher.callback(events, *watcher.args) + +class _SimulatedWithAsyncMixin(object): + _watcher_skip_ffi = True + + def __init__(self, loop, *args, **kwargs): + self._async = loop.async_() + try: + super(_SimulatedWithAsyncMixin, self).__init__(loop, *args, **kwargs) + except: + self._async.close() + raise + + def _watcher_create(self, _args): + return + + @property + def _watcher_handle(self): + return None + + def _watcher_ffi_init(self, _args): + return + + def _watcher_ffi_set_init_ref(self, ref): + self._async.ref = ref + + @property + def active(self): + return self._async.active + + def start(self, cb, *args): + assert self._async is not None + self._register_loop_callback() + self.callback = cb + self.args = args + self._async.start(cb, *args) + + def stop(self): + self._unregister_loop_callback() + self.callback = None + self.args = None + if self._async is not None: + # If we're stop() after close(). + # That should be allowed. + self._async.stop() + + def close(self): + if self._async is not None: + a = self._async + self._async = None + a.close() + + def _register_loop_callback(self): + # called from start() + raise NotImplementedError() + + def _unregister_loop_callback(self): + # called from stop + raise NotImplementedError() + +class fork(_SimulatedWithAsyncMixin, + _base.ForkMixin, + watcher): + # We'll have to implement this one completely manually. + _watcher_skip_ffi = False + + def _register_loop_callback(self): + self.loop._fork_watchers.add(self) + + def _unregister_loop_callback(self): + try: + # stop() should be idempotent + self.loop._fork_watchers.remove(self) + except KeyError: + pass + + def _on_fork(self): + self._async.send() + + +class child(_SimulatedWithAsyncMixin, + _base.ChildMixin, + watcher): + _watcher_skip_ffi = True + # We'll have to implement this one completely manually. + # Our approach is to use a SIGCHLD handler and the original + # os.waitpid call. + + # On Unix, libuv's uv_process_t and uv_spawn use SIGCHLD, + # just like libev does for its child watchers. So + # we're not adding any new SIGCHLD related issues not already + # present in libev. + + + def _register_loop_callback(self): + self.loop._register_child_watcher(self) + + def _unregister_loop_callback(self): + self.loop._unregister_child_watcher(self) + + def _set_waitpid_status(self, pid, status): + self._rpid = pid + self._rstatus = status + self._async.send() + + +class async_(_base.AsyncMixin, watcher): + _watcher_callback_name = '_gevent_async_callback0' + + # libuv async watchers are different than all other watchers: + # They don't have a separate start/stop method (presumably + # because of race conditions). Simply initing them places them + # into the active queue. + # + # In the past, we sent a NULL C callback to the watcher, trusting + # that no one would call send() without actually starting us (or after + # closing us); doing so would crash. But we don't want to delay + # initing the struct because it will crash in uv_close() when we get GC'd, + # and send() will also crash. Plus that complicates our lifecycle (managing + # the memory). + # + # Now, we always init the correct C callback, and use a dummy + # Python callback that gets replaced when we are started and + # stopped. This prevents mistakes from being crashes. + _callback = lambda: None + + def _watcher_ffi_init(self, args): + # NOTE: uv_async_init is NOT idempotent. Calling it more than + # once adds the uv_async_t to the internal queue multiple times, + # and uv_close only cleans up one of them, meaning that we tend to + # crash. Thus we have to be very careful not to allow that. + return self._watcher_init(self.loop.ptr, self._watcher, + self._watcher_callback) + + def _watcher_ffi_start(self): + pass + + def _watcher_ffi_stop(self): + pass + + def send(self): + assert self._callback is not async_._callback, "Sending to a closed watcher" + if libuv.uv_is_closing(self._watcher): + # pylint:disable-next=broad-exception-raised + raise Exception("Closing handle") + libuv.uv_async_send(self._watcher) + + @property + def pending(self): + return None + +locals()['async'] = async_ + +class timer(_base.TimerMixin, watcher): + + _watcher_callback_name = '_gevent_timer_callback0' + + # In libuv, timer callbacks continue running while any timer is + # expired, including newly added timers. Newly added non-zero + # timers (especially of small duration) can be seen to be expired + # if the loop time is updated while we are in a timer callback. + # This can lead to us being stuck running timers for a terribly + # long time, which is not good. So default to not updating the + # time. + + # Also, newly-added timers of 0 duration can *also* stall the + # loop, because they'll be seen to be expired immediately. + # Updating the time can prevent that, *if* there was already a + # timer for a longer duration scheduled. + + # To mitigate the above problems, our loop implementation turns + # zero duration timers into check watchers instead using OneShotCheck. + # This ensures the loop cycles. Of course, the 'again' method does + # nothing on them and doesn't exist. In practice that's not an issue. + + _again = False + + def _watcher_ffi_init(self, args): + self._watcher_init(self.loop.ptr, self._watcher) + self._after, self._repeat = args + if self._after and self._after < 0.001: + import warnings + # XXX: The stack level is hard to determine, could be getting here + # through a number of different ways. + warnings.warn("libuv only supports millisecond timer resolution; " + "all times less will be set to 1 ms", + stacklevel=6) + # The alternative is to effectively pass in int(0.1) == 0, which + # means no sleep at all, which leads to excessive wakeups + self._after = 0.001 + if self._repeat and self._repeat < 0.001: + import warnings + warnings.warn("libuv only supports millisecond timer resolution; " + "all times less will be set to 1 ms", + stacklevel=6) + self._repeat = 0.001 + + def _watcher_ffi_start(self): + if self._again: + libuv.uv_timer_again(self._watcher) + else: + try: + self._watcher_start(self._watcher, self._watcher_callback, + int(self._after * 1000), + int(self._repeat * 1000)) + except ValueError: + # in case of non-ints in _after/_repeat + raise TypeError() + + def again(self, callback, *args, **kw): + if not self.active: + # If we've never been started, this is the same as starting us. + # libuv makes the distinction, libev doesn't. + self.start(callback, *args, **kw) + return + + self._again = True + try: + self.start(callback, *args, **kw) + finally: + del self._again + + +class stat(_base.StatMixin, watcher): + _watcher_type = 'fs_poll' + _watcher_struct_name = 'gevent_fs_poll_t' + _watcher_callback_name = '_gevent_fs_poll_callback3' + + def _watcher_set_data(self, the_watcher, data): + the_watcher.handle.data = data + return data + + def _watcher_ffi_init(self, args): + return self._watcher_init(self.loop.ptr, self._watcher) + + MIN_STAT_INTERVAL = 0.1074891 # match libev; 0.0 is default + + def _watcher_ffi_start(self): + # libev changes this when the watcher is started + self._interval = max(self._interval, self.MIN_STAT_INTERVAL) + self._watcher_start(self._watcher, self._watcher_callback, + self._cpath, + int(self._interval * 1000)) + + @property + def _watcher_handle(self): + return self._watcher.handle.data + + @property + def attr(self): + if not self._watcher.curr.st_nlink: + return + return self._watcher.curr + + @property + def prev(self): + if not self._watcher.prev.st_nlink: + return + return self._watcher.prev + + +class signal(_base.SignalMixin, watcher): + _watcher_callback_name = '_gevent_signal_callback1' + + def _watcher_ffi_init(self, args): + self._watcher_init(self.loop.ptr, self._watcher) + self.ref = False # libev doesn't ref these by default + + + def _watcher_ffi_start(self): + self._watcher_start(self._watcher, self._watcher_callback, + self._signalnum) + + +class idle(_base.IdleMixin, watcher): + # Because libuv doesn't support priorities, idle watchers are + # potentially quite a bit different than under libev + _watcher_callback_name = '_gevent_idle_callback0' + + +class check(_base.CheckMixin, watcher): + _watcher_callback_name = '_gevent_check_callback0' + +class OneShotCheck(check): + + _watcher_skip_ffi = True + + def __make_cb(self, func): + stop = self.stop + @functools.wraps(func) + def cb(*args): + stop() + return func(*args) + return cb + + def start(self, callback, *args): + return check.start(self, self.__make_cb(callback), *args) + +class prepare(_base.PrepareMixin, watcher): + _watcher_callback_name = '_gevent_prepare_callback0' diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/local.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/local.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb0be09caa0b3f98380ba0155e0d45fcff66f54 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/local.py @@ -0,0 +1,610 @@ +# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False +""" +Greenlet-local objects. + +This module is based on `_threading_local.py`__ from the standard +library of Python 3.4. + +__ https://github.com/python/cpython/blob/3.4/Lib/_threading_local.py + +Greenlet-local objects support the management of greenlet-local data. +If you have data that you want to be local to a greenlet, simply create +a greenlet-local object and use its attributes: + + >>> import gevent + >>> from gevent.local import local + >>> mydata = local() + >>> mydata.number = 42 + >>> mydata.number + 42 + +You can also access the local-object's dictionary: + + >>> mydata.__dict__ + {'number': 42} + >>> mydata.__dict__.setdefault('widgets', []) + [] + >>> mydata.widgets + [] + +What's important about greenlet-local objects is that their data are +local to a greenlet. If we access the data in a different greenlet: + + >>> log = [] + >>> def f(): + ... items = list(mydata.__dict__.items()) + ... items.sort() + ... log.append(items) + ... mydata.number = 11 + ... log.append(mydata.number) + >>> greenlet = gevent.spawn(f) + >>> greenlet.join() + >>> log + [[], 11] + +we get different data. Furthermore, changes made in the other greenlet +don't affect data seen in this greenlet: + + >>> mydata.number + 42 + +Of course, values you get from a local object, including a __dict__ +attribute, are for whatever greenlet was current at the time the +attribute was read. For that reason, you generally don't want to save +these values across greenlets, as they apply only to the greenlet they +came from. + +You can create custom local objects by subclassing the local class: + + >>> class MyLocal(local): + ... number = 2 + ... initialized = False + ... def __init__(self, **kw): + ... if self.initialized: + ... raise SystemError('__init__ called too many times') + ... self.initialized = True + ... self.__dict__.update(kw) + ... def squared(self): + ... return self.number ** 2 + +This can be useful to support default values, methods and +initialization. Note that if you define an __init__ method, it will be +called each time the local object is used in a separate greenlet. This +is necessary to initialize each greenlet's dictionary. + +Now if we create a local object: + + >>> mydata = MyLocal(color='red') + +Now we have a default number: + + >>> mydata.number + 2 + +an initial color: + + >>> mydata.color + 'red' + >>> del mydata.color + +And a method that operates on the data: + + >>> mydata.squared() + 4 + +As before, we can access the data in a separate greenlet: + + >>> log = [] + >>> greenlet = gevent.spawn(f) + >>> greenlet.join() + >>> log + [[('color', 'red'), ('initialized', True)], 11] + +without affecting this greenlet's data: + + >>> mydata.number + 2 + >>> mydata.color + Traceback (most recent call last): + ... + AttributeError: 'MyLocal' object has no attribute 'color' + +Note that subclasses can define slots, but they are not greenlet +local. They are shared across greenlets:: + + >>> class MyLocal(local): + ... __slots__ = 'number' + + >>> mydata = MyLocal() + >>> mydata.number = 42 + >>> mydata.color = 'red' + +So, the separate greenlet: + + >>> greenlet = gevent.spawn(f) + >>> greenlet.join() + +affects what we see: + + >>> mydata.number + 11 + +>>> del mydata + +.. versionchanged:: 1.1a2 + Update the implementation to match Python 3.4 instead of Python 2.5. + This results in locals being eligible for garbage collection as soon + as their greenlet exits. + +.. versionchanged:: 1.2.3 + Use a weak-reference to clear the greenlet link we establish in case + the local object dies before the greenlet does. + +.. versionchanged:: 1.3a1 + Implement the methods for attribute access directly, handling + descriptors directly here. This allows removing the use of a lock + and facilitates greatly improved performance. + +.. versionchanged:: 1.3a1 + The ``__init__`` method of subclasses of ``local`` is no longer + called with a lock held. CPython does not use such a lock in its + native implementation. This could potentially show as a difference + if code that uses multiple dependent attributes in ``__slots__`` + (which are shared across all greenlets) switches during ``__init__``. + +""" +from __future__ import print_function + +from copy import copy +from weakref import ref + + +locals()['getcurrent'] = __import__('greenlet').getcurrent +locals()['greenlet_init'] = lambda: None + +__all__ = [ + "local", +] + +# The key used in the Thread objects' attribute dicts. +# We keep it a string for speed but make it unlikely to clash with +# a "real" attribute. +key_prefix = '_gevent_local_localimpl_' + +# The overall structure is as follows: +# For each local() object: +# greenlet.__dict__[key_prefix + str(id(local))] +# => _localimpl.dicts[id(greenlet)] => (ref(greenlet), {}) + +# That final tuple is actually a localimpl_dict_entry object. + +def all_local_dicts_for_greenlet(greenlet): + """ + Internal debug helper for getting the local values associated + with a greenlet. This is subject to change or removal at any time. + + :return: A list of ((type, id), {}) pairs, where the first element + is the type and id of the local object and the second object is its + instance dictionary, as seen from this greenlet. + + .. versionadded:: 1.3a2 + """ + + result = [] + id_greenlet = id(greenlet) + greenlet_dict = greenlet.__dict__ + for k, v in greenlet_dict.items(): + if not k.startswith(key_prefix): + continue + local_impl = v() + if local_impl is None: + continue + entry = local_impl.dicts.get(id_greenlet) + if entry is None: + # Not yet used in this greenlet. + continue + assert entry.wrgreenlet() is greenlet + result.append((local_impl.localtypeid, entry.localdict)) + + return result + + +class _wrefdict(dict): + """A dict that can be weak referenced""" + +class _greenlet_deleted(object): + """ + A weakref callback for when the greenlet + is deleted. + + If the greenlet is a `gevent.greenlet.Greenlet` and + supplies ``rawlink``, that will be used instead of a + weakref. + """ + __slots__ = ('idt', 'wrdicts') + + def __init__(self, idt, wrdicts): + self.idt = idt + self.wrdicts = wrdicts + + def __call__(self, _unused): + dicts = self.wrdicts() + if dicts: + dicts.pop(self.idt, None) + +class _local_deleted(object): + __slots__ = ('key', 'wrthread', 'greenlet_deleted') + + def __init__(self, key, wrthread, greenlet_deleted): + self.key = key + self.wrthread = wrthread + self.greenlet_deleted = greenlet_deleted + + def __call__(self, _unused): + thread = self.wrthread() + if thread is not None: + try: + unlink = thread.unlink + except AttributeError: + pass + else: + unlink(self.greenlet_deleted) + del thread.__dict__[self.key] + +class _localimpl(object): + """A class managing thread-local dicts""" + __slots__ = ('key', 'dicts', + 'localargs', 'localkwargs', + 'localtypeid', + '__weakref__',) + + def __init__(self, args, kwargs, local_type, id_local): + self.key = key_prefix + str(id(self)) + # { id(greenlet) -> _localimpl_dict_entry(ref(greenlet), greenlet-local dict) } + self.dicts = _wrefdict() + self.localargs = args + self.localkwargs = kwargs + self.localtypeid = local_type, id_local + + # We need to create the thread dict in anticipation of + # __init__ being called, to make sure we don't call it + # again ourselves. MUST do this before setting any attributes. + greenlet = getcurrent() # pylint:disable=undefined-variable + _localimpl_create_dict(self, greenlet, id(greenlet)) + +class _localimpl_dict_entry(object): + """ + The object that goes in the ``dicts`` of ``_localimpl`` + object for each thread. + """ + # This is a class, not just a tuple, so that cython can optimize + # attribute access + __slots__ = ('wrgreenlet', 'localdict') + + def __init__(self, wrgreenlet, localdict): + self.wrgreenlet = wrgreenlet + self.localdict = localdict + +# We use functions instead of methods so that they can be cdef'd in +# local.pxd; if they were cdef'd as methods, they would cause +# the creation of a pointer and a vtable. This happens +# even if we declare the class @cython.final. functions thus save memory overhead +# (but not pointer chasing overhead; the vtable isn't used when we declare +# the class final). + + +def _localimpl_create_dict(self, greenlet, id_greenlet): + """Create a new dict for the current thread, and return it.""" + localdict = {} + key = self.key + + wrdicts = ref(self.dicts) + + # When the greenlet is deleted, remove the local dict. + # Note that this is suboptimal if the greenlet object gets + # caught in a reference loop. We would like to be called + # as soon as the OS-level greenlet ends instead. + + # If we are working with a gevent.greenlet.Greenlet, we + # can pro-actively clear out with a link, avoiding the + # issue described above. Use rawlink to avoid spawning any + # more greenlets. + greenlet_deleted = _greenlet_deleted(id_greenlet, wrdicts) + + rawlink = getattr(greenlet, 'rawlink', None) + if rawlink is not None: + rawlink(greenlet_deleted) + wrthread = ref(greenlet) + else: + wrthread = ref(greenlet, greenlet_deleted) + + + # When the localimpl is deleted, remove the thread attribute. + local_deleted = _local_deleted(key, wrthread, greenlet_deleted) + + + wrlocal = ref(self, local_deleted) + greenlet.__dict__[key] = wrlocal + + self.dicts[id_greenlet] = _localimpl_dict_entry(wrthread, localdict) + return localdict + + +_marker = object() + +def _local_get_dict(self): + impl = self._local__impl + # Cython can optimize dict[], but not dict.get() + greenlet = getcurrent() # pylint:disable=undefined-variable + idg = id(greenlet) + try: + entry = impl.dicts[idg] + dct = entry.localdict + except KeyError: + dct = _localimpl_create_dict(impl, greenlet, idg) + self.__init__(*impl.localargs, **impl.localkwargs) + return dct + +def _init(): + greenlet_init() # pylint:disable=undefined-variable + +_local_attrs = { + '_local__impl', + '_local_type_get_descriptors', + '_local_type_set_or_del_descriptors', + '_local_type_del_descriptors', + '_local_type_set_descriptors', + '_local_type', + '_local_type_vars', + '__class__', + '__cinit__', +} + +class local(object): + """ + An object whose attributes are greenlet-local. + """ + __slots__ = tuple(_local_attrs - {'__class__', '__cinit__'}) + + def __cinit__(self, *args, **kw): # pylint:disable=bad-dunder-name + if args or kw: + if type(self).__init__ == object.__init__: # pylint:disable=comparison-with-callable + raise TypeError("Initialization arguments are not supported", args, kw) + impl = _localimpl(args, kw, type(self), id(self)) + # pylint:disable=attribute-defined-outside-init + self._local__impl = impl + get, dels, sets_or_dels, sets = _local_find_descriptors(self) + self._local_type_get_descriptors = get + self._local_type_set_or_del_descriptors = sets_or_dels + self._local_type_del_descriptors = dels + self._local_type_set_descriptors = sets + self._local_type = type(self) + self._local_type_vars = set(dir(self._local_type)) + + def __getattribute__(self, name): # pylint:disable=too-many-return-statements + if name in _local_attrs: + # The _local__impl, __cinit__, etc, won't be hit by the + # Cython version, if we've done things right. If we haven't, + # they will be, and this will produce an error. + return object.__getattribute__(self, name) + + dct = _local_get_dict(self) + + if name == '__dict__': + return dct + # If there's no possible way we can switch, because this + # attribute is *not* found in the class where it might be a + # data descriptor (property), and it *is* in the dict + # then we don't need to swizzle the dict and take the lock. + + # We don't have to worry about people overriding __getattribute__ + # because if they did, the dict-swizzling would only last as + # long as we were in here anyway. + # Similarly, a __getattr__ will still be called by _oga() if needed + # if it's not in the dict. + + # Optimization: If we're not subclassed, then + # there can be no descriptors except for methods, which will + # never need to use __dict__. + if self._local_type is local: + return dct[name] if name in dct else object.__getattribute__(self, name) + + # NOTE: If this is a descriptor, this will invoke its __get__. + # A broken descriptor that doesn't return itself when called with + # a None for the instance argument could mess us up here. + # But this is faster than a loop over mro() checking each class __dict__ + # manually. + if name in dct: + if name not in self._local_type_vars: + # If there is a dict value, and nothing in the type, + # it can't possibly be a descriptor, so it is just returned. + return dct[name] + + # It's in the type *and* in the dict. If the type value is + # a data descriptor (defines __get__ *and* either __set__ or + # __delete__), then the type wins. If it's a non-data descriptor + # (defines just __get__), then the instance wins. If it's not a + # descriptor at all (doesn't have __get__), the instance wins. + # NOTE that the docs for descriptors say that these methods must be + # defined on the *class* of the object in the type. + if name not in self._local_type_get_descriptors: + # Entirely not a descriptor. Instance wins. + return dct[name] + if name in self._local_type_set_or_del_descriptors: + # A data descriptor. + # arbitrary code execution while these run. If they touch self again, + # they'll call back into us and we'll repeat the dance. + type_attr = getattr(self._local_type, name) + return type(type_attr).__get__(type_attr, self, self._local_type) + # Last case is a non-data descriptor. Instance wins. + return dct[name] + + if name in self._local_type_vars: + # Not in the dictionary, but is found in the type. It could be + # a non-data descriptor still. Some descriptors, like @staticmethod, + # return objects (functions, in this case), that are *themselves* + # descriptors, which when invoked, again, would do the wrong thing. + # So we can't rely on getattr() on the type for them, we have to + # look through the MRO dicts ourself. + if name not in self._local_type_get_descriptors: + # Not a descriptor, can't execute code. So all we need is + # the return value of getattr() on our type. + return getattr(self._local_type, name) + + for base in self._local_type.mro(): + bd = base.__dict__ + if name in bd: + attr_on_type = bd[name] + result = type(attr_on_type).__get__(attr_on_type, self, self._local_type) + return result + + # It wasn't in the dict and it wasn't in the type. + # So the next step is to invoke type(self)__getattr__, if it + # exists, otherwise raise an AttributeError. + # we will invoke type(self).__getattr__ or raise an attribute error. + if hasattr(self._local_type, '__getattr__'): + return self._local_type.__getattr__(self, name) + raise AttributeError("%r object has no attribute '%s'" + % (self._local_type.__name__, name)) + + def __setattr__(self, name, value): + if name == '__dict__': + raise AttributeError( + "%r object attribute '__dict__' is read-only" + % type(self)) + + if name in _local_attrs: + object.__setattr__(self, name, value) + return + + dct = _local_get_dict(self) + + if self._local_type is local: + # Optimization: If we're not subclassed, we can't + # have data descriptors, so this goes right in the dict. + dct[name] = value + return + + if name in self._local_type_vars: + if name in self._local_type_set_descriptors: + type_attr = getattr(self._local_type, name, _marker) + # A data descriptor, like a property or a slot. + type(type_attr).__set__(type_attr, self, value) + return + # Otherwise it goes directly in the dict + dct[name] = value + + def __delattr__(self, name): + if name == '__dict__': + raise AttributeError( + "%r object attribute '__dict__' is read-only" + % self.__class__.__name__) + + if name in self._local_type_vars: + if name in self._local_type_del_descriptors: + # A data descriptor, like a property or a slot. + type_attr = getattr(self._local_type, name, _marker) + type(type_attr).__delete__(type_attr, self) + return + # Otherwise it goes directly in the dict + + # Begin inlined function _get_dict() + dct = _local_get_dict(self) + + try: + del dct[name] + except KeyError: + raise AttributeError(name) + + def __copy__(self): + impl = self._local__impl + entry = impl.dicts[id(getcurrent())] # pylint:disable=undefined-variable + + dct = entry.localdict + duplicate = copy(dct) + + cls = type(self) + instance = cls(*impl.localargs, **impl.localkwargs) + _local__copy_dict_from(instance, impl, duplicate) + return instance + +def _local__copy_dict_from(self, impl, duplicate): + current = getcurrent() # pylint:disable=undefined-variable + currentId = id(current) + new_impl = self._local__impl + assert new_impl is not impl + entry = new_impl.dicts[currentId] + new_impl.dicts[currentId] = _localimpl_dict_entry(entry.wrgreenlet, duplicate) + +def _local_find_descriptors(self): + type_self = type(self) + gets = set() + dels = set() + set_or_del = set() + sets = set() + mro = list(type_self.mro()) + + for attr_name in dir(type_self): + # Conventionally, descriptors when called on a class + # return themself, but not all do. Notable exceptions are + # in the zope.interface package, where things like __provides__ + # return other class attributes. So we can't use getattr, and instead + # walk up the dicts + for base in mro: + bd = base.__dict__ + if attr_name in bd: + attr = bd[attr_name] + break + else: + raise AttributeError(attr_name) + + type_attr = type(attr) + if hasattr(type_attr, '__get__'): + gets.add(attr_name) + if hasattr(type_attr, '__delete__'): + dels.add(attr_name) + set_or_del.add(attr_name) + if hasattr(type_attr, '__set__'): + sets.add(attr_name) + + return (gets, dels, set_or_del, sets) + +# Cython doesn't let us use __new__, it requires +# __cinit__. But we need __new__ if we're not compiled +# (e.g., on PyPy). So we set it at runtime. Cython +# will raise an error if we're compiled. +def __new__(cls, *args, **kw): + self = super(local, cls).__new__(cls) # pylint:disable=no-value-for-parameter + # We get the cls in *args for some reason + # too when we do it this way....except on PyPy3, which does + # not *unless* it's wrapped in a classmethod (which it is) + self.__cinit__(*args[1:], **kw) + return self + +if local.__module__ == 'gevent.local': + # PyPy2/3 and CPython handle adding a __new__ to the class + # in different ways. In CPython and PyPy3, it must be wrapped with classmethod; + # in PyPy2 < 7.3.3, it must not. In either case, the args that get passed to + # it are stil wrong. + # + # Prior to Python 3.10, Cython-compiled classes were immutable and + # raised a TypeError on assignment to __new__, and we relied on that + # to detect the compiled version; but that breaks in + # 3.10 as classes are now mutable. (See + # https://github.com/cython/cython/issues/4326). + # + # That's OK; post https://github.com/gevent/gevent/issues/1480, the Cython-compiled + # module has a different name than the pure-Python version and we can check for that. + # It's not as direct, but it works. + # So here we're not compiled + local.__new__ = classmethod(__new__) +else: # pragma: no cover + # Make sure we revisit in case of changes to the (accelerator) module names. + if local.__module__ != 'gevent._gevent_clocal': # pylint:disable=else-if-used + raise AssertionError("Module names changed (local: %r; __name__: %r); revisit this code" % ( + local.__module__, __name__) ) + +_init() + +from gevent._util import import_c_accel +import_c_accel(globals(), 'gevent._local') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/lock.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..09e41a5a08227787355652f049d7a4534888720e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/lock.py @@ -0,0 +1,372 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +""" +Locking primitives. + +These include semaphores with arbitrary bounds (:class:`Semaphore` and +its safer subclass :class:`BoundedSemaphore`) and a semaphore with +infinite bounds (:class:`DummySemaphore`), along with a reentrant lock +(:class:`RLock`) with the same API as :class:`threading.RLock`. +""" +from __future__ import absolute_import +from __future__ import print_function + +from gevent.hub import getcurrent +from gevent._compat import PURE_PYTHON + +# This is the one exception to the rule of where to +# import Semaphore, obviously +from gevent import monkey +from gevent._semaphore import Semaphore +from gevent._semaphore import BoundedSemaphore + + +__all__ = [ + 'Semaphore', + 'BoundedSemaphore', + 'DummySemaphore', + 'RLock', +] + +# On PyPy, we don't compile the Semaphore class with Cython. Under +# Cython, each individual method holds the GIL for its entire +# duration, ensuring that no other thread can interrupt us in an +# unsafe state (only when we _wait do we call back into Python and +# allow switching threads; this is broken down into the +# _drop_lock_for_switch_out and _acquire_lock_for_switch_in methods). +# Simulate that here through the use of a manual lock. (We use a +# separate lock for each semaphore to allow sys.settrace functions to +# use locks *other* than the one being traced.) This, of course, must +# also hold for PURE_PYTHON mode when no optional C extensions are +# used. + +_allocate_lock, _get_ident = monkey.get_original( + ('_thread', 'thread'), + ('allocate_lock', 'get_ident') +) + +def atomic(meth): + def m(self, *args): + with self._atomic: + return meth(self, *args) + return m + + +class _GILLock(object): + __slots__ = ( + '_owned_thread_id', + '_gil', + '_atomic', + '_recursion_depth', + ) + # Don't allow re-entry to these functions in a single thread, as + # can happen if a sys.settrace is used. (XXX: What does that even + # mean? Our original implementation that did that has been + # replaced by something more robust) + # + # This is essentially a variant of the (pure-Python) RLock from the + # standard library. + def __init__(self): + self._owned_thread_id = None + self._gil = _allocate_lock() + self._atomic = _allocate_lock() + self._recursion_depth = 0 + + @atomic + def acquire(self): + current_tid = _get_ident() + if self._owned_thread_id == current_tid: + self._recursion_depth += 1 + return True + + # Not owned by this thread. Only one thread will make it through this point. + while 1: + self._atomic.release() + try: + self._gil.acquire() + finally: + self._atomic.acquire() + if self._owned_thread_id is None: + break + + self._owned_thread_id = current_tid + self._recursion_depth = 1 + return True + + @atomic + def release(self): + current_tid = _get_ident() + if current_tid != self._owned_thread_id: + raise RuntimeError("%s: Releasing lock not owned by you. You: 0x%x; Owner: 0x%x" % ( + self, + current_tid, self._owned_thread_id or 0, + )) + + self._recursion_depth -= 1 + + if not self._recursion_depth: + self._owned_thread_id = None + self._gil.release() + + def __enter__(self): + self.acquire() + + def __exit__(self, t, v, tb): + self.release() + + def locked(self): + return self._gil.locked() + +class _AtomicSemaphoreMixin(object): + # Behaves as though the GIL was held for the duration of acquire, wait, + # and release, just as if we were in Cython. + # + # acquire, wait, and release all acquire the lock on entry and release it + # on exit. acquire and wait can call _wait, which must release it on entry + # and re-acquire it for them on exit. + # + # Note that this does *NOT*, in-and-of itself, make semaphores safe to use from multiple threads + __slots__ = () + def __init__(self, *args, **kwargs): + self._lock_lock = _GILLock() # pylint:disable=assigning-non-slot + super(_AtomicSemaphoreMixin, self).__init__(*args, **kwargs) + + def _acquire_lock_for_switch_in(self): + self._lock_lock.acquire() + + def _drop_lock_for_switch_out(self): + self._lock_lock.release() + + def _notify_links(self, arrived_while_waiting): + with self._lock_lock: + return super(_AtomicSemaphoreMixin, self)._notify_links(arrived_while_waiting) + + def release(self): + with self._lock_lock: + return super(_AtomicSemaphoreMixin, self).release() + + def acquire(self, blocking=True, timeout=None): + with self._lock_lock: + return super(_AtomicSemaphoreMixin, self).acquire(blocking, timeout) + + _py3k_acquire = acquire + + def wait(self, timeout=None): + with self._lock_lock: + return super(_AtomicSemaphoreMixin, self).wait(timeout) + +class _AtomicSemaphore(_AtomicSemaphoreMixin, Semaphore): + __doc__ = Semaphore.__doc__ + __slots__ = ( + '_lock_lock', + ) + + +class _AtomicBoundedSemaphore(_AtomicSemaphoreMixin, BoundedSemaphore): + __doc__ = BoundedSemaphore.__doc__ + __slots__ = ( + '_lock_lock', + ) + + def release(self): # pylint:disable=useless-super-delegation + # This method is duplicated here so that it can get + # properly documented. + return super(_AtomicBoundedSemaphore, self).release() + + +def _fixup_docstrings(): + for c in _AtomicSemaphore, _AtomicBoundedSemaphore: + b = c.__mro__[2] + assert b.__name__.endswith('Semaphore') and 'Atomic' not in b.__name__ + assert c.__doc__ == b.__doc__ + for m in 'acquire', 'release', 'wait': + c_meth = getattr(c, m) + b_meth = getattr(b, m) + c_meth.__doc__ = b_meth.__doc__ + +_fixup_docstrings() +del _fixup_docstrings + + +if PURE_PYTHON: + Semaphore = _AtomicSemaphore + Semaphore.__name__ = 'Semaphore' + BoundedSemaphore = _AtomicBoundedSemaphore + BoundedSemaphore.__name__ = 'BoundedSemaphore' + + +class DummySemaphore(object): + """ + DummySemaphore(value=None) -> DummySemaphore + + An object with the same API as :class:`Semaphore`, + initialized with "infinite" initial value. None of its + methods ever block. + + This can be used to parameterize on whether or not to actually + guard access to a potentially limited resource. If the resource is + actually limited, such as a fixed-size thread pool, use a real + :class:`Semaphore`, but if the resource is unbounded, use an + instance of this class. In that way none of the supporting code + needs to change. + + Similarly, it can be used to parameterize on whether or not to + enforce mutual exclusion to some underlying object. If the + underlying object is known to be thread-safe itself mutual + exclusion is not needed and a ``DummySemaphore`` can be used, but + if that's not true, use a real ``Semaphore``. + """ + + # Internally this is used for exactly the purpose described in the + # documentation. gevent.pool.Pool uses it instead of a Semaphore + # when the pool size is unlimited, and + # gevent.fileobject.FileObjectThread takes a parameter that + # determines whether it should lock around IO to the underlying + # file object. + + def __init__(self, value=None): + """ + .. versionchanged:: 1.1rc3 + Accept and ignore a *value* argument for compatibility with Semaphore. + """ + + def __str__(self): + return '<%s>' % self.__class__.__name__ + + def locked(self): + """A DummySemaphore is never locked so this always returns False.""" + return False + + def ready(self): + """A DummySemaphore is never locked so this always returns True.""" + return True + + def release(self): + """Releasing a dummy semaphore does nothing.""" + + def rawlink(self, callback): + # XXX should still work and notify? + pass + + def unlink(self, callback): + pass + + def wait(self, timeout=None): # pylint:disable=unused-argument + """Waiting for a DummySemaphore returns immediately.""" + return 1 + + def acquire(self, blocking=True, timeout=None): + """ + A DummySemaphore can always be acquired immediately so this always + returns True and ignores its arguments. + + .. versionchanged:: 1.1a1 + Always return *true*. + """ + # pylint:disable=unused-argument + return True + + def __enter__(self): + pass + + def __exit__(self, typ, val, tb): + pass + + +class RLock(object): + """ + A mutex that can be acquired more than once by the same greenlet. + + A mutex can only be locked by one greenlet at a time. A single greenlet + can `acquire` the mutex as many times as desired, though. Each call to + `acquire` must be paired with a matching call to `release`. + + It is an error for a greenlet that has not acquired the mutex + to release it. + + Instances are context managers. + """ + + __slots__ = ( + '_block', + '_owner', + '_count', + '__weakref__', + ) + + def __init__(self, hub=None): + """ + .. versionchanged:: 20.5.1 + Add the ``hub`` argument. + """ + self._block = Semaphore(1, hub) + self._owner = None + self._count = 0 + + def __repr__(self): + return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % ( + self.__class__.__name__, + id(self), + self._block, + self._count, + self._owner) + + def acquire(self, blocking=True, timeout=None): + """ + Acquire the mutex, blocking if *blocking* is true, for up to + *timeout* seconds. + + .. versionchanged:: 1.5a4 + Added the *timeout* parameter. + + :return: A boolean indicating whether the mutex was acquired. + """ + me = getcurrent() + if self._owner is me: + self._count += 1 + return 1 + rc = self._block.acquire(blocking, timeout) + if rc: + self._owner = me + self._count = 1 + return rc + + def __enter__(self): + return self.acquire() + + def release(self): + """ + Release the mutex. + + Only the greenlet that originally acquired the mutex can + release it. + """ + if self._owner is not getcurrent(): + raise RuntimeError("cannot release un-acquired lock. Owner: %r Current: %r" % ( + self._owner, getcurrent() + )) + self._count = count = self._count - 1 # pylint:disable=consider-using-augmented-assign + if not count: + self._owner = None + self._block.release() + + def __exit__(self, typ, value, tb): + self.release() + + # Internal methods used by condition variables + + def _acquire_restore(self, count_owner): + count, owner = count_owner + self._block.acquire() + self._count = count + self._owner = owner + + def _release_save(self): + count = self._count + self._count = 0 + owner = self._owner + self._owner = None + self._block.release() + return (count, owner) + + def _is_owned(self): + return self._owner is getcurrent() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..098d4cb5bfbed6ec135d1b77eca35f4e0613adc7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__init__.py @@ -0,0 +1,704 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +# pylint: disable=redefined-outer-name,too-many-lines +""" +Make the standard library cooperative. + +The primary purpose of this module is to carefully patch, in place, +portions of the standard library with gevent-friendly functions that +behave in the same way as the original (at least as closely as possible). + +The primary interface to this is the :func:`patch_all` function, which +performs all the available patches. It accepts arguments to limit the +patching to certain modules, but most programs **should** use the +default values as they receive the most wide-spread testing, and some monkey +patches have dependencies on others. + +Patching **should be done as early as possible** in the lifecycle of the +program. For example, the main module (the one that tests against +``__main__`` or is otherwise the first imported) should begin with +this code, ideally before any other imports:: + + from gevent import monkey + monkey.patch_all() + +A corollary of the above is that patching **should be done on the main +thread** and **should be done while the program is single-threaded**. + +.. tip:: + + Some frameworks, such as gunicorn, handle monkey-patching for you. + Check their documentation to be sure. + +.. warning:: + + Patching too late can lead to unreliable behaviour (for example, some + modules may still use blocking sockets) or even errors. + +.. tip:: + + Be sure to read the documentation for each patch function to check for + known incompatibilities. + +Querying +======== + +Sometimes it is helpful to know if objects have been monkey-patched, and in +advanced cases even to have access to the original standard library functions. This +module provides functions for that purpose. + +- :func:`is_module_patched` +- :func:`is_object_patched` +- :func:`get_original` + +.. _plugins: + +Plugins and Events +================== + +Beginning in gevent 1.3, events are emitted during the monkey patching process. +These events are delivered first to :mod:`gevent.events` subscribers, and then +to `setuptools entry points`_. + +The following events are defined. They are listed in (roughly) the order +that a call to :func:`patch_all` will emit them. + +- :class:`gevent.events.GeventWillPatchAllEvent` +- :class:`gevent.events.GeventWillPatchModuleEvent` +- :class:`gevent.events.GeventDidPatchModuleEvent` +- :class:`gevent.events.GeventDidPatchBuiltinModulesEvent` +- :class:`gevent.events.GeventDidPatchAllEvent` + +Each event class documents the corresponding setuptools entry point name. The +entry points will be called with a single argument, the same instance of +the class that was sent to the subscribers. + +You can subscribe to the events to monitor the monkey-patching process and +to manipulate it, for example by raising :exc:`gevent.events.DoNotPatch`. + +You can also subscribe to the events to provide additional patching beyond what +gevent distributes, either for additional standard library modules, or +for third-party packages. The suggested time to do this patching is in +the subscriber for :class:`gevent.events.GeventDidPatchBuiltinModulesEvent`. +For example, to automatically patch `psycopg2`_ using `psycogreen`_ +when the call to :func:`patch_all` is made, you could write code like this:: + + # mypackage.py + def patch_psycopg(event): + from psycogreen.gevent import patch_psycopg + patch_psycopg() + +In your ``setup.py`` you would register it like this:: + + from setuptools import setup + setup( + ... + entry_points={ + 'gevent.plugins.monkey.did_patch_builtins': [ + 'psycopg2 = mypackage:patch_psycopg', + ], + }, + ... + ) + +For more complex patching, gevent provides a helper method +that you can call to replace attributes of modules with attributes of your +own modules. This function also takes care of emitting the appropriate events. + +- :func:`patch_module` + +.. _setuptools entry points: http://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins +.. _psycopg2: https://pypi.python.org/pypi/psycopg2 +.. _psycogreen: https://pypi.python.org/pypi/psycogreen + +Use as a module +=============== + +Sometimes it is useful to run existing python scripts or modules that +were not built to be gevent aware under gevent. To do so, this module +can be run as the main module, passing the script and its arguments. +For details, see the :func:`main` function. + +.. versionchanged:: 1.3b1 + Added support for plugins and began emitting will/did patch events. +""" + +import sys + +#### +# gevent developers: IMPORTANT: Keep imports +# as limited and localized as possible to avoid +# interfering with the monkey-patch process. +# This is why many imports are nested inside functions. +# +# This applies for this entire package. +### + +__all__ = [ + 'patch_all', + 'patch_builtins', + 'patch_dns', + 'patch_os', + 'patch_queue', + 'patch_select', + 'patch_signal', + 'patch_socket', + 'patch_ssl', + 'patch_subprocess', + 'patch_sys', + 'patch_thread', + 'patch_time', + # query functions + 'get_original', + 'is_module_patched', + 'is_object_patched', + + # 'is_anything_patched', <- see docstring + + # plugin API + 'patch_module', + # module functions + 'main', + # Errors and warnings + 'MonkeyPatchWarning', +] + +WIN = sys.platform.startswith("win") + +# Unused imports may be removed in a major release after 2024-10. +# Used private imports may be renamed or removed or changed +# in an incompatible way at that time. + + + +from ._errors import MonkeyPatchWarning + +from ._util import _notify_patch +from ._util import _ignores_DoNotPatch + +from ._state import saved +from ._state import is_module_patched +from ._state import is_object_patched + +# Never documented as a public API, but +# potentially in use by third parties +# given the naming convention. +from ._state import is_anything_patched # pylint:disable=unused-import +from ._errors import _BadImplements # pylint:disable=unused-import + + + +from .api import get_original +from .api import patch_module + + + +# These are not part of the documented public API, +# but they could be used by plugins. TODO: Do we +# want to make them public with __all__? +from .api import patch_item +from .api import remove_item + + + + + + + + +from ._util import _check_availability +from ._util import _patch_module +from ._util import _queue_warning +from ._util import _process_warnings + + + +def _patch_sys_std(name): + from gevent.fileobject import FileObjectThread + orig = getattr(sys, name) + if not isinstance(orig, FileObjectThread): + patch_item(sys, name, FileObjectThread(orig)) + +@_ignores_DoNotPatch +def patch_sys(stdin=True, stdout=True, stderr=True): # pylint:disable=unused-argument + """ + Patch sys.std[in,out,err] to use a cooperative IO via a + threadpool. + + This is relatively dangerous and can have unintended consequences + such as hanging the process or `misinterpreting control keys`_ + when :func:`input` and :func:`raw_input` are used. :func:`patch_all` + does *not* call this function by default. + + This method does nothing on Python 3. The Python 3 interpreter + wants to flush the TextIOWrapper objects that make up + stderr/stdout at shutdown time, but using a threadpool at that + time leads to a hang. + + .. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274 + + .. deprecated:: 23.7.0 + Does nothing on any supported version. + """ + return + +@_ignores_DoNotPatch +def patch_os(): + """ + Replace :func:`os.fork` with :func:`gevent.fork`, and, on POSIX, + :func:`os.waitpid` with :func:`gevent.os.waitpid` (if the + environment variable ``GEVENT_NOWAITPID`` is not defined). Does + nothing if fork is not available. + + .. caution:: This method must be used with :func:`patch_signal` to have proper `SIGCHLD` + handling and thus correct results from ``waitpid``. + :func:`patch_all` calls both by default. + + .. caution:: For `SIGCHLD` handling to work correctly, the event loop must run. + The easiest way to help ensure this is to use :func:`patch_all`. + """ + _patch_module('os') + + +@_ignores_DoNotPatch +def patch_queue(): + """ + Patch objects in :mod:`queue`. + + + Currently, this just replaces :class:`queue.SimpleQueue` (implemented + in C) with its Python counterpart, but the details may change at any time. + + .. versionadded:: 1.3.5 + """ + _patch_module('queue', items=[ + 'SimpleQueue', + ]) + + +@_ignores_DoNotPatch +def patch_time(): + """ + Replace :func:`time.sleep` with :func:`gevent.sleep`. + """ + _patch_module('time') + +@_ignores_DoNotPatch +def patch_contextvars(): + """ + Replaces the implementations of :mod:`contextvars` with + :mod:`gevent.contextvars`. + + On Python 3.7 and above, this is a standard library module. On + earlier versions, a backport that uses the same distribution name + and import name is available on PyPI (though this is not + recommended). If that is installed, it will be patched. + + .. versionchanged:: 20.04.0 + Clarify that the backport is also patched. + + .. versionchanged:: 20.9.0 + This now does nothing on Python 3.7 and above. + gevent now depends on greenlet 0.4.17, which + natively handles switching context vars when greenlets are switched. + Older versions of Python that have the backport installed will + still be patched. + + .. deprecated:: 23.7.0 + Does nothing on any supported version. + """ + return + + + +@_ignores_DoNotPatch +def patch_thread(threading=True, _threading_local=True, Event=True, logging=True, + existing_locks=True, + _warnings=None): + """ + patch_thread(threading=True, _threading_local=True, Event=True, logging=True, existing_locks=True) -> None + + Replace the standard :mod:`thread` module to make it greenlet-based. + + :keyword bool threading: When True (the default), + also patch :mod:`threading`. + :keyword bool _threading_local: When True (the default), + also patch :class:`_threading_local.local`. + :keyword bool logging: When True (the default), also patch locks + taken if the logging module has been configured. + + :keyword bool existing_locks: When True (the default), and the + process is still single threaded, make sure that any + :class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`) + instances that are currently locked can be properly unlocked. **Important**: This is a + best-effort attempt and, on certain implementations, may not detect all + locks. It is important to monkey-patch extremely early in the startup process. + Setting this to False is not recommended, especially on Python 2. + + .. caution:: + Monkey-patching :mod:`thread` and using + :class:`multiprocessing.Queue` or + :class:`concurrent.futures.ProcessPoolExecutor` (which uses a + ``Queue``) will hang the process. + + Monkey-patching with this function and using + sub-interpreters (and advanced C-level API) and threads may be + unstable on certain platforms. + + .. versionchanged:: 1.1b1 + Add *logging* and *existing_locks* params. + .. versionchanged:: 1.3a2 + ``Event`` defaults to True. + """ + if sys.version_info[:2] < (3, 13): + from ._patch_thread_lt313 import Patcher + else: + from ._patch_thread_gte313 import Patcher + patch = Patcher(threading=threading, _threading_local=_threading_local, Event=Event, + logging=logging, existing_locks=existing_locks, _warnings=_warnings) + patch() + + +@_ignores_DoNotPatch +def patch_socket(dns=True, aggressive=True): + """ + Replace the standard socket object with gevent's cooperative + sockets. + + :keyword bool dns: When true (the default), also patch address + resolution functions in :mod:`socket`. See :doc:`/dns` for details. + """ + from gevent import socket + # Note: although it seems like it's not strictly necessary to monkey patch 'create_connection', + # it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module + # was, create_connection would still use "green" getaddrinfo and "green" socket. + # However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes + # _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail. + if dns: + items = socket.__implements__ # pylint:disable=no-member + else: + items = set(socket.__implements__) - set(socket.__dns__) # pylint:disable=no-member + _patch_module('socket', items=items) + if aggressive: + if 'ssl' not in socket.__implements__: # pylint:disable=no-member + remove_item(socket, 'ssl') + +@_ignores_DoNotPatch +def patch_dns(): + """ + Replace :doc:`DNS functions ` in :mod:`socket` with + cooperative versions. + + This is only useful if :func:`patch_socket` has been called and is + done automatically by that method if requested. + """ + from gevent import socket + _patch_module('socket', items=socket.__dns__) # pylint:disable=no-member + + +def _find_module_refs(to, excluding_names=()): + # Looks specifically for module-level references, + # i.e., 'from foo import Bar'. We define a module reference + # as a dict (subclass) that also has a __name__ attribute. + # This does not handle subclasses, but it does find them. + # Returns two sets. The first is modules (name, file) that were + # found. The second is subclasses that were found. + gc = __import__('gc') + direct_ref_modules = set() + subclass_modules = set() + + def report(mod): + return mod['__name__'], mod.get('__file__', '') + + for r in gc.get_referrers(to): + if isinstance(r, dict) and '__name__' in r: + if r['__name__'] in excluding_names: + continue + + for v in r.values(): + if v is to: + direct_ref_modules.add(report(r)) + elif isinstance(r, type) and to in r.__bases__ and 'gevent.' not in r.__module__: + subclass_modules.add(r) + + return direct_ref_modules, subclass_modules + +@_ignores_DoNotPatch +def patch_ssl(_warnings=None, _first_time=True): + """ + patch_ssl() -> None + + Replace :class:`ssl.SSLSocket` object and socket wrapping functions in + :mod:`ssl` with cooperative versions. + + This is only useful if :func:`patch_socket` has been called. + """ + may_need_warning = ( + _first_time + and 'ssl' in sys.modules + and hasattr(sys.modules['ssl'], 'SSLContext')) + # Previously, we didn't warn on Python 2 if pkg_resources has been imported + # because that imports ssl and it's commonly used for namespace packages, + # which typically means we're still in some early part of the import cycle. + # However, with our new more discriminating check, that no longer seems to be a problem. + # Prior to 3.6, we don't have the RecursionError problem, and prior to 3.7 we don't have the + # SSLContext.sslsocket_class/SSLContext.sslobject_class problem. + + gevent_mod, _ = _patch_module('ssl', _warnings=_warnings) + if may_need_warning: + direct_ref_modules, subclass_modules = _find_module_refs( + gevent_mod.orig_SSLContext, + excluding_names=('ssl', 'gevent.ssl', 'gevent._ssl3', 'gevent._sslgte279')) + if direct_ref_modules or subclass_modules: + # Normally you don't want to have dynamic warning strings, because + # the cache in the warning module is based on the string. But we + # specifically only do this the first time we patch ourself, so it's + # ok. + direct_ref_mod_str = subclass_str = '' + if direct_ref_modules: + direct_ref_mod_str = 'Modules that had direct imports (NOT patched): %s. ' % ([ + "%s (%s)" % (name, fname) + for name, fname in direct_ref_modules + ]) + if subclass_modules: + subclass_str = 'Subclasses (NOT patched): %s. ' % ([ + str(t) for t in subclass_modules + ]) + _queue_warning( + 'Monkey-patching ssl after ssl has already been imported ' + 'may lead to errors, including RecursionError on Python 3.6. ' + 'It may also silently lead to incorrect behaviour on Python 3.7. ' + 'Please monkey-patch earlier. ' + 'See https://github.com/gevent/gevent/issues/1016. ' + + direct_ref_mod_str + subclass_str, + _warnings) + + +@_ignores_DoNotPatch +def patch_select(aggressive=True): + """ + Replace :func:`select.select` with :func:`gevent.select.select` + and :func:`select.poll` with :class:`gevent.select.poll` (where available). + + If ``aggressive`` is true (the default), also remove other + blocking functions from :mod:`select` . + + - :func:`select.epoll` + - :func:`select.kqueue` + - :func:`select.kevent` + - :func:`select.devpoll` (Python 3.5+) + """ + _patch_module('select', + _patch_kwargs={'aggressive': aggressive}) + +@_ignores_DoNotPatch +def patch_selectors(aggressive=True): + """ + Replace :class:`selectors.DefaultSelector` with + :class:`gevent.selectors.GeventSelector`. + + If ``aggressive`` is true (the default), also remove other + blocking classes :mod:`selectors`: + + - :class:`selectors.EpollSelector` + - :class:`selectors.KqueueSelector` + - :class:`selectors.DevpollSelector` (Python 3.5+) + + On Python 2, the :mod:`selectors2` module is used instead + of :mod:`selectors` if it is available. If this module cannot + be imported, no patching is done and :mod:`gevent.selectors` is + not available. + + In :func:`patch_all`, the *select* argument controls both this function + and :func:`patch_select`. + + .. versionadded:: 20.6.0 + """ + try: + _check_availability('selectors') + except ImportError: # pragma: no cover + return + + _patch_module('selectors', + _patch_kwargs={'aggressive': aggressive}) + + +@_ignores_DoNotPatch +def patch_subprocess(): + """ + Replace :func:`subprocess.call`, :func:`subprocess.check_call`, + :func:`subprocess.check_output` and :class:`subprocess.Popen` with + :mod:`cooperative versions `. + + .. note:: + On Windows under Python 3, the API support may not completely match + the standard library. + + """ + _patch_module('subprocess') + +@_ignores_DoNotPatch +def patch_builtins(): + """ + Make the builtin :func:`__import__` function `greenlet safe`_ under Python 2. + + .. note:: + This does nothing under Python 3 as it is not necessary. Python 3 features + improved import locks that are per-module, not global. + + .. _greenlet safe: https://github.com/gevent/gevent/issues/108 + + .. deprecated:: 23.7.0 + Does nothing on any supported platform. + """ + + +@_ignores_DoNotPatch +def patch_signal(): + """ + Make the :func:`signal.signal` function work with a :func:`monkey-patched os `. + + .. caution:: This method must be used with :func:`patch_os` to have proper ``SIGCHLD`` + handling. :func:`patch_all` calls both by default. + + .. caution:: For proper ``SIGCHLD`` handling, you must yield to the event loop. + Using :func:`patch_all` is the easiest way to ensure this. + + .. seealso:: :mod:`gevent.signal` + """ + _patch_module("signal") + + +def _check_repatching(**module_settings): + _warnings = [] + key = '_gevent_saved_patch_all_module_settings' + + del module_settings['kwargs'] + currently_patched = saved.setdefault(key, {}) + first_time = not currently_patched + if not first_time and currently_patched != module_settings: + _queue_warning("Patching more than once will result in the union of all True" + " parameters being patched", + _warnings) + + to_patch = {} + for k, v in module_settings.items(): + # If we haven't seen the setting at all, record it and echo it. + # If we have seen the setting, but it became true, record it and echo it. + if k not in currently_patched: + to_patch[k] = currently_patched[k] = v + elif v and not currently_patched[k]: + to_patch[k] = currently_patched[k] = True + + return _warnings, first_time, to_patch + + +def _subscribe_signal_os(will_patch_all): + if will_patch_all.will_patch_module('signal') and not will_patch_all.will_patch_module('os'): + warnings = will_patch_all._warnings # Internal + _queue_warning('Patching signal but not os will result in SIGCHLD handlers' + ' installed after this not being called and os.waitpid may not' + ' function correctly if gevent.subprocess is used. This may raise an' + ' error in the future.', + warnings) + +def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, + subprocess=True, sys=False, aggressive=True, Event=True, + builtins=True, signal=True, + queue=True, contextvars=True, + **kwargs): + """ + Do all of the default monkey patching (calls every other applicable + function in this module). + + :return: A true value if patching all modules wasn't cancelled, a false + value if it was. + + .. versionchanged:: 1.1 + Issue a :mod:`warning ` if this function is called multiple times + with different arguments. The second and subsequent calls will only add more + patches, they can never remove existing patches by setting an argument to ``False``. + .. versionchanged:: 1.1 + Issue a :mod:`warning ` if this function is called with ``os=False`` + and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may + be an error in the future. + .. versionchanged:: 1.3a2 + ``Event`` defaults to True. + .. versionchanged:: 1.3b1 + Defined the return values. + .. versionchanged:: 1.3b1 + Add ``**kwargs`` for the benefit of event subscribers. CAUTION: gevent may add + and interpret additional arguments in the future, so it is suggested to use prefixes + for kwarg values to be interpreted by plugins, for example, `patch_all(mylib_futures=True)`. + .. versionchanged:: 1.3.5 + Add *queue*, defaulting to True, for Python 3.7. + .. versionchanged:: 1.5 + Remove the ``httplib`` argument. Previously, setting it raised a ``ValueError``. + .. versionchanged:: 1.5a3 + Add the ``contextvars`` argument. + .. versionchanged:: 1.5 + Better handling of patching more than once. + """ + # pylint:disable=too-many-locals,too-many-branches + + # Check to see if they're changing the patched list + _warnings, first_time, modules_to_patch = _check_repatching(**locals()) + + if not modules_to_patch: + # Nothing to do. Either the arguments were identical to what + # we previously did, or they specified false values + # for things we had previously patched. + _process_warnings(_warnings) + return + + for k, v in modules_to_patch.items(): + locals()[k] = v + + from gevent import events + try: + _notify_patch(events.GeventWillPatchAllEvent(modules_to_patch, kwargs), _warnings) + except events.DoNotPatch: + return False + + # order is important + if os: + patch_os() + if thread: + patch_thread(Event=Event, _warnings=_warnings) + if time: + # time must be patched after thread, some modules used by thread + # need access to the real time.sleep function. + patch_time() + + # sys must be patched after thread. in other cases threading._shutdown will be + # initiated to _MainThread with real thread ident + if sys: + patch_sys() + if socket: + patch_socket(dns=dns, aggressive=aggressive) + if select: + patch_select(aggressive=aggressive) + patch_selectors(aggressive=aggressive) + if ssl: + patch_ssl(_warnings=_warnings, _first_time=first_time) + if subprocess: + patch_subprocess() + if builtins: + patch_builtins() + if signal: + patch_signal() + if queue: + patch_queue() + if contextvars: + patch_contextvars() + + _notify_patch(events.GeventDidPatchBuiltinModulesEvent(modules_to_patch, kwargs), _warnings) + _notify_patch(events.GeventDidPatchAllEvent(modules_to_patch, kwargs), _warnings) + + _process_warnings(_warnings) + return True + +def __getattr__(name): + if name == 'main': + from ._main import main + return main + raise AttributeError(name) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__main__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..be7e86a53e0af1deaa6ff8f24f9b8d6aafb980ee --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__main__.py @@ -0,0 +1,2 @@ +from ._main import main +main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_errors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d88a06da96c3c905bd2ee6d95687545653dcca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_errors.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +""" +Exception classes and errors that this package may raise. + +""" +import logging + +logger = logging.getLogger(__name__) + +class _BadImplements(AttributeError): + """ + Raised when ``__implements__`` is incorrect. + """ + + def __init__(self, module): + AttributeError.__init__( + self, + "Module %r has a bad or missing value for __implements__" % (module,) + ) + +class MonkeyPatchWarning(RuntimeWarning): + """ + The type of warnings we issue. + + .. versionadded:: 1.3a2 + """ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_main.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..306cf877872f3aead2ef57a9d73a9ee1c3ebcdd1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_main.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +""" +The real functionality to run this package as a main module. + +""" + + +def main(): + # TODO: Now that this is its own module, see if + # we can refactor. + # pylint:disable=too-many-locals + import sys + from . import patch_all + + args = {} + argv = sys.argv[1:] + verbose = False + run_fn = "run_path" + script_help, patch_all_args, modules = _get_script_help() + while argv and argv[0].startswith('--'): + option = argv[0][2:] + if option == 'verbose': + verbose += 1 + elif option == 'module': + run_fn = "run_module" + elif option.startswith('no-') and option.replace('no-', '') in patch_all_args: + args[option[3:]] = False + elif option in patch_all_args: + args[option] = True + if option in modules: + for module in modules: + args.setdefault(module, False) + else: + sys.exit(script_help + '\n\n' + 'Cannot patch %r' % option) + del argv[0] + # TODO: break on -- + if verbose: + import pprint + import os + print('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items())) + print('sys.version=%s' % (sys.version.strip().replace('\n', ' '), )) + print('sys.path=%s' % pprint.pformat(sys.path)) + print('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys()))) + print('cwd=%s' % os.getcwd()) + + if not argv: + print(script_help) + return + + sys.argv[:] = argv + # Make sure that we don't get imported again under a different + # name (usually it's ``__main__`` here) because that could lead to + # double-patching, and making monkey.get_original() not work. + try: + mod_name = __spec__.name + except NameError: + # Py2: __spec__ is not defined as standard + mod_name = 'gevent.monkey' + sys.modules[mod_name] = sys.modules[__name__] + # On Python 2, we have to set the gevent.monkey attribute + # manually; putting gevent.monkey into sys.modules stops the + # import machinery from making that connection, and ``from gevent + # import monkey`` is broken. On Python 3 (.8 at least) that's not + # necessary. + assert 'gevent.monkey' in sys.modules + + # Running ``patch_all()`` will load pkg_resources entry point plugins + # which may attempt to import ``gevent.monkey``, so it is critical that + # we have established the correct saved module name first. + patch_all(**args) + + import runpy + # Use runpy.run_path to closely (exactly) match what the + # interpreter does given 'python '. This includes allowing + # passing .pyc/.pyo files and packages with a __main__ and + # potentially even zip files. Previously we used exec, which only + # worked if we directly read a python source file. + run_meth = getattr(runpy, run_fn) + return run_meth(sys.argv[0], run_name='__main__') + + +def _get_script_help(): + # pylint:disable=deprecated-method + import inspect + from . import patch_all + getter = inspect.getfullargspec + + patch_all_args = getter(patch_all)[0] + modules = [x for x in patch_all_args if 'patch_' + x in globals()] + script_help = """gevent.monkey - monkey patch the standard modules to use gevent. + +USAGE: ``python -m gevent.monkey [MONKEY OPTIONS] [--module] (script|module) [SCRIPT OPTIONS]`` + +If no MONKEY OPTIONS are present, monkey patches all the modules as if by calling ``patch_all()``. +You can exclude a module with --no-, e.g. --no-thread. You can +specify a module to patch with --, e.g. --socket. In the latter +case only the modules specified on the command line will be patched. + +The default behavior is to execute the script passed as argument. If you wish +to run a module instead, pass the `--module` argument before the module name. + +.. versionchanged:: 1.3b1 + The *script* argument can now be any argument that can be passed to `runpy.run_path`, + just like the interpreter itself does, for example a package directory containing ``__main__.py``. + Previously it had to be the path to + a .py source file. + +.. versionchanged:: 1.5 + The `--module` option has been added. + +MONKEY OPTIONS: ``--verbose %s``""" % ', '.join('--[no-]%s' % m for m in modules) + return script_help, patch_all_args, modules + +main.__doc__ = _get_script_help()[0] + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c664cb1335ba5f637d3933061e657be2fa4f75 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_common.py @@ -0,0 +1,311 @@ +# -*- coding: utf-8 -*- +""" +The implementation of thread patching for Python versions +prior to 3.13. + +Internal use only. +""" +import sys + +from ._util import _patch_module +from ._util import _queue_warning +from ._util import _notify_patch + +from ._state import is_object_patched + +def _patch_existing_locks(threading): + if len(list(threading.enumerate())) != 1: + return + # This is used to protect internal data structures for enumerate. + # It's acquired when threads are started and when they're stopped. + # Stopping a thread checks a Condition, which on Python 2 wants to test + # _is_owned of its (patched) Lock. Since our LockType doesn't have + # _is_owned, it tries to acquire the lock non-blocking; that triggers a + # switch. If the next thing in the callback list was a thread that needed + # to start or end, we wouldn't be able to acquire this native lock + # because it was being held already; we couldn't switch either, so we'd + # block permanently. + threading._active_limbo_lock = threading._allocate_lock() + try: + tid = threading.get_ident() + except AttributeError: + tid = threading._get_ident() + rlock_type = type(threading.RLock()) + try: + import importlib._bootstrap + except ImportError: + class _ModuleLock(object): + pass + else: + _ModuleLock = importlib._bootstrap._ModuleLock # python 2 pylint: disable=no-member + # It might be possible to walk up all the existing stack frames to find + # locked objects...at least if they use `with`. To be sure, we look at every object + # Since we're supposed to be done very early in the process, there shouldn't be + # too many. + + # Note that the C implementation of locks, at least on some + # versions of CPython, cannot be found and cannot be fixed (they simply + # don't show up to GC; see https://github.com/gevent/gevent/issues/1354) + + # By definition there's only one thread running, so the various + # owner attributes were the old (native) thread id. Make it our + # current greenlet id so that when it wants to unlock and compare + # self.__owner with _get_ident(), they match. + gc = __import__('gc') + for o in gc.get_objects(): + if isinstance(o, rlock_type): + for owner_name in ( + '_owner', # Python 3 or backported PyPy2 + '_RLock__owner', # Python 2 + ): + if hasattr(o, owner_name): + if getattr(o, owner_name) is not None: + setattr(o, owner_name, tid) + break + else: # pragma: no cover + raise AssertionError( + "Unsupported Python implementation; " + "Found unknown lock implementation.", + vars(o) + ) + elif isinstance(o, _ModuleLock): + if o.owner is not None: + o.owner = tid + + + +class BasePatcher: + # Description of the hang: + # There is an incompatibility with patching 'thread' and the 'multiprocessing' module: + # The problem is that multiprocessing.queues.Queue uses a half-duplex multiprocessing.Pipe, + # which is implemented with os.pipe() and _multiprocessing.Connection. os.pipe isn't patched + # by gevent, as it returns just a fileno. _multiprocessing.Connection is an internal implementation + # class implemented in C, which exposes a 'poll(timeout)' method; under the covers, this issues a + # (blocking) select() call: hence the need for a real thread. Except for that method, we could + # almost replace Connection with gevent.fileobject.SocketAdapter, plus a trivial + # patch to os.pipe (below). Sigh, so close. (With a little work, we could replicate that method) + + # import os + # import fcntl + # os_pipe = os.pipe + # def _pipe(): + # r, w = os_pipe() + # fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK) + # fcntl.fcntl(w, fcntl.F_SETFL, os.O_NONBLOCK) + # return r, w + # os.pipe = _pipe + + gevent_threading_mod = None + gevent_thread_mod = None + + thread_mod = None + threading_mod = None + orig_current_thread = None + main_thread = None + orig_shutdown = None + + def __init__(self, threading=True, _threading_local=True, Event=True, logging=True, + existing_locks=True, + _warnings=None): + self.threading = threading + self.threading_local = _threading_local + self.Event = Event + self.logging = logging + self.existing_locks = existing_locks + self.warnings = _warnings + + + + def __call__(self): + # The 'threading' module copies some attributes from the + # thread module the first time it is imported. If we patch 'thread' + # before that happens, then we store the wrong values in 'saved', + # So if we're going to patch threading, we either need to import it + # before we patch thread, or manually clean up the attributes that + # are in trouble. The latter is tricky because of the different names + # on different versions. + + + self.threading_mod = __import__('threading') + # Capture the *real* current thread object before + # we start returning DummyThread objects, for comparison + # to the main thread. + self.orig_current_thread = self.threading_mod.current_thread() + self.main_thread = self.threading_mod.main_thread() + self.orig_shutdown = self.threading_mod._shutdown + + gevent_thread_mod, thread_mod = _patch_module('thread', + _warnings=self.warnings, + _notify_did_subscribers=False) + + + if self.threading: + self.patch_threading_event_logging_existing_locks() + + if self.threading_local: + self.patch__threading_local() + + if self.threading: + self.patch_active_threads() + + + # Issue 18808 changes the nature of Thread.join() to use + # locks. This means that a greenlet spawned in the main thread + # (which is already running) cannot wait for the main thread---it + # hangs forever. We patch around this if possible. See also + # gevent.threading. + already_patched = is_object_patched('threading', '_shutdown') + + if self.orig_current_thread == self.threading_mod.main_thread() and not already_patched: + self.patch_threading_shutdown_on_main_thread_not_already_patched() + self.patch_main_thread_cleanup() + + elif not already_patched: + self.patch_shutdown_not_on_main_thread() + + from gevent import events + _notify_patch(events.GeventDidPatchModuleEvent('thread', + gevent_thread_mod, + thread_mod)) + if self.gevent_threading_mod is not None: + _notify_patch(events.GeventDidPatchModuleEvent('threading', + self.gevent_threading_mod, + self.threading_mod)) + + def patch_threading_event_logging_existing_locks(self): + + self.gevent_threading_mod, patched_mod = _patch_module( + 'threading', + _warnings=self.warnings, + _notify_did_subscribers=False) + + assert patched_mod is self.threading_mod + + if self.Event: + self.patch_event() + + if self.existing_locks: + _patch_existing_locks(self.threading_mod) + + if self.logging and 'logging' in sys.modules: + self.patch_logging() + + def patch_event(self): + from .api import patch_item + from gevent.event import Event + patch_item(self.threading_mod, 'Event', Event) + # Python 2 had `Event` as a function returning + # the private class `_Event`. Some code may be relying + # on that. + if hasattr(self.threading_mod, '_Event'): + patch_item(self.threading_mod, '_Event', Event) + + def patch_logging(self): + from .api import patch_item + logging = __import__('logging') + patch_item(logging, '_lock', self.threading_mod.RLock()) + for wr in logging._handlerList: + # In py26, these are actual handlers, not weakrefs + handler = wr() if callable(wr) else wr + if handler is None: + continue + if not hasattr(handler, 'lock'): + raise TypeError("Unknown/unsupported handler %r" % handler) + handler.lock = self.threading_mod.RLock() + + def patch__threading_local(self): + _threading_local = __import__('_threading_local') + from .api import patch_item + from gevent.local import local + patch_item(_threading_local, 'local', local) + + def patch_active_threads(self): + raise NotImplementedError + + def patch_threading_shutdown_on_main_thread_not_already_patched(self): + raise NotImplementedError + + def patch_main_thread_cleanup(self): + # We create a bit of a reference cycle here, + # so main_thread doesn't get to be collected in a timely way. + # Not good. Take it out of dangling so we don't get + # warned about it. + main_thread = self.main_thread + self.threading_mod._dangling.remove(main_thread) + + # Patch up the ident of the main thread to match. This + # matters if threading was imported before monkey-patching + # thread + oldid = main_thread.ident + main_thread._ident = self.threading_mod.get_ident() + if oldid in self.threading_mod._active: + self.threading_mod._active[main_thread.ident] = self.threading_mod._active[oldid] + if oldid != main_thread.ident: + del self.threading_mod._active[oldid] + + def patch_shutdown_not_on_main_thread(self): + _queue_warning("Monkey-patching not on the main thread; " + "threading.main_thread().join() will hang from a greenlet", + self.warnings) + + from .api import patch_item + + main_thread = self.main_thread + threading_mod = self.threading_mod + get_ident = self.threading_mod.get_ident + orig_shutdown = self.orig_shutdown + def _shutdown(): + # We've patched get_ident but *did not* patch the + # main_thread.ident value. Beginning in Python 3.9.8 + # and then later releases (3.10.1, probably), the + # _main_thread object is only _stop() if the ident of + # the current thread (the *real* main thread) matches + # the ident of the _main_thread object. But without doing that, + # the main thread's shutdown lock (threading._shutdown_locks) is never + # removed *or released*, thus hanging the interpreter. + # XXX: There's probably a better way to do this. Probably need to take a + # step back and look at the whole picture. + main_thread._ident = get_ident() + orig_shutdown() + patch_item(threading_mod, '_shutdown', orig_shutdown) + patch_item(threading_mod, '_shutdown', _shutdown) + + @staticmethod # Static to be sure we don't accidentally capture `self` and keep it alive + def _make_existing_non_main_thread_join_func(thread, thread_greenlet, threading_mod): + from gevent.hub import sleep + from time import time + # TODO: This is almost the algorithm that the 3.13 _ThreadHandle class + # employs. UNIFY them. + def join(timeout=None): + end = None + if threading_mod.current_thread() is thread: + raise RuntimeError("Cannot join current thread") + if thread_greenlet is not None and thread_greenlet.dead: + return + # You may ask: Why not call thread_greenlet.join()? + # Well, in the one case we actually have a greenlet, it's the + # low-level greenlet.greenlet object for the main thread, which + # doesn't have a join method. + # + # You may ask: Why not become the main greenlet's *parent* + # so you can get notified when it finishes? Because you can't + # create a greenlet cycle (the current greenlet is a descendent + # of the parent), and nor can you set a greenlet's parent to None, + # so there can only ever be one greenlet with a parent of None: the main + # greenlet, the one we need to watch. + # + # You may ask: why not swizzle out the problematic lock on the main thread + # into a gevent friendly lock? Well, the interpreter actually depends on that + # for the main thread in threading._shutdown; see below. + + if not thread.is_alive(): + return + + if timeout: + end = time() + timeout + + while thread.is_alive(): + if end is not None and time() > end: + return + sleep(0.01) + return join diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_gte313.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_gte313.py new file mode 100644 index 0000000000000000000000000000000000000000..19ac85b0bfbda24cfeb71c362286dc0079f1063c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_gte313.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +""" +The implementation of thread patching for Python versions +after 3.13. + +Internal use only. +""" +import sys + + +from ._patch_thread_common import BasePatcher + +class Patcher(BasePatcher): + + + def patch_active_threads(self): + from gevent.threading import main_native_thread + + for thread in self.threading_mod._active.values(): + if thread == main_native_thread(): + from greenlet import getcurrent + from gevent.thread import _ThreadHandle + thread._after_fork = lambda new_ident=None: new_ident + thread._handle = _ThreadHandle() + thread._handle._set_greenlet(getcurrent()) + thread._ident = thread._handle.ident + assert thread.ident == thread._handle.ident + continue + thread.join = self._make_existing_non_main_thread_join_func(thread, + None, + self.threading_mod) + + def patch_threading_shutdown_on_main_thread_not_already_patched(self): + import greenlet + from .api import patch_item + + main_thread = self.main_thread + threading_mod = self.threading_mod + orig_shutdown = self.orig_shutdown + _greenlet = main_thread._greenlet = greenlet.getcurrent() + + def _shutdown(): + # Release anyone trying to join() me, + # and let us switch to them. + main_thread._handle._set_done() + from gevent import sleep + try: + sleep() + except: # pylint:disable=bare-except + # A greenlet could have .kill() us + # or .throw() to us. I'm the main greenlet, + # there's no where else for this to go. + from gevent import get_hub + get_hub().print_exception(_greenlet, *sys.exc_info()) + + # Now, this may have resulted in us getting stopped + # if some other greenlet actually just ran there. + # That's not good, we're not supposed to be stopped + # when we enter _shutdown. + class FakeHandle: + def is_done(self): + return False + def _set_done(self): + return + def join(self): + return + main_thread._handle = FakeHandle() + assert main_thread.is_alive() + # main_thread._is_stopped = False + # main_thread._tstate_lock = main_thread.__real_tstate_lock + # main_thread.__real_tstate_lock = None + # The only truly blocking native shutdown lock to + # acquire should be our own (hopefully), and the call to + # _stop that orig_shutdown makes will discard it. + + # XXX: What if more get spawned? + for t in list(threading_mod.enumerate()): + if t.daemon or t is main_thread: + continue + while t.is_alive(): + try: + t._handle.join(0.001) + except RuntimeError: + # Joining ourself. + t._handle._set_done() + break + + orig_shutdown() + patch_item(threading_mod, '_shutdown', self.orig_shutdown) + + patch_item(self.threading_mod, '_shutdown', _shutdown) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_lt313.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_lt313.py new file mode 100644 index 0000000000000000000000000000000000000000..146804dd97da0031e7aa1e94e8a42070f855a53d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_lt313.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +""" +The implementation of thread patching for Python versions +prior to 3.13. + +Internal use only. +""" +import sys + + +from ._patch_thread_common import BasePatcher + + +class Patcher(BasePatcher): + + def patch_active_threads(self): + from gevent.threading import main_native_thread + threading_mod = self.threading_mod + for thread in threading_mod._active.values(): + if thread == main_native_thread(): + continue + thread.join = self._make_existing_non_main_thread_join_func(thread, None, threading_mod) + + + def patch_threading_shutdown_on_main_thread_not_already_patched(self): + import greenlet + from .api import patch_item + threading_mod = self.threading_mod + main_thread = self.main_thread + orig_shutdown = self.orig_shutdown + + _greenlet = main_thread._greenlet = greenlet.getcurrent() + main_thread._gevent_real_tstate_lock = main_thread._tstate_lock + assert main_thread._gevent_real_tstate_lock is not None + # The interpreter will call threading._shutdown + # when the main thread exits and is about to + # go away. It is called *in* the main thread. This + # is a perfect place to notify other greenlets that + # the main thread is done. We do this by overriding the + # lock of the main thread during operation, and only restoring + # it to the native blocking version at shutdown time + # (the interpreter also has a reference to this lock in a + # C data structure). + main_thread._tstate_lock = threading_mod.Lock() + main_thread._tstate_lock.acquire() + + def _shutdown(): + # Release anyone trying to join() me, + # and let us switch to them. + if not main_thread._tstate_lock: + return + + main_thread._tstate_lock.release() + from gevent import sleep + try: + sleep() + except: # pylint:disable=bare-except + # A greenlet could have .kill() us + # or .throw() to us. I'm the main greenlet, + # there's no where else for this to go. + from gevent import get_hub + get_hub().print_exception(_greenlet, *sys.exc_info()) + + # Now, this may have resulted in us getting stopped + # if some other greenlet actually just ran there. + # That's not good, we're not supposed to be stopped + # when we enter _shutdown. + main_thread._is_stopped = False + main_thread._tstate_lock = main_thread._gevent_real_tstate_lock + main_thread._gevent_real_tstate_lock = None + # The only truly blocking native shutdown lock to + # acquire should be our own (hopefully), and the call to + # _stop that orig_shutdown makes will discard it. + + orig_shutdown() + patch_item(threading_mod, '_shutdown', orig_shutdown) + + patch_item(threading_mod, '_shutdown', _shutdown) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_state.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_state.py new file mode 100644 index 0000000000000000000000000000000000000000..d3315ac70021c7137e56ed2be3da29d43af7889f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_state.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +""" +State management and query functions for tracking and discovering what +has been patched. +""" +import logging + +logger = logging.getLogger(__name__) + + +# maps module name -> {attribute name: original item} +# e.g. "time" -> {"sleep": built-in function sleep} +# NOT A PUBLIC API. However, third-party monkey-patchers may be using +# it? TODO: Provide better API for them. +saved:dict = {} + + +def is_module_patched(mod_name): + """ + Check if a module has been replaced with a cooperative version. + + :param str mod_name: The name of the standard library module, + e.g., ``'socket'``. + + """ + return mod_name in saved + + +def is_object_patched(mod_name, item_name): + """ + Check if an object in a module has been replaced with a + cooperative version. + + :param str mod_name: The name of the standard library module, + e.g., ``'socket'``. + :param str item_name: The name of the attribute in the module, + e.g., ``'create_connection'``. + + """ + return is_module_patched(mod_name) and item_name in saved[mod_name] + + +def is_anything_patched(): + """ + Check if this module has done any patching in the current process. + This is currently only used in gevent tests. + + Not currently a documented, public API, because I'm not convinced + it is 100% reliable in the event of third-party patch functions that + don't use ``saved``. + + .. versionadded:: 21.1.0 + """ + return bool(saved) + +def _get_original(name, items): + d = saved.get(name, {}) + values = [] + module = None + for item in items: + if item in d: + values.append(d[item]) + else: + if module is None: + module = __import__(name) + values.append(getattr(module, item)) + return values + +def _save(module, attr_name, item): + saved.setdefault(module.__name__, {}).setdefault(attr_name, item) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_util.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ca12e06d2d6e1aed65afd039a8ac79fdf32c915e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_util.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +""" +Utilities used in patching. + +Internal use only. + +""" +import sys + + +def _notify_patch(event, _warnings=None): + # Raises DoNotPatch if we're not supposed to patch + from gevent.events import notify_and_call_entry_points + + event._warnings = _warnings + notify_and_call_entry_points(event) + +def _ignores_DoNotPatch(func): + + from functools import wraps + + @wraps(func) + def ignores(*args, **kwargs): + from gevent.events import DoNotPatch + try: + return func(*args, **kwargs) + except DoNotPatch: + return False + + return ignores + +def _check_availability(name): + """ + Test that the source and target modules for *name* are + available and return them. + + :raise ImportError: If the source or target cannot be imported. + :return: The tuple ``(gevent_module, target_module, target_module_name)`` + """ + # Always import the gevent module first. This helps us be sure we can + # use regular imports in gevent files (when we can't use gevent.monkey.get_original()) + gevent_module = getattr(__import__('gevent.' + name), name) + target_module_name = getattr(gevent_module, '__target__', name) + target_module = __import__(target_module_name) + + return gevent_module, target_module, target_module_name + + +def _patch_module(name, + items=None, + _warnings=None, + _patch_kwargs=None, + _notify_will_subscribers=True, + _notify_did_subscribers=True, + _call_hooks=True): + + from .api import patch_module + + gevent_module, target_module, target_module_name = _check_availability(name) + + patch_module(target_module, gevent_module, items=items, + _warnings=_warnings, _patch_kwargs=_patch_kwargs, + _notify_will_subscribers=_notify_will_subscribers, + _notify_did_subscribers=_notify_did_subscribers, + _call_hooks=_call_hooks) + + # On Python 2, the `futures` package will install + # a bunch of modules with the same name as those from Python 3, + # such as `_thread`; primarily these just do `from thread import *`, + # meaning we have alternate references. If that's already been imported, + # we need to attempt to patch that too. + + # Be sure to keep the original states matching also. + + alternate_names = getattr(gevent_module, '__alternate_targets__', ()) + from ._state import saved # TODO: Add apis for these use cases. + for alternate_name in alternate_names: + alternate_module = sys.modules.get(alternate_name) + if alternate_module is not None and alternate_module is not target_module: + saved.pop(alternate_name, None) + patch_module(alternate_module, gevent_module, items=items, + _warnings=_warnings, + _notify_will_subscribers=False, + _notify_did_subscribers=False, + _call_hooks=False) + saved[alternate_name] = saved[target_module_name] + + return gevent_module, target_module + + +def _queue_warning(message, _warnings): + # Queues a warning to show after the monkey-patching process is all done. + # Done this way to avoid extra imports during the process itself, just + # in case. If we're calling a function one-off (unusual) go ahead and do it + if _warnings is None: + _process_warnings([message]) + else: + _warnings.append(message) + + +def _process_warnings(_warnings): + import warnings + from ._errors import MonkeyPatchWarning + for warning in _warnings: + warnings.warn(warning, MonkeyPatchWarning, stacklevel=3) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/api.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/api.py new file mode 100644 index 0000000000000000000000000000000000000000..66642cfac23d79e6b9b9c458a62cf95d85d96b16 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/api.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +""" +Higher level functions that comprise parts of +the public monkey patching API. + + +""" + + +def get_original(mod_name, item_name): + """ + Retrieve the original object from a module. + + If the object has not been patched, then that object will still be + retrieved. + + :param str|sequence mod_name: The name of the standard library module, + e.g., ``'socket'``. Can also be a sequence of standard library + modules giving alternate names to try, e.g., ``('thread', '_thread')``; + the first importable module will supply all *item_name* items. + :param str|sequence item_name: A string or sequence of strings naming the + attribute(s) on the module ``mod_name`` to return. + + :return: The original value if a string was given for + ``item_name`` or a sequence of original values if a + sequence was passed. + """ + from ._state import _get_original + + mod_names = [mod_name] if isinstance(mod_name, str) else mod_name + if isinstance(item_name, str): + item_names = [item_name] + unpack = True + else: + item_names = item_name + unpack = False + + for mod in mod_names: + try: + result = _get_original(mod, item_names) + except ImportError: + if mod is mod_names[-1]: + raise + else: + return result[0] if unpack else result + +_NONE = object() + +def patch_item(module, attr, newitem): + from ._state import _save + + olditem = getattr(module, attr, _NONE) + if olditem is not _NONE: + _save(module, attr, olditem) + setattr(module, attr, newitem) + + +def remove_item(module, attr): + from ._state import _save + + olditem = getattr(module, attr, _NONE) + if olditem is _NONE: + return + _save(module, attr, olditem) + + delattr(module, attr) + +def patch_module(target_module, source_module, items=None, + _warnings=None, + _patch_kwargs=None, + _notify_will_subscribers=True, + _notify_did_subscribers=True, + _call_hooks=True): + """ + patch_module(target_module, source_module, items=None) + + Replace attributes in *target_module* with the attributes of the + same name in *source_module*. + + The *source_module* can provide some attributes to customize the process: + + * ``__implements__`` is a list of attribute names to copy; if not present, + the *items* keyword argument is mandatory. ``__implements__`` must only have + names from the standard library module in it. + * ``_gevent_will_monkey_patch(target_module, items, warn, **kwargs)`` + * ``_gevent_did_monkey_patch(target_module, items, warn, **kwargs)`` + These two functions in the *source_module* are called *if* they exist, + before and after copying attributes, respectively. The "will" function + may modify *items*. The value of *warn* is a function that should be called + with a single string argument to issue a warning to the user. If the "will" + function raises :exc:`gevent.events.DoNotPatch`, no patching will be done. These functions + are called before any event subscribers or plugins. + + :keyword list items: A list of attribute names to replace. If + not given, this will be taken from the *source_module* ``__implements__`` + attribute. + :return: A true value if patching was done, a false value if patching was canceled. + + .. versionadded:: 1.3b1 + """ + from gevent import events + from ._errors import _BadImplements + from ._util import _notify_patch + + if items is None: + try: + items = source_module.__implements__ + except AttributeError as e: + raise _BadImplements(source_module) from e + + if items is None: + raise _BadImplements(source_module) + + try: + if _call_hooks: + __call_module_hook(source_module, 'will', target_module, items, _warnings) + if _notify_will_subscribers: + _notify_patch( + events.GeventWillPatchModuleEvent(target_module.__name__, source_module, + target_module, items), + _warnings) + except events.DoNotPatch: + return False + + # Undocumented, internal use: If the module defines + # `_gevent_do_monkey_patch(patch_request: _GeventDoPatchRequest)` call that; + # the module is responsible for its own patching. + do_patch = getattr( + source_module, + '_gevent_do_monkey_patch', + _GeventDoPatchRequest.default_patch_items + ) + request = _GeventDoPatchRequest(target_module, source_module, items, _patch_kwargs) + do_patch(request) + + if _call_hooks: + __call_module_hook(source_module, 'did', target_module, items, _warnings) + + if _notify_did_subscribers: + # We allow turning off the broadcast of the 'did' event for the benefit + # of our internal functions which need to do additional work (besides copying + # attributes) before their patch can be considered complete. + _notify_patch( + events.GeventDidPatchModuleEvent(target_module.__name__, source_module, + target_module) + ) + + return True + +class _GeventDoPatchRequest(object): + + get_original = staticmethod(get_original) + + def __init__(self, + target_module, + source_module, + items, + patch_kwargs): + self.target_module = target_module + self.source_module = source_module + self.items = items + self.patch_kwargs = patch_kwargs or {} + + def __repr__(self): + return '<%s target=%r source=%r items=%r kwargs=%r>' % ( + self.__class__.__name__, + self.target_module, + self.source_module, + self.items, + self.patch_kwargs + ) + + def default_patch_items(self): + for attr in self.items: + patch_item(self.target_module, attr, getattr(self.source_module, attr)) + + def remove_item(self, target_module, *items): + if isinstance(target_module, str): + items = (target_module,) + items + target_module = self.target_module + + for item in items: + remove_item(target_module, item) + +def __call_module_hook(gevent_module, name, module, items, _warnings): + # This function can raise DoNotPatch on 'will' + + def warn(message): + from ._util import _queue_warning + _queue_warning(message, _warnings) + + func_name = '_gevent_' + name + '_monkey_patch' + try: + func = getattr(gevent_module, func_name) + except AttributeError: + func = lambda *args: None + + + func(module, items, warn) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/os.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/os.py new file mode 100644 index 0000000000000000000000000000000000000000..c23c326725ba1592aba26cf005834de5791faa53 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/os.py @@ -0,0 +1,543 @@ +""" +Low-level operating system functions from :mod:`os`. + +Cooperative I/O +=============== + +This module provides cooperative versions of :func:`os.read` and +:func:`os.write`. These functions are *not* monkey-patched; you +must explicitly call them or monkey patch them yourself. + +POSIX functions +--------------- + +On POSIX, non-blocking IO is available. + +- :func:`nb_read` +- :func:`nb_write` +- :func:`make_nonblocking` + +All Platforms +------------- + +On non-POSIX platforms (e.g., Windows), non-blocking IO is not +available. On those platforms (and on POSIX), cooperative IO can +be done with the threadpool. + +- :func:`tp_read` +- :func:`tp_write` + +Child Processes +=============== + +The functions :func:`fork` and (on POSIX) :func:`forkpty` and :func:`waitpid` can be used +to manage child processes. + +.. warning:: + + Forking a process that uses greenlets does not eliminate all non-running + greenlets. Any that were scheduled in the hub of the forking thread in the parent + remain scheduled in the child; compare this to how normal threads operate. (This behaviour + may change is a subsequent major release.) +""" + +from __future__ import absolute_import + +import os + +from gevent.hub import _get_hub_noargs as get_hub +from gevent.hub import reinit +from gevent._config import config +from gevent._util import copy_globals +import errno + +EAGAIN = getattr(errno, 'EAGAIN', 11) + +try: + import fcntl +except ImportError: + fcntl = None + +__implements__ = ['fork'] +__extensions__ = ['tp_read', 'tp_write'] + +_read = os.read +_write = os.write + + +ignored_errors = [EAGAIN, errno.EINTR] + + +if fcntl: + + __extensions__ += ['make_nonblocking', 'nb_read', 'nb_write'] + + def make_nonblocking(fd): + """Put the file descriptor *fd* into non-blocking mode if + possible. + + :return: A boolean value that evaluates to True if successful. + """ + flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0) + if not bool(flags & os.O_NONBLOCK): + fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) + return True + + def nb_read(fd, n): + """ + Read up to *n* bytes from file descriptor *fd*. Return a + byte string containing the bytes read, which may be shorter than + *n*. If end-of-file is reached, an empty string is returned. + + The descriptor must be in non-blocking mode. + """ + hub = None + event = None + try: + while 1: + try: + result = _read(fd, n) + return result + except OSError as e: + if e.errno not in ignored_errors: + raise + if hub is None: + hub = get_hub() + event = hub.loop.io(fd, 1) + hub.wait(event) + finally: + if event is not None: + event.close() + event = None + hub = None + + + def nb_write(fd, buf): + """ + Write some number of bytes from buffer *buf* to file + descriptor *fd*. Return the number of bytes written, which may + be less than the length of *buf*. + + The file descriptor must be in non-blocking mode. + """ + hub = None + event = None + try: + while 1: + try: + result = _write(fd, buf) + return result + except OSError as e: + if e.errno not in ignored_errors: + raise + if hub is None: + hub = get_hub() + event = hub.loop.io(fd, 2) + hub.wait(event) + finally: + if event is not None: + event.close() + event = None + hub = None + + +def tp_read(fd, n): + """Read up to *n* bytes from file descriptor *fd*. Return a string + containing the bytes read. If end-of-file is reached, an empty string + is returned. + + Reading is done using the threadpool. + """ + return get_hub().threadpool.apply(_read, (fd, n)) + + +def tp_write(fd, buf): + """Write bytes from buffer *buf* to file descriptor *fd*. Return the + number of bytes written. + + Writing is done using the threadpool. + """ + return get_hub().threadpool.apply(_write, (fd, buf)) + + +if hasattr(os, 'fork'): + # pylint:disable=function-redefined,redefined-outer-name + + _raw_fork = os.fork + + def fork_gevent(): + """ + Forks the process using :func:`os.fork` and prepares the + child process to continue using gevent before returning. + + .. note:: + + The PID returned by this function may not be waitable with + either the original :func:`os.waitpid` or this module's + :func:`waitpid` and it may not generate SIGCHLD signals if + libev child watchers are or ever have been in use. For + example, the :mod:`gevent.subprocess` module uses libev + child watchers (which parts of gevent use libev child + watchers is subject to change at any time). Most + applications should use :func:`fork_and_watch`, which is + monkey-patched as the default replacement for + :func:`os.fork` and implements the ``fork`` function of + this module by default, unless the environment variable + ``GEVENT_NOWAITPID`` is defined before this module is + imported. + + .. versionadded:: 1.1b2 + """ + import warnings + # The simple `catch_warnings(action='ignore', category=DeprecationWarning)` + # is only available in 3.11+. + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + result = _raw_fork() + if not result: + reinit() + return result + + def fork(): + """ + A wrapper for :func:`fork_gevent` for non-POSIX platforms. + """ + return fork_gevent() + + if hasattr(os, 'forkpty'): + _raw_forkpty = os.forkpty + + def forkpty_gevent(): + """ + Forks the process using :func:`os.forkpty` and prepares the + child process to continue using gevent before returning. + + Returns a tuple (pid, master_fd). The `master_fd` is *not* put into + non-blocking mode. + + Availability: Some Unix systems. + + .. seealso:: This function has the same limitations as :func:`fork_gevent`. + + .. versionadded:: 1.1b5 + """ + pid, master_fd = _raw_forkpty() + if not pid: + reinit() + return pid, master_fd + + forkpty = forkpty_gevent + + __implements__.append('forkpty') + __extensions__.append("forkpty_gevent") + + if hasattr(os, 'WNOWAIT') or hasattr(os, 'WNOHANG'): + # We can only do this on POSIX + import time + + _waitpid = os.waitpid + _WNOHANG = os.WNOHANG + + # replaced by the signal module. + _on_child_hook = lambda: None + + # {pid -> watcher or tuple(pid, rstatus, timestamp)} + _watched_children = {} + + def _on_child(watcher, callback): + # XXX: Could handle tracing here by not stopping + # until the pid is terminated + watcher.stop() + try: + _watched_children[watcher.pid] = (watcher.pid, watcher.rstatus, time.time()) + if callback: + callback(watcher) + # dispatch an "event"; used by gevent.signal.signal + _on_child_hook() + # now is as good a time as any to reap children + _reap_children() + finally: + watcher.close() + + def _reap_children(timeout=60): + # Remove all the dead children that haven't been waited on + # for the *timeout* seconds. + # Some platforms queue delivery of SIGCHLD for all children that die; + # in that case, a well-behaved application should call waitpid() for each + # signal. + # Some platforms (linux) only guarantee one delivery if multiple children + # die. On that platform, the well-behave application calls waitpid() in a loop + # until it gets back -1, indicating no more dead children need to be waited for. + # In either case, waitpid should be called the same number of times as dead children, + # thus removing all the watchers when a SIGCHLD arrives. The (generous) timeout + # is to work with applications that neglect to call waitpid and prevent "unlimited" + # growth. + # Note that we don't watch for the case of pid wraparound. That is, we fork a new + # child with the same pid as an existing watcher, but the child is already dead, + # just not waited on yet. + now = time.time() + oldest_allowed = now - timeout + dead = [ + pid for pid, val + in _watched_children.items() + if isinstance(val, tuple) and val[2] < oldest_allowed + ] + for pid in dead: + del _watched_children[pid] + + def waitpid(pid, options): + """ + Wait for a child process to finish. + + If the child process was spawned using + :func:`fork_and_watch`, then this function behaves + cooperatively. If not, it *may* have race conditions; see + :func:`fork_gevent` for more information. + + The arguments are as for the underlying + :func:`os.waitpid`. Some combinations of *options* may not + be supported cooperatively (as of 1.1 that includes + WUNTRACED). Using a *pid* of 0 to request waiting on only processes + from the current process group is not cooperative. A *pid* of -1 + to wait for any child is non-blocking, but may or may not + require a trip around the event loop, depending on whether any children + have already terminated but not been waited on. + + Availability: POSIX. + + .. versionadded:: 1.1b1 + .. versionchanged:: 1.2a1 + More cases are handled in a cooperative manner. + """ + # pylint: disable=too-many-return-statements + # XXX Does not handle tracing children + + # So long as libev's loop doesn't run, it's OK to add + # child watchers. The SIGCHLD handler only feeds events + # for the next iteration of the loop to handle. (And the + # signal handler itself is only called from the next loop + # iteration.) + + if pid <= 0: + # magic functions for multiple children. + if pid == -1: + # Any child. If we have one that we're watching + # and that finished, we will use that one, + # preferring the oldest. Otherwise, let the OS + # take care of it. + finished_at = None + for k, v in _watched_children.items(): + if ( + isinstance(v, tuple) + and (finished_at is None or v[2] < finished_at) + ): + pid = k + finished_at = v[2] + + if pid <= 0: + # We didn't have one that was ready. If there are + # no funky options set, and the pid was -1 + # (meaning any process, not 0, which means process + # group--- libev doesn't know about process + # groups) then we can use a child watcher of pid 0; otherwise, + # pass through to the OS. + if pid == -1 and options == 0: + hub = get_hub() + with hub.loop.child(0, False) as watcher: + hub.wait(watcher) + return watcher.rpid, watcher.rstatus + # There were funky options/pid, so we must go to the OS. + return _waitpid(pid, options) + + if pid in _watched_children: + # yes, we're watching it + + # Note that the remainder of this code must be careful to NOT + # yield to the event loop except at well known times, or + # we have a race condition between the _on_child callback and the + # code here that could lead to a process to hang. + if options & _WNOHANG or isinstance(_watched_children[pid], tuple): + # We're either asked not to block, or it already finished, in which + # case blocking doesn't matter + result = _watched_children[pid] + if isinstance(result, tuple): + # it finished. libev child watchers + # are one-shot + del _watched_children[pid] + return result[:2] + # it's not finished + return (0, 0) + + # Ok, we need to "block". Do so via a watcher so that we're + # cooperative. We know it's our child, etc, so this should work. + watcher = _watched_children[pid] + # We can't start a watcher that's already started, + # so we can't reuse the existing watcher. Notice that the + # old watcher must not have fired already, or during this time, but + # only after we successfully `start()` the watcher. So this must + # not yield to the event loop. + with watcher.loop.child(pid, False) as new_watcher: + get_hub().wait(new_watcher) + # Ok, so now the new watcher is done. That means + # the old watcher's callback (_on_child) should + # have fired, potentially taking this child out of + # _watched_children (but that could depend on how + # many callbacks there were to run, so use the + # watcher object directly; libev sets all the + # watchers at the same time). + return watcher.rpid, watcher.rstatus + + # we're not watching it and it may not even be our child, + # so we must go to the OS to be sure to get the right semantics (exception) + # XXX + # libuv has a race condition because the signal + # handler is a Python function, so the InterruptedError + # is raised before the signal handler runs and calls the + # child watcher + # we're not watching it + return _waitpid(pid, options) + + def _watch_child(pid, callback=None, loop=None, ref=False): + loop = loop or get_hub().loop + watcher = loop.child(pid, ref=ref) + _watched_children[pid] = watcher + watcher.start(_on_child, watcher, callback) + + def fork_and_watch(callback=None, loop=None, ref=False, fork=fork_gevent): + """ + Fork a child process and start a child watcher for it in the parent process. + + This call cooperates with :func:`waitpid` to enable cooperatively waiting + for children to finish. When monkey-patching, these functions are patched in as + :func:`os.fork` and :func:`os.waitpid`, respectively. + + In the child process, this function calls :func:`gevent.hub.reinit` before returning. + + Availability: POSIX. + + :keyword callback: If given, a callable that will be called with the child watcher + when the child finishes. + :keyword loop: The loop to start the watcher in. Defaults to the + loop of the current hub. + :keyword fork: The fork function. Defaults to :func:`the one defined in this + module ` (which automatically calls :func:`gevent.hub.reinit`). + Pass the builtin :func:`os.fork` function if you do not need to + initialize gevent in the child process. + + .. versionadded:: 1.1b1 + .. seealso:: + :func:`gevent.monkey.get_original` To access the builtin :func:`os.fork`. + """ + pid = fork() + if pid: + # parent + _watch_child(pid, callback, loop, ref) + return pid + + __extensions__.append('fork_and_watch') + __extensions__.append('fork_gevent') + + if 'forkpty' in __implements__: + def forkpty_and_watch(callback=None, loop=None, ref=False, forkpty=forkpty_gevent): + """ + Like :func:`fork_and_watch`, except using :func:`forkpty_gevent`. + + Availability: Some Unix systems. + + .. versionadded:: 1.1b5 + """ + result = [] + + def _fork(): + pid_and_fd = forkpty() + result.append(pid_and_fd) + return pid_and_fd[0] + fork_and_watch(callback, loop, ref, _fork) + return result[0] + + __extensions__.append('forkpty_and_watch') + + # Watch children by default + if not config.disable_watch_children: + # Broken out into separate functions instead of simple name aliases + # for documentation purposes. + def fork(*args, **kwargs): + """ + Forks a child process and starts a child watcher for it in the + parent process so that ``waitpid`` and SIGCHLD work as expected. + + This implementation of ``fork`` is a wrapper for :func:`fork_and_watch` + when the environment variable ``GEVENT_NOWAITPID`` is *not* defined. + This is the default and should be used by most applications. + + .. versionchanged:: 1.1b2 + """ + # take any args to match fork_and_watch + return fork_and_watch(*args, **kwargs) + + if 'forkpty' in __implements__: + def forkpty(*args, **kwargs): + """ + Like :func:`fork`, but using :func:`forkpty_gevent`. + + This implementation of ``forkpty`` is a wrapper for :func:`forkpty_and_watch` + when the environment variable ``GEVENT_NOWAITPID`` is *not* defined. + This is the default and should be used by most applications. + + .. versionadded:: 1.1b5 + """ + # take any args to match fork_and_watch + return forkpty_and_watch(*args, **kwargs) + __implements__.append("waitpid") + + if hasattr(os, 'posix_spawn'): + _raw_posix_spawn = os.posix_spawn + _raw_posix_spawnp = os.posix_spawnp + + def posix_spawn(*args, **kwargs): + pid = _raw_posix_spawn(*args, **kwargs) + _watch_child(pid) + return pid + + def posix_spawnp(*args, **kwargs): + pid = _raw_posix_spawnp(*args, **kwargs) + _watch_child(pid) + return pid + + __implements__.append("posix_spawn") + __implements__.append("posix_spawnp") + else: + def fork(): + """ + Forks a child process, initializes gevent in the child, + but *does not* prepare the parent to wait for the child or receive SIGCHLD. + + This implementation of ``fork`` is a wrapper for :func:`fork_gevent` + when the environment variable ``GEVENT_NOWAITPID`` *is* defined. + This is not recommended for most applications. + """ + return fork_gevent() + + if 'forkpty' in __implements__: + def forkpty(): + """ + Like :func:`fork`, but using :func:`os.forkpty` + + This implementation of ``forkpty`` is a wrapper for :func:`forkpty_gevent` + when the environment variable ``GEVENT_NOWAITPID`` *is* defined. + This is not recommended for most applications. + + .. versionadded:: 1.1b5 + """ + return forkpty_gevent() + __extensions__.append("waitpid") + +else: + __implements__.remove('fork') + + +__imports__ = copy_globals(os, globals(), + names_to_ignore=__implements__ + __extensions__, + dunder_names_to_keep=()) + +__all__ = list(set(__implements__ + __extensions__)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pool.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..411957953b523879b7aab8f0410e882218109577 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pool.py @@ -0,0 +1,677 @@ +# Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details. +""" +Managing greenlets in a group. + +The :class:`Group` class in this module abstracts a group of running +greenlets. When a greenlet dies, it's automatically removed from the +group. All running greenlets in a group can be waited on with +:meth:`Group.join`, or all running greenlets can be killed with +:meth:`Group.kill`. + +The :class:`Pool` class, which is a subclass of :class:`Group`, +provides a way to limit concurrency: its :meth:`spawn ` +method blocks if the number of greenlets in the pool has already +reached the limit, until there is a free slot. +""" +from __future__ import print_function, absolute_import, division + + +from gevent.hub import GreenletExit, getcurrent, kill as _kill +from gevent.greenlet import joinall, Greenlet +from gevent.queue import Full as QueueFull +from gevent.timeout import Timeout +from gevent.event import Event +from gevent.lock import Semaphore, DummySemaphore + +from gevent._compat import izip +from gevent._imap import IMap +from gevent._imap import IMapUnordered + +__all__ = [ + 'Group', + 'Pool', + 'PoolFull', +] + + + + +class GroupMappingMixin(object): + # Internal, non-public API class. + # Provides mixin methods for implementing mapping pools. Subclasses must define: + + __slots__ = () + + def spawn(self, func, *args, **kwargs): + """ + A function that runs *func* with *args* and *kwargs*, potentially + asynchronously. Return a value with a ``get`` method that blocks + until the results of func are available, and a ``rawlink`` method + that calls a callback when the results are available. + + If this object has an upper bound on how many asyncronously executing + tasks can exist, this method may block until a slot becomes available. + """ + raise NotImplementedError() + + def _apply_immediately(self): + """ + should the function passed to apply be called immediately, + synchronously? + """ + raise NotImplementedError() + + def _apply_async_use_greenlet(self): + """ + Should apply_async directly call Greenlet.spawn(), bypassing + `spawn`? + + Return true when self.spawn would block. + """ + raise NotImplementedError() + + def _apply_async_cb_spawn(self, callback, result): + """ + Run the given callback function, possibly + asynchronously, possibly synchronously. + """ + raise NotImplementedError() + + def apply_cb(self, func, args=None, kwds=None, callback=None): + """ + :meth:`apply` the given *func(\\*args, \\*\\*kwds)*, and, if a *callback* is given, run it with the + results of *func* (unless an exception was raised.) + + The *callback* may be called synchronously or asynchronously. If called + asynchronously, it will not be tracked by this group. (:class:`Group` and :class:`Pool` + call it asynchronously in a new greenlet; :class:`~gevent.threadpool.ThreadPool` calls + it synchronously in the current greenlet.) + """ + result = self.apply(func, args, kwds) + if callback is not None: + self._apply_async_cb_spawn(callback, result) + return result + + def apply_async(self, func, args=None, kwds=None, callback=None): + """ + A variant of the :meth:`apply` method which returns a :class:`~.Greenlet` object. + + When the returned greenlet gets to run, it *will* call :meth:`apply`, + passing in *func*, *args* and *kwds*. + + If *callback* is specified, then it should be a callable which + accepts a single argument. When the result becomes ready + callback is applied to it (unless the call failed). + + This method will never block, even if this group is full (that is, + even if :meth:`spawn` would block, this method will not). + + .. caution:: The returned greenlet may or may not be tracked + as part of this group, so :meth:`joining ` this group is + not a reliable way to wait for the results to be available or + for the returned greenlet to run; instead, join the returned + greenlet. + + .. tip:: Because :class:`~.ThreadPool` objects do not track greenlets, the returned + greenlet will never be a part of it. To reduce overhead and improve performance, + :class:`Group` and :class:`Pool` may choose to track the returned + greenlet. These are implementation details that may change. + """ + if args is None: + args = () + if kwds is None: + kwds = {} + if self._apply_async_use_greenlet(): + # cannot call self.spawn() directly because it will block + # XXX: This is always the case for ThreadPool, but for Group/Pool + # of greenlets, this is only the case when they are full...hence + # the weasely language about "may or may not be tracked". Should we make + # Group/Pool always return true as well so it's never tracked by any + # implementation? That would simplify that logic, but could increase + # the total number of greenlets in the system and add a layer of + # overhead for the simple cases when the pool isn't full. + return Greenlet.spawn(self.apply_cb, func, args, kwds, callback) + + greenlet = self.spawn(func, *args, **kwds) + if callback is not None: + greenlet.link(pass_value(callback)) + return greenlet + + def apply(self, func, args=None, kwds=None): + """ + Rough quivalent of the :func:`apply()` builtin function blocking until + the result is ready and returning it. + + The ``func`` will *usually*, but not *always*, be run in a way + that allows the current greenlet to switch out (for example, + in a new greenlet or thread, depending on implementation). But + if the current greenlet or thread is already one that was + spawned by this pool, the pool may choose to immediately run + the `func` synchronously. + + Any exception ``func`` raises will be propagated to the caller of ``apply`` (that is, + this method will raise the exception that ``func`` raised). + """ + if args is None: + args = () + if kwds is None: + kwds = {} + if self._apply_immediately(): + return func(*args, **kwds) + return self.spawn(func, *args, **kwds).get() + + def __map(self, func, iterable): + return [g.get() for g in + [self.spawn(func, i) for i in iterable]] + + def map(self, func, iterable): + """Return a list made by applying the *func* to each element of + the iterable. + + .. seealso:: :meth:`imap` + """ + # We can't return until they're all done and in order. It + # wouldn't seem to much matter what order we wait on them in, + # so the simple, fast (50% faster than imap) solution would be: + + # return [g.get() for g in + # [self.spawn(func, i) for i in iterable]] + + # If the pool size is unlimited (or more than the len(iterable)), this + # is equivalent to imap (spawn() will never block, all of them run concurrently, + # we call get() in the order the iterable was given). + + # Now lets imagine the pool if is limited size. Suppose the + # func is time.sleep, our pool is limited to 3 threads, and + # our input is [10, 1, 10, 1, 1] We would start three threads, + # one to sleep for 10, one to sleep for 1, and the last to + # sleep for 10. We would block starting the fourth thread. At + # time 1, we would finish the second thread and start another + # one for time 1. At time 2, we would finish that one and + # start the last thread, and then begin executing get() on the first + # thread. + + # Because it's spawn that blocks, this is *also* equivalent to what + # imap would do. + + # The one remaining difference is that imap runs in its own + # greenlet, potentially changing the way the event loop runs. + # That's easy enough to do. + + g = Greenlet.spawn(self.__map, func, iterable) + return g.get() + + def map_cb(self, func, iterable, callback=None): + result = self.map(func, iterable) + if callback is not None: + callback(result) # pylint:disable=not-callable + return result + + def map_async(self, func, iterable, callback=None): + """ + A variant of the map() method which returns a Greenlet object that is executing + the map function. + + If callback is specified then it should be a callable which accepts a + single argument. + """ + return Greenlet.spawn(self.map_cb, func, iterable, callback) + + def __imap(self, cls, func, *iterables, **kwargs): + # Python 2 doesn't support the syntax that lets us mix varargs and + # a named kwarg, so we have to unpack manually + maxsize = kwargs.pop('maxsize', None) + if kwargs: + raise TypeError("Unsupported keyword arguments") + return cls.spawn(func, izip(*iterables), spawn=self.spawn, + _zipped=True, maxsize=maxsize) + + def imap(self, func, *iterables, **kwargs): + """ + imap(func, *iterables, maxsize=None) -> iterable + + An equivalent of :func:`itertools.imap`, operating in parallel. + The *func* is applied to each element yielded from each + iterable in *iterables* in turn, collecting the result. + + If this object has a bound on the number of active greenlets it can + contain (such as :class:`Pool`), then at most that number of tasks will operate + in parallel. + + :keyword int maxsize: If given and not-None, specifies the maximum number of + finished results that will be allowed to accumulate awaiting the reader; + more than that number of results will cause map function greenlets to begin + to block. This is most useful if there is a great disparity in the speed of + the mapping code and the consumer and the results consume a great deal of resources. + + .. note:: This is separate from any bound on the number of active parallel + tasks, though they may have some interaction (for example, limiting the + number of parallel tasks to the smallest bound). + + .. note:: Using a bound is slightly more computationally expensive than not using a bound. + + .. tip:: The :meth:`imap_unordered` method makes much better + use of this parameter. Some additional, unspecified, + number of objects may be required to be kept in memory + to maintain order by this function. + + :return: An iterable object. + + .. versionchanged:: 1.1b3 + Added the *maxsize* keyword parameter. + .. versionchanged:: 1.1a1 + Accept multiple *iterables* to iterate in parallel. + """ + return self.__imap(IMap, func, *iterables, **kwargs) + + def imap_unordered(self, func, *iterables, **kwargs): + """ + imap_unordered(func, *iterables, maxsize=None) -> iterable + + The same as :meth:`imap` except that the ordering of the results + from the returned iterator should be considered in arbitrary + order. + + This is lighter weight than :meth:`imap` and should be preferred if order + doesn't matter. + + .. seealso:: :meth:`imap` for more details. + """ + return self.__imap(IMapUnordered, func, *iterables, **kwargs) + + +class Group(GroupMappingMixin): + """ + Maintain a group of greenlets that are still running, without + limiting their number. + + Links to each item and removes it upon notification. + + Groups can be iterated to discover what greenlets they are tracking, + they can be tested to see if they contain a greenlet, and they know the + number (len) of greenlets they are tracking. If they are not tracking any + greenlets, they are False in a boolean context. + + .. attribute:: greenlet_class + + Either :class:`gevent.Greenlet` (the default) or a subclass. + These are the type of + object we will :meth:`spawn`. This can be + changed on an instance or in a subclass. + """ + + greenlet_class = Greenlet + + def __init__(self, *args): + assert len(args) <= 1, args + self.greenlets = set(*args) + if args: + for greenlet in args[0]: + greenlet.rawlink(self._discard) + # each item we kill we place in dying, to avoid killing the same greenlet twice + self.dying = set() + self._empty_event = Event() + self._empty_event.set() + + def __repr__(self): + return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self.greenlets) + + def __len__(self): + """ + Answer how many greenlets we are tracking. Note that if we are empty, + we are False in a boolean context. + """ + return len(self.greenlets) + + def __contains__(self, item): + """ + Answer if we are tracking the given greenlet. + """ + return item in self.greenlets + + def __iter__(self): + """ + Iterate across all the greenlets we are tracking, in no particular order. + """ + return iter(self.greenlets) + + def add(self, greenlet): + """ + Begin tracking the *greenlet*. + + If this group is :meth:`full`, then this method may block + until it is possible to track the greenlet. + + Typically the *greenlet* should **not** be started when + it is added because if this object blocks in this method, + then the *greenlet* may run to completion before it is tracked. + """ + try: + rawlink = greenlet.rawlink + except AttributeError: + pass # non-Greenlet greenlet, like MAIN + else: + rawlink(self._discard) + self.greenlets.add(greenlet) + self._empty_event.clear() + + def _discard(self, greenlet): + self.greenlets.discard(greenlet) + self.dying.discard(greenlet) + if not self.greenlets: + self._empty_event.set() + + def discard(self, greenlet): + """ + Stop tracking the greenlet. + """ + self._discard(greenlet) + try: + unlink = greenlet.unlink + except AttributeError: + pass # non-Greenlet greenlet, like MAIN + else: + unlink(self._discard) + + def start(self, greenlet): + """ + Add the **unstarted** *greenlet* to the collection of greenlets + this group is monitoring, and then start it. + """ + self.add(greenlet) + greenlet.start() + + def spawn(self, *args, **kwargs): # pylint:disable=arguments-differ + """ + Begin a new greenlet with the given arguments (which are passed + to the greenlet constructor) and add it to the collection of greenlets + this group is monitoring. + + :return: The newly started greenlet. + """ + greenlet = self.greenlet_class(*args, **kwargs) + self.start(greenlet) + return greenlet + +# def close(self): +# """Prevents any more tasks from being submitted to the pool""" +# self.add = RaiseException("This %s has been closed" % self.__class__.__name__) + + def join(self, timeout=None, raise_error=False): + """ + Wait for this group to become empty *at least once*. + + If there are no greenlets in the group, returns immediately. + + .. note:: By the time the waiting code (the caller of this + method) regains control, a greenlet may have been added to + this group, and so this object may no longer be empty. (That + is, ``group.join(); assert len(group) == 0`` is not + guaranteed to hold.) This method only guarantees that the group + reached a ``len`` of 0 at some point. + + :keyword bool raise_error: If True (*not* the default), if any + greenlet that finished while the join was in progress raised + an exception, that exception will be raised to the caller of + this method. If multiple greenlets raised exceptions, which + one gets re-raised is not determined. Only greenlets currently + in the group when this method is called are guaranteed to + be checked for exceptions. + + :return bool: A value indicating whether this group became empty. + If the timeout is specified and the group did not become empty + during that timeout, then this will be a false value. Otherwise + it will be a true value. + + .. versionchanged:: 1.2a1 + Add the return value. + """ + greenlets = list(self.greenlets) if raise_error else () + result = self._empty_event.wait(timeout=timeout) + + for greenlet in greenlets: + if greenlet.exception is not None: + if hasattr(greenlet, '_raise_exception'): + greenlet._raise_exception() + raise greenlet.exception + + return result + + def kill(self, exception=GreenletExit, block=True, timeout=None): + """ + Kill all greenlets being tracked by this group. + """ + timer = Timeout._start_new_or_dummy(timeout) + try: + while self.greenlets: + for greenlet in list(self.greenlets): + if greenlet in self.dying: + continue + try: + kill = greenlet.kill + except AttributeError: + _kill(greenlet, exception) + else: + kill(exception, block=False) + self.dying.add(greenlet) + if not block: + break + joinall(self.greenlets) + except Timeout as ex: + if ex is not timer: + raise + finally: + timer.cancel() + + def killone(self, greenlet, exception=GreenletExit, block=True, timeout=None): + """ + If the given *greenlet* is running and being tracked by this group, + kill it. + """ + if greenlet not in self.dying and greenlet in self.greenlets: + greenlet.kill(exception, block=False) + self.dying.add(greenlet) + if block: + greenlet.join(timeout) + + def full(self): + """ + Return a value indicating whether this group can track more greenlets. + + In this implementation, because there are no limits on the number of + tracked greenlets, this will always return a ``False`` value. + """ + return False + + def wait_available(self, timeout=None): + """ + Block until it is possible to :meth:`spawn` a new greenlet. + + In this implementation, because there are no limits on the number + of tracked greenlets, this will always return immediately. + """ + + # MappingMixin methods + + def _apply_immediately(self): + # If apply() is called from one of our own + # worker greenlets, don't spawn a new one---if we're full, that + # could deadlock. + return getcurrent() in self + + def _apply_async_cb_spawn(self, callback, result): + Greenlet.spawn(callback, result) + + def _apply_async_use_greenlet(self): + # cannot call self.spawn() because it will block, so + # use a fresh, untracked greenlet that when run will + # (indirectly) call self.spawn() for us. + return self.full() + + + +class PoolFull(QueueFull): + """ + Raised when a Pool is full and an attempt was made to + add a new greenlet to it in non-blocking mode. + """ + + +class Pool(Group): + + def __init__(self, size=None, greenlet_class=None): + """ + Create a new pool. + + A pool is like a group, but the maximum number of members + is governed by the *size* parameter. + + :keyword int size: If given, this non-negative integer is the + maximum count of active greenlets that will be allowed in + this pool. A few values have special significance: + + * `None` (the default) places no limit on the number of + greenlets. This is useful when you want to track, but not limit, + greenlets. In general, a :class:`Group` + may be a more efficient way to achieve the same effect, but some things + need the additional abilities of this class (one example being the *spawn* + parameter of :class:`gevent.baseserver.BaseServer` and + its subclass :class:`gevent.pywsgi.WSGIServer`). + + * ``0`` creates a pool that can never have any active greenlets. Attempting + to spawn in this pool will block forever. This is only useful + if an application uses :meth:`wait_available` with a timeout and checks + :meth:`free_count` before attempting to spawn. + """ + if size is not None and size < 0: + raise ValueError('size must not be negative: %r' % (size, )) + Group.__init__(self) + self.size = size + if greenlet_class is not None: + self.greenlet_class = greenlet_class + if size is None: + factory = DummySemaphore + else: + factory = Semaphore + self._semaphore = factory(size) + + def wait_available(self, timeout=None): + """ + Wait until it's possible to spawn a greenlet in this pool. + + :param float timeout: If given, only wait the specified number + of seconds. + + .. warning:: If the pool was initialized with a size of 0, this + method will block forever unless a timeout is given. + + :return: A number indicating how many new greenlets can be put into + the pool without blocking. + + .. versionchanged:: 1.1a3 + Added the ``timeout`` parameter. + """ + return self._semaphore.wait(timeout=timeout) + + def full(self): + """ + Return a boolean indicating whether this pool is full, e.g. if + :meth:`add` would block. + + :return: False if there is room for new members, True if there isn't. + """ + return self.free_count() <= 0 + + def free_count(self): + """ + Return a number indicating *approximately* how many more members + can be added to this pool. + """ + if self.size is None: + return 1 + return max(0, self.size - len(self)) + + def start(self, greenlet, *args, **kwargs): # pylint:disable=arguments-differ + """ + start(greenlet, blocking=True, timeout=None) -> None + + Add the **unstarted** *greenlet* to the collection of greenlets + this group is monitoring and then start it. + + Parameters are as for :meth:`add`. + """ + self.add(greenlet, *args, **kwargs) + greenlet.start() + + def add(self, greenlet, blocking=True, timeout=None): # pylint:disable=arguments-differ + """ + Begin tracking the given **unstarted** greenlet, possibly blocking + until space is available. + + Usually you should call :meth:`start` to track and start the greenlet + instead of using this lower-level method, or :meth:`spawn` to + also create the greenlet. + + :keyword bool blocking: If True (the default), this function + will block until the pool has space or a timeout occurs. If + False, this function will immediately raise a Timeout if the + pool is currently full. + :keyword float timeout: The maximum number of seconds this + method will block, if ``blocking`` is True. (Ignored if + ``blocking`` is False.) + :raises PoolFull: if either ``blocking`` is False and the pool + was full, or if ``blocking`` is True and ``timeout`` was + exceeded. + + .. caution:: If the *greenlet* has already been started and + *blocking* is true, then the greenlet may run to completion + while the current greenlet blocks waiting to track it. This would + enable higher concurrency than desired. + + .. seealso:: :meth:`Group.add` + + .. versionchanged:: 1.3.0 Added the ``blocking`` and + ``timeout`` parameters. + """ + if not self._semaphore.acquire(blocking=blocking, timeout=timeout): + # We failed to acquire the semaphore. + # If blocking was True, then there was a timeout. If blocking was + # False, then there was no capacity. Either way, raise PoolFull. + raise PoolFull() + + try: + Group.add(self, greenlet) + except: + self._semaphore.release() + raise + + def _discard(self, greenlet): + Group._discard(self, greenlet) + self._semaphore.release() + + +class pass_value(object): + __slots__ = ['callback'] + + def __init__(self, callback): + self.callback = callback + + def __call__(self, source): + if source.successful(): + self.callback(source.value) + + def __hash__(self): + return hash(self.callback) + + def __eq__(self, other): + return self.callback == getattr(other, 'callback', other) + + def __str__(self): + return str(self.callback) + + def __repr__(self): + return repr(self.callback) + + def __getattr__(self, item): + assert item != 'callback' + return getattr(self.callback, item) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pywsgi.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pywsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..918ea480e06bd30ee92c36bbdc83dbe38329bb19 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pywsgi.py @@ -0,0 +1,1727 @@ +# Copyright (c) 2005-2009, eventlet contributors +# Copyright (c) 2009-2018, gevent contributors +""" +A pure-Python, gevent-friendly WSGI server implementing HTTP/1.1. + +The server is provided in :class:`WSGIServer`, but most of the actual +WSGI work is handled by :class:`WSGIHandler` --- a new instance is +created for each request. The server can be customized to use +different subclasses of :class:`WSGIHandler`. + +.. important:: + + This server is intended primarily for development and testing, and + secondarily for other "safe" scenarios where it will not be exposed to + potentially malicious input. The code has not been security audited, + and is not intended for direct exposure to the public Internet. For production + usage on the Internet, either choose a production-strength server such as + gunicorn, or put a reverse proxy between gevent and the Internet. + +.. versionchanged:: 23.9.0 + + Complies more closely with the HTTP specification for chunked transfer encoding. + In particular, we are much stricter about trailers, and trailers that + are invalid (too long or featuring disallowed characters) forcibly close + the connection to the client *after* the results have been sent. + + Trailers otherwise continue to be ignored and are not available to the + WSGI application. + +""" +from __future__ import absolute_import + +# FIXME: Can we refactor to make smallor? +# pylint:disable=too-many-lines + +import errno +from io import BytesIO +import string +import sys +import time +import traceback +from datetime import datetime + +from urllib.parse import unquote + +from gevent import socket +import gevent +from gevent.server import StreamServer +from gevent.hub import GreenletExit +from gevent._compat import reraise + +from functools import partial +unquote_latin1 = partial(unquote, encoding='latin-1') + +_no_undoc_members = True # Don't put undocumented things into sphinx + +__all__ = [ + 'WSGIServer', + 'WSGIHandler', + 'LoggingLogAdapter', + 'Environ', + 'SecureEnviron', + 'WSGISecureEnviron', +] + + +MAX_REQUEST_LINE = 8192 +# Weekday and month names for HTTP date/time formatting; always English! +_WEEKDAYNAME = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHNAME = (None, # Dummy so we can use 1-based month numbers + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") + +# The contents of the "HEX" grammar rule for HTTP, upper and lowercase A-F plus digits, +# in byte form for comparing to the network. +_HEX = string.hexdigits.encode('ascii') + +# The characters allowed in "token" rules. + +# token = 1*tchar +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" +# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" +# / DIGIT / ALPHA +# ; any VCHAR, except delimiters +# ALPHA = %x41-5A / %x61-7A ; A-Z / a-z +_ALLOWED_TOKEN_CHARS = frozenset( + # Remember we have to be careful because bytestrings + # inexplicably iterate as integers, which are not equal to bytes. + + # explicit chars then DIGIT + (c.encode('ascii') for c in "!#$%&'*+-.^_`|~0123456789") + # Then we add ALPHA +) | {c.encode('ascii') for c in string.ascii_letters} +assert b'A' in _ALLOWED_TOKEN_CHARS + + +# Errors +_ERRORS = {} +_INTERNAL_ERROR_STATUS = '500 Internal Server Error' +_INTERNAL_ERROR_BODY = b'Internal Server Error' +_INTERNAL_ERROR_HEADERS = ( + ('Content-Type', 'text/plain'), + ('Connection', 'close'), + ('Content-Length', str(len(_INTERNAL_ERROR_BODY))) +) +_ERRORS[500] = (_INTERNAL_ERROR_STATUS, _INTERNAL_ERROR_HEADERS, _INTERNAL_ERROR_BODY) + +_BAD_REQUEST_STATUS = '400 Bad Request' +_BAD_REQUEST_BODY = '' +_BAD_REQUEST_HEADERS = ( + ('Content-Type', 'text/plain'), + ('Connection', 'close'), + ('Content-Length', str(len(_BAD_REQUEST_BODY))) +) +_ERRORS[400] = (_BAD_REQUEST_STATUS, _BAD_REQUEST_HEADERS, _BAD_REQUEST_BODY) + +_REQUEST_TOO_LONG_RESPONSE = b"HTTP/1.1 414 Request URI Too Long\r\nConnection: close\r\nContent-length: 0\r\n\r\n" +_BAD_REQUEST_RESPONSE = b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-length: 0\r\n\r\n" +_CONTINUE_RESPONSE = b"HTTP/1.1 100 Continue\r\n\r\n" + + +def format_date_time(timestamp): + # Return a byte-string of the date and time in HTTP format + # .. versionchanged:: 1.1b5 + # Return a byte string, not a native string + year, month, day, hh, mm, ss, wd, _y, _z = time.gmtime(timestamp) + value = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (_WEEKDAYNAME[wd], day, _MONTHNAME[month], year, hh, mm, ss) + value = value.encode("latin-1") + return value + + +class _InvalidClientInput(IOError): + # Internal exception raised by Input indicating that the client + # sent invalid data at the lowest level of the stream. The result + # *should* be a HTTP 400 error. + pass + + +class _InvalidClientRequest(ValueError): + # Internal exception raised by WSGIHandler.read_request indicating + # that the client sent an HTTP request that cannot be parsed + # (e.g., invalid grammar). The result *should* be an HTTP 400 + # error. It must have exactly one argument, the fully formatted + # error string. + + def __init__(self, message): + ValueError.__init__(self, message) + self.formatted_message = message + + +class Input(object): + + __slots__ = ('rfile', 'content_length', 'socket', 'position', + 'chunked_input', 'chunk_length', '_chunked_input_error') + + def __init__(self, rfile, content_length, socket=None, chunked_input=False): + # pylint:disable=redefined-outer-name + self.rfile = rfile + self.content_length = content_length + self.socket = socket + self.position = 0 + self.chunked_input = chunked_input + self.chunk_length = -1 + self._chunked_input_error = False + + def _discard(self): + if self._chunked_input_error: + # We are in an unknown state, so we can't necessarily discard + # the body (e.g., if the client keeps the socket open, we could hang + # here forever). + # In this case, we've raised an exception and the user of this object + # is going to close the socket, so we don't have to discard + return + + if self.socket is None and (self.position < (self.content_length or 0) or self.chunked_input): + # ## Read and discard body + while 1: + d = self.read(16384) + if not d: + break + + def _send_100_continue(self): + if self.socket is not None: + self.socket.sendall(_CONTINUE_RESPONSE) + self.socket = None + + def _do_read(self, length=None, use_readline=False): + if use_readline: + reader = self.rfile.readline + else: + reader = self.rfile.read + content_length = self.content_length + if content_length is None: + # Either Content-Length or "Transfer-Encoding: chunked" must be present in a request with a body + # if it was chunked, then this function would have not been called + return b'' + + self._send_100_continue() + left = content_length - self.position + if length is None: + length = left + elif length > left: + length = left + if not length: + return b'' + + # On Python 2, self.rfile is usually socket.makefile(), which + # uses cStringIO.StringIO. If *length* is greater than the C + # sizeof(int) (typically 32 bits signed), parsing the argument to + # readline raises OverflowError. StringIO.read(), OTOH, uses + # PySize_t, typically a long (64 bits). In a bare readline() + # case, because the header lines we're trying to read with + # readline are typically expected to be small, we can correct + # that failure by simply doing a smaller call to readline and + # appending; failures in read we let propagate. + try: + read = reader(length) + except OverflowError: + if not use_readline: + # Expecting to read more than 64 bits of data. Ouch! + raise + # We could loop on calls to smaller readline(), appending them + # until we actually get a newline. For uses in this module, + # we expect the actual length to be small, but WSGI applications + # are allowed to pass in an arbitrary length. (This loop isn't optimal, + # but even client applications *probably* have short lines.) + read = b'' + while len(read) < length and not read.endswith(b'\n'): + read += reader(MAX_REQUEST_LINE) + + self.position += len(read) + if len(read) < length: + if (use_readline and not read.endswith(b"\n")) or not use_readline: + raise IOError("unexpected end of file while reading request at position %s" % (self.position,)) + + return read + + def __read_chunk_length(self, rfile): + # Read and return the next integer chunk length. If no + # chunk length can be read, raises _InvalidClientInput. + + # Here's the production for a chunk (actually the whole body): + # (https://www.rfc-editor.org/rfc/rfc7230#section-4.1) + + # chunked-body = *chunk + # last-chunk + # trailer-part + # CRLF + # + # chunk = chunk-size [ chunk-ext ] CRLF + # chunk-data CRLF + # chunk-size = 1*HEXDIG + # last-chunk = 1*("0") [ chunk-ext ] CRLF + # trailer-part = *( header-field CRLF ) + # chunk-data = 1*OCTET ; a sequence of chunk-size octets + # + # chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) + # + # chunk-ext-name = token + # chunk-ext-val = token / quoted-string + + # To cope with malicious or broken clients that fail to send + # valid chunk lines, the strategy is to read character by + # character until we either reach a ; or newline. If at any + # time we read a non-HEX digit, we bail. If we hit a ;, + # indicating an chunk-extension, we'll read up to the next + # MAX_REQUEST_LINE characters ("A server ought to limit the + # total length of chunk extensions received") looking for the + # CRLF, and if we don't find it, we bail. If we read more than + # 16 hex characters, (the number needed to represent a 64-bit + # chunk size), we bail (this protects us from a client that + # sends an infinite stream of `F`, for example). + + buf = BytesIO() + while 1: + char = rfile.read(1) + if not char: + self._chunked_input_error = True + raise _InvalidClientInput("EOF before chunk end reached") + + if char in ( + b'\r', # Beginning EOL + b';', # Beginning extension + ): + break + + if char not in _HEX: # Invalid data. + self._chunked_input_error = True + raise _InvalidClientInput("Non-hex data", char) + + buf.write(char) + + if buf.tell() > 16: # Too many hex bytes + self._chunked_input_error = True + raise _InvalidClientInput("Chunk-size too large.") + + if char == b';': + i = 0 + while i < MAX_REQUEST_LINE: + char = rfile.read(1) + if char == b'\r': + break + i += 1 + else: + # we read more than MAX_REQUEST_LINE without + # hitting CR + self._chunked_input_error = True + raise _InvalidClientInput("Too large chunk extension") + + if char == b'\r': + # We either got here from the main loop or from the + # end of an extension + self.__read_chunk_size_crlf(rfile, newline_only=True) + result = int(buf.getvalue(), 16) + if result == 0: + # The only time a chunk size of zero is allowed is the final + # chunk. It is either followed by another \r\n, or some trailers + # which are then followed by \r\n. + while self.__read_chunk_trailer(rfile): + pass + return result + + # Trailers have the following production (they are a header-field followed by CRLF) + # See above for the definition of "token". + # + # header-field = field-name ":" OWS field-value OWS + # field-name = token + # field-value = *( field-content / obs-fold ) + # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + # field-vchar = VCHAR / obs-text + # obs-fold = CRLF 1*( SP / HTAB ) + # ; obsolete line folding + # ; see Section 3.2.4 + + + def __read_chunk_trailer(self, rfile, ): + # With rfile positioned just after a \r\n, read a trailer line. + # Return a true value if a non-empty trailer was read, and + # return false if an empty trailer was read (meaning the trailers are + # done). + # If a single line exceeds the MAX_REQUEST_LINE, raise an exception. + # If the field-name portion contains invalid characters, raise an exception. + + i = 0 + empty = True + seen_field_name = False + while i < MAX_REQUEST_LINE: + char = rfile.read(1) + if char == b'\r': + # Either read the next \n or raise an error. + self.__read_chunk_size_crlf(rfile, newline_only=True) + break + # Not a \r, so we are NOT an empty chunk. + empty = False + if char == b':' and i > 0: + # We're ending the field-name part; stop validating characters. + # Unless : was the first character... + seen_field_name = True + if not seen_field_name and char not in _ALLOWED_TOKEN_CHARS: + raise _InvalidClientInput('Invalid token character: %r' % (char,)) + i += 1 + else: + # We read too much + self._chunked_input_error = True + raise _InvalidClientInput("Too large chunk trailer") + return not empty + + def __read_chunk_size_crlf(self, rfile, newline_only=False): + # Also for safety, correctly verify that we get \r\n when expected. + if not newline_only: + char = rfile.read(1) + if char != b'\r': + self._chunked_input_error = True + raise _InvalidClientInput("Line didn't end in CRLF: %r" % (char,)) + char = rfile.read(1) + if char != b'\n': + self._chunked_input_error = True + raise _InvalidClientInput("Line didn't end in LF: %r" % (char,)) + + def _chunked_read(self, length=None, use_readline=False): + # pylint:disable=too-many-branches + rfile = self.rfile + self._send_100_continue() + + if length == 0: + return b"" + + if use_readline: + reader = self.rfile.readline + else: + reader = self.rfile.read + + response = [] + while self.chunk_length != 0: + maxreadlen = self.chunk_length - self.position + if length is not None and length < maxreadlen: + maxreadlen = length + + if maxreadlen > 0: + data = reader(maxreadlen) + if not data: + self.chunk_length = 0 + self._chunked_input_error = True + raise IOError("unexpected end of file while parsing chunked data") + + datalen = len(data) + response.append(data) + + self.position += datalen + if self.chunk_length == self.position: + self.__read_chunk_size_crlf(rfile) + + if length is not None: + length -= datalen + if length == 0: + break + if use_readline and data[-1] == b"\n"[0]: + break + else: + # We're at the beginning of a chunk, so we need to + # determine the next size to read + self.chunk_length = self.__read_chunk_length(rfile) + self.position = 0 + # If chunk_length was 0, we already read any trailers and + # validated that we have ended with \r\n\r\n. + + return b''.join(response) + + def read(self, length=None): + if length is not None and length < 0: + length = None + if self.chunked_input: + return self._chunked_read(length) + return self._do_read(length) + + def readline(self, size=None): + if size is not None and size < 0: + size = None + if self.chunked_input: + return self._chunked_read(size, True) + return self._do_read(size, use_readline=True) + + def readlines(self, hint=None): + # pylint:disable=unused-argument + return list(self) + + def __iter__(self): + return self + + def next(self): + line = self.readline() + if not line: + raise StopIteration + return line + __next__ = next + + +try: + import mimetools + headers_factory = mimetools.Message +except ImportError: + # adapt Python 3 HTTP headers to old API + from http import client # pylint:disable=import-error + + class OldMessage(client.HTTPMessage): + def __init__(self, **kwargs): + super(client.HTTPMessage, self).__init__(**kwargs) # pylint:disable=bad-super-call + self.status = '' + + def getheader(self, name, default=None): + return self.get(name, default) + + @property + def headers(self): + for key, value in self._headers: + yield '%s: %s\r\n' % (key, value) + + @property + def typeheader(self): + return self.get('content-type') + + def headers_factory(fp, *args): # pylint:disable=unused-argument + try: + ret = client.parse_headers(fp, _class=OldMessage) + except client.LineTooLong: + ret = OldMessage() + ret.status = 'Line too long' + return ret + + +class WSGIHandler(object): + """ + Handles HTTP requests from a socket, creates the WSGI environment, and + interacts with the WSGI application. + + This is the default value of :attr:`WSGIServer.handler_class`. + This class may be subclassed carefully, and that class set on a + :class:`WSGIServer` instance through a keyword argument at + construction time. + + Instances are constructed with the same arguments as passed to the + server's :meth:`WSGIServer.handle` method followed by the server + itself. The application and environment are obtained from the server. + + """ + # pylint:disable=too-many-instance-attributes + + protocol_version = 'HTTP/1.1' + + def MessageClass(self, *args): + return headers_factory(*args) + + # Attributes reset at various times for each request; not public + # documented. Class attributes to keep the constructor fast + # (but not make lint tools complain) + + status = None # byte string: b'200 OK' + _orig_status = None # native string: '200 OK' + response_headers = None # list of tuples (b'name', b'value') + code = None # Integer parsed from status + provided_date = None + provided_content_length = None + close_connection = False + time_start = 0 # time.time() when begin handling request + time_finish = 0 # time.time() when done handling request + headers_sent = False # Have we already sent headers? + response_use_chunked = False # Write with transfer-encoding chunked + # Was the connection upgraded? We shouldn't try to chunk writes in that + # case. + connection_upgraded = False + environ = None # Dict from self.get_environ + application = None # application callable from self.server.application + requestline = None # native str 'GET / HTTP/1.1' + response_length = 0 # How much data we sent + result = None # The return value of the WSGI application + wsgi_input = None # Instance of Input() + content_length = 0 # From application-provided headers Incoming + # request headers, instance of MessageClass (gunicorn uses hasattr + # on this so the default value needs to be compatible with the + # API) + headers = headers_factory(BytesIO()) + request_version = None # str: 'HTTP 1.1' + command = None # str: 'GET' + path = None # str: '/' + + def __init__(self, sock, address, server, rfile=None): + # Deprecation: The rfile kwarg was introduced in 1.0a1 as part + # of a refactoring. It was never documented or used. It is + # considered DEPRECATED and may be removed in the future. Its + # use is not supported. + + self.socket = sock + self.client_address = address + self.server = server + if rfile is None: + self.rfile = sock.makefile('rb', -1) + else: + self.rfile = rfile + + def handle(self): + """ + The main request handling method, called by the server. + + This method runs a request handling loop, calling + :meth:`handle_one_request` until all requests on the + connection have been handled (that is, it implements + keep-alive). + """ + try: + while self.socket is not None: + self.time_start = time.time() + self.time_finish = 0 + + result = self.handle_one_request() + if result is None: + break + if result is True: + continue + + self.status, response_body = result # pylint:disable=unpacking-non-sequence + self.socket.sendall(response_body) + if self.time_finish == 0: + self.time_finish = time.time() + self.log_request() + break + finally: + if self.socket is not None: + _sock = getattr(self.socket, '_sock', None) # Python 3 + try: + # read out request data to prevent error: [Errno 104] Connection reset by peer + if _sock: + try: + # socket.recv would hang + _sock.recv(16384) + finally: + _sock.close() + self.socket.close() + except socket.error: + pass + self.__dict__.pop('socket', None) + self.__dict__.pop('rfile', None) + self.__dict__.pop('wsgi_input', None) + + def _check_http_version(self): + version_str = self.request_version + if not version_str.startswith("HTTP/"): + return False + version = tuple(int(x) for x in version_str[5:].split(".")) # "HTTP/" + if version[1] < 0 or version < (0, 9) or version >= (2, 0): + return False + return True + + def read_request(self, raw_requestline): + """ + Parse the incoming request. + + Parses various headers into ``self.headers`` using + :attr:`MessageClass`. Other attributes that are set upon a successful + return of this method include ``self.content_length`` and ``self.close_connection``. + + :param str raw_requestline: A native :class:`str` representing + the request line. A processed version of this will be stored + into ``self.requestline``. + + :raises ValueError: If the request is invalid. This error will + not be logged as a traceback (because it's a client issue, not a server problem). + :return: A boolean value indicating whether the request was successfully parsed. + This method should either return a true value or have raised a ValueError + with details about the parsing error. + + .. versionchanged:: 1.1b6 + Raise the previously documented :exc:`ValueError` in more cases instead of returning a + false value; this allows subclasses more opportunity to customize behaviour. + """ + # pylint:disable=too-many-branches + self.requestline = raw_requestline.rstrip() + words = self.requestline.split() + if len(words) == 3: + self.command, self.path, self.request_version = words + if not self._check_http_version(): + raise _InvalidClientRequest('Invalid http version: %r' % (raw_requestline,)) + elif len(words) == 2: + self.command, self.path = words + if self.command != "GET": + raise _InvalidClientRequest('Expected GET method; Got command=%r; path=%r; raw=%r' % ( + self.command, self.path, raw_requestline,)) + self.request_version = "HTTP/0.9" + # QQQ I'm pretty sure we can drop support for HTTP/0.9 + else: + raise _InvalidClientRequest('Invalid HTTP method: %r' % (raw_requestline,)) + + self.headers = self.MessageClass(self.rfile, 0) + + if self.headers.status: + raise _InvalidClientRequest('Invalid headers status: %r' % (self.headers.status,)) + + if self.headers.get("transfer-encoding", "").lower() == "chunked": + try: + del self.headers["content-length"] + except KeyError: + pass + + content_length = self.headers.get("content-length") + if content_length is not None: + content_length = int(content_length) + if content_length < 0: + raise _InvalidClientRequest('Invalid Content-Length: %r' % (content_length,)) + + if content_length and self.command in ('HEAD', ): + raise _InvalidClientRequest('Unexpected Content-Length') + + self.content_length = content_length + + if self.request_version == "HTTP/1.1": + conntype = self.headers.get("Connection", "").lower() + self.close_connection = (conntype == 'close') # pylint:disable=superfluous-parens + elif self.request_version == 'HTTP/1.0': + conntype = self.headers.get("Connection", "close").lower() + self.close_connection = (conntype != 'keep-alive') # pylint:disable=superfluous-parens + else: + # XXX: HTTP 0.9. We should drop support + self.close_connection = True + + return True + + _print_unexpected_exc = staticmethod(traceback.print_exc) + + def log_error(self, msg, *args): + if not args: + # Already fully formatted, no need to do it again; msg + # might contain % chars that would lead to a formatting + # error. + message = msg + else: + try: + message = msg % args + except Exception: # pylint:disable=broad-except + self._print_unexpected_exc() + message = '%r %r' % (msg, args) + try: + message = '%s: %s' % (self.socket, message) + except Exception: # pylint:disable=broad-except + pass + + try: + self.server.error_log.write(message + '\n') + except Exception: # pylint:disable=broad-except + self._print_unexpected_exc() + + def read_requestline(self): + """ + Read and return the HTTP request line. + + Under both Python 2 and 3, this should return the native + ``str`` type; under Python 3, this probably means the bytes read + from the network need to be decoded (using the ISO-8859-1 charset, aka + latin-1). + """ + line = self.rfile.readline(MAX_REQUEST_LINE) + line = line.decode('latin-1') + return line + + def handle_one_request(self): + """ + Handles one HTTP request using ``self.socket`` and ``self.rfile``. + + Each invocation of this method will do several things, including (but not limited to): + + - Read the request line using :meth:`read_requestline`; + - Read the rest of the request, including headers, with :meth:`read_request`; + - Construct a new WSGI environment in ``self.environ`` using :meth:`get_environ`; + - Store the application in ``self.application``, retrieving it from the server; + - Handle the remainder of the request, including invoking the application, + with :meth:`handle_one_response` + + There are several possible return values to indicate the state + of the client connection: + + - ``None`` + The client connection is already closed or should + be closed because the WSGI application or client set the + ``Connection: close`` header. The request handling + loop should terminate and perform cleanup steps. + - (status, body) + An HTTP status and body tuple. The request was in error, + as detailed by the status and body. The request handling + loop should terminate, close the connection, and perform + cleanup steps. Note that the ``body`` is the complete contents + to send to the client, including all headers and the initial + status line. + - ``True`` + The literal ``True`` value. The request was successfully handled + and the response sent to the client by :meth:`handle_one_response`. + The connection remains open to process more requests and the connection + handling loop should call this method again. This is the typical return + value. + + .. seealso:: :meth:`handle` + + .. versionchanged:: 1.1b6 + Funnel exceptions having to do with invalid HTTP requests through + :meth:`_handle_client_error` to allow subclasses to customize. Note that + this is experimental and may change in the future. + """ + # pylint:disable=too-many-return-statements + if self.rfile.closed: + return + + try: + self.requestline = self.read_requestline() + # Account for old subclasses that haven't done this + if isinstance(self.requestline, bytes): + self.requestline = self.requestline.decode('latin-1') + except socket.error: + # "Connection reset by peer" or other socket errors aren't interesting here + return + + if not self.requestline: + return + + self.response_length = 0 + + if len(self.requestline) >= MAX_REQUEST_LINE: + return ('414', _REQUEST_TOO_LONG_RESPONSE) + + try: + # for compatibility with older versions of pywsgi, we pass self.requestline as an argument there + # NOTE: read_request is supposed to raise ValueError on invalid input; allow old + # subclasses that return a False value instead. + # NOTE: This can mutate the value of self.headers, so self.get_environ() must not be + # called until AFTER this call is done. + if not self.read_request(self.requestline): + return ('400', _BAD_REQUEST_RESPONSE) + except Exception as ex: # pylint:disable=broad-except + # Notice we don't use self.handle_error because it reports + # a 500 error to the client, and this is almost certainly + # a client error. + # Provide a hook for subclasses. + return self._handle_client_error(ex) + + self.environ = self.get_environ() + self.application = self.server.application + + self.handle_one_response() + + if self.close_connection: + return + + if self.rfile.closed: + return + + return True # read more requests + + def _connection_upgrade_requested(self): + if self.headers.get('Connection', '').lower() == 'upgrade': + return True + if self.headers.get('Upgrade', '').lower() == 'websocket': + return True + return False + + def finalize_headers(self): + if self.provided_date is None: + self.response_headers.append((b'Date', format_date_time(time.time()))) + + self.connection_upgraded = self.code == 101 + + if self.code not in (304, 204): + # the reply will include message-body; make sure we have either Content-Length or chunked + if self.provided_content_length is None: + if hasattr(self.result, '__len__'): + total_len = sum(len(chunk) for chunk in self.result) + total_len_str = str(total_len) + total_len_str = total_len_str.encode("latin-1") + self.response_headers.append((b'Content-Length', total_len_str)) + else: + self.response_use_chunked = ( + not self.connection_upgraded + and self.request_version != 'HTTP/1.0' + ) + if self.response_use_chunked: + self.response_headers.append((b'Transfer-Encoding', b'chunked')) + + def _sendall(self, data): + try: + self.socket.sendall(data) + except socket.error as ex: + self.status = 'socket error: %s' % ex + if self.code > 0: + self.code = -self.code + raise + self.response_length += len(data) + + def _write(self, data, + _bytearray=bytearray): + if not data: + # The application/middleware are allowed to yield + # empty bytestrings. + return + + if self.response_use_chunked: + # Write the chunked encoding header + header_str = b'%x\r\n' % len(data) + towrite = _bytearray(header_str) + + # data + towrite += data + # trailer + towrite += b'\r\n' + self._sendall(towrite) + else: + self._sendall(data) + + ApplicationError = AssertionError + + def write(self, data): + # The write() callable we return from start_response. + # https://www.python.org/dev/peps/pep-3333/#the-write-callable + # Supposed to do pretty much the same thing as yielding values + # from the application's return. + if self.code in (304, 204) and data: + raise self.ApplicationError('The %s response must have no body' % self.code) + + if self.headers_sent: + self._write(data) + else: + if not self.status: + raise self.ApplicationError("The application did not call start_response()") + self._write_with_headers(data) + + def _write_with_headers(self, data): + self.headers_sent = True + self.finalize_headers() + + # self.response_headers and self.status are already in latin-1, as encoded by self.start_response + towrite = bytearray(b'HTTP/1.1 ') + towrite += self.status + towrite += b'\r\n' + for header, value in self.response_headers: + towrite += header + towrite += b': ' + towrite += value + towrite += b"\r\n" + + towrite += b'\r\n' + self._sendall(towrite) + # No need to copy the data into towrite; we may make an extra syscall + # but the copy time could be substantial too, and it reduces the chances + # of sendall being able to send everything in one go + self._write(data) + + def start_response(self, status, headers, exc_info=None): + """ + .. versionchanged:: 1.2a1 + Avoid HTTP header injection by raising a :exc:`ValueError` + if *status* or any *header* name or value contains a carriage + return or newline. + .. versionchanged:: 1.1b5 + Pro-actively handle checking the encoding of the status line + and headers during this method. On Python 2, avoid some + extra encodings. + """ + # pylint:disable=too-many-branches,too-many-statements + if exc_info: + try: + if self.headers_sent: + # Re-raise original exception if headers sent + reraise(*exc_info) + finally: + # Avoid dangling circular ref + exc_info = None + + # Pep 3333, "The start_response callable": + # https://www.python.org/dev/peps/pep-3333/#the-start-response-callable + # "Servers should check for errors in the headers at the time + # start_response is called, so that an error can be raised + # while the application is still running." Here, we check the encoding. + # This aids debugging: headers especially are generated programmatically + # and an encoding error in a loop or list comprehension yields an opaque + # UnicodeError without any clue which header was wrong. + # Note that this results in copying the header list at this point, not modifying it, + # although we are allowed to do so if needed. This slightly increases memory usage. + # We also check for HTTP Response Splitting vulnerabilities + response_headers = [] + header = None + value = None + try: + for header, value in headers: + if not isinstance(header, str): + raise UnicodeError("The header must be a native string", header, value) + if not isinstance(value, str): + raise UnicodeError("The value must be a native string", header, value) + if '\r' in header or '\n' in header: + raise ValueError('carriage return or newline in header name', header) + if '\r' in value or '\n' in value: + raise ValueError('carriage return or newline in header value', value) + # Either we're on Python 2, in which case bytes is correct, or + # we're on Python 3 and the user screwed up (because it should be a native + # string). In either case, make sure that this is latin-1 compatible. Under + # Python 2, bytes.encode() will take a round-trip through the system encoding, + # which may be ascii, which is not really what we want. However, the latin-1 encoding + # can encode everything except control characters and the block from 0x7F to 0x9F, so + # explicitly round-tripping bytes through the encoding is unlikely to be of much + # benefit, so we go for speed (the WSGI spec specifically calls out allowing the range + # from 0x00 to 0xFF, although the HTTP spec forbids the control characters). + # Note: Some Python 2 implementations, like Jython, may allow non-octet (above 255) values + # in their str implementation; this is mentioned in the WSGI spec, but we don't + # run on any platform like that so we can assume that a str value is pure bytes. + response_headers.append((header.encode("latin-1"), + value.encode("latin-1"))) + except UnicodeEncodeError: + # If we get here, we're guaranteed to have a header and value + raise UnicodeError("Non-latin1 header", repr(header), repr(value)) + + # Same as above + if not isinstance(status, str): + raise UnicodeError("The status string must be a native string") + if '\r' in status or '\n' in status: + raise ValueError("carriage return or newline in status", status) + # don't assign to anything until the validation is complete, including parsing the + # code + code = int(status.split(' ', 1)[0]) + + self.status = status.encode("latin-1") + self._orig_status = status # Preserve the native string for logging + self.response_headers = response_headers + self.code = code + + provided_connection = None # Did the wsgi app give us a Connection header? + self.provided_date = None + self.provided_content_length = None + + for header, value in headers: + header = header.lower() + if header == 'connection': + provided_connection = value + elif header == 'date': + self.provided_date = value + elif header == 'content-length': + self.provided_content_length = value + + if self.request_version == 'HTTP/1.0' and provided_connection is None: + conntype = b'close' if self.close_connection else b'keep-alive' + response_headers.append((b'Connection', conntype)) + elif provided_connection == 'close': + self.close_connection = True + + if self.code in (304, 204): + if self.provided_content_length is not None and self.provided_content_length != '0': + msg = 'Invalid Content-Length for %s response: %r (must be absent or zero)' % (self.code, self.provided_content_length) + msg = msg.encode('latin-1') + raise self.ApplicationError(msg) + + return self.write + + def log_request(self): + self.server.log.write(self.format_request() + '\n') + + def format_request(self): + now = datetime.now().replace(microsecond=0) + length = self.response_length or '-' + if self.time_finish: + delta = '%.6f' % (self.time_finish - self.time_start) + else: + delta = '-' + client_address = self.client_address[0] if isinstance(self.client_address, tuple) else self.client_address + return '%s - - [%s] "%s" %s %s %s' % ( + client_address or '-', + now, + self.requestline or '', + # Use the native string version of the status, saved so we don't have to + # decode. But fallback to the encoded 'status' in case of subclasses + # (Is that really necessary? At least there's no overhead.) + (self._orig_status or self.status or '000').split()[0], + length, + delta) + + def process_result(self): + for data in self.result: + if data: + self.write(data) + if self.status and not self.headers_sent: + # In other words, the application returned an empty + # result iterable (and did not use the write callable) + # Trigger the flush of the headers. + self.write(b'') + if self.response_use_chunked: + self._sendall(b'0\r\n\r\n') + + + def run_application(self): + assert self.result is None + try: + self.result = self.application(self.environ, self.start_response) + self.process_result() + finally: + close = getattr(self.result, 'close', None) + try: + if close is not None: + close() + finally: + # Discard the result. If it's a generator this can + # free a lot of hidden resources (if we failed to iterate + # all the way through it---the frames are automatically + # cleaned up when StopIteration is raised); but other cases + # could still free up resources sooner than otherwise. + close = None + self.result = None + + #: These errors are silently ignored by :meth:`handle_one_response` to avoid producing + #: excess log entries on normal operating conditions. They indicate + #: a remote client has disconnected and there is little or nothing + #: this process can be expected to do about it. You may change this + #: value in a subclass. + #: + #: The default value includes :data:`errno.EPIPE` and :data:`errno.ECONNRESET`. + #: On Windows this also includes :data:`errno.WSAECONNABORTED`. + #: + #: This is a provisional API, subject to change. See :pr:`377`, :pr:`999` + #: and :issue:`136`. + #: + #: .. versionadded:: 1.3 + ignored_socket_errors = (errno.EPIPE, errno.ECONNRESET) + try: + ignored_socket_errors += (errno.WSAECONNABORTED,) + except AttributeError: + pass # Not windows + + def handle_one_response(self): + """ + Invoke the application to produce one response. + + This is called by :meth:`handle_one_request` after all the + state for the request has been established. It is responsible + for error handling. + """ + self.time_start = time.time() + self.status = None + self.headers_sent = False + + self.result = None + self.response_use_chunked = False + self.connection_upgraded = False + self.response_length = 0 + + try: + try: + self.run_application() + finally: + try: + self.wsgi_input._discard() + except _InvalidClientInput: + # This one is deliberately raised to the outer + # scope, because, with the incoming stream in some bad state, + # we can't be sure we can synchronize and properly parse the next + # request. + raise + except socket.error: + # Don't let socket exceptions during discarding + # input override any exception that may have been + # raised by the application, such as our own _InvalidClientInput. + # In the general case, these aren't even worth logging (see the comment + # just below) + pass + except _InvalidClientInput as ex: + # DO log this one because: + # - Some of the data may have been read and acted on by the + # application; + # - The response may or may not have been sent; + # - It's likely that the client is bad, or malicious, and + # users might wish to take steps to block the client. + self._handle_client_error(ex) + self.close_connection = True + self._send_error_response_if_possible(400) + except socket.error as ex: + if ex.args[0] in self.ignored_socket_errors: + # See description of self.ignored_socket_errors. + self.close_connection = True + else: + self.handle_error(*sys.exc_info()) + except: # pylint:disable=bare-except + self.handle_error(*sys.exc_info()) + finally: + self.time_finish = time.time() + self.log_request() + + def _send_error_response_if_possible(self, error_code): + if self.response_length: + self.close_connection = True + else: + status, headers, body = _ERRORS[error_code] + try: + self.start_response(status, headers[:]) + self.write(body) + except socket.error: + self.close_connection = True + + def _log_error(self, t, v, tb): + # TODO: Shouldn't we dump this to wsgi.errors? If we did that now, it would + # wind up getting logged twice + if not issubclass(t, GreenletExit): + context = self.environ + if not isinstance(context, self.server.secure_environ_class): + context = self.server.secure_environ_class(context) + self.server.loop.handle_error(context, t, v, tb) + + def handle_error(self, t, v, tb): + # Called for internal, unexpected errors, NOT invalid client input + self._log_error(t, v, tb) + t = v = tb = None + self._send_error_response_if_possible(500) + + def _handle_client_error(self, ex): + # Called for invalid client input + # Returns the appropriate error response. + if not isinstance(ex, (ValueError, _InvalidClientInput)): + # XXX: Why not self._log_error to send it through the loop's + # handle_error method? + # _InvalidClientRequest is a ValueError; _InvalidClientInput is an IOError. + traceback.print_exc() + if isinstance(ex, _InvalidClientRequest): + # No formatting needed, that's already been handled. In fact, because the + # formatted message contains user input, it might have a % in it, and attempting + # to format that with no arguments would be an error. + # However, the error messages do not include the requesting IP + # necessarily, so we do add that. + self.log_error('(from %s) %s', self.client_address, ex.formatted_message) + else: + self.log_error('Invalid request (from %s): %s', + self.client_address, + str(ex) or ex.__class__.__name__) + return ('400', _BAD_REQUEST_RESPONSE) + + def _headers(self): + key = None + value = None + IGNORED_KEYS = (None, 'CONTENT_TYPE', 'CONTENT_LENGTH') + for header in self.headers.headers: + if key is not None and header[:1] in " \t": + value += header + continue + + if key not in IGNORED_KEYS: + yield 'HTTP_' + key, value.strip() + + key, value = header.split(':', 1) + if '_' in key: + # strip incoming bad veaders + key = None + else: + key = key.replace('-', '_').upper() + + if key not in IGNORED_KEYS: + yield 'HTTP_' + key, value.strip() + + def get_environ(self): + """ + Construct and return a new WSGI environment dictionary for a specific request. + + This should begin with asking the server for the base environment + using :meth:`WSGIServer.get_environ`, and then proceed to add the + request specific values. + + By the time this method is invoked the request line and request shall have + been parsed and ``self.headers`` shall be populated. + """ + env = self.server.get_environ() + env['REQUEST_METHOD'] = self.command + # SCRIPT_NAME is explicitly implementation defined. Using an + # empty value for SCRIPT_NAME is both explicitly allowed by + # both the CGI standard and WSGI PEPs, and also the thing that + # makes the most sense from a generic server perspective (we + # have no hierarchy or understanding of URLs or files, just a + # single application to call. The empty string represents the + # application root, which is what we have). Different WSGI + # implementations handle this very differently, so portable + # applications that rely on SCRIPT_NAME will have to use a + # WSGI middleware to set it to a defined value, or otherwise + # rely on server-specific mechanisms (e.g, on waitress, use + # ``--url-prefix``, in gunicorn set the ``SCRIPT_NAME`` header + # or process environment variable, in gevent subclass + # WSGIHandler.) + # + # See https://github.com/gevent/gevent/issues/1667 for discussion. + env['SCRIPT_NAME'] = '' + + path, query = self.path.split('?', 1) if '?' in self.path else (self.path, '') + # Note that self.path contains the original str object; if it contains + # encoded escapes, it will NOT match PATH_INFO. + env['PATH_INFO'] = unquote_latin1(path) + env['QUERY_STRING'] = query + + if self.headers.typeheader is not None: + env['CONTENT_TYPE'] = self.headers.typeheader + + length = self.headers.getheader('content-length') + if length: + env['CONTENT_LENGTH'] = length + env['SERVER_PROTOCOL'] = self.request_version + + client_address = self.client_address + if isinstance(client_address, tuple): + env['REMOTE_ADDR'] = str(client_address[0]) + env['REMOTE_PORT'] = str(client_address[1]) + + for key, value in self._headers(): + if key in env: + if 'COOKIE' in key: + env[key] += '; ' + value + else: + env[key] += ',' + value + else: + env[key] = value + + sock = self.socket if env.get('HTTP_EXPECT') == '100-continue' else None + + chunked = env.get('HTTP_TRANSFER_ENCODING', '').lower() == 'chunked' + # Input refuses to read if the data isn't chunked, and there is no content_length + # provided. For 'Upgrade: Websocket' requests, neither of those things is true. + handling_reads = not self._connection_upgrade_requested() + + self.wsgi_input = Input(self.rfile, self.content_length, socket=sock, chunked_input=chunked) + + env['wsgi.input'] = self.wsgi_input if handling_reads else self.rfile + # This is a non-standard flag indicating that our input stream is + # self-terminated (returns EOF when consumed). + # See https://github.com/gevent/gevent/issues/1308 + env['wsgi.input_terminated'] = handling_reads + return env + + +class _NoopLog(object): + # Does nothing; implements just enough file-like methods + # to pass the WSGI validator + + def write(self, *args, **kwargs): + # pylint:disable=unused-argument + return + + def flush(self): + pass + + def writelines(self, *args, **kwargs): + pass + + +class LoggingLogAdapter(object): + """ + An adapter for :class:`logging.Logger` instances + to let them be used with :class:`WSGIServer`. + + .. warning:: Unless the entire process is monkey-patched at a very + early part of the lifecycle (before logging is configured), + loggers are likely to not be gevent-cooperative. For example, + the socket and syslog handlers use the socket module in a way + that can block, and most handlers acquire threading locks. + + .. warning:: It *may* be possible for the logging functions to be + called in the :class:`gevent.Hub` greenlet. Code running in the + hub greenlet cannot use any gevent blocking functions without triggering + a ``LoopExit``. + + .. versionadded:: 1.1a3 + + .. versionchanged:: 1.1b6 + Attributes not present on this object are proxied to the underlying + logger instance. This permits using custom :class:`~logging.Logger` + subclasses (or indeed, even duck-typed objects). + + .. versionchanged:: 1.1 + Strip trailing newline characters on the message passed to :meth:`write` + because log handlers will usually add one themselves. + """ + + # gevent avoids importing and using logging because importing it and + # creating loggers creates native locks unless monkey-patched. + + __slots__ = ('_logger', '_level') + + def __init__(self, logger, level=20): + """ + Write information to the *logger* at the given *level* (default to INFO). + """ + self._logger = logger + self._level = level + + def write(self, msg): + if msg and msg.endswith('\n'): + msg = msg[:-1] + self._logger.log(self._level, msg) + + def flush(self): + "No-op; required to be a file-like object" + + def writelines(self, lines): + for line in lines: + self.write(line) + + def __getattr__(self, name): + return getattr(self._logger, name) + + def __setattr__(self, name, value): + if name not in LoggingLogAdapter.__slots__: + setattr(self._logger, name, value) + else: + object.__setattr__(self, name, value) + + def __delattr__(self, name): + delattr(self._logger, name) + +#### +## Environ classes. +# These subclass dict. They could subclass collections.UserDict on +# 3.3+ and proxy to the underlying real dict to avoid a copy if we +# have to print them (on 2.7 it's slightly more complicated to be an +# instance of collections.MutableMapping; UserDict.UserDict isn't.) +# Then we could have either the WSGIHandler.get_environ or the +# WSGIServer.get_environ return one of these proxies, and +# WSGIHandler.run_application would know to access the `environ.data` +# attribute to be able to pass the *real* dict to the application +# (because PEP3333 requires no subclasses, only actual dict objects; +# wsgiref.validator and webob.Request both enforce this). This has the +# advantage of not being fragile if anybody else tries to print/log +# self.environ (and not requiring a copy). However, if there are any +# subclasses of Handler or Server, this could break if they don't know +# to return this type. +#### + +class Environ(dict): + """ + A base class that can be used for WSGI environment objects. + + Provisional API. + + .. versionadded:: 1.2a1 + """ + + __slots__ = () # add no ivars or weakref ability + + def copy(self): + return self.__class__(self) + + if not hasattr(dict, 'iteritems'): + # Python 3 + def iteritems(self): + return self.items() + + def __reduce_ex__(self, proto): + return (dict, (), None, None, iter(self.iteritems())) + +class SecureEnviron(Environ): + """ + An environment that does not print its keys and values + by default. + + Provisional API. + + This is intended to keep potentially sensitive information like + HTTP authorization and cookies from being inadvertently printed + or logged. + + For debugging, each instance can have its *secure_repr* attribute + set to ``False``, which will cause it to print like a normal dict. + + When *secure_repr* is ``True`` (the default), then the value of + the *whitelist_keys* attribute is consulted; if this value is + true-ish, it should be a container (something that responds to + ``in``) of key names (typically a list or set). Keys and values in + this dictionary that are in *whitelist_keys* will then be printed, + while all other values will be masked. These values may be + customized on the class by setting the *default_secure_repr* and + *default_whitelist_keys*, respectively:: + + >>> environ = SecureEnviron(key='value') + >>> environ # doctest: +ELLIPSIS + >> environ.whitelist_keys = {'key'} + >>> environ + {'key': 'value'} + + A non-whitelisted key (*only*, to avoid doctest issues) is masked:: + + >>> environ['secure'] = 'secret'; del environ['key'] + >>> environ + {'secure': ''} + + We can turn it off entirely for the instance:: + + >>> environ.secure_repr = False + >>> environ + {'secure': 'secret'} + + We can also customize it at the class level (here we use a new + class to be explicit and to avoid polluting the true default + values; we would set this class to be the ``environ_class`` of the + server):: + + >>> class MyEnviron(SecureEnviron): + ... default_whitelist_keys = ('key',) + ... + >>> environ = MyEnviron({'key': 'value'}) + >>> environ + {'key': 'value'} + + .. versionadded:: 1.2a1 + """ + + default_secure_repr = True + default_whitelist_keys = () + default_print_masked_keys = True + + # Allow instances to override the class values, + # but inherit from the class if not present. Keeps instances + # small since we can't combine __slots__ with class attributes + # of the same name. + __slots__ = ('secure_repr', 'whitelist_keys', 'print_masked_keys') + + def __getattr__(self, name): + if name in SecureEnviron.__slots__: + return getattr(type(self), 'default_' + name) + raise AttributeError(name) + + def __repr__(self): + if self.secure_repr: + whitelist = self.whitelist_keys + print_masked = self.print_masked_keys + if whitelist: + safe = {k: self[k] if k in whitelist else "" + for k in self + if k in whitelist or print_masked} + safe_repr = repr(safe) + if not print_masked and len(safe) != len(self): + safe_repr = safe_repr[:-1] + ", (hidden keys: %d)}" % (len(self) - len(safe)) + return safe_repr + return "" % (len(self), id(self)) + return Environ.__repr__(self) + __str__ = __repr__ + + +class WSGISecureEnviron(SecureEnviron): + """ + Specializes the default list of whitelisted keys to a few + common WSGI variables. + + Example:: + + >>> environ = WSGISecureEnviron(REMOTE_ADDR='::1', HTTP_AUTHORIZATION='secret') + >>> environ + {'REMOTE_ADDR': '::1', (hidden keys: 1)} + >>> import pprint + >>> pprint.pprint(environ) + {'REMOTE_ADDR': '::1', (hidden keys: 1)} + >>> print(pprint.pformat(environ)) + {'REMOTE_ADDR': '::1', (hidden keys: 1)} + """ + default_whitelist_keys = ('REMOTE_ADDR', 'REMOTE_PORT', 'HTTP_HOST') + default_print_masked_keys = False + + +class WSGIServer(StreamServer): + """ + A WSGI server based on :class:`StreamServer` that supports HTTPS. + + + :keyword log: If given, an object with a ``write`` method to which + request (access) logs will be written. If not given, defaults + to :obj:`sys.stderr`. You may pass ``None`` to disable request + logging. You may use a wrapper, around e.g., :mod:`logging`, + to support objects that don't implement a ``write`` method. + (If you pass a :class:`~logging.Logger` instance, or in + general something that provides a ``log`` method but not a + ``write`` method, such a wrapper will automatically be created + and it will be logged to at the :data:`~logging.INFO` level.) + + :keyword error_log: If given, a file-like object with ``write``, + ``writelines`` and ``flush`` methods to which error logs will + be written. If not given, defaults to :obj:`sys.stderr`. You + may pass ``None`` to disable error logging (not recommended). + You may use a wrapper, around e.g., :mod:`logging`, to support + objects that don't implement the proper methods. This + parameter will become the value for ``wsgi.errors`` in the + WSGI environment (if not already set). (As with *log*, + wrappers for :class:`~logging.Logger` instances and the like + will be created automatically and logged to at the :data:`~logging.ERROR` + level.) + + .. seealso:: + + :class:`LoggingLogAdapter` + See important warnings before attempting to use :mod:`logging`. + + .. versionchanged:: 1.1a3 + Added the ``error_log`` parameter, and set ``wsgi.errors`` in the WSGI + environment to this value. + .. versionchanged:: 1.1a3 + Add support for passing :class:`logging.Logger` objects to the ``log`` and + ``error_log`` arguments. + .. versionchanged:: 20.6.0 + Passing a ``handle`` kwarg to the constructor is now officially deprecated. + """ + + #: A callable taking three arguments: (socket, address, server) and returning + #: an object with a ``handle()`` method. The callable is called once for + #: each incoming socket request, as is its handle method. The handle method should not + #: return until all use of the socket is complete. + #: + #: This class uses the :class:`WSGIHandler` object as the default value. You may + #: subclass this class and set a different default value, or you may pass + #: a value to use in the ``handler_class`` keyword constructor argument. + handler_class = WSGIHandler + + #: The object to which request logs will be written. + #: It must never be None. Initialized from the ``log`` constructor + #: parameter. + log = None + + #: The object to which error logs will be written. + #: It must never be None. Initialized from the ``error_log`` constructor + #: parameter. + error_log = None + + #: The class of environ objects passed to the handlers. + #: Must be a dict subclass. For compliance with :pep:`3333` + #: and libraries like WebOb, this is simply :class:`dict` + #: but this can be customized in a subclass or per-instance + #: (probably to :class:`WSGISecureEnviron`). + #: + #: .. versionadded:: 1.2a1 + environ_class = dict + + # Undocumented internal detail: the class that WSGIHandler._log_error + # will cast to before passing to the loop. + secure_environ_class = WSGISecureEnviron + + base_env = {'GATEWAY_INTERFACE': 'CGI/1.1', + 'SERVER_SOFTWARE': 'gevent/%d.%d Python/%d.%d' % (gevent.version_info[:2] + sys.version_info[:2]), + 'SCRIPT_NAME': '', + 'wsgi.version': (1, 0), + 'wsgi.multithread': False, # XXX: Aren't we really, though? + 'wsgi.multiprocess': False, + 'wsgi.run_once': False} + + def __init__(self, listener, application=None, backlog=None, spawn='default', + log='default', error_log='default', + handler_class=None, + environ=None, **ssl_args): + if 'handle' in ssl_args: + # The ultimate base class (BaseServer) uses 'handle' for + # the thing we call 'application'. We never deliberately + # bass a `handle` argument to the base class, but one + # could sneak in through ``**ssl_args``, even though that + # is not the intent, while application is None. That + # causes our own ``def handle`` method to be replaced, + # probably leading to bad results. Passing a 'handle' + # instead of an 'application' can really confuse things. + import warnings + warnings.warn("Passing 'handle' kwarg to WSGIServer is deprecated. " + "Did you mean application?", DeprecationWarning, stacklevel=2) + + StreamServer.__init__(self, listener, backlog=backlog, spawn=spawn, **ssl_args) + + if application is not None: + self.application = application + if handler_class is not None: + self.handler_class = handler_class + + # Note that we can't initialize these as class variables: + # sys.stderr might get monkey patched at runtime. + def _make_log(l, level=20): + if l == 'default': + return sys.stderr + if l is None: + return _NoopLog() + if not hasattr(l, 'write') and hasattr(l, 'log'): + return LoggingLogAdapter(l, level) + return l + self.log = _make_log(log) + self.error_log = _make_log(error_log, 40) # logging.ERROR + + self.set_environ(environ) + self.set_max_accept() + + def set_environ(self, environ=None): + if environ is not None: + self.environ = environ + environ_update = getattr(self, 'environ', None) + + self.environ = self.environ_class(self.base_env) + if self.ssl_enabled: + self.environ['wsgi.url_scheme'] = 'https' + else: + self.environ['wsgi.url_scheme'] = 'http' + if environ_update is not None: + self.environ.update(environ_update) + if self.environ.get('wsgi.errors') is None: + self.environ['wsgi.errors'] = self.error_log + + def set_max_accept(self): + if self.environ.get('wsgi.multiprocess'): + self.max_accept = 1 + + def get_environ(self): + return self.environ_class(self.environ) + + def init_socket(self): + StreamServer.init_socket(self) + self.update_environ() + + def update_environ(self): + """ + Called before the first request is handled to fill in WSGI environment values. + + This includes getting the correct server name and port. + """ + address = self.address + if isinstance(address, tuple): + if 'SERVER_NAME' not in self.environ: + try: + name = socket.getfqdn(address[0]) + except socket.error: + name = str(address[0]) + if not isinstance(name, str): + name = name.decode('ascii') + self.environ['SERVER_NAME'] = name + self.environ.setdefault('SERVER_PORT', str(address[1])) + else: + self.environ.setdefault('SERVER_NAME', '') + self.environ.setdefault('SERVER_PORT', '') + + def handle(self, sock, address): + """ + Create an instance of :attr:`handler_class` to handle the request. + + This method blocks until the handler returns. + """ + # pylint:disable=method-hidden + handler = self.handler_class(sock, address, self) + handler.handle() + +def _main(): + # Provisional main handler, for quick tests, not production + # usage. + from gevent import monkey; monkey.patch_all() + + import argparse + import importlib + + parser = argparse.ArgumentParser() + parser.add_argument("app", help="dotted name of WSGI app callable [module:callable]") + parser.add_argument("-b", "--bind", + help="The socket to bind", + default=":8080") + + args = parser.parse_args() + + module_name, app_name = args.app.split(':') + module = importlib.import_module(module_name) + app = getattr(module, app_name) + bind = args.bind + + server = WSGIServer(bind, app) + server.serve_forever() + +if __name__ == '__main__': + _main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/queue.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/queue.py new file mode 100644 index 0000000000000000000000000000000000000000..cd666d063d34289b27ce132822f7ee91865675e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/queue.py @@ -0,0 +1,772 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +# copyright (c) 2018 gevent +# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False +""" +Synchronized queues. + +The :mod:`gevent.queue` module implements multi-producer, multi-consumer queues +that work across greenlets, with the API similar to the classes found in the +standard :mod:`Queue` and :class:`multiprocessing ` modules. + +The classes in this module implement the iterator protocol. Iterating +over a queue means repeatedly calling :meth:`get ` until +:meth:`get ` returns ``StopIteration`` (specifically that +class, not an instance or subclass). + + >>> import gevent.queue + >>> queue = gevent.queue.Queue() + >>> queue.put(1) + >>> queue.put(2) + >>> queue.put(StopIteration) + >>> for item in queue: + ... print(item) + 1 + 2 + +.. versionchanged:: 1.0 + ``Queue(0)`` now means queue of infinite size, not a channel. A :exc:`DeprecationWarning` + will be issued with this argument. +""" + + +import sys +from heapq import heappush as _heappush +from heapq import heappop as _heappop +from heapq import heapify as _heapify +import collections + +import queue as __queue__ +# We re-export these exceptions to client modules. +# But we also want fast access to them from Cython with a cdef, +# and we do that with the _ definition. +_Full = Full = __queue__.Full +_Empty = Empty = __queue__.Empty + +from gevent.timeout import Timeout +from gevent._hub_local import get_hub_noargs as get_hub +from gevent.exceptions import InvalidSwitchError + +__all__ = [] +__implements__ = ['Queue', 'PriorityQueue', 'LifoQueue'] +__extensions__ = ['JoinableQueue', 'Channel'] +__imports__ = ['Empty', 'Full'] + + +__all__.append('SimpleQueue') +# SimpleQueue is implemented in C and directly allocates locks +# unaffected by monkey patching. We need the Python version. +SimpleQueue = __queue__._PySimpleQueue # pylint:disable=no-member + +if hasattr(__queue__, 'ShutDown'): # New in 3.13 + ShutDown = __queue__.ShutDown + __imports__.append('ShutDown') +else: + class ShutDown(Exception): + """ + gevent extension for Python versions less than 3.13 + """ + __extensions__.append('ShutDown') + + +__all__ += (__implements__ + __extensions__ + __imports__) + + +# pylint 2.0.dev2 things collections.dequeue.popleft() doesn't return +# pylint:disable=assignment-from-no-return + +def _safe_remove(deq, item): + # For when the item may have been removed by + # Queue._unlock + try: + deq.remove(item) + except ValueError: + pass + +import gevent._waiter +locals()['Waiter'] = gevent._waiter.Waiter +locals()['getcurrent'] = __import__('greenlet').getcurrent +locals()['greenlet_init'] = lambda: None + +class ItemWaiter(Waiter): # pylint:disable=undefined-variable + # pylint:disable=assigning-non-slot + __slots__ = ( + 'item', + 'queue', + ) + + def __init__(self, item, queue): + Waiter.__init__(self) # pylint:disable=undefined-variable + self.item = item + self.queue = queue + + def put_and_switch(self): + self.queue._put(self.item) + self.queue = None + self.item = None + return self.switch(self) + +class Queue(object): + """ + Create a queue object with a given maximum size. + + If *maxsize* is less than or equal to zero or ``None``, the queue + size is infinite. + + Queues have a ``len`` equal to the number of items in them (the :meth:`qsize`), + but in a boolean context they are always True. + + .. versionchanged:: 1.1b3 + Queues now support :func:`len`; it behaves the same as :meth:`qsize`. + .. versionchanged:: 1.1b3 + Multiple greenlets that block on a call to :meth:`put` for a full queue + will now be awakened to put their items into the queue in the order in which + they arrived. Likewise, multiple greenlets that block on a call to :meth:`get` for + an empty queue will now receive items in the order in which they blocked. An + implementation quirk under CPython *usually* ensured this was roughly the case + previously anyway, but that wasn't the case for PyPy. + .. versionchanged:: 24.10.1 + Implement the ``shutdown`` methods from Python 3.13. + """ + + __slots__ = ( + '_maxsize', + 'getters', + 'putters', + 'hub', + '_event_unlock', + 'queue', + '__weakref__', + 'is_shutdown', # 3.13 + ) + + + def __init__(self, maxsize=None, items=(), _warn_depth=2): + if maxsize is not None and maxsize <= 0: + if maxsize == 0: + import warnings + warnings.warn( + 'Queue(0) now equivalent to Queue(None); if you want a channel, use Channel', + DeprecationWarning, + stacklevel=_warn_depth) + maxsize = None + + self._maxsize = maxsize if maxsize is not None else -1 + # Explicitly maintain order for getters and putters that block + # so that callers can consistently rely on getting things out + # in the apparent order they went in. This was once required by + # imap_unordered. Previously these were set() objects, and the + # items put in the set have default hash() and eq() methods; + # under CPython, since new objects tend to have increasing + # hash values, this tended to roughly maintain order anyway, + # but that's not true under PyPy. An alternative to a deque + # (to avoid the linear scan of remove()) might be an + # OrderedDict, but it's 2.7 only; we don't expect to have so + # many waiters that removing an arbitrary element is a + # bottleneck, though. + self.getters = collections.deque() + self.putters = collections.deque() + self.hub = get_hub() + self._event_unlock = None + self.queue = self._create_queue(items) + self.is_shutdown = False + + @property + def maxsize(self): + return self._maxsize if self._maxsize > 0 else None + + @maxsize.setter + def maxsize(self, nv): + # QQQ make maxsize into a property with setter that schedules unlock if necessary + if nv is None or nv <= 0: + self._maxsize = -1 + else: + self._maxsize = nv + + def copy(self): + return type(self)(self.maxsize, self.queue) + + def _create_queue(self, items=()): + return collections.deque(items) + + def _get(self): + return self.queue.popleft() + + def _peek(self): + return self.queue[0] + + def _put(self, item): + self.queue.append(item) + + def __repr__(self): + return '<%s at %s%s>' % (type(self).__name__, hex(id(self)), self._format()) + + def __str__(self): + return '<%s%s>' % (type(self).__name__, self._format()) + + def _format(self): + result = [] + if self.maxsize is not None: + result.append('maxsize=%r' % (self.maxsize, )) + if getattr(self, 'queue', None): + result.append('queue=%r' % (self.queue, )) + if self.getters: + result.append('getters[%s]' % len(self.getters)) + if self.putters: + result.append('putters[%s]' % len(self.putters)) + if result: + return ' ' + ' '.join(result) + return '' + + def qsize(self): + """Return the size of the queue.""" + return len(self.queue) + + def __len__(self): + """ + Return the size of the queue. This is the same as :meth:`qsize`. + + .. versionadded: 1.1b3 + + Previously, getting len() of a queue would raise a TypeError. + """ + + return self.qsize() + + def __bool__(self): + """ + A queue object is always True. + + .. versionadded: 1.1b3 + + Now that queues support len(), they need to implement ``__bool__`` + to return True for backwards compatibility. + """ + return True + + def empty(self): + """Return ``True`` if the queue is empty, ``False`` otherwise.""" + return not self.qsize() + + def full(self): + """Return ``True`` if the queue is full, ``False`` otherwise. + + ``Queue(None)`` is never full. + """ + return self._maxsize > 0 and self.qsize() >= self._maxsize + + def put(self, item, block=True, timeout=None): + """ + Put an item into the queue. + + If optional arg *block* is true and *timeout* is ``None`` (the default), + block if necessary until a free slot is available. If *timeout* is + a positive number, it blocks at most *timeout* seconds and raises + the :class:`Full` exception if no free slot was available within that time. + Otherwise (*block* is false), put an item on the queue if a free slot + is immediately available, else raise the :class:`Full` exception (*timeout* + is ignored in that case). + + ... versionchanged:: 24.10.1 + Now raises a ``ValueError`` for a negative *timeout* in the cases + that CPython does. + """ + if self.is_shutdown: + raise ShutDown + if self._maxsize == -1 or self.qsize() < self._maxsize: + # there's a free slot, put an item right away. + # For compatibility with CPython, verify that the timeout is non-negative. + if block and timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + self._put(item) + if self.getters: + self._schedule_unlock() + return + + if self.hub is getcurrent(): # pylint:disable=undefined-variable + # We're in the mainloop, so we cannot wait; we can switch to other greenlets though. + # Check if possible to get a free slot in the queue. + while self.getters and self.qsize() and self.qsize() >= self._maxsize: + getter = self.getters.popleft() + getter.switch(getter) + if self.qsize() < self._maxsize: + self._put(item) + return + raise Full + + if block: + waiter = ItemWaiter(item, self) + self.putters.append(waiter) + timeout = Timeout._start_new_or_dummy(timeout, Full) + try: + if self.getters: + self._schedule_unlock() + result = waiter.get() + if result is not waiter: + raise InvalidSwitchError("Invalid switch into Queue.put: %r" % (result, )) + finally: + timeout.cancel() + _safe_remove(self.putters, waiter) + return + + raise Full + + def put_nowait(self, item): + """Put an item into the queue without blocking. + + Only enqueue the item if a free slot is immediately available. + Otherwise raise the :class:`Full` exception. + """ + self.put(item, False) + + def __get_or_peek(self, method, block, timeout): + # Internal helper method. The `method` should be either + # self._get when called from self.get() or self._peek when + # called from self.peek(). Call this after the initial check + # to see if there are items in the queue. + + if self.is_shutdown: + raise ShutDown + + if block and timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + if self.hub is getcurrent(): # pylint:disable=undefined-variable + # special case to make get_nowait() or peek_nowait() runnable in the mainloop greenlet + # there are no items in the queue; try to fix the situation by unlocking putters + while self.putters: + # Note: get() used popleft(), peek used pop(); popleft + # is almost certainly correct. + self.putters.popleft().put_and_switch() + if self.qsize(): + return method() + raise Empty + + if not block: + # We can't block, we're not the hub, and we have nothing + # to return. No choice but to raise the Empty exception. + # + # CAUTION: Calling ``q.get(False)`` in a tight loop won't + # work like it does in CPython where it should eventually + # let another thread make progress, because there's never + # a chance to switch greenlets here. We don't sleep() + # to enforce that, as that would be a significant behaviour + # change. + raise Empty + + waiter = Waiter() # pylint:disable=undefined-variable + timeout = Timeout._start_new_or_dummy(timeout, Empty) + try: + self.getters.append(waiter) + if self.putters: + self._schedule_unlock() + result = waiter.get() + if result is not waiter: + raise InvalidSwitchError('Invalid switch into Queue.get: %r' % (result, )) + return method() + finally: + timeout.cancel() + _safe_remove(self.getters, waiter) + + def get(self, block=True, timeout=None): + """ + Remove and return an item from the queue. + + If optional args *block* is true and *timeout* is ``None`` (the default), + block if necessary until an item is available. If *timeout* is a positive number, + it blocks at most *timeout* seconds and raises the :class:`Empty` exception + if no item was available within that time. Otherwise (*block* is false), return + an item if one is immediately available, else raise the :class:`Empty` exception + (*timeout* is ignored in that case). + """ + if self.qsize(): + if self.putters: + self._schedule_unlock() + return self._get() + + return self.__get_or_peek(self._get, block, timeout) + + def get_nowait(self): + """Remove and return an item from the queue without blocking. + + Only get an item if one is immediately available. Otherwise + raise the :class:`Empty` exception. + """ + return self.get(False) + + def peek(self, block=True, timeout=None): + """Return an item from the queue without removing it. + + If optional args *block* is true and *timeout* is ``None`` (the default), + block if necessary until an item is available. If *timeout* is a positive number, + it blocks at most *timeout* seconds and raises the :class:`Empty` exception + if no item was available within that time. Otherwise (*block* is false), return + an item if one is immediately available, else raise the :class:`Empty` exception + (*timeout* is ignored in that case). + """ + if self.qsize(): + # This doesn't schedule an unlock like get() does because we're not + # actually making any space. + return self._peek() + + return self.__get_or_peek(self._peek, block, timeout) + + def peek_nowait(self): + """Return an item from the queue without blocking. + + Only return an item if one is immediately available. Otherwise + raise the :class:`Empty` exception. + """ + return self.peek(False) + + def _unlock(self): + while True: + repeat = False + if self.putters and (self._maxsize == -1 or self.qsize() < self._maxsize): + repeat = True + try: + putter = self.putters.popleft() + self._put(putter.item) + except: # pylint:disable=bare-except + putter.throw(*sys.exc_info()) + else: + putter.switch(putter) + if self.getters and self.qsize(): + repeat = True + getter = self.getters.popleft() + getter.switch(getter) + if not repeat: + return + + def _schedule_unlock(self): + if not self._event_unlock: + self._event_unlock = self.hub.loop.run_callback(self._unlock) + + def __iter__(self): + return self + + def __next__(self): + result = self.get() + if result is StopIteration: + raise result + return result + + def shutdown(self, immediate=False): + """ + "Shut-down the queue, making queue gets and puts raise + `ShutDown`. + + By default, gets will only raise once the queue is empty. Set + *immediate* to True to make gets raise immediately instead. + + All blocked callers of `put` and `get` will be unblocked. + + In joinable queues, if *immediate*, a task is marked as done + for each item remaining in the queue, which may unblock + callers of `join`. + """ + self.is_shutdown = True + if immediate: + self._drain_for_immediate_shutdown() + getters = list(self.getters) + putters = list(self.putters) + self.getters.clear() + self.putters.clear() + for waiter in getters + putters: + self.hub.loop.run_callback(waiter.throw, ShutDown) + + def _drain_for_immediate_shutdown(self): + while self.qsize(): + self.get() + +class UnboundQueue(Queue): + # A specialization of Queue that knows it can never + # be bound. Changing its maxsize has no effect. + + __slots__ = () + + def __init__(self, maxsize=None, items=()): + if maxsize is not None: + raise ValueError("UnboundQueue has no maxsize") + Queue.__init__(self, maxsize, items) + self.putters = None # Will never be used. + + def put(self, item, block=True, timeout=None): + self._put(item) + if self.getters: + self._schedule_unlock() + + +class PriorityQueue(Queue): + '''A subclass of :class:`Queue` that retrieves entries in priority order (lowest first). + + Entries are typically tuples of the form: ``(priority number, data)``. + + .. versionchanged:: 1.2a1 + Any *items* given to the constructor will now be passed through + :func:`heapq.heapify` to ensure the invariants of this class hold. + Previously it was just assumed that they were already a heap. + ''' + + __slots__ = () + + def _create_queue(self, items=()): + q = list(items) + _heapify(q) + return q + + def _put(self, item): + _heappush(self.queue, item) + + def _get(self): + return _heappop(self.queue) + + +class JoinableQueue(Queue): + """ + A subclass of :class:`Queue` that additionally has + :meth:`task_done` and :meth:`join` methods. + """ + + __slots__ = ( + '_cond', + 'unfinished_tasks', + ) + + def __init__(self, maxsize=None, items=(), unfinished_tasks=None): + """ + + .. versionchanged:: 1.1a1 + If *unfinished_tasks* is not given, then all the given *items* + (if any) will be considered unfinished. + + """ + Queue.__init__(self, maxsize, items, _warn_depth=3) + + from gevent.event import Event + self._cond = Event() + self._cond.set() + + if unfinished_tasks: + self.unfinished_tasks = unfinished_tasks + elif items: + self.unfinished_tasks = len(items) + else: + self.unfinished_tasks = 0 + + if self.unfinished_tasks: + self._cond.clear() + + def copy(self): + return type(self)(self.maxsize, self.queue, self.unfinished_tasks) + + def _format(self): + result = Queue._format(self) + if self.unfinished_tasks: + result += ' tasks=%s _cond=%s' % (self.unfinished_tasks, self._cond) + return result + + def _put(self, item): + Queue._put(self, item) + self._did_put_task() + + def _did_put_task(self): + self.unfinished_tasks += 1 + self._cond.clear() + + def task_done(self): + '''Indicate that a formerly enqueued task is complete. Used by queue consumer threads. + For each :meth:`get ` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue + that the processing on the task is complete. + + If a :meth:`join` is currently blocking, it will resume when all items have been processed + (meaning that a :meth:`task_done` call was received for every item that had been + :meth:`put ` into the queue). + + Raises a :exc:`ValueError` if called more times than there were items placed in the queue. + ''' + if self.unfinished_tasks <= 0: + raise ValueError('task_done() called too many times') + self.unfinished_tasks -= 1 + if self.unfinished_tasks == 0: + self._cond.set() + + def join(self, timeout=None): + ''' + Block until all items in the queue have been gotten and processed. + + The count of unfinished tasks goes up whenever an item is added to the queue. + The count goes down whenever a consumer thread calls :meth:`task_done` to indicate + that the item was retrieved and all work on it is complete. When the count of + unfinished tasks drops to zero, :meth:`join` unblocks. + + :param float timeout: If not ``None``, then wait no more than this time in seconds + for all tasks to finish. + :return: ``True`` if all tasks have finished; if ``timeout`` was given and expired before + all tasks finished, ``False``. + + .. versionchanged:: 1.1a1 + Add the *timeout* parameter. + ''' + return self._cond.wait(timeout=timeout) + + def _drain_for_immediate_shutdown(self): + while self.qsize(): + self.get() + self.task_done() + + +class LifoQueue(JoinableQueue): + """ + A subclass of :class:`JoinableQueue` that retrieves most recently added entries first. + + .. versionchanged:: 24.10.1 + Now extends :class:`JoinableQueue` instead of just :class:`Queue`. + + """ + __slots__ = () + + def _create_queue(self, items=()): + return list(items) + + def _put(self, item): + self.queue.append(item) + self._did_put_task() + + def _get(self): + return self.queue.pop() + + def _peek(self): + return self.queue[-1] + + +class Channel(object): + + __slots__ = ( + 'getters', + 'putters', + 'hub', + '_event_unlock', + '__weakref__', + ) + + def __init__(self, maxsize=1): + # We take maxsize to simplify certain kinds of code + if maxsize != 1: + raise ValueError("Channels have a maxsize of 1") + self.getters = collections.deque() + self.putters = collections.deque() + self.hub = get_hub() + self._event_unlock = None + + def __repr__(self): + return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._format()) + + def __str__(self): + return '<%s %s>' % (type(self).__name__, self._format()) + + def _format(self): + result = '' + if self.getters: + result += ' getters[%s]' % len(self.getters) + if self.putters: + result += ' putters[%s]' % len(self.putters) + return result + + @property + def balance(self): + return len(self.putters) - len(self.getters) + + def qsize(self): + return 0 + + def empty(self): + return True + + def full(self): + return True + + def put(self, item, block=True, timeout=None): + if self.hub is getcurrent(): # pylint:disable=undefined-variable + if self.getters: + getter = self.getters.popleft() + getter.switch(item) + return + raise Full + + if not block: + timeout = 0 + + waiter = Waiter() # pylint:disable=undefined-variable + item = (item, waiter) + self.putters.append(item) + timeout = Timeout._start_new_or_dummy(timeout, Full) + try: + if self.getters: + self._schedule_unlock() + result = waiter.get() + if result is not waiter: + raise InvalidSwitchError("Invalid switch into Channel.put: %r" % (result, )) + except: + _safe_remove(self.putters, item) + raise + finally: + timeout.cancel() + + def put_nowait(self, item): + self.put(item, False) + + def get(self, block=True, timeout=None): + if self.hub is getcurrent(): # pylint:disable=undefined-variable + if self.putters: + item, putter = self.putters.popleft() + self.hub.loop.run_callback(putter.switch, putter) + return item + + if not block: + timeout = 0 + + waiter = Waiter() # pylint:disable=undefined-variable + timeout = Timeout._start_new_or_dummy(timeout, Empty) + try: + self.getters.append(waiter) + if self.putters: + self._schedule_unlock() + return waiter.get() + except: + self.getters.remove(waiter) + raise + finally: + timeout.close() + + def get_nowait(self): + return self.get(False) + + def _unlock(self): + while self.putters and self.getters: + getter = self.getters.popleft() + item, putter = self.putters.popleft() + getter.switch(item) + putter.switch(putter) + + def _schedule_unlock(self): + if not self._event_unlock: + self._event_unlock = self.hub.loop.run_callback(self._unlock) + + def __iter__(self): + return self + + def __next__(self): + result = self.get() + if result is StopIteration: + raise result + return result + + next = __next__ # Py2 + +def _init(): + greenlet_init() # pylint:disable=undefined-variable + +_init() + + +from gevent._util import import_c_accel +import_c_accel(globals(), 'gevent._queue') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5fc123ef3eb4f3642025f8774668a1a4bd92f0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/__init__.py @@ -0,0 +1,285 @@ +# Copyright (c) 2018 gevent contributors. See LICENSE for details. + +import _socket +from _socket import AF_INET +from _socket import AF_UNSPEC +from _socket import AI_CANONNAME +from _socket import AI_PASSIVE +from _socket import AI_NUMERICHOST +from _socket import EAI_NONAME +from _socket import EAI_SERVICE +from _socket import SOCK_DGRAM +from _socket import SOCK_STREAM +from _socket import SOL_TCP +from _socket import error +from _socket import gaierror +from _socket import getaddrinfo as native_getaddrinfo +from _socket import getnameinfo as native_getnameinfo +from _socket import gethostbyaddr as native_gethostbyaddr +from _socket import gethostbyname as native_gethostbyname +from _socket import gethostbyname_ex as native_gethostbyname_ex +from _socket import getservbyname as native_getservbyname + + +from gevent._compat import string_types +from gevent._compat import text_type +from gevent._compat import hostname_types +from gevent._compat import integer_types +from gevent._compat import PYPY +from gevent._compat import MAC + +from gevent.resolver._addresses import is_ipv6_addr +# Nothing public here. +__all__ = () + +# trigger import of encodings.idna to avoid https://github.com/gevent/gevent/issues/349 +u'foo'.encode('idna') + + +def _lookup_port(port, socktype): + # pylint:disable=too-many-branches + socktypes = [] + if isinstance(port, string_types): + try: + port = int(port) + except ValueError: + try: + if socktype == 0: + origport = port + try: + port = native_getservbyname(port, 'tcp') + socktypes.append(SOCK_STREAM) + except error: + port = native_getservbyname(port, 'udp') + socktypes.append(SOCK_DGRAM) + else: + try: + if port == native_getservbyname(origport, 'udp'): + socktypes.append(SOCK_DGRAM) + except error: + pass + elif socktype == SOCK_STREAM: + port = native_getservbyname(port, 'tcp') + elif socktype == SOCK_DGRAM: + port = native_getservbyname(port, 'udp') + else: + raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype') + except error as ex: + if 'not found' in str(ex): + raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype') + raise gaierror(str(ex)) + except UnicodeEncodeError: + raise error('Int or String expected', port) + elif port is None: + port = 0 + elif isinstance(port, integer_types): + pass + else: + raise error('Int or String expected', port, type(port)) + port = int(port % 65536) + if not socktypes and socktype: + socktypes.append(socktype) + return port, socktypes + + + +def _resolve_special(hostname, family): + if not isinstance(hostname, hostname_types): + raise TypeError("argument 1 must be str, bytes or bytearray, not %s" % (type(hostname),)) + + if hostname in (u'', b''): + result = native_getaddrinfo(None, 0, family, SOCK_DGRAM, 0, AI_PASSIVE) + if len(result) != 1: + raise error('wildcard resolved to multiple address') + return result[0][4][0] + return hostname + + +class AbstractResolver(object): + + HOSTNAME_ENCODING = 'idna' + + _LOCAL_HOSTNAMES = ( + b'localhost', + b'ip6-localhost', + b'::1', + b'127.0.0.1', + ) + + _LOCAL_AND_BROADCAST_HOSTNAMES = _LOCAL_HOSTNAMES + ( + b'255.255.255.255', + b'', + ) + + EAI_NONAME_MSG = ( + 'nodename nor servname provided, or not known' + if MAC else + 'Name or service not known' + ) + + EAI_FAMILY_MSG = ( + 'ai_family not supported' + ) + + _KNOWN_ADDR_FAMILIES = { + v + for k, v in vars(_socket).items() + if k.startswith('AF_') + } + + _KNOWN_SOCKTYPES = { + v + for k, v in vars(_socket).items() + if k.startswith('SOCK_') + and k not in ('SOCK_CLOEXEC', 'SOCK_MAX_SIZE') + } + + def close(self): + """ + Release resources held by this object. + + Subclasses that define resources should override. + + .. versionadded:: 22.10.1 + """ + + @staticmethod + def fixup_gaierror(func): + import functools + + @functools.wraps(func) + def resolve(self, *args, **kwargs): + try: + return func(self, *args, **kwargs) + except gaierror as ex: + if ex.args[0] == EAI_NONAME and len(ex.args) == 1: + # dnspython doesn't set an error message + ex.args = (EAI_NONAME, self.EAI_NONAME_MSG) + ex.errno = EAI_NONAME + raise + return resolve + + def _hostname_to_bytes(self, hostname): + if isinstance(hostname, text_type): + hostname = hostname.encode(self.HOSTNAME_ENCODING) + elif not isinstance(hostname, (bytes, bytearray)): + raise TypeError('Expected str, bytes or bytearray, not %s' % type(hostname).__name__) + + return bytes(hostname) + + def gethostbyname(self, hostname, family=AF_INET): + # The native ``gethostbyname`` and ``gethostbyname_ex`` have some different + # behaviour with special names. Notably, ``gethostbyname`` will handle + # both "" and "255.255.255.255", while ``gethostbyname_ex`` refuses to + # handle those; they result in different errors, too. So we can't + # pass those through. + hostname = self._hostname_to_bytes(hostname) + if hostname in self._LOCAL_AND_BROADCAST_HOSTNAMES: + return native_gethostbyname(hostname) + hostname = _resolve_special(hostname, family) + return self.gethostbyname_ex(hostname, family)[-1][0] + + def _gethostbyname_ex(self, hostname_bytes, family): + """Raise an ``herror`` or a ``gaierror``.""" + aliases = self._getaliases(hostname_bytes, family) + addresses = [] + tuples = self.getaddrinfo(hostname_bytes, 0, family, + SOCK_STREAM, + SOL_TCP, AI_CANONNAME) + canonical = tuples[0][3] + for item in tuples: + addresses.append(item[4][0]) + # XXX we just ignore aliases + return (canonical, aliases, addresses) + + def gethostbyname_ex(self, hostname, family=AF_INET): + hostname = self._hostname_to_bytes(hostname) + if hostname in self._LOCAL_AND_BROADCAST_HOSTNAMES: + # The broadcast specials aren't handled here, but they may produce + # special errors that are hard to replicate across all systems. + return native_gethostbyname_ex(hostname) + return self._gethostbyname_ex(hostname, family) + + def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags): + raise NotImplementedError + + def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0): + host = self._hostname_to_bytes(host) if host is not None else None + + if ( + not isinstance(host, bytes) # 1, 2 + or (flags & AI_NUMERICHOST) # 3 + or host in self._LOCAL_HOSTNAMES # 4 + or (is_ipv6_addr(host) and host.startswith(b'fe80')) # 5 + ): + # This handles cases which do not require network access + # 1) host is None + # 2) host is of an invalid type + # 3) AI_NUMERICHOST flag is set + # 4) It's a well-known alias. TODO: This is special casing for c-ares that we don't + # really want to do. It's here because it resolves a discrepancy with the system + # resolvers caught by test cases. In gevent 20.4.0, this only worked correctly on + # Python 3 and not Python 2, by accident. + # 5) host is a link-local ipv6; dnspython returns the wrong + # scope-id for those. + return native_getaddrinfo(host, port, family, socktype, proto, flags) + + return self._getaddrinfo(host, port, family, socktype, proto, flags) + + def _getaliases(self, hostname, family): + # pylint:disable=unused-argument + return [] + + def _gethostbyaddr(self, ip_address_bytes): + """Raises herror.""" + raise NotImplementedError + + def gethostbyaddr(self, ip_address): + ip_address = _resolve_special(ip_address, AF_UNSPEC) + ip_address = self._hostname_to_bytes(ip_address) + if ip_address in self._LOCAL_AND_BROADCAST_HOSTNAMES: + return native_gethostbyaddr(ip_address) + + return self._gethostbyaddr(ip_address) + + def _getnameinfo(self, address_bytes, port, sockaddr, flags): + raise NotImplementedError + + def getnameinfo(self, sockaddr, flags): + if not isinstance(flags, integer_types): + raise TypeError('an integer is required') + if not isinstance(sockaddr, tuple): + raise TypeError('getnameinfo() argument 1 must be a tuple') + + address = sockaddr[0] + address = self._hostname_to_bytes(sockaddr[0]) + + if address in self._LOCAL_AND_BROADCAST_HOSTNAMES: + return native_getnameinfo(sockaddr, flags) + + port = sockaddr[1] + if not isinstance(port, integer_types): + raise TypeError('port must be an integer, not %s' % type(port)) + + if not PYPY and port >= 65536: + # System resolvers do different things with an + # out-of-bound port; macOS CPython 3.8 raises ``gaierror: [Errno 8] + # nodename nor servname provided, or not known``, while + # manylinux CPython 2.7 appears to ignore it and raises ``error: + # sockaddr resolved to multiple addresses``. TravisCI, at least ot + # one point, successfully resolved www.gevent.org to ``(readthedocs.org, '0')``. + # But c-ares 1.16 would raise ``gaierror(25, 'ARES_ESERVICE: unknown')``. + # Doing this appears to get the expected results on CPython + port = 0 + if PYPY and (port < 0 or port >= 65536): + # PyPy seems to always be strict about that and produce the same results + # on all platforms. + raise OverflowError("port must be 0-65535.") + + if len(sockaddr) > 2: + # Must be IPv6: (host, port, [flowinfo, [scopeid]]) + flowinfo = sockaddr[2] + if flowinfo > 0xfffff: + raise OverflowError("getnameinfo(): flowinfo must be 0-1048575.") + + return self._getnameinfo(address, port, sockaddr, flags) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_addresses.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_addresses.py new file mode 100644 index 0000000000000000000000000000000000000000..f6682a1a802709a4dbfc034e5385e05cece41c95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_addresses.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019 gevent contributors. See LICENSE for details. +# +# Portions of this code taken from dnspython +# https://github.com/rthalley/dnspython +# +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, 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. +""" +Private support for parsing textual addresses. + +""" +from __future__ import absolute_import, division, print_function + +import binascii +import re +import struct + +from gevent.resolver import hostname_types + + +class AddressSyntaxError(ValueError): + pass + + +def _ipv4_inet_aton(text): + """ + Convert an IPv4 address in text form to binary struct. + + *text*, a ``text``, the IPv4 address in textual form. + + Returns a ``binary``. + """ + + if not isinstance(text, bytes): + text = text.encode() + parts = text.split(b'.') + if len(parts) != 4: + raise AddressSyntaxError(text) + for part in parts: + if not part.isdigit(): + raise AddressSyntaxError + if len(part) > 1 and part[0] == '0': + # No leading zeros + raise AddressSyntaxError(text) + try: + ints = [int(part) for part in parts] + return struct.pack('BBBB', *ints) + except: + raise AddressSyntaxError(text) + + +def _ipv6_inet_aton(text, + _v4_ending=re.compile(br'(.*):(\d+\.\d+\.\d+\.\d+)$'), + _colon_colon_start=re.compile(br'::.*'), + _colon_colon_end=re.compile(br'.*::$')): + """ + Convert an IPv6 address in text form to binary form. + + *text*, a ``text``, the IPv6 address in textual form. + + Returns a ``binary``. + """ + # pylint:disable=too-many-branches + + # + # Our aim here is not something fast; we just want something that works. + # + if not isinstance(text, bytes): + text = text.encode() + + if text == b'::': + text = b'0::' + # + # Get rid of the icky dot-quad syntax if we have it. + # + m = _v4_ending.match(text) + if not m is None: + b = bytearray(_ipv4_inet_aton(m.group(2))) + text = (u"{}:{:02x}{:02x}:{:02x}{:02x}".format(m.group(1).decode(), + b[0], b[1], b[2], + b[3])).encode() + # + # Try to turn '::' into ':'; if no match try to + # turn '::' into ':' + # + m = _colon_colon_start.match(text) + if not m is None: + text = text[1:] + else: + m = _colon_colon_end.match(text) + if not m is None: + text = text[:-1] + # + # Now canonicalize into 8 chunks of 4 hex digits each + # + chunks = text.split(b':') + l = len(chunks) + if l > 8: + raise SyntaxError + seen_empty = False + canonical = [] + for c in chunks: + if c == b'': + if seen_empty: + raise AddressSyntaxError(text) + seen_empty = True + for _ in range(0, 8 - l + 1): + canonical.append(b'0000') + else: + lc = len(c) + if lc > 4: + raise AddressSyntaxError(text) + if lc != 4: + c = (b'0' * (4 - lc)) + c + canonical.append(c) + if l < 8 and not seen_empty: + raise AddressSyntaxError(text) + text = b''.join(canonical) + + # + # Finally we can go to binary. + # + try: + return binascii.unhexlify(text) + except (binascii.Error, TypeError): + raise AddressSyntaxError(text) + + +def _is_addr(host, parse=_ipv4_inet_aton): + if not host or not isinstance(host, hostname_types): + return False + + try: + parse(host) + except AddressSyntaxError: + return False + return True + +# Return True if host is a valid IPv4 address +is_ipv4_addr = _is_addr + + +def is_ipv6_addr(host): + # Return True if host is a valid IPv6 address + if host and isinstance(host, hostname_types): + s = '%' if isinstance(host, str) else b'%' + host = host.split(s, 1)[0] + return _is_addr(host, _ipv6_inet_aton) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_hostsfile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_hostsfile.py new file mode 100644 index 0000000000000000000000000000000000000000..792f849d94da15d51eebfe4795bb7c68e2a53ae2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_hostsfile.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2019 gevent contributors. See LICENSE for details. +# +# Portions of this code taken from dnspython +# https://github.com/rthalley/dnspython +# +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, 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. +""" +Private support for parsing /etc/hosts. + +""" +from __future__ import absolute_import, division, print_function + +import sys +import os +import re + +from gevent.resolver._addresses import is_ipv4_addr +from gevent.resolver._addresses import is_ipv6_addr + +from gevent._compat import iteritems + + +class HostsFile(object): + """ + A class to read the contents of a hosts file (/etc/hosts). + """ + + LINES_RE = re.compile(r""" + \s* # Leading space + ([^\r\n#]+?) # The actual match, non-greedy so as not to include trailing space + \s* # Trailing space + (?:[#][^\r\n]+)? # Comments + (?:$|[\r\n]+) # EOF or newline + """, re.VERBOSE) + + def __init__(self, fname=None): + self.v4 = {} # name -> ipv4 + self.v6 = {} # name -> ipv6 + self.aliases = {} # name -> canonical_name + self.reverse = {} # ip addr -> some name + if fname is None: + if os.name == 'posix': + fname = '/etc/hosts' + elif os.name == 'nt': # pragma: no cover + fname = os.path.expandvars( + r'%SystemRoot%\system32\drivers\etc\hosts') + self.fname = fname + assert self.fname + self._last_load = 0 + + + def _readlines(self): + # Read the contents of the hosts file. + # + # Return list of lines, comment lines and empty lines are + # excluded. Note that this performs disk I/O so can be + # blocking. + with open(self.fname, 'rb') as fp: + fdata = fp.read() + + + # XXX: Using default decoding. Is that correct? + udata = fdata.decode(errors='ignore') if not isinstance(fdata, str) else fdata + + return self.LINES_RE.findall(udata) + + def load(self): # pylint:disable=too-many-locals + # Load hosts file + + # This will (re)load the data from the hosts + # file if it has changed. + + try: + load_time = os.stat(self.fname).st_mtime + needs_load = load_time > self._last_load + except OSError: + from gevent import get_hub + get_hub().handle_error(self, *sys.exc_info()) + needs_load = False + + if not needs_load: + return + + v4 = {} + v6 = {} + aliases = {} + reverse = {} + + for line in self._readlines(): + parts = line.split() + if len(parts) < 2: + continue + ip = parts.pop(0) + if is_ipv4_addr(ip): + ipmap = v4 + elif is_ipv6_addr(ip): + if ip.startswith('fe80'): + # Do not use link-local addresses, OSX stores these here + continue + ipmap = v6 + else: + continue + cname = parts.pop(0).lower() + ipmap[cname] = ip + for alias in parts: + alias = alias.lower() + ipmap[alias] = ip + aliases[alias] = cname + + # XXX: This is wrong for ipv6 + if ipmap is v4: + ptr = '.'.join(reversed(ip.split('.'))) + '.in-addr.arpa' + else: + ptr = ip + '.ip6.arpa.' + if ptr not in reverse: + reverse[ptr] = cname + + self._last_load = load_time + self.v4 = v4 + self.v6 = v6 + self.aliases = aliases + self.reverse = reverse + + def iter_all_host_addr_pairs(self): + self.load() + for name, addr in iteritems(self.v4): + yield name, addr + for name, addr in iteritems(self.v6): + yield name, addr diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/ares.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/ares.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec22256f8ed30c40069e76dd5e6f8bb463bd40a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/ares.py @@ -0,0 +1,355 @@ +# Copyright (c) 2011-2015 Denis Bilenko. See LICENSE for details. +""" +c-ares based hostname resolver. +""" +from __future__ import absolute_import, print_function, division +import os +import warnings + +from _socket import gaierror +from _socket import herror +from _socket import error +from _socket import EAI_NONAME + +from gevent._compat import text_type +from gevent._compat import integer_types + +from gevent.hub import Waiter +from gevent.hub import get_hub + +from gevent.socket import AF_UNSPEC +from gevent.socket import AF_INET +from gevent.socket import AF_INET6 +from gevent.socket import SOCK_DGRAM +from gevent.socket import SOCK_STREAM +from gevent.socket import SOL_TCP +from gevent.socket import SOL_UDP + + +from gevent._config import config +from gevent._config import AresSettingMixin + +from .cares import channel, InvalidIP # pylint:disable=import-error,no-name-in-module +from . import _lookup_port as lookup_port +from . import AbstractResolver + +__all__ = ['Resolver'] + + +class Resolver(AbstractResolver): + """ + Implementation of the resolver API using the `c-ares`_ library. + + This implementation uses the c-ares library to handle name + resolution. c-ares is natively asynchronous at the socket level + and so integrates well into gevent's event loop. + + In comparison to :class:`gevent.resolver_thread.Resolver` (which + delegates to the native system resolver), the implementation is + much more complex. In addition, there have been reports of it not + properly honoring certain system configurations (for example, the + order in which IPv4 and IPv6 results are returned may not match + the threaded resolver). However, because it does not use threads, + it may scale better for applications that make many lookups. + + There are some known differences from the system resolver. + + - ``gethostbyname_ex`` and ``gethostbyaddr`` may return + different for the ``aliaslist`` tuple member. (Sometimes the + same, sometimes in a different order, sometimes a different + alias altogether.) + + - ``gethostbyname_ex`` may return the ``ipaddrlist`` in a + different order. + + - ``getaddrinfo`` does not return ``SOCK_RAW`` results. + + - ``getaddrinfo`` may return results in a different order. + + - Handling of ``.local`` (mDNS) names may be different, even + if they are listed in the hosts file. + + - c-ares will not resolve ``broadcasthost``, even if listed in + the hosts file prior to 2020-04-30. + + - This implementation may raise ``gaierror(4)`` where the + system implementation would raise ``herror(1)`` or vice versa, + with different error numbers. However, after 2020-04-30, this should be + much reduced. + + - The results for ``localhost`` may be different. In + particular, some system resolvers will return more results + from ``getaddrinfo`` than c-ares does, such as SOCK_DGRAM + results, and c-ares may report more ips on a multi-homed + host. + + - The system implementation may return some names fully qualified, where + this implementation returns only the host name. This appears to be + the case only with entries found in ``/etc/hosts``. + + - c-ares supports a limited set of flags for ``getnameinfo`` and + ``getaddrinfo``; unknown flags are ignored. System-specific flags + such as ``AI_V4MAPPED_CFG`` are not supported. + + - ``getaddrinfo`` may return canonical names even without the ``AI_CANONNAME`` + being set. + + - ``getaddrinfo`` does not appear to support IPv6 symbolic scope IDs. + + .. caution:: + + This module is considered extremely experimental on PyPy, and + due to its implementation in cython, it may be slower. It may also lead to + interpreter crashes. + + .. versionchanged:: 1.5.0 + This version of gevent typically embeds c-ares 1.15.0 or newer. In + that version of c-ares, domains ending in ``.onion`` `are never + resolved `_ or even + sent to the DNS server. + + .. versionchanged:: 20.5.0 + ``getaddrinfo`` is now implemented using the native c-ares function + from c-ares 1.16 or newer. + + .. versionchanged:: 20.5.0 + Now ``herror`` and ``gaierror`` are raised more consistently with + the standard library resolver, and have more consistent errno values. + + Handling of localhost and broadcast names is now more consistent. + + .. versionchanged:: 22.10.1 + Now has a ``__del__`` method that warns if the object is destroyed + without being properly closed. + + .. _c-ares: http://c-ares.haxx.se + """ + + cares_class = channel + + def __init__(self, hub=None, use_environ=True, **kwargs): + AbstractResolver.__init__(self) + if hub is None: + hub = get_hub() + self.hub = hub + if use_environ: + for setting in config.settings.values(): + if isinstance(setting, AresSettingMixin): + value = setting.get() + if value is not None: + kwargs.setdefault(setting.kwarg_name, value) + self.cares = self.cares_class(hub.loop, **kwargs) + self.pid = os.getpid() + self.params = kwargs + self.fork_watcher = hub.loop.fork(ref=False) # We shouldn't keep the loop alive + self.fork_watcher.start(self._on_fork) + + def __repr__(self): + return '' % (id(self), self.cares) + + def _on_fork(self): + # NOTE: See comment in gevent.hub.reinit. + pid = os.getpid() + if pid != self.pid: + self.hub.loop.run_callback(self.cares.destroy) + self.cares = self.cares_class(self.hub.loop, **self.params) + self.pid = pid + + def close(self): + AbstractResolver.close(self) + if self.cares is not None: + self.hub.loop.run_callback(self.cares.destroy) + self.cares = None + self.fork_watcher.stop() + + def __del__(self): + if self.cares is not None: + warnings.warn("cares Resolver destroyed while not closed", + ResourceWarning) + self.close() + + def _gethostbyname_ex(self, hostname_bytes, family): + while True: + ares = self.cares + try: + waiter = Waiter(self.hub) + ares.gethostbyname(waiter, hostname_bytes, family) + result = waiter.get() + if not result[-1]: + raise herror(EAI_NONAME, self.EAI_NONAME_MSG) + return result + except herror as ex: + if ares is self.cares: + if ex.args[0] == 1: + # Somewhere along the line, the internal + # implementation of gethostbyname_ex changed to invoke + # getaddrinfo() as a first pass, much like we do for ``getnameinfo()``; + # this means it raises a different error for not-found hosts. + raise gaierror(EAI_NONAME, self.EAI_NONAME_MSG) + raise + # "self.cares is not ares" means channel was destroyed (because we were forked) + + def _lookup_port(self, port, socktype): + return lookup_port(port, socktype) + + def __getaddrinfo( + self, host, port, + family=0, socktype=0, proto=0, flags=0, + fill_in_type_proto=True + ): + """ + Returns a list ``(family, socktype, proto, canonname, sockaddr)`` + + :raises gaierror: If no results are found. + """ + # pylint:disable=too-many-locals,too-many-branches + if isinstance(host, text_type): + host = host.encode('idna') + + + if isinstance(port, text_type): + port = port.encode('ascii') + elif isinstance(port, integer_types): + if port == 0: + port = None + else: + port = str(port).encode('ascii') + + waiter = Waiter(self.hub) + self.cares.getaddrinfo( + waiter, + host, + port, + family, + socktype, + proto, + flags, + ) + # Result is a list of: + # (family, socktype, proto, canonname, sockaddr) + # Where sockaddr depends on family; for INET it is + # (address, port) + # and INET6 is + # (address, port, flow info, scope id) + result = waiter.get() + + if not result: + raise gaierror(EAI_NONAME, self.EAI_NONAME_MSG) + + if fill_in_type_proto: + # c-ares 1.16 DOES NOT fill in socktype or proto in the results, + # ever. It's at least supposed to do that if they were given as + # hints, but it doesn't (https://github.com/c-ares/c-ares/issues/317) + # Sigh. + # The SOL_* constants are another (older?) name for IPPROTO_* + if socktype: + hard_type_proto = [ + (socktype, SOL_TCP if socktype == SOCK_STREAM else SOL_UDP), + ] + elif proto: + hard_type_proto = [ + (SOCK_STREAM if proto == SOL_TCP else SOCK_DGRAM, proto), + ] + else: + hard_type_proto = [ + (SOCK_STREAM, SOL_TCP), + (SOCK_DGRAM, SOL_UDP), + ] + + # pylint:disable=not-an-iterable,unsubscriptable-object + result = [ + (rfamily, + hard_type if not rtype else rtype, + hard_proto if not rproto else rproto, + rcanon, + raddr) + for rfamily, rtype, rproto, rcanon, raddr + in result + for hard_type, hard_proto + in hard_type_proto + ] + return result + + def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags): + while True: + ares = self.cares + try: + return self.__getaddrinfo(host_bytes, port, family, socktype, proto, flags) + except gaierror: + if ares is self.cares: + raise + + def __gethostbyaddr(self, ip_address): + waiter = Waiter(self.hub) + try: + self.cares.gethostbyaddr(waiter, ip_address) + return waiter.get() + except InvalidIP: + result = self._getaddrinfo(ip_address, None, + family=AF_UNSPEC, socktype=SOCK_DGRAM, + proto=0, flags=0) + if not result: + raise + # pylint:disable=unsubscriptable-object + _ip_address = result[0][-1][0] + if isinstance(_ip_address, text_type): + _ip_address = _ip_address.encode('ascii') + if _ip_address == ip_address: + raise + waiter.clear() + self.cares.gethostbyaddr(waiter, _ip_address) + return waiter.get() + + def _gethostbyaddr(self, ip_address_bytes): + while True: + ares = self.cares + try: + return self.__gethostbyaddr(ip_address_bytes) + except herror: + if ares is self.cares: + raise + + def __getnameinfo(self, hostname, port, sockaddr, flags): + result = self.__getaddrinfo( + hostname, port, + family=AF_UNSPEC, socktype=SOCK_DGRAM, + proto=0, flags=0, + fill_in_type_proto=False) + if len(result) != 1: + raise error('sockaddr resolved to multiple addresses') + + family, _socktype, _proto, _name, address = result[0] + + if family == AF_INET: + if len(sockaddr) != 2: + raise error("IPv4 sockaddr must be 2 tuple") + elif family == AF_INET6: + address = address[:2] + sockaddr[2:] + + waiter = Waiter(self.hub) + self.cares.getnameinfo(waiter, address, flags) + node, service = waiter.get() + + if service is None: + # ares docs: "If the query did not complete + # successfully, or one of the values was not + # requested, node or service will be NULL ". Python 2 + # allows that for the service, but Python 3 raises + # an error. This is tested by test_socket in py 3.4 + err = gaierror(EAI_NONAME, self.EAI_NONAME_MSG) + err.errno = EAI_NONAME + raise err + + return node, service or '0' + + def _getnameinfo(self, address_bytes, port, sockaddr, flags): + while True: + ares = self.cares + try: + return self.__getnameinfo(address_bytes, port, sockaddr, flags) + except gaierror: + if ares is self.cares: + raise + + # # Things that need proper error handling + # gethostbyaddr = AbstractResolver.convert_gaierror_to_herror(AbstractResolver.gethostbyaddr) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/blocking.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/blocking.py new file mode 100644 index 0000000000000000000000000000000000000000..4a26a764f91c9328e58e1679814a45499aa929c6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/blocking.py @@ -0,0 +1,45 @@ +# Copyright (c) 2018 gevent contributors. See LICENSE for details. + +import _socket + +__all__ = [ + 'Resolver', +] + +class Resolver(object): + """ + A resolver that directly uses the system's resolver functions. + + .. caution:: + + This resolver is *not* cooperative. + + This resolver has the lowest overhead of any resolver and + typically approaches the speed of the unmodified :mod:`socket` + functions. However, it is not cooperative, so if name resolution + blocks, the entire thread and all its greenlets will be blocked. + + This can be useful during debugging, or it may be a good choice if + your operating system provides a good caching resolver (such as + macOS's Directory Services) that is usually very fast and + functionally non-blocking. + + .. versionchanged:: 1.3a2 + This was previously undocumented and existed in :mod:`gevent.socket`. + + """ + + def __init__(self, hub=None): + pass + + def close(self): + pass + + for method in ( + 'gethostbyname', + 'gethostbyname_ex', + 'getaddrinfo', + 'gethostbyaddr', + 'getnameinfo' + ): + locals()[method] = staticmethod(getattr(_socket, method)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/dnspython.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/dnspython.py new file mode 100644 index 0000000000000000000000000000000000000000..df7aded5f5bb38d7fd72ebddfa4d6e907ffd0e67 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/dnspython.py @@ -0,0 +1,511 @@ +# Copyright (c) 2018 gevent contributors. See LICENSE for details. + +# Portions of this code taken from the gogreen project: +# http://github.com/slideinc/gogreen +# +# Copyright (c) 2005-2010 Slide, Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the author nor the names of other +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Portions of this code taken from the eventlet project: +# https://github.com/eventlet/eventlet/blob/master/eventlet/support/greendns.py + +# Unless otherwise noted, the files in Eventlet are under the following MIT license: + +# Copyright (c) 2005-2006, Bob Ippolito +# Copyright (c) 2007-2010, Linden Research, Inc. +# Copyright (c) 2008-2010, Eventlet Contributors (see AUTHORS) + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import sys +import time + +from _socket import error +from _socket import gaierror +from _socket import herror +from _socket import NI_NUMERICSERV +from _socket import AF_INET +from _socket import AF_INET6 +from _socket import AF_UNSPEC +from _socket import EAI_NONAME +from _socket import EAI_FAMILY + + +import socket + +from gevent.resolver import AbstractResolver +from gevent.resolver._hostsfile import HostsFile + +from gevent.builtins import __import__ as g_import + +from gevent._compat import string_types +from gevent._compat import iteritems +from gevent._config import config + + +__all__ = [ + 'Resolver', +] + +# Import the DNS packages to use the gevent modules, +# even if the system is not monkey-patched. If it *is* already +# patched, this imports a second copy under a different name, +# which is probably not strictly necessary, but matches +# what we've historically done, and allows configuring the resolvers +# differently. + +def _patch_dns(): + from gevent._patcher import import_patched as importer + # The dns package itself is empty but defines __all__ + # we make sure to import all of those things now under the + # patch. Note this triggers two DeprecationWarnings, + # one of which we could avoid. + extras = { + 'dns': ('rdata', 'resolver', 'rdtypes'), + 'dns.rdtypes': ('IN', 'ANY', ), + 'dns.rdtypes.IN': ('A', 'AAAA',), + 'dns.rdtypes.ANY': ('SOA', 'PTR'), + } + def extra_all(mod_name): + return extras.get(mod_name, ()) + + def after_import_hook(dns): # pylint:disable=redefined-outer-name + # Runs while still in the original patching scope. + # The dns.rdata:get_rdata_class() function tries to + # dynamically import modules using __import__ and then walk + # through the attribute tree to find classes in `dns.rdtypes`. + # It is critical that this all matches up, otherwise we can + # get different exception classes that don't get caught. + # We could patch __import__ to do things at runtime, but it's + # easier to enumerate the world and populate the cache now + # before we then switch the names back. + rdata = dns.rdata + get_rdata_class = rdata.get_rdata_class + try: + rdclass_values = list(dns.rdataclass.RdataClass) + except AttributeError: + # dnspython < 2.0 + rdclass_values = dns.rdataclass._by_value + + try: + rdtype_values = list(dns.rdatatype.RdataType) + except AttributeError: + # dnspython < 2.0 + rdtype_values = dns.rdatatype._by_value + + + for rdclass in rdclass_values: + for rdtype in rdtype_values: + get_rdata_class(rdclass, rdtype) + + patcher = importer('dns', extra_all, after_import_hook) + top = patcher.module + + # Now disable the dynamic imports + def _no_dynamic_imports(name): + raise ValueError(name) + + top.rdata.__import__ = _no_dynamic_imports + + return top + +dns = _patch_dns() + +resolver = dns.resolver +dTimeout = dns.resolver.Timeout + +# This is a wrapper for dns.resolver._getaddrinfo with two crucial changes. +# First, it backports https://github.com/rthalley/dnspython/issues/316 +# from version 2.0. This can be dropped when we support only dnspython 2 +# (which means only Python 3.) + +# Second, it adds calls to sys.exc_clear() to avoid failing tests in +# test__refcount.py (timeouts) on Python 2. (Actually, this isn't +# strictly necessary, it was necessary to increase the timeouts in +# that function because dnspython is doing some parsing/regex/host +# lookups that are not super fast. But it does have a habit of leaving +# exceptions around which can complicate our memleak checks.) +def _getaddrinfo(host=None, service=None, family=AF_UNSPEC, socktype=0, + proto=0, flags=0, + _orig_gai=resolver._getaddrinfo, + _exc_clear=getattr(sys, 'exc_clear', lambda: None)): + if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0: + # Not implemented. We raise a gaierror as opposed to a + # NotImplementedError as it helps callers handle errors more + # appropriately. [Issue #316] + raise socket.gaierror(socket.EAI_SYSTEM) + res = _orig_gai(host, service, family, socktype, proto, flags) + _exc_clear() + return res + + +resolver._getaddrinfo = _getaddrinfo + +HOSTS_TTL = 300.0 + + +class _HostsAnswer(dns.resolver.Answer): + # Answer class for HostsResolver object + + def __init__(self, qname, rdtype, rdclass, rrset, raise_on_no_answer=True): + self.response = None + self.qname = qname + self.rdtype = rdtype + self.rdclass = rdclass + self.canonical_name = qname + if not rrset and raise_on_no_answer: + raise dns.resolver.NoAnswer() + self.rrset = rrset + self.expiration = (time.time() + + rrset.ttl if hasattr(rrset, 'ttl') else 0) + + +class _HostsResolver(object): + """ + Class to parse the hosts file + """ + + def __init__(self, fname=None, interval=HOSTS_TTL): + self.hosts_file = HostsFile(fname) + self.interval = interval + self._last_load = 0 + + def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, + tcp=False, source=None, raise_on_no_answer=True): # pylint:disable=unused-argument + # Query the hosts file + # + # The known rdtypes are dns.rdatatype.A, dns.rdatatype.AAAA and + # dns.rdatatype.CNAME. + # The ``rdclass`` parameter must be dns.rdataclass.IN while the + # ``tcp`` and ``source`` parameters are ignored. + # Return a HostAnswer instance or raise a dns.resolver.NoAnswer + # exception. + + now = time.time() + hosts_file = self.hosts_file + if self._last_load + self.interval < now: + self._last_load = now + hosts_file.load() + + rdclass = dns.rdataclass.IN # Always + if isinstance(qname, string_types): + name = qname + qname = dns.name.from_text(qname) + else: + name = str(qname) + + name = name.lower() + rrset = dns.rrset.RRset(qname, rdclass, rdtype) + rrset.ttl = self._last_load + self.interval - now + + mapping = None + kind = None + if rdtype == dns.rdatatype.A: + mapping = hosts_file.v4 + kind = dns.rdtypes.IN.A.A + elif rdtype == dns.rdatatype.AAAA: + mapping = hosts_file.v6 + kind = dns.rdtypes.IN.AAAA.AAAA + elif rdtype == dns.rdatatype.CNAME: + mapping = hosts_file.aliases + kind = lambda c, t, addr: dns.rdtypes.ANY.CNAME.CNAME(c, t, dns.name.from_text(addr)) + elif rdtype == dns.rdatatype.PTR: + mapping = hosts_file.reverse + kind = lambda c, t, addr: dns.rdtypes.ANY.PTR.PTR(c, t, dns.name.from_text(addr)) + + + addr = mapping.get(name) + if not addr and qname.is_absolute(): + addr = mapping.get(name[:-1]) + if addr: + rrset.add(kind(rdclass, rdtype, addr)) + return _HostsAnswer(qname, rdtype, rdclass, rrset, raise_on_no_answer) + + def getaliases(self, hostname): + # Return a list of all the aliases of a given cname + + # Due to the way store aliases this is a bit inefficient, this + # clearly was an afterthought. But this is only used by + # gethostbyname_ex so it's probably fine. + aliases = self.hosts_file.aliases + result = [] + if hostname in aliases: # pylint:disable=consider-using-get + cannon = aliases[hostname] + else: + cannon = hostname + result.append(cannon) + for alias, cname in iteritems(aliases): + if cannon == cname: + result.append(alias) + result.remove(hostname) + return result + +class _DualResolver(object): + + def __init__(self): + self.hosts_resolver = _HostsResolver() + self.network_resolver = resolver.get_default_resolver() + self.network_resolver.cache = resolver.LRUCache() + + def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, + tcp=False, source=None, raise_on_no_answer=True, + _hosts_rdtypes=(dns.rdatatype.A, dns.rdatatype.AAAA, dns.rdatatype.PTR)): + # Query the resolver, using /etc/hosts + + # Behavior: + # 1. if hosts is enabled and contains answer, return it now + # 2. query nameservers for qname + if qname is None: + qname = '0.0.0.0' + + if not isinstance(qname, string_types): + if isinstance(qname, bytes): + qname = qname.decode("idna") + + if isinstance(qname, string_types): + qname = dns.name.from_text(qname, None) + + if isinstance(rdtype, string_types): + rdtype = dns.rdatatype.from_text(rdtype) + + if rdclass == dns.rdataclass.IN and rdtype in _hosts_rdtypes: + try: + answer = self.hosts_resolver.query(qname, rdtype, raise_on_no_answer=False) + except Exception: # pylint: disable=broad-except + from gevent import get_hub + get_hub().handle_error(self, *sys.exc_info()) + else: + if answer.rrset: + return answer + + return self.network_resolver.query(qname, rdtype, rdclass, + tcp, source, raise_on_no_answer=raise_on_no_answer) + +def _family_to_rdtype(family): + if family == socket.AF_INET: + rdtype = dns.rdatatype.A + elif family == socket.AF_INET6: + rdtype = dns.rdatatype.AAAA + else: + raise socket.gaierror(socket.EAI_FAMILY, + 'Address family not supported') + return rdtype + + +class Resolver(AbstractResolver): + """ + An *experimental* resolver that uses `dnspython`_. + + This is typically slower than the default threaded resolver + (unless there's a cache hit, in which case it can be much faster). + It is usually much faster than the c-ares resolver. It tends to + scale well as more concurrent resolutions are attempted. + + Under Python 2, if the ``idna`` package is installed, this + resolver can resolve Unicode host names that the system resolver + cannot. + + .. note:: + + This **does not** use dnspython's default resolver object, or share any + classes with ``import dns``. A separate copy of the objects is imported to + be able to function in a non monkey-patched process. The documentation for the resolver + object still applies. + + The resolver that we use is available as the :attr:`resolver` attribute + of this object (typically ``gevent.get_hub().resolver.resolver``). + + .. caution:: + + Many of the same caveats about DNS results apply here as are documented + for :class:`gevent.resolver.ares.Resolver`. In addition, the handling of + symbolic scope IDs in IPv6 addresses passed to ``getaddrinfo`` exhibits + some differences. + + On PyPy, ``getnameinfo`` can produce results when CPython raises + ``socket.error``, and gevent's DNSPython resolver also + raises ``socket.error``. + + .. caution:: + + This resolver is experimental. It may be removed or modified in + the future. As always, feedback is welcome. + + .. versionadded:: 1.3a2 + + .. versionchanged:: 20.5.0 + The errors raised are now much more consistent with those + raised by the standard library resolvers. + + Handling of localhost and broadcast names is now more consistent. + + .. _dnspython: http://www.dnspython.org + """ + + def __init__(self, hub=None): # pylint: disable=unused-argument + if resolver._resolver is None: + _resolver = resolver._resolver = _DualResolver() + if config.resolver_nameservers: + _resolver.network_resolver.nameservers[:] = config.resolver_nameservers + if config.resolver_timeout: + _resolver.network_resolver.lifetime = config.resolver_timeout + # Different hubs in different threads could be sharing the same + # resolver. + assert isinstance(resolver._resolver, _DualResolver) + self._resolver = resolver._resolver + + @property + def resolver(self): + """ + The dnspython resolver object we use. + + This object has several useful attributes that can be used to + adjust the behaviour of the DNS system: + + * ``cache`` is a :class:`dns.resolver.LRUCache`. Its maximum size + can be configured by calling :meth:`resolver.cache.set_max_size` + * ``nameservers`` controls which nameservers to talk to + * ``lifetime`` configures a timeout for each individual query. + """ + return self._resolver.network_resolver + + def close(self): + pass + + def _getaliases(self, hostname, family): + if not isinstance(hostname, str): + if isinstance(hostname, bytes): + hostname = hostname.decode("idna") + aliases = self._resolver.hosts_resolver.getaliases(hostname) + net_resolver = self._resolver.network_resolver + rdtype = _family_to_rdtype(family) + while 1: + try: + ans = net_resolver.query(hostname, dns.rdatatype.CNAME, rdtype) + except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.resolver.NoNameservers): + break + except dTimeout: + break + except AttributeError as ex: + if hostname is None or isinstance(hostname, int): + raise TypeError(ex) + raise + else: + aliases.extend(str(rr.target) for rr in ans.rrset) + hostname = ans[0].target + return aliases + + def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags): + # dnspython really wants the host to be in native format. + if not isinstance(host_bytes, str): + host_bytes = host_bytes.decode(self.HOSTNAME_ENCODING) + + if host_bytes == 'ff02::1de:c0:face:8D': + # This is essentially a hack to make stdlib + # test_socket:GeneralModuleTests.test_getaddrinfo_ipv6_basic + # pass. They expect to get back a lowercase ``D``, but + # dnspython does not do that. + # ``test_getaddrinfo_ipv6_scopeid_symbolic`` also expect + # the scopeid to be dropped, but again, dnspython does not + # do that; we cant fix that here so we skip that test. + host_bytes = 'ff02::1de:c0:face:8d' + + if family == AF_UNSPEC: + # This tends to raise in the case that a v6 address did not exist + # but a v4 does. So we break it into two parts. + + # Note that if there is no ipv6 in the hosts file, but there *is* + # an ipv4, and there *is* an ipv6 in the nameservers, we will return + # both (from the first call). The system resolver on OS X only returns + # the results from the hosts file. doubleclick.com is one example. + + # See also https://github.com/gevent/gevent/issues/1012 + try: + return _getaddrinfo(host_bytes, port, family, socktype, proto, flags) + except gaierror: + try: + return _getaddrinfo(host_bytes, port, AF_INET6, socktype, proto, flags) + except gaierror: + return _getaddrinfo(host_bytes, port, AF_INET, socktype, proto, flags) + else: + try: + return _getaddrinfo(host_bytes, port, family, socktype, proto, flags) + except gaierror as ex: + if ex.args[0] == EAI_NONAME and family not in self._KNOWN_ADDR_FAMILIES: + # It's possible that we got sent an unsupported family. Check + # that. + ex.args = (EAI_FAMILY, self.EAI_FAMILY_MSG) + ex.errno = EAI_FAMILY + raise + + def _getnameinfo(self, address_bytes, port, sockaddr, flags): + try: + return resolver._getnameinfo(sockaddr, flags) + except error: + if not flags: + # dnspython doesn't like getting ports it can't resolve. + # We have one test, test__socket_dns.py:Test_getnameinfo_geventorg.test_port_zero + # that does this. We conservatively fix it here; this could be expanded later. + return resolver._getnameinfo(sockaddr, NI_NUMERICSERV) + + def _gethostbyaddr(self, ip_address_bytes): + try: + return resolver._gethostbyaddr(ip_address_bytes) + except gaierror as ex: + if ex.args[0] == EAI_NONAME: + # Note: The system doesn't *always* raise herror; + # sometimes the original gaierror propagates through. + # It's impossible to say ahead of time or just based + # on the name which it should be. The herror seems to + # be by far the most common, though. + raise herror(1, "Unknown host") + raise + + # Things that need proper error handling + getnameinfo = AbstractResolver.fixup_gaierror(AbstractResolver.getnameinfo) + gethostbyaddr = AbstractResolver.fixup_gaierror(AbstractResolver.gethostbyaddr) + gethostbyname_ex = AbstractResolver.fixup_gaierror(AbstractResolver.gethostbyname_ex) + getaddrinfo = AbstractResolver.fixup_gaierror(AbstractResolver.getaddrinfo) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..6912b7811b66826d24bb9c5503519c4677d31166 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/thread.py @@ -0,0 +1,69 @@ +# Copyright (c) 2012-2015 Denis Bilenko. See LICENSE for details. +""" +Native thread-based hostname resolver. +""" +import _socket + +from gevent.hub import get_hub + + +__all__ = ['Resolver'] + + +class Resolver(object): + """ + Implementation of the resolver API using native threads and native resolution + functions. + + Using the native resolution mechanisms ensures the highest + compatibility with what a non-gevent program would return + including good support for platform specific configuration + mechanisms. The use of native (non-greenlet) threads ensures that + a caller doesn't block other greenlets. + + This implementation also has the benefit of being very simple in comparison to + :class:`gevent.resolver_ares.Resolver`. + + .. tip:: + + Most users find this resolver to be quite reliable in a + properly monkey-patched environment. However, there have been + some reports of long delays, slow performance or even hangs, + particularly in long-lived programs that make many, many DNS + requests. If you suspect that may be happening to you, try the + dnspython or ares resolver (and submit a bug report). + """ + def __init__(self, hub=None): + if hub is None: + hub = get_hub() + self.pool = hub.threadpool + if _socket.gaierror not in hub.NOT_ERROR: + # Do not cause lookup failures to get printed by the default + # error handler. This can be very noisy. + hub.NOT_ERROR += (_socket.gaierror, _socket.herror) + + def __repr__(self): + return '<%s.%s at 0x%x pool=%r>' % (type(self).__module__, + type(self).__name__, + id(self), self.pool) + + def close(self): + pass + + # from briefly reading socketmodule.c, it seems that all of the functions + # below are thread-safe in Python, even if they are not thread-safe in C. + + def gethostbyname(self, *args): + return self.pool.apply(_socket.gethostbyname, args) + + def gethostbyname_ex(self, *args): + return self.pool.apply(_socket.gethostbyname_ex, args) + + def getaddrinfo(self, *args, **kwargs): + return self.pool.apply(_socket.getaddrinfo, args, kwargs) + + def gethostbyaddr(self, *args, **kwargs): + return self.pool.apply(_socket.gethostbyaddr, args, kwargs) + + def getnameinfo(self, *args, **kwargs): + return self.pool.apply(_socket.getnameinfo, args, kwargs) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_ares.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_ares.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0c44914695af83bf1123545cf04ea5cf3792e2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_ares.py @@ -0,0 +1,17 @@ +"""Backwards compatibility alias for :mod:`gevent.resolver.ares`. + +.. deprecated:: 1.3 + Use :mod:`gevent.resolver.ares` +""" +import warnings +warnings.warn( + "gevent.resolver_ares is deprecated and will be removed in 1.5. " + "Use gevent.resolver.ares instead.", + DeprecationWarning, + stacklevel=2 +) +del warnings +from gevent.resolver.ares import * # pylint:disable=wildcard-import,unused-wildcard-import +import gevent.resolver.ares as _ares +__all__ = _ares.__all__ +del _ares diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..1486e422a040c81772378b30b2d563d2457cee08 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver_thread.py @@ -0,0 +1,17 @@ +"""Backwards compatibility alias for :mod:`gevent.resolver.thread`. + +.. deprecated:: 1.3 + Use :mod:`gevent.resolver.thread` +""" +import warnings +warnings.warn( + "gevent.resolver_thread is deprecated and will be removed in 1.5. " + "Use gevent.resolver.thread instead.", + DeprecationWarning, + stacklevel=2 +) +del warnings +from gevent.resolver.thread import * # pylint:disable=wildcard-import,unused-wildcard-import +import gevent.resolver.thread as _thread +__all__ = _thread.__all__ +del _thread diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/select.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/select.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c3a4576d809461931e4e28443e3e640c8bf271 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/select.py @@ -0,0 +1,372 @@ +# Copyright (c) 2009-2011 Denis Bilenko. See LICENSE for details. +""" +Waiting for I/O completion. +""" +from __future__ import absolute_import, division, print_function + +import sys +import select as __select__ + +from gevent.event import Event +from gevent.hub import _get_hub_noargs as get_hub +from gevent.hub import sleep as _g_sleep +from gevent._compat import integer_types +from gevent._compat import iteritems +from gevent._util import copy_globals +from gevent._util import _NONE + +from errno import EINTR +_real_original_select = __select__.select +if sys.platform.startswith('win32'): + def _original_select(r, w, x, t): + # windows can't handle three empty lists, but we've always + # accepted that + if not r and not w and not x: + return ((), (), ()) + return _real_original_select(r, w, x, t) +else: + _original_select = _real_original_select + +# These will be replaced by copy_globals if they are defined by the +# platform. They're not defined on Windows, but we still provide +# poll() there. We only pay attention to POLLIN and POLLOUT. +POLLIN = 1 +POLLPRI = 2 +POLLOUT = 4 +POLLERR = 8 +POLLHUP = 16 +POLLNVAL = 32 + +POLLRDNORM = 64 +POLLRDBAND = 128 +POLLWRNORM = 4 +POLLWRBAND = 256 + +__implements__ = [ + 'select', +] +if hasattr(__select__, 'poll'): + __implements__.append('poll') +else: + __extra__ = [ + 'poll', + ] + +__all__ = ['error'] + __implements__ + +error = __select__.error + +__imports__ = copy_globals(__select__, globals(), + names_to_ignore=__all__, + dunder_names_to_keep=()) + +_EV_READ = 1 +_EV_WRITE = 2 + +def get_fileno(obj): + try: + fileno_f = obj.fileno + except AttributeError: + if not isinstance(obj, integer_types): + raise TypeError('argument must be an int, or have a fileno() method: %r' % (obj,)) + return obj + return fileno_f() + + +class SelectResult(object): + __slots__ = () + + @staticmethod + def _make_callback(ready_collection, event, mask): + def cb(fd, watcher): + ready_collection.append(fd) + watcher.close() + event.set() + cb.mask = mask + return cb + + @classmethod + def _make_watchers(cls, watchers, *fd_cb): + loop = get_hub().loop + io = loop.io + MAXPRI = loop.MAXPRI + + for fdlist, callback in fd_cb: + try: + for fd in fdlist: + watcher = io(get_fileno(fd), callback.mask) + watcher.priority = MAXPRI + watchers.append(watcher) + watcher.start(callback, fd, watcher) + except IOError as ex: + raise error(*ex.args) + + @staticmethod + def _closeall(watchers): + for watcher in watchers: + watcher.stop() + watcher.close() + del watchers[:] + + def select(self, rlist, wlist, timeout): + watchers = [] + # read and write are the collected ready objects, accumulated + # by the callback. Note that we could get spurious callbacks + # if the socket is closed while we're blocked. We can't easily + # detect that (libev filters the events passed so we can't + # pass arbitrary events). After an iteration of polling for + # IO, libev will invoke all the pending IO watchers, and then + # any newly added (fed) events, and then we will invoke added + # callbacks. With libev 4.27+ and EV_VERIFY, it's critical to + # close our watcher immediately once we get an event. That + # could be the close event (coming just before the actual + # close happens), and once the FD is closed, libev will abort + # the process if we stop the watcher. + read = [] + write = [] + event = Event() + add_read = self._make_callback(read, event, _EV_READ) + add_write = self._make_callback(write, event, _EV_WRITE) + + try: + self._make_watchers(watchers, + (rlist, add_read), + (wlist, add_write)) + event.wait(timeout=timeout) + return read, write, [] + finally: + self._closeall(watchers) + + +def select(rlist, wlist, xlist, timeout=None): # pylint:disable=unused-argument + """An implementation of :obj:`select.select` that blocks only the current greenlet. + + .. caution:: *xlist* is ignored. + + .. versionchanged:: 1.2a1 + Raise a :exc:`ValueError` if timeout is negative. This matches Python 3's + behaviour (Python 2 would raise a ``select.error``). Previously gevent had + undefined behaviour. + .. versionchanged:: 1.2a1 + Raise an exception if any of the file descriptors are invalid. + """ + if timeout is not None and timeout < 0: + # Raise an error like the real implementation; which error + # depends on the version. Python 3, where select.error is OSError, + # raises a ValueError (which makes sense). Older pythons raise + # the error from the select syscall...but we don't actually get there. + # We choose to just raise the ValueError as it makes more sense and is + # forward compatible + raise ValueError("timeout must be non-negative") + + # since rlist and wlist can be any iterable we will have to first + # copy them into a list, so we can use them in both _original_select + # and in SelectResult.select. We don't need to do it for xlist, since + # that one will only be passed into _original_select + rlist = rlist if isinstance(rlist, (list, tuple)) else list(rlist) + wlist = wlist if isinstance(wlist, (list, tuple)) else list(wlist) + + # First, do a poll with the original select system call. This is + # the most efficient way to check to see if any of the file + # descriptors have previously been closed and raise the correct + # corresponding exception. (Because libev tends to just return + # them as ready, or, if built with EV_VERIFY >= 2 and libev >= + # 4.27, crash the process. And libuv also tends to crash the + # process.) + # + # We accept the *xlist* here even though we can't + # below because this is all about error handling. + sel_results = ((), (), ()) + try: + sel_results = _original_select(rlist, wlist, xlist, 0) + except error as e: + enumber = getattr(e, 'errno', None) or e.args[0] + if enumber != EINTR: + # Ignore interrupted syscalls + raise + + if sel_results[0] or sel_results[1] or sel_results[2] or (timeout is not None and timeout == 0): + # If we actually had stuff ready, go ahead and return it. No need + # to go through the trouble of doing our own stuff. + + # Likewise, if the timeout is 0, we already did a 0 timeout + # select and we don't need to do it again. Note that in libuv, + # zero duration timers may be called immediately, without + # cycling the event loop at all. 2.7/test_telnetlib.py "hangs" + # calling zero-duration timers if we go to the loop here. + + # However, because this is typically a place where scheduling switches + # can occur, we need to make sure that's still the case; otherwise a single + # consumer could monopolize the thread. (shows up in test_ftplib.) + _g_sleep() + return sel_results + + result = SelectResult() + return result.select(rlist, wlist, timeout) + + + +class PollResult(object): + __slots__ = ('events', 'event') + + def __init__(self): + self.events = set() + self.event = Event() + + def add_event(self, events, fd): + if events < 0: + result_flags = POLLNVAL + else: + result_flags = 0 + if events & _EV_READ: + result_flags = POLLIN + if events & _EV_WRITE: + result_flags |= POLLOUT + + self.events.add((fd, result_flags)) + self.event.set() + +class poll(object): + """ + An implementation of :obj:`select.poll` that blocks only the current greenlet. + + With only one exception, the interface is the same as the standard library interface. + + .. caution:: ``POLLPRI`` data is not supported. + + .. versionadded:: 1.1b1 + .. versionchanged:: 1.5 + This is now always defined, regardless of whether the standard library + defines :func:`select.poll` or not. Note that it may have different performance + characteristics. + """ + def __init__(self): + # {int -> flags} + # We can't keep watcher objects in here because people commonly + # just drop the poll object when they're done, without calling + # unregister(). dnspython does this. + self.fds = {} + self.loop = get_hub().loop + + def register(self, fd, eventmask=_NONE): + """ + Register a file descriptor *fd* with the polling object. + + Future calls to the :meth:`poll`` method will then check + whether the file descriptor has any pending I/O events. *fd* can + be either an integer, or an object with a ``fileno()`` method that + returns an integer. File objects implement ``fileno()``, so they + can also be used as the argument (but remember that regular + files are usually always ready). + + *eventmask* is an optional bitmask describing the type of events + you want to check for, and can be a combination of the + constants ``POLLIN``, and ``POLLOUT`` (``POLLPRI`` is not supported). + """ + if eventmask is _NONE: + flags = _EV_READ | _EV_WRITE + else: + flags = 0 + if eventmask & POLLIN: + flags = _EV_READ + if eventmask & POLLOUT: + flags |= _EV_WRITE + # If they ask for POLLPRI, we can't support + # that. Should we raise an error? + + fileno = get_fileno(fd) + self.fds[fileno] = flags + + def modify(self, fd, eventmask): + """ + Change the set of events being watched on *fd*. + """ + self.register(fd, eventmask) + + def _get_started_watchers(self, watcher_cb): + watchers = [] + io = self.loop.io + MAXPRI = self.loop.MAXPRI + + try: + for fd, flags in iteritems(self.fds): + watcher = io(fd, flags) + watchers.append(watcher) + watcher.priority = MAXPRI + watcher.start(watcher_cb, fd, pass_events=True) + except: + for awatcher in watchers: + awatcher.stop() + awatcher.close() + raise + return watchers + + + def poll(self, timeout=None): + """ + poll the registered fds. + + .. versionchanged:: 1.2a1 + File descriptors that are closed are reported with POLLNVAL. + + .. versionchanged:: 1.3a2 + Under libuv, interpret *timeout* values less than 0 the same as *None*, + i.e., block. This was always the case with libev. + """ + result = PollResult() + watchers = self._get_started_watchers(result.add_event) + try: + if timeout is not None: + if timeout < 0: + # The docs for python say that an omitted timeout, + # a negative timeout and a timeout of None are all + # supposed to block forever. Many, but not all + # OS's accept any negative number to mean that. Some + # OS's raise errors for anything negative but not -1. + # Python 3.7 changes to always pass exactly -1 in that + # case from selectors. + + # Our Timeout class currently does not have a defined behaviour + # for negative values. On libuv, it uses a check watcher and effectively + # doesn't block. On libev, it seems to block. In either case, we + # *want* to block, so turn this into the sure fire block request. + timeout = None + elif timeout: + # The docs for poll.poll say timeout is in + # milliseconds. Our result objects work in + # seconds, so this should be *=, shouldn't it? + timeout /= 1000.0 + result.event.wait(timeout=timeout) + return list(result.events) + finally: + for awatcher in watchers: + awatcher.stop() + awatcher.close() + + def unregister(self, fd): + """ + Unregister the *fd*. + + .. versionchanged:: 1.2a1 + Raise a `KeyError` if *fd* was not registered, like the standard + library. Previously gevent did nothing. + """ + fileno = get_fileno(fd) + del self.fds[fileno] + + +def _gevent_do_monkey_patch(patch_request): + aggressive = patch_request.patch_kwargs['aggressive'] + + patch_request.default_patch_items() + + if aggressive: + # since these are blocking we're removing them here. This makes some other + # modules (e.g. asyncore) non-blocking, as they use select that we provide + # when none of these are available. + patch_request.remove_item( + 'epoll', + 'kqueue', + 'kevent', + 'devpoll', + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/selectors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/selectors.py new file mode 100644 index 0000000000000000000000000000000000000000..47eb85585346c1004c76c7632399099b3a228996 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/selectors.py @@ -0,0 +1,316 @@ +# Copyright (c) 2020 gevent contributors. +""" +This module provides :class:`GeventSelector`, a high-level IO +multiplexing mechanism. This is aliased to :class:`DefaultSelector`. + +This module provides the same API as the selectors defined in :mod:`selectors`. + +On Python 2, this module is only available if the `selectors2 +`_ backport is installed. + +.. versionadded:: 20.6.0 +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from collections import defaultdict + +try: + import selectors as __selectors__ +except ImportError: + # Probably on Python 2. Do we have the backport? + import selectors2 as __selectors__ + __target__ = 'selectors2' + +from gevent.hub import _get_hub_noargs as get_hub +from gevent import sleep +from gevent._compat import iteritems +from gevent._compat import itervalues +from gevent._util import copy_globals +from gevent._util import Lazy + +from gevent.event import Event +from gevent.select import _EV_READ +from gevent.select import _EV_WRITE + +__implements__ = [ + 'DefaultSelector', +] +__extra__ = [ + 'GeventSelector', +] +__all__ = __implements__ + __extra__ + +__imports__ = copy_globals( + __selectors__, globals(), + names_to_ignore=__all__, + # Copy __all__; __all__ is defined by selectors2 but not Python 3. + dunder_names_to_keep=('__all__',) +) + +_POLL_ALL = _EV_READ | _EV_WRITE + +EVENT_READ = __selectors__.EVENT_READ +EVENT_WRITE = __selectors__.EVENT_WRITE +_ALL_EVENTS = EVENT_READ | EVENT_WRITE +SelectorKey = __selectors__.SelectorKey + +# In 3.4 and selectors2, BaseSelector is a concrete +# class that can be called. In 3.5 and later, it's an +# ABC, with the real implementation being +# passed to _BaseSelectorImpl. +_BaseSelectorImpl = getattr( + __selectors__, + '_BaseSelectorImpl', + __selectors__.BaseSelector +) + +class GeventSelector(_BaseSelectorImpl): + """ + A selector implementation using gevent primitives. + + This is a type of :class:`selectors.BaseSelector`, so the documentation + for that class applies here. + + .. caution:: + As the base class indicates, it is critically important to + unregister file objects before closing them. (Or close the selector + they are registered with before closing them.) Failure to do so + may crash the process or have other unintended results. + """ + + # Notes on the approach: + # + # It's easy to wrap a selector implementation around + # ``gevent.select.poll``; in fact that's what happens by default + # when monkey-patching in Python 3. But the problem with that is + # each call to ``selector.select()`` will result in creating and + # then destroying new kernel-level polling resources, as nothing + # in ``gevent.select`` can keep watchers around (because the underlying + # file could be closed at any time). This ends up producing a large + # number of syscalls that are unnecessary. + # + # So here, we take advantage of the fact that it is documented and + # required that files not be closed while they are registered. + # This lets us persist watchers. Indeed, it lets us continually + # accrue events in the background before a call to ``select()`` is even + # made. We can take advantage of this to return results immediately, without + # a syscall, if we have them. + # + # We create watchers in ``register()`` and destroy them in + # ``unregister()``. They do not get started until the first call + # to ``select()``, though. Once they are started, they don't get + # stopped until they deliver an event. + # Lifecycle: + # register() -> inactive_watchers + # select() -> inactive_watchers -> active_watchers; + # active_watchers -> inactive_watchers + + def __init__(self, hub=None): + if hub is not None: + self.hub = hub + # {fd: watcher} + self._active_watchers = {} + self._inactive_watchers = {} + # {fd: EVENT_READ|EVENT_WRITE} + self._accumulated_events = defaultdict(int) + self._ready = Event() + super(GeventSelector, self).__init__() + + if not hasattr(_BaseSelectorImpl, '_key_from_fd'): + def _key_from_fd(self, fd): + # Removed in 3.13; this duplicates the old function. + try: + return self._fd_to_key[fd] + except KeyError: + return None + + + def __callback(self, events, fd): + if events > 0: + cur_event_for_fd = self._accumulated_events[fd] + if events & _EV_READ: + cur_event_for_fd |= EVENT_READ + if events & _EV_WRITE: + cur_event_for_fd |= EVENT_WRITE + self._accumulated_events[fd] = cur_event_for_fd + + self._ready.set() + + @Lazy + def hub(self): # pylint:disable=method-hidden + return get_hub() + + def register(self, fileobj, events, data=None): + key = _BaseSelectorImpl.register(self, fileobj, events, data) + + if events == _ALL_EVENTS: + flags = _POLL_ALL + elif events == EVENT_READ: + flags = _EV_READ + else: + flags = _EV_WRITE + + + loop = self.hub.loop + io = loop.io + MAXPRI = loop.MAXPRI + + self._inactive_watchers[key.fd] = watcher = io(key.fd, flags) + watcher.priority = MAXPRI + return key + + def unregister(self, fileobj): + key = _BaseSelectorImpl.unregister(self, fileobj) + if key.fd in self._active_watchers: + watcher = self._active_watchers.pop(key.fd) + else: + watcher = self._inactive_watchers.pop(key.fd) + watcher.stop() + watcher.close() + self._accumulated_events.pop(key.fd, None) + return key + + # XXX: Can we implement ``modify`` more efficiently than + # ``unregister()``+``register()``? We could detect the no-change + # case and do nothing; recent versions of the standard library + # do that. + + def select(self, timeout=None): + """ + Poll for I/O. + + Note that, like the built-in selectors, this will block + indefinitely if no timeout is given and no files have been + registered. + """ + # timeout > 0 : block seconds + # timeout <= 0 : No blocking. + # timeout = None: Block forever + + # Event.wait doesn't deal with negative values + if timeout is not None and timeout < 0: + timeout = 0 + + # Start any watchers that need started. Note that they may + # not actually get a chance to do anything yet if we already had + # events set. + for fd, watcher in iteritems(self._inactive_watchers): + watcher.start(self.__callback, fd, pass_events=True) + self._active_watchers.update(self._inactive_watchers) + self._inactive_watchers.clear() + + # The _ready event is either already set (in which case + # there are some results waiting in _accumulated_events) or + # not set, in which case we have to block. But to make the two cases + # behave the same, we will always yield to the event loop. + if self._ready.is_set(): + sleep() + self._ready.wait(timeout) + self._ready.clear() + # TODO: If we have nothing ready, but they ask us not to block, + # should we make an effort to actually spin the event loop and let + # it check for events? + + result = [] + for fd, event in iteritems(self._accumulated_events): + key = self._key_from_fd(fd) + watcher = self._active_watchers.pop(fd) + + ## The below is taken without comment from + ## https://github.com/gevent/gevent/pull/1523/files and + ## hasn't been checked: + # + # Since we are emulating an epoll object within another epoll object, + # once a watcher has fired, we must deactivate it until poll is called + # next. If we did not, someone else could call, e.g., gevent.time.sleep + # and any unconsumed bytes on our watched fd would prevent the process + # from sleeping correctly. + watcher.stop() + if key: + result.append((key, event & key.events)) + self._inactive_watchers[fd] = watcher + else: # pragma: no cover + # If the key was gone, then somehow we've been unregistered. + # Don't put it back in inactive, close it. + watcher.close() + + self._accumulated_events.clear() + return result + + def close(self): + for d in self._active_watchers, self._inactive_watchers: + if d is None: + continue # already closed + for watcher in itervalues(d): + watcher.stop() + watcher.close() + self._active_watchers = self._inactive_watchers = None + self._accumulated_events = None + self.hub = None + _BaseSelectorImpl.close(self) + + +DefaultSelector = GeventSelector + +def _gevent_do_monkey_patch(patch_request): + aggressive = patch_request.patch_kwargs['aggressive'] + target_mod = patch_request.target_module + + patch_request.default_patch_items() + + import sys + if 'selectors' not in sys.modules: + # Py2: Make 'import selectors' work + sys.modules['selectors'] = sys.modules[__name__] + + # Python 3 wants to use `select.select` as a member function, + # leading to this error in selectors.py (because + # gevent.select.select is not a builtin and doesn't get the + # magic auto-static that they do): + # + # r, w, _ = self._select(self._readers, self._writers, [], timeout) + # TypeError: select() takes from 3 to 4 positional arguments but 5 were given + # + # Note that this obviously only happens if selectors was + # imported after we had patched select; but there is a code + # path that leads to it being imported first (but now we've + # patched select---so we can't compare them identically). It also doesn't + # happen on Windows, because they define a normal method for _select, to work around + # some weirdness in the handling of the third argument. + # + # The backport doesn't have that. + orig_select_select = patch_request.get_original('select', 'select') + assert target_mod.select is not orig_select_select + selectors = __selectors__ + SelectSelector = selectors.SelectSelector + if hasattr(SelectSelector, '_select') and SelectSelector._select in ( + target_mod.select, orig_select_select + ): + from gevent.select import select + def _select(self, *args, **kwargs): # pylint:disable=unused-argument + return select(*args, **kwargs) + selectors.SelectSelector._select = _select + _select._gevent_monkey = True # prove for test cases + + if aggressive: + # If `selectors` had already been imported before we removed + # select.epoll|kqueue|devpoll, these may have been defined in terms + # of those functions. They'll fail at runtime. + patch_request.remove_item( + selectors, + 'EpollSelector', + 'KqueueSelector', + 'DevpollSelector', + ) + selectors.DefaultSelector = DefaultSelector + + # Python 3.7 refactors the poll-like selectors to use a common + # base class and capture a reference to select.poll, etc, at + # import time. selectors tends to get imported early + # (importing 'platform' does it: platform -> subprocess -> selectors), + # so we need to clean that up. + if hasattr(selectors, 'PollSelector') and hasattr(selectors.PollSelector, '_selector_cls'): + from gevent.select import poll + selectors.PollSelector._selector_cls = poll diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/server.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/server.py new file mode 100644 index 0000000000000000000000000000000000000000..612a49d6822f95f560d4ae66739a766fffa2267e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/server.py @@ -0,0 +1,290 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +"""TCP/SSL server""" +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division + +import sys + +from _socket import error as SocketError +from _socket import SOL_SOCKET +from _socket import SO_REUSEADDR +from _socket import AF_INET +from _socket import SOCK_DGRAM + +from gevent.baseserver import BaseServer +from gevent.socket import EWOULDBLOCK +from gevent.socket import socket as GeventSocket + +__all__ = ['StreamServer', 'DatagramServer'] + + +if sys.platform == 'win32': + # SO_REUSEADDR on Windows does not mean the same thing as on *nix (issue #217) + DEFAULT_REUSE_ADDR = None +else: + DEFAULT_REUSE_ADDR = 1 + + +# sockets and SSL sockets are context managers on Python 3 +def _closing_socket(sock): + return sock + + +class StreamServer(BaseServer): + """ + A generic TCP server. + + Accepts connections on a listening socket and spawns user-provided + *handle* function for each connection with 2 arguments: the client + socket and the client address. + + Note that although the errors in a successfully spawned handler + will not affect the server or other connections, the errors raised + by :func:`accept` and *spawn* cause the server to stop accepting + for a short amount of time. The exact period depends on the values + of :attr:`min_delay` and :attr:`max_delay` attributes. + + The delay starts with :attr:`min_delay` and doubles with each + successive error until it reaches :attr:`max_delay`. A successful + :func:`accept` resets the delay to :attr:`min_delay` again. + + See :class:`~gevent.baseserver.BaseServer` for information on defining the *handle* + function and important restrictions on it. + + **SSL Support** + + The server can optionally work in SSL mode when given the correct + keyword arguments. (That is, the presence of any keyword arguments + will trigger SSL mode.) On Python 2.7.9 and later (any Python + version that supports the :class:`ssl.SSLContext`), this can be + done with a configured ``SSLContext``. On any Python version, it + can be done by passing the appropriate arguments for + :func:`ssl.wrap_socket`. + + The incoming socket will be wrapped into an SSL socket before + being passed to the *handle* function. + + If the *ssl_context* keyword argument is present, it should + contain an :class:`ssl.SSLContext`. The remaining keyword + arguments are passed to the :meth:`ssl.SSLContext.wrap_socket` + method of that object. Depending on the Python version, supported arguments + may include: + + - server_hostname + - suppress_ragged_eofs + - do_handshake_on_connect + + .. caution:: When using an SSLContext, it should either be + imported from :mod:`gevent.ssl`, or the process needs to be monkey-patched. + If the process is not monkey-patched and you pass the standard library + SSLContext, the resulting client sockets will not cooperate with gevent. + + Otherwise, keyword arguments are assumed to apply to :func:`ssl.wrap_socket`. + These keyword arguments may include: + + - keyfile + - certfile + - cert_reqs + - ssl_version + - ca_certs + - suppress_ragged_eofs + - do_handshake_on_connect + - ciphers + + .. versionchanged:: 1.2a2 + Add support for the *ssl_context* keyword argument. + + """ + # the default backlog to use if none was provided in __init__ + # For TCP, 128 is the (default) maximum at the operating system level on Linux and macOS + # larger values are truncated to 128. + # + # Windows defines SOMAXCONN=0x7fffffff to mean "max reasonable value" --- that value + # was undocumented and subject to change, but appears to be 200. + # Beginning in Windows 8 there's SOMAXCONN_HINT(b)=(-(b)) which means "at least + # as many SOMAXCONN but no more than b" which is a portable way to write 200. + backlog = 128 + + reuse_addr = DEFAULT_REUSE_ADDR + + def __init__(self, listener, handle=None, backlog=None, spawn='default', **ssl_args): + BaseServer.__init__(self, listener, handle=handle, spawn=spawn) + try: + if ssl_args: + ssl_args.setdefault('server_side', True) + if 'ssl_context' in ssl_args: + ssl_context = ssl_args.pop('ssl_context') + self.wrap_socket = ssl_context.wrap_socket + self.ssl_args = ssl_args + else: + from gevent.ssl import wrap_socket + self.wrap_socket = wrap_socket + self.ssl_args = ssl_args + else: + self.ssl_args = None + if backlog is not None: + if hasattr(self, 'socket'): + raise TypeError('backlog must be None when a socket instance is passed') + self.backlog = backlog + except: + self.close() + raise + + @property + def ssl_enabled(self): + return self.ssl_args is not None + + def set_listener(self, listener): + BaseServer.set_listener(self, listener) + + def _make_socket_stdlib(self, fresh): + # We want to unwrap the gevent wrapping of the listening socket. + # This lets us be just a hair more efficient: when our 'do_read' is + # called, we've already waited on the socket to be ready to accept(), so + # we don't need to (potentially) do it again. Also we avoid a layer + # of method calls. The cost, though, is that we have to manually wrap + # sockets back up to be non-blocking in do_read(). I'm not sure that's worth + # it. + # + # In the past, we only did this when set_listener() was called with a socket + # object and not an address. It makes sense to do it always though, + # so that we get consistent behaviour. + while hasattr(self.socket, '_sock'): + if fresh: + if hasattr(self.socket, '_drop_events'): + # Discard event listeners. This socket object is not shared, + # so we don't need them anywhere else. + # This matters somewhat for libuv, where we have to multiplex + # listeners, and we're about to create a new listener. + # If we don't do this, on Windows libuv tends to miss incoming + # connects and our _do_read callback doesn't get called. + self.socket._drop_events() + # XXX: Do we need to _drop() for PyPy? + + self.socket = self.socket._sock # pylint:disable=attribute-defined-outside-init + + def init_socket(self): + fresh = False + if not hasattr(self, 'socket'): + fresh = True + # FIXME: clean up the socket lifetime + # pylint:disable=attribute-defined-outside-init + self.socket = self.get_listener(self.address, self.backlog, self.family) + self.address = self.socket.getsockname() + if self.ssl_args: + self._handle = self.wrap_socket_and_handle + else: + self._handle = self.handle + self._make_socket_stdlib(fresh) + + @classmethod + def get_listener(cls, address, backlog=None, family=None): + if backlog is None: + backlog = cls.backlog + return _tcp_listener(address, backlog=backlog, reuse_addr=cls.reuse_addr, family=family) + + def do_read(self): + sock = self.socket + try: + fd, address = sock._accept() + except BlockingIOError: # python 2: pylint: disable=undefined-variable + if not sock.timeout: + return + raise + + sock = GeventSocket(sock.family, sock.type, sock.proto, fileno=fd) + # XXX Python issue #7995? "if no default timeout is set + # and the listening socket had a (non-zero) timeout, force + # the new socket in blocking mode to override + # platform-specific socket flags inheritance." + return sock, address + + def do_close(self, sock, *args): + # pylint:disable=arguments-differ + sock.close() + + def wrap_socket_and_handle(self, client_socket, address): + # used in case of ssl sockets + with _closing_socket(self.wrap_socket(client_socket, **self.ssl_args)) as ssl_socket: + return self.handle(ssl_socket, address) + + +class DatagramServer(BaseServer): + """A UDP server""" + + reuse_addr = DEFAULT_REUSE_ADDR + + def __init__(self, *args, **kwargs): + # The raw (non-gevent) socket, if possible + self._socket = None + BaseServer.__init__(self, *args, **kwargs) + from gevent.lock import Semaphore + self._writelock = Semaphore() + + def init_socket(self): + if not hasattr(self, 'socket'): + # FIXME: clean up the socket lifetime + # pylint:disable=attribute-defined-outside-init + self.socket = self.get_listener(self.address, self.family) + self.address = self.socket.getsockname() + self._socket = self.socket + try: + self._socket = self._socket._sock + except AttributeError: + pass + + @classmethod + def get_listener(cls, address, family=None): + return _udp_socket(address, reuse_addr=cls.reuse_addr, family=family) + + def do_read(self): + try: + data, address = self._socket.recvfrom(8192) + except SocketError as err: + if err.args[0] == EWOULDBLOCK: + return + raise + return data, address + + def sendto(self, *args): + self._writelock.acquire() + try: + self.socket.sendto(*args) + finally: + self._writelock.release() + + +def _tcp_listener(address, backlog=50, reuse_addr=None, family=AF_INET): + """A shortcut to create a TCP socket, bind it and put it into listening state.""" + sock = GeventSocket(family=family) + if reuse_addr is not None: + sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, reuse_addr) + try: + sock.bind(address) + except SocketError as ex: + strerror = getattr(ex, 'strerror', None) + if strerror is not None: + ex.strerror = strerror + ': ' + repr(address) + raise + sock.listen(backlog) + sock.setblocking(0) + return sock + + +def _udp_socket(address, backlog=50, reuse_addr=None, family=AF_INET): + # backlog argument for compat with tcp_listener + # pylint:disable=unused-argument + + # we want gevent.socket.socket here + sock = GeventSocket(family=family, type=SOCK_DGRAM) + if reuse_addr is not None: + sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, reuse_addr) + try: + sock.bind(address) + except SocketError as ex: + strerror = getattr(ex, 'strerror', None) + if strerror is not None: + ex.strerror = strerror + ': ' + repr(address) + raise + return sock diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/signal.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/signal.py new file mode 100644 index 0000000000000000000000000000000000000000..35b6332a8299fa6de4531fd53ee1be7df81b64b6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/signal.py @@ -0,0 +1,143 @@ +""" +Cooperative implementation of special cases of :func:`signal.signal`. + +This module is designed to work with libev's child watchers, as used +by default in :func:`gevent.os.fork` Note that each ``SIGCHLD`` +handler will be run in a new greenlet when the signal is delivered +(just like :class:`gevent.hub.signal`) + +The implementations in this module are only monkey patched if +:func:`gevent.os.waitpid` is being used (the default) and if +:const:`signal.SIGCHLD` is available; see :func:`gevent.os.fork` for +information on configuring this not to be the case for advanced uses. + +.. versionadded:: 1.1b4 +.. versionchanged:: 1.5a4 + Previously there was a backwards compatibility alias + ``gevent.signal``, introduced in 1.1b4, that partly shadowed this + module, confusing humans and static analysis tools alike. That alias + has been removed. (See `gevent.signal_handler`.) +""" + +from __future__ import absolute_import + +from gevent._util import _NONE as _INITIAL +from gevent._util import copy_globals + +import signal as _signal + +__implements__ = [] +__extensions__ = [] + + +_child_handler = _INITIAL + +_signal_signal = _signal.signal +_signal_getsignal = _signal.getsignal + + +def getsignal(signalnum): + """ + Exactly the same as :func:`signal.getsignal` except where + :const:`signal.SIGCHLD` is concerned. + + For :const:`signal.SIGCHLD`, this cooperates with :func:`signal` + to provide consistent answers. + """ + if signalnum != _signal.SIGCHLD: + return _signal_getsignal(signalnum) + + global _child_handler + if _child_handler is _INITIAL: + _child_handler = _signal_getsignal(_signal.SIGCHLD) + + return _child_handler + + +def signal(signalnum, handler): + """ + Exactly the same as :func:`signal.signal` except where + :const:`signal.SIGCHLD` is concerned. + + .. note:: + + A :const:`signal.SIGCHLD` handler installed with this function + will only be triggered for children that are forked using + :func:`gevent.os.fork` (:func:`gevent.os.fork_and_watch`); + children forked before monkey patching, or otherwise by the raw + :func:`os.fork`, will not trigger the handler installed by this + function. (It's unlikely that a SIGCHLD handler installed with + the builtin :func:`signal.signal` would be triggered either; + libev typically overwrites such a handler at the C level. At + the very least, it's full of race conditions.) + + .. note:: + + Use of ``SIG_IGN`` and ``SIG_DFL`` may also have race conditions + with libev child watchers and the :mod:`gevent.subprocess` module. + + .. versionchanged:: 1.2a1 + If ``SIG_IGN`` or ``SIG_DFL`` are used to ignore ``SIGCHLD``, a + future use of ``gevent.subprocess`` and libev child watchers + will once again work. However, on Python 2, use of ``os.popen`` + will fail. + + .. versionchanged:: 1.1rc2 + Allow using ``SIG_IGN`` and ``SIG_DFL`` to reset and ignore ``SIGCHLD``. + However, this allows the possibility of a race condition if ``gevent.subprocess`` + had already been used. + """ + if signalnum != _signal.SIGCHLD: + return _signal_signal(signalnum, handler) + + # TODO: raise value error if not called from the main + # greenlet, just like threads + + if handler != _signal.SIG_IGN and handler != _signal.SIG_DFL and not callable(handler): + # exact same error message raised by the stdlib + raise TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object") + + old_handler = getsignal(signalnum) + global _child_handler + _child_handler = handler + if handler in (_signal.SIG_IGN, _signal.SIG_DFL): + # Allow resetting/ignoring this signal at the process level. + # Note that this conflicts with gevent.subprocess and other users + # of child watchers, until the next time gevent.subprocess/loop.install_sigchld() + # is called. + from gevent.hub import get_hub # Are we always safe to import here? + _signal_signal(signalnum, handler) + get_hub().loop.reset_sigchld() + return old_handler + + +def _on_child_hook(): + # This is called in the hub greenlet. To let the function + # do more useful work, like use blocking functions, + # we run it in a new greenlet; see gevent.hub.signal + if callable(_child_handler): + # None is a valid value for the frame argument + from gevent import Greenlet + greenlet = Greenlet(_child_handler, _signal.SIGCHLD, None) + greenlet.switch() + + +import gevent.os + +# pylint:disable=no-member +if 'waitpid' in gevent.os.__implements__ and hasattr(_signal, 'SIGCHLD'): + # Tightly coupled here to gevent.os and its waitpid implementation; only use these + # if necessary. + gevent.os._on_child_hook = _on_child_hook + __implements__.append("signal") + __implements__.append("getsignal") +else: + # XXX: This breaks test__all__ on windows + __extensions__.append("signal") + __extensions__.append("getsignal") + +__imports__ = copy_globals(_signal, globals(), + names_to_ignore=__implements__ + __extensions__, + dunder_names_to_keep=()) + +__all__ = __implements__ + __extensions__ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/socket.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..761b3b545fb0c885049abcac9cb770924c7f664a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/socket.py @@ -0,0 +1,166 @@ +# Copyright (c) 2009-2014 Denis Bilenko and gevent contributors. See LICENSE for details. + +"""Cooperative low-level networking interface. + +This module provides socket operations and some related functions. +The API of the functions and classes matches the API of the corresponding +items in the standard :mod:`socket` module exactly, but the synchronous functions +in this module only block the current greenlet and let the others run. + +For convenience, exceptions (like :class:`error ` and :class:`timeout `) +as well as the constants from the :mod:`socket` module are imported into this module. +""" +# Our import magic sadly makes this warning useless +# pylint: disable=undefined-variable + + +from gevent._compat import PY311 +from gevent._compat import exc_clear +from gevent._util import copy_globals + + + +from gevent import _socket3 as _source + + +# define some things we're expecting to overwrite; each module +# needs to define these +__implements__ = __dns__ = __all__ = __extensions__ = __imports__ = () + + +class error(Exception): + errno = None + + +def getfqdn(*args): + # pylint:disable=unused-argument + raise NotImplementedError() + +copy_globals(_source, globals(), + dunder_names_to_keep=('__implements__', '__dns__', '__all__', + '__extensions__', '__imports__', '__socket__'), + cleanup_globs=False) + +# The _socket2 and _socket3 don't import things defined in +# __extensions__, to help avoid confusing reference cycles in the +# documentation and to prevent importing from the wrong place, but we +# *do* need to expose them here. (NOTE: This may lead to some sphinx +# warnings like: +# WARNING: missing attribute mentioned in :members: or __all__: +# module gevent._socket2, attribute cancel_wait +# These can be ignored.) +from gevent import _socketcommon +copy_globals(_socketcommon, globals(), + only_names=_socketcommon.__extensions__) + +try: + _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT +except AttributeError: + _GLOBAL_DEFAULT_TIMEOUT = object() + + +def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None, *, + all_errors=False): + """ + create_connection(address, timeout=None, source_address=None, *, all_errors=False) -> socket + + Connect to *address* and return the :class:`gevent.socket.socket` + object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by + :func:`getdefaulttimeout` is used. If *source_address* is set it + must be a tuple of (host, port) for the socket to bind as a source + address before making the connection. A host of '' or port 0 tells + the OS to use the default. + + .. versionchanged:: 20.6.0 + If the host part of the address includes an IPv6 scope ID, + it will be used instead of ignored, if the platform supplies + :func:`socket.inet_pton`. + .. versionchanged:: 22.08.0 + Add the *all_errors* argument. This only has meaning on Python 3.11+; + it is a programming error to pass it on earlier versions. + .. versionchanged:: 23.7.0 + You can pass a value for ``all_errors`` on any version of Python. + It is forced to false for any version before 3.11 inside the function. + """ + # Sigh. This function is a near-copy of the CPython implementation. + # Even though we simplified some things, it's still a little complex to + # cope with error handling, which got even more complicated in 3.11. + # pylint:disable=too-many-locals,too-many-branches + if not PY311: + all_errors = False + + host, port = address + exceptions = [] + # getaddrinfo is documented as returning a list, but our interface + # is pluggable, so be sure it does. + addrs = list(getaddrinfo(host, port, 0, SOCK_STREAM)) + if not addrs: + raise error("getaddrinfo returns an empty list") + + for res in addrs: + af, socktype, proto, _canonname, sa = res + sock = None + try: + sock = socket(af, socktype, proto) + if timeout is not _GLOBAL_DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + + except error as exc: + if not all_errors: + exceptions = [exc] # raise only the last error + else: + exceptions.append(exc) + del exc # cycle + if sock is not None: + sock.close() + sock = None + if res is addrs[-1]: + if not all_errors: + del exceptions[:] + raise + try: + # pylint isn't smart enough to see that we only use this + # on supported versions. + # pylint:disable=using-exception-groups-in-unsupported-version + raise ExceptionGroup("create_connection failed", exceptions) + finally: + # Break explicitly a reference cycle + del exceptions[:] + # without exc_clear(), if connect() fails once, the socket + # is referenced by the frame in exc_info and the next + # bind() fails (see test__socket.TestCreateConnection) + # that does not happen with regular sockets though, + # because _socket.socket.connect() is a built-in. this is + # similar to "getnameinfo loses a reference" failure in + # test_socket.py + exc_clear() + except BaseException: + # Things like GreenletExit, Timeout and KeyboardInterrupt. + # These get raised immediately, being sure to + # close the socket + if sock is not None: + sock.close() + sock = None + raise + else: + # break reference cycles + del exceptions[:] + try: + return sock + finally: + sock = None + + +# This is promised to be in the __all__ of the _source, but, for circularity reasons, +# we implement it in this module. Mostly for documentation purposes, put it +# in the _source too. +_source.create_connection = create_connection diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/ssl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cd5ca4c0ea0f83788d05581eca099ad4903d16 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/ssl.py @@ -0,0 +1,894 @@ +# Wrapper module for _ssl. Written by Bill Janssen. +# Ported to gevent by Denis Bilenko. +"""SSL wrapper for socket objects on Python 3. + +For the documentation, refer to :mod:`ssl` module manual. + +This module implements cooperative SSL socket wrappers. +""" + +from __future__ import absolute_import +import ssl as __ssl__ + +_ssl = __ssl__._ssl + +import errno + + +from gevent.socket import socket, timeout_default +from gevent.socket import timeout as _socket_timeout +from gevent._util import copy_globals +socket_error = OSError + +from weakref import ref as _wref + +__implements__ = [ + 'SSLContext', + 'SSLSocket', + 'get_server_certificate', +] + +if hasattr(__ssl__, 'wrap_socket'): + __implements__.append('wrap_socket') + __extra__ = [] +else: + __extra__ = [ + 'wrap_socket', + ] + +# Manually import things we use so we get better linting. +# Also, in the past (adding 3.9 support) it turned out we were +# relying on certain global variables being defined in the ssl module +# that weren't required to be there, e.g., AF_INET, which should be imported +# from socket +from socket import AF_INET +from socket import SOCK_STREAM +from socket import SO_TYPE +from socket import SOL_SOCKET + +from ssl import SSLWantReadError +from ssl import SSLWantWriteError +from ssl import SSLEOFError +from ssl import SSLZeroReturnError +from ssl import CERT_NONE +from ssl import SSLError +from ssl import SSL_ERROR_EOF +from ssl import SSL_ERROR_WANT_READ +from ssl import SSL_ERROR_WANT_WRITE +from ssl import PROTOCOL_SSLv23 +#from ssl import SSLObject + +from ssl import CHANNEL_BINDING_TYPES +from ssl import CERT_REQUIRED +from ssl import DER_cert_to_PEM_cert +from ssl import create_connection + +# Import all symbols from Python's ssl.py, except those that we are implementing +# and "private" symbols. +__imports__ = copy_globals( + __ssl__, globals(), + # SSLSocket *must* subclass gevent.socket.socket; see issue 597 + names_to_ignore=__implements__ + ['socket'], + dunder_names_to_keep=()) + +__all__ = __implements__ + __imports__ + __extra__ +if 'namedtuple' in __all__: + __all__.remove('namedtuple') + +orig_SSLContext = __ssl__.SSLContext # pylint:disable=no-member + +# We have to pass the raw stdlib socket to SSLContext.wrap_socket. +# That method in turn can pass that object on to things like SNI callbacks. +# It wouldn't have access to any of the attributes on the SSLSocket, like +# context, that it's supposed to (see test_ssl.test_sni_callback). Previously +# we just delegated to the sslsocket with __getattr__, but 3.8 +# added some new callbacks and a test that the object they get is an instance +# of the high-level SSLSocket class, so that doesn't work anymore. Instead, +# we wrap the callback and get the real socket to pass on. +class _contextawaresock(socket._gevent_sock_class): + __slots__ = ('_sslsock',) + + def __init__(self, family, type, proto, fileno, sslsocket_wref): + super().__init__(family, type, proto, fileno) + self._sslsock = sslsocket_wref + + +class _Callback(object): + + __slots__ = ('user_function',) + + def __init__(self, user_function): + self.user_function = user_function + + def __call__(self, conn, *args): + conn = conn._sslsock() + return self.user_function(conn, *args) + +class SSLContext(orig_SSLContext): + + __slots__ = () + + # Added in Python 3.7 + sslsocket_class = None # SSLSocket is assigned later + + def wrap_socket(self, sock, server_side=False, + do_handshake_on_connect=True, + suppress_ragged_eofs=True, + server_hostname=None, + session=None): + # pylint:disable=arguments-differ,not-callable + # (3.6 adds session) + # Sadly, using *args and **kwargs doesn't work + return self.sslsocket_class( + sock=sock, server_side=server_side, + do_handshake_on_connect=do_handshake_on_connect, + suppress_ragged_eofs=suppress_ragged_eofs, + server_hostname=server_hostname, + _context=self, + _session=session) + + if hasattr(orig_SSLContext.options, 'setter'): + # In 3.6, these became properties. They want to access the + # property __set__ method in the superclass, and they do so by using + # super(SSLContext, SSLContext). But we rebind SSLContext when we monkey + # patch, which causes infinite recursion. + # https://github.com/python/cpython/commit/328067c468f82e4ec1b5c510a4e84509e010f296 + # pylint:disable=no-member + @orig_SSLContext.options.setter + def options(self, value): + super(orig_SSLContext, orig_SSLContext).options.__set__(self, value) + + @orig_SSLContext.verify_flags.setter + def verify_flags(self, value): + super(orig_SSLContext, orig_SSLContext).verify_flags.__set__(self, value) + + @orig_SSLContext.verify_mode.setter + def verify_mode(self, value): + super(orig_SSLContext, orig_SSLContext).verify_mode.__set__(self, value) + + if hasattr(orig_SSLContext, 'minimum_version'): + # Like the above, added in 3.7 + # pylint:disable=no-member + @orig_SSLContext.minimum_version.setter + def minimum_version(self, value): + super(orig_SSLContext, orig_SSLContext).minimum_version.__set__(self, value) + + @orig_SSLContext.maximum_version.setter + def maximum_version(self, value): + super(orig_SSLContext, orig_SSLContext).maximum_version.__set__(self, value) + + if hasattr(orig_SSLContext, '_msg_callback'): + # And ditto for 3.8 + # msg_callback is more complex because they want to actually *do* stuff + # in the setter, so we need to call it. For that to work we temporarily rebind + # SSLContext back. This function cannot switch, so it should be safe, + # unless somehow we have multiple threads in a monkey-patched ssl module + # at the same time, which doesn't make much sense. + @property + def _msg_callback(self): + result = super()._msg_callback + if isinstance(result, _Callback): + result = result.user_function + return result + + @_msg_callback.setter + def _msg_callback(self, value): + if value and callable(value): + value = _Callback(value) + + __ssl__.SSLContext = orig_SSLContext + try: + super(SSLContext, SSLContext)._msg_callback.__set__(self, value) # pylint:disable=no-member + finally: + __ssl__.SSLContext = SSLContext + + if hasattr(orig_SSLContext, 'sni_callback'): + # Added in 3.7. + @property + def sni_callback(self): + result = super().sni_callback + if isinstance(result, _Callback): + result = result.user_function # pylint:disable=no-member + return result + @sni_callback.setter + def sni_callback(self, value): + if value and callable(value): + value = _Callback(value) + super(orig_SSLContext, orig_SSLContext).sni_callback.__set__(self, value) # pylint:disable=no-member + else: + # In newer versions, this just sets sni_callback. + def set_servername_callback(self, server_name_callback): + if server_name_callback and callable(server_name_callback): + server_name_callback = _Callback(server_name_callback) + super().set_servername_callback(server_name_callback) + + +class SSLSocket(socket): + """ + gevent `ssl.SSLSocket + `_ for + Python 3. + """ + + # pylint:disable=too-many-instance-attributes,too-many-public-methods + + def __init__(self, sock=None, keyfile=None, certfile=None, + server_side=False, cert_reqs=CERT_NONE, + ssl_version=PROTOCOL_SSLv23, ca_certs=None, + do_handshake_on_connect=True, + family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, + suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, + server_hostname=None, + _session=None, # 3.6 + _context=None): + # When a *sock* argument is passed, it is used only for its fileno() + # and is immediately detach()'d *unless* we raise an error. + + # pylint:disable=too-many-locals,too-many-statements,too-many-branches + + if _context: + self._context = _context + else: + if server_side and not certfile: + raise ValueError("certfile must be specified for server-side " + "operations") + if keyfile and not certfile: + raise ValueError("certfile must be specified") + if certfile and not keyfile: + keyfile = certfile + self._context = SSLContext(ssl_version) + self._context.verify_mode = cert_reqs + if ca_certs: + self._context.load_verify_locations(ca_certs) + if certfile: + self._context.load_cert_chain(certfile, keyfile) + if npn_protocols: + self._context.set_npn_protocols(npn_protocols) + if ciphers: + self._context.set_ciphers(ciphers) + self.keyfile = keyfile + self.certfile = certfile + self.cert_reqs = cert_reqs + self.ssl_version = ssl_version + self.ca_certs = ca_certs + self.ciphers = ciphers + # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get + # mixed in. + if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: + raise NotImplementedError("only stream sockets are supported") + if server_side: + if server_hostname: + raise ValueError("server_hostname can only be specified " + "in client mode") + if _session is not None: + raise ValueError("session can only be specified " + "in client mode") + if self._context.check_hostname and not server_hostname: + raise ValueError("check_hostname requires server_hostname") + self._session = _session + self.server_side = server_side + self.server_hostname = server_hostname + self.do_handshake_on_connect = do_handshake_on_connect + self.suppress_ragged_eofs = suppress_ragged_eofs + connected = False + sock_timeout = None + if sock is not None: + # We're going non-blocking below, can't set timeout yet. + sock_timeout = sock.gettimeout() + socket.__init__(self, + family=sock.family, + type=sock.type, + proto=sock.proto, + fileno=sock.fileno()) + + # When Python 3 sockets are __del__, they close() themselves, + # including their underlying fd, unless they have been detached. + # Only detach if we succeed in taking ownership; if we raise an exception, + # then the user might have no way to close us and release the resources. + sock.detach() + elif fileno is not None: + socket.__init__(self, fileno=fileno) + else: + socket.__init__(self, family=family, type=type, proto=proto) + + self._closed = False + self._sslobj = None + # see if we're connected + try: + self._sock.getpeername() + except OSError as e: + if e.errno != errno.ENOTCONN: + # This file descriptor is hosed, shared or not. + # Clean up. + self.close() + raise + # Next block is originally from + # https://github.com/python/cpython/commit/75a875e0df0530b75b1470d797942f90f4a718d3, + # intended to fix https://github.com/python/cpython/issues/108310 + blocking = self.getblocking() + self.setblocking(False) + try: + # We are not connected so this is not supposed to block, but + # testing revealed otherwise on macOS and Windows so we do + # the non-blocking dance regardless. Our raise when any data + # is found means consuming the data is harmless. + notconn_pre_handshake_data = self.recv(1) + except OSError as e: # pylint:disable=redefined-outer-name + # EINVAL occurs for recv(1) on non-connected on unix sockets. + if e.errno not in (errno.ENOTCONN, errno.EINVAL): + raise + notconn_pre_handshake_data = b'' + self.setblocking(blocking) + if notconn_pre_handshake_data: + # This prevents pending data sent to the socket before it was + # closed from escaping to the caller who could otherwise + # presume it came through a successful TLS connection. + reason = "Closed before TLS handshake with data in recv buffer." + notconn_pre_handshake_data_error = SSLError(e.errno, reason) + # Add the SSLError attributes that _ssl.c always adds. + notconn_pre_handshake_data_error.reason = reason + notconn_pre_handshake_data_error.library = None + try: + self.close() + except OSError: + pass + raise notconn_pre_handshake_data_error + else: + connected = True + + self.settimeout(sock_timeout) + self._connected = connected + if connected: + # create the SSL object + try: + self._sslobj = self.__create_sslobj(server_side, _session) + + if do_handshake_on_connect: + timeout = self.gettimeout() + if timeout == 0.0: + # non-blocking + raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") + self.do_handshake() + except OSError: + self.close() + raise + + def _gevent_sock_class(self, family, type, proto, fileno): + return _contextawaresock(family, type, proto, fileno, _wref(self)) + + def _extra_repr(self): + return ' server=%s, cipher=%r' % ( + self.server_side, + self._sslobj.cipher() if self._sslobj is not None else '' + + ) + + @property + def context(self): + return self._context + + @context.setter + def context(self, ctx): + self._context = ctx + self._sslobj.context = ctx + + @property + def session(self): + """The SSLSession for client socket.""" + if self._sslobj is not None: + return self._sslobj.session + + @session.setter + def session(self, session): + self._session = session + if self._sslobj is not None: + self._sslobj.session = session + + @property + def session_reused(self): + """Was the client session reused during handshake""" + if self._sslobj is not None: + return self._sslobj.session_reused + + def dup(self): + raise NotImplementedError("Can't dup() %s instances" % + self.__class__.__name__) + + def _checkClosed(self, msg=None): + # raise an exception here if you wish to check for spurious closes + pass + + def _check_connected(self): + if not self._connected: + # getpeername() will raise ENOTCONN if the socket is really + # not connected; note that we can be connected even without + # _connected being set, e.g. if connect() first returned + # EAGAIN. + self.getpeername() + + def read(self, nbytes=2014, buffer=None): + """Read up to LEN bytes and return them. + Return zero-length string on EOF. + + .. versionchanged:: 24.2.1 + No longer requires a non-None *buffer* to implement ``len()``. + This is a backport from 3.11.8. + """ + # pylint:disable=too-many-branches + self._checkClosed() + # The stdlib signature is (len=1024, buffer=None) + # but that shadows the len builtin, and its hard/annoying to + # get it back. + # + # Also, the return values are weird. If *buffer* is given, + # we return the count of bytes added to buffer. Otherwise, + # we return the string we read. + bytes_read = 0 + + while True: + if not self._sslobj: + raise ValueError("Read on closed or unwrapped SSL socket.") + if nbytes == 0: + return b'' if buffer is None else 0 + # Negative lengths are handled natively when the buffer is None + # to raise a ValueError + try: + if buffer is not None: + bytes_read += self._sslobj.read(nbytes, buffer) + return bytes_read + return self._sslobj.read(nbytes or 1024) + except SSLWantReadError: + if self.timeout == 0.0: + raise + self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout) + except SSLWantWriteError: + if self.timeout == 0.0: + raise + # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional + self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout) + except SSLZeroReturnError: + # This one is only seen in PyPy 7.3.17 + if self.suppress_ragged_eofs: + return b'' if buffer is None else bytes_read + raise + except SSLError as ex: + # All the other SSLxxxxxError classes extend SSLError, + # so catch it last. + if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: + return b'' if buffer is None else bytes_read + raise + # Certain versions of Python, built against certain + # versions of OpenSSL operating in certain modes, can + # produce ``ConnectionResetError`` instead of + # ``SSLError``. Notably, it looks like anything built + # against 1.1.1c does that? gevent briefly (from support of TLS 1.3 + # in Sept 2019 to issue #1637 it June 2020) caught that error and treaded + # it just like SSL_ERROR_EOF. But that's not what the standard library does. + # So presumably errors that result from unexpected ``ConnectionResetError`` + # are issues in gevent tests. + + def write(self, data): + """Write DATA to the underlying SSL channel. Returns + number of bytes of DATA actually transmitted.""" + self._checkClosed() + + while True: + if not self._sslobj: + raise ValueError("Write on closed or unwrapped SSL socket.") + + try: + return self._sslobj.write(data) + except SSLError as ex: + if ex.args[0] == SSL_ERROR_WANT_READ: + if self.timeout == 0.0: + raise + self._wait(self._read_event, timeout_exc=_SSLErrorWriteTimeout) + elif ex.args[0] == SSL_ERROR_WANT_WRITE: + if self.timeout == 0.0: + raise + self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout) + else: + raise + + def getpeercert(self, binary_form=False): + """Returns a formatted version of the data in the + certificate provided by the other end of the SSL channel. + Return None if no certificate was provided, {} if a + certificate was provided, but not validated.""" + + self._checkClosed() + self._check_connected() + try: + c = self._sslobj.peer_certificate + except AttributeError: + # 3.6 + c = self._sslobj.getpeercert + + return c(binary_form) + + def selected_npn_protocol(self): + self._checkClosed() + if not self._sslobj or not _ssl.HAS_NPN: + return None + return self._sslobj.selected_npn_protocol() + + if hasattr(_ssl, 'HAS_ALPN'): + # 3.5+ + def selected_alpn_protocol(self): + self._checkClosed() + if not self._sslobj or not _ssl.HAS_ALPN: # pylint:disable=no-member + return None + return self._sslobj.selected_alpn_protocol() + + def shared_ciphers(self): + """Return a list of ciphers shared by the client during the handshake or + None if this is not a valid server connection. + """ + return self._sslobj.shared_ciphers() + + def version(self): + """Return a string identifying the protocol version used by the + current SSL channel. """ + if not self._sslobj: + return None + return self._sslobj.version() + + # We inherit sendfile from super(); it always uses `send` + + def cipher(self): + self._checkClosed() + if not self._sslobj: + return None + return self._sslobj.cipher() + + def compression(self): + self._checkClosed() + if not self._sslobj: + return None + return self._sslobj.compression() + + def send(self, data, flags=0, timeout=timeout_default): + self._checkClosed() + if timeout is timeout_default: + timeout = self.timeout + if self._sslobj: + if flags != 0: + raise ValueError( + "non-zero flags not allowed in calls to send() on %s" % + self.__class__) + while True: + try: + return self._sslobj.write(data) + except SSLWantReadError: + if self.timeout == 0.0: + return 0 + self._wait(self._read_event) + except SSLWantWriteError: + if self.timeout == 0.0: + return 0 + self._wait(self._write_event) + else: + return socket.send(self, data, flags, timeout) + + def sendto(self, data, flags_or_addr, addr=None): + self._checkClosed() + if self._sslobj: + raise ValueError("sendto not allowed on instances of %s" % + self.__class__) + if addr is None: + return socket.sendto(self, data, flags_or_addr) + return socket.sendto(self, data, flags_or_addr, addr) + + def sendmsg(self, *args, **kwargs): + # Ensure programs don't send data unencrypted if they try to + # use this method. + raise NotImplementedError("sendmsg not allowed on instances of %s" % + self.__class__) + + def sendall(self, data, flags=0): + self._checkClosed() + if self._sslobj: + if flags != 0: + raise ValueError( + "non-zero flags not allowed in calls to sendall() on %s" % + self.__class__) + + try: + return socket.sendall(self, data, flags) + except _socket_timeout: + if self.timeout == 0.0: + # Raised by the stdlib on non-blocking sockets + raise SSLWantWriteError("The operation did not complete (write)") + raise + + def recv(self, buflen=1024, flags=0): + self._checkClosed() + if self._sslobj: + if flags != 0: + raise ValueError( + "non-zero flags not allowed in calls to recv() on %s" % + self.__class__) + if buflen == 0: + # https://github.com/python/cpython/commit/00915577dd84ba75016400793bf547666e6b29b5 + # Python #23804 + return b'' + return self.read(buflen) + return socket.recv(self, buflen, flags) + + def recv_into(self, buffer, nbytes=None, flags=0): + """ + .. versionchanged:: 24.2.1 + No longer requires a non-None *buffer* to implement ``len()``. + This is a backport from 3.11.8. + """ + self._checkClosed() + if nbytes is None: + if buffer is not None: + with memoryview(buffer) as view: + nbytes = view.nbytes + if not nbytes: + nbytes = 1024 + + if self._sslobj: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into() on %s" % self.__class__) + return self.read(nbytes, buffer) + return socket.recv_into(self, buffer, nbytes, flags) + + def recvfrom(self, buflen=1024, flags=0): + self._checkClosed() + if self._sslobj: + raise ValueError("recvfrom not allowed on instances of %s" % + self.__class__) + return socket.recvfrom(self, buflen, flags) + + def recvfrom_into(self, buffer, nbytes=None, flags=0): + self._checkClosed() + if self._sslobj: + raise ValueError("recvfrom_into not allowed on instances of %s" % + self.__class__) + return socket.recvfrom_into(self, buffer, nbytes, flags) + + def recvmsg(self, *args, **kwargs): + raise NotImplementedError("recvmsg not allowed on instances of %s" % + self.__class__) + + def recvmsg_into(self, *args, **kwargs): + raise NotImplementedError("recvmsg_into not allowed on instances of " + "%s" % self.__class__) + + def pending(self): + self._checkClosed() + if self._sslobj: + return self._sslobj.pending() + return 0 + + def shutdown(self, how): + self._checkClosed() + self._sslobj = None + socket.shutdown(self, how) + + def unwrap(self): + if not self._sslobj: + raise ValueError("No SSL wrapper around " + str(self)) + + try: + # 3.7 and newer, that use the SSLSocket object + # call its shutdown. + shutdown = self._sslobj.shutdown + except AttributeError: + # Earlier versions use SSLObject, which covers + # that with a layer. + shutdown = self._sslobj.unwrap + + s = self._sock + while True: + try: + s = shutdown() + break + except SSLWantReadError: + # Callers of this method expect to get a socket + # back, so we can't simply return 0, we have + # to let these be raised + if self.timeout == 0.0: + raise + self._wait(self._read_event) + except SSLWantWriteError: + if self.timeout == 0.0: + raise + self._wait(self._write_event) + except SSLEOFError: + break + except SSLZeroReturnError: + # Between PyPy 7.3.12 and PyPy 7.3.17, it started raising + # this. This is equivalent to SSLEOFError for our purposes: + # both indicate the connection has been closed, + # the former uncleanly, the latter cleanly. + break + except OSError as e: + if e.errno == 0: + # The equivalent of SSLEOFError on unpatched versions of Python. + # https://bugs.python.org/issue31122 + break + raise + + self._sslobj = None + + # The return value of shutting down the SSLObject is the + # original wrapped socket passed to _wrap_socket, i.e., + # _contextawaresock. But that object doesn't have the + # gevent wrapper around it so it can't be used. We have to + # wrap it back up with a gevent wrapper. + assert s is self._sock + # In the stdlib, SSLSocket subclasses socket.socket and passes itself + # to _wrap_socket, so it gets itself back. We can't do that, we have to + # pass our subclass of _socket.socket, _contextawaresock. + # So ultimately we should return ourself. + + # See test_ftplib.py:TestTLS_FTPClass.test_ccc + return self + + def _real_close(self): + self._sslobj = None + socket._real_close(self) + + def do_handshake(self): + """Perform a TLS/SSL handshake.""" + self._check_connected() + while True: + try: + self._sslobj.do_handshake() + break + except SSLWantReadError: + if self.timeout == 0.0: + raise + self._wait(self._read_event, timeout_exc=_SSLErrorHandshakeTimeout) + except SSLWantWriteError: + if self.timeout == 0.0: + raise + self._wait(self._write_event, timeout_exc=_SSLErrorHandshakeTimeout) + + # 3.7+, making it difficult to create these objects. + # There's a new type, _ssl.SSLSocket, that takes the + # place of SSLObject for self._sslobj. This one does it all. + def __create_sslobj(self, server_side=False, session=None): + return self.context._wrap_socket( + self._sock, server_side, self.server_hostname, + owner=self._sock, session=session + ) + + def _real_connect(self, addr, connect_ex): + if self.server_side: + raise ValueError("can't connect in server-side mode") + # Here we assume that the socket is client-side, and not + # connected at the time of the call. We connect it, then wrap it. + if self._connected: + raise ValueError("attempt to connect already-connected SSLSocket!") + self._sslobj = self.__create_sslobj(False, self._session) + + try: + if connect_ex: + rc = socket.connect_ex(self, addr) + else: + rc = None + socket.connect(self, addr) + if not rc: + if self.do_handshake_on_connect: + self.do_handshake() + self._connected = True + return rc + except socket_error: + self._sslobj = None + raise + + def connect(self, addr): + """Connects to remote ADDR, and then wraps the connection in + an SSL channel.""" + self._real_connect(addr, False) + + def connect_ex(self, addr): + """Connects to remote ADDR, and then wraps the connection in + an SSL channel.""" + return self._real_connect(addr, True) + + def accept(self): + """ + Accepts a new connection from a remote client, and returns a + tuple containing that new connection wrapped with a + server-side SSL channel, and the address of the remote client. + """ + newsock, addr = super().accept() + try: + newsock = self._context.wrap_socket( + newsock, + do_handshake_on_connect=self.do_handshake_on_connect, + suppress_ragged_eofs=self.suppress_ragged_eofs, + server_side=True + ) + return newsock, addr + except: + newsock.close() + raise + + def get_channel_binding(self, cb_type="tls-unique"): + """Get channel binding data for current connection. Raise ValueError + if the requested `cb_type` is not supported. Return bytes of the data + or None if the data is not available (e.g. before the handshake). + """ + if hasattr(self._sslobj, 'get_channel_binding'): + # 3.7+, and sslobj is not None + return self._sslobj.get_channel_binding(cb_type) + if cb_type not in CHANNEL_BINDING_TYPES: + raise ValueError("Unsupported channel binding type") + if cb_type != "tls-unique": + raise NotImplementedError("{0} channel binding type not implemented".format(cb_type)) + if self._sslobj is None: + return None + return self._sslobj.tls_unique_cb() + + def verify_client_post_handshake(self): + # Only present in 3.7.1+; an attributeerror is alright + if self._sslobj: + return self._sslobj.verify_client_post_handshake() + raise ValueError("No SSL wrapper around " + str(self)) + + if hasattr(__ssl__.SSLSocket, 'get_verified_chain'): + # Added in 3.13 + def get_verified_chain(self): + chain = self._sslobj.get_verified_chain() + + if chain is None: + return [] + + return [cert.public_bytes(_ssl.ENCODING_DER) for cert in chain] + + def get_unverified_chain(self): + chain = self._sslobj.get_unverified_chain() + + if chain is None: + return [] + + return [cert.public_bytes(_ssl.ENCODING_DER) for cert in chain] + +# Python does not support forward declaration of types +SSLContext.sslsocket_class = SSLSocket + +# Python 3.2 onwards raise normal timeout errors, not SSLError. +# See https://bugs.python.org/issue10272 +_SSLErrorReadTimeout = _socket_timeout('The read operation timed out') +_SSLErrorWriteTimeout = _socket_timeout('The write operation timed out') +_SSLErrorHandshakeTimeout = _socket_timeout('The handshake operation timed out') + + +def wrap_socket(sock, keyfile=None, certfile=None, + server_side=False, cert_reqs=CERT_NONE, + ssl_version=PROTOCOL_SSLv23, ca_certs=None, + do_handshake_on_connect=True, + suppress_ragged_eofs=True, + ciphers=None): + + return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, + server_side=server_side, cert_reqs=cert_reqs, + ssl_version=ssl_version, ca_certs=ca_certs, + do_handshake_on_connect=do_handshake_on_connect, + suppress_ragged_eofs=suppress_ragged_eofs, + ciphers=ciphers) + + +def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): + """Retrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.""" + + _, _ = addr + if ca_certs is not None: + cert_reqs = CERT_REQUIRED + else: + cert_reqs = CERT_NONE + with create_connection(addr) as sock: + with wrap_socket(sock, ssl_version=ssl_version, + cert_reqs=cert_reqs, ca_certs=ca_certs) as sslsock: + dercert = sslsock.getpeercert(True) + sslsock = sock = None + return DER_cert_to_PEM_cert(dercert) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/subprocess.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a4846b8a60e7b8ee973787f8711f93bbbbef90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/subprocess.py @@ -0,0 +1,2041 @@ +""" +Cooperative ``subprocess`` module. + +.. caution:: On POSIX platforms, this module is not usable from native + threads other than the main thread; attempting to do so will raise + a :exc:`TypeError`. This module depends on libev's fork watchers. + On POSIX systems, fork watchers are implemented using signals, and + the thread to which process-directed signals are delivered `is not + defined`_. Because each native thread has its own gevent/libev + loop, this means that a fork watcher registered with one loop + (thread) may never see the signal about a child it spawned if the + signal is sent to a different thread. + +.. note:: The interface of this module is intended to match that of + the standard library :mod:`subprocess` module (with many backwards + compatible extensions from Python 3 backported to Python 2). There + are some small differences between the Python 2 and Python 3 + versions of that module (the Python 2 ``TimeoutExpired`` exception, + notably, extends ``Timeout`` and there is no ``SubprocessError``) and between the + POSIX and Windows versions. The HTML documentation here can only + describe one version; for definitive documentation, see the + standard library or the source code. + +.. _is not defined: http://www.linuxprogrammingblog.com/all-about-linux-signals?page=11 +""" +from __future__ import absolute_import, print_function +# Can we split this up to make it cleaner? See https://github.com/gevent/gevent/issues/748 +# pylint: disable=too-many-lines +# Most of this we inherit from the standard lib +# pylint: disable=bare-except,too-many-locals,too-many-statements,attribute-defined-outside-init +# pylint: disable=too-many-branches,too-many-instance-attributes +# Most of this is cross-platform +# pylint: disable=no-member,expression-not-assigned,unused-argument,unused-variable +import errno +import gc +import os +import signal +import sys +import traceback +# Python 3.9 +try: + from types import GenericAlias +except ImportError: + GenericAlias = None + +try: + import grp +except ImportError: + grp = None + +try: + import pwd +except ImportError: + pwd = None + +from gevent.event import AsyncResult +from gevent.hub import _get_hub_noargs as get_hub +from gevent.hub import linkproxy +from gevent.hub import sleep +from gevent.hub import getcurrent +from gevent._compat import integer_types, string_types, xrange + +from gevent._compat import PY311 +from gevent._compat import PYPY +from gevent._compat import PY313 +from gevent._compat import WIN + +from gevent._compat import fsdecode +from gevent._compat import fsencode +from gevent._compat import PathLike +from gevent._util import _NONE +from gevent._util import copy_globals + +from gevent.greenlet import Greenlet, joinall +spawn = Greenlet.spawn +import subprocess as __subprocess__ + + +# Standard functions and classes that this module re-implements in a gevent-aware way. +__implements__ = [ + 'Popen', + 'call', + 'check_call', + 'check_output', +] +if not sys.platform.startswith('win32'): + __implements__.append("_posixsubprocess") + _posixsubprocess = None + + +# Some symbols we define that we expect to export; +# useful for static analysis +PIPE = "PIPE should be imported" + +# Standard functions and classes that this module re-imports. +__imports__ = [ + 'PIPE', + 'STDOUT', + 'CalledProcessError', + # Windows: + 'CREATE_NEW_CONSOLE', + 'CREATE_NEW_PROCESS_GROUP', + 'STD_INPUT_HANDLE', + 'STD_OUTPUT_HANDLE', + 'STD_ERROR_HANDLE', + 'SW_HIDE', + 'STARTF_USESTDHANDLES', + 'STARTF_USESHOWWINDOW', +] + + +__extra__ = [ + 'MAXFD', + '_eintr_retry_call', + 'STARTUPINFO', + 'pywintypes', + 'list2cmdline', + '_subprocess', + '_winapi', + # Python 2.5 does not have _subprocess, so we don't use it + # XXX We don't run on Py 2.5 anymore; can/could/should we use _subprocess? + # It's only used on mswindows + 'WAIT_OBJECT_0', + 'WaitForSingleObject', + 'GetExitCodeProcess', + 'GetStdHandle', + 'CreatePipe', + 'DuplicateHandle', + 'GetCurrentProcess', + 'DUPLICATE_SAME_ACCESS', + 'GetModuleFileName', + 'GetVersion', + 'CreateProcess', + 'INFINITE', + 'TerminateProcess', + 'STILL_ACTIVE', + + # These were added for 3.5, but we make them available everywhere. + 'run', + 'CompletedProcess', +] + +__imports__ += [ + 'DEVNULL', + 'getstatusoutput', + 'getoutput', + 'SubprocessError', + 'TimeoutExpired', +] + +# Became standard in 3.5 +__extra__.remove('run') +__extra__.remove('CompletedProcess') +__implements__.append('run') +__implements__.append('CompletedProcess') + +# Removed in Python 3.5; this is the exact code that was removed: +# https://hg.python.org/cpython/rev/f98b0a5e5ef5 +__extra__.remove('MAXFD') +try: + MAXFD = os.sysconf("SC_OPEN_MAX") +except: + MAXFD = 256 + + +# This was added to __all__ for windows in 3.6 +__extra__.remove('STARTUPINFO') +__imports__.append('STARTUPINFO') + +__imports__.extend([ + 'ABOVE_NORMAL_PRIORITY_CLASS', 'BELOW_NORMAL_PRIORITY_CLASS', + 'HIGH_PRIORITY_CLASS', 'IDLE_PRIORITY_CLASS', + 'NORMAL_PRIORITY_CLASS', + 'REALTIME_PRIORITY_CLASS', + 'CREATE_NO_WINDOW', 'DETACHED_PROCESS', + 'CREATE_DEFAULT_ERROR_MODE', + 'CREATE_BREAKAWAY_FROM_JOB' +]) + +if PY313 and WIN: + __imports__.extend([ + 'STARTF_FORCEONFEEDBACK', + 'STARTF_FORCEOFFFEEDBACK' + ]) + + +# Using os.posix_spawn() to start subprocesses +# bypasses our child watchers on certain operating systems, +# and with certain library versions. Possibly the right +# fix is to monkey-patch os.posix_spawn like we do os.fork? +# These have no effect, they're just here to match the stdlib. +# TODO: When available, given a monkey patch on them, I think +# we ought to be able to use them if the stdlib has identified them +# as suitable. +__implements__.extend([ + '_use_posix_spawn', +]) + +def _use_posix_spawn(): + return False + +_USE_POSIX_SPAWN = False + +if __subprocess__._USE_POSIX_SPAWN: + __implements__.extend([ + '_USE_POSIX_SPAWN', + ]) +else: + __imports__.extend([ + '_USE_POSIX_SPAWN', + ]) + +if PY311: + # Python 3.11 added some module-level attributes to control the + # use of vfork. The docs specifically say that you should not try to read + # them, only set them, so we don't provide them. + # + # Python 3.11 also added a test, test_surrogates_error_message, that behaves + # differently based on whether or not the pure python implementation of forking + # is in use, or the one written in C from _posixsubprocess. Obviously we don't call + # that, so we need to make us look like a pure python version; it checks that this attribute + # is none for that. + _fork_exec = None + __implements__.extend([ + '_fork_exec', + ] if sys.platform != 'win32' else [ + ]) + +actually_imported = copy_globals(__subprocess__, globals(), + only_names=__imports__, + ignore_missing_names=True) +# anything we couldn't import from here we may need to find +# elsewhere +__extra__.extend(set(__imports__).difference(set(actually_imported))) +__imports__ = actually_imported +del actually_imported + + +# In Python 3 on Windows, a lot of the functions previously +# in _subprocess moved to _winapi +_subprocess = getattr(__subprocess__, '_subprocess', _NONE) +_winapi = getattr(__subprocess__, '_winapi', _NONE) + +_attr_resolution_order = [__subprocess__, _subprocess, _winapi] + +for name in list(__extra__): + if name in globals(): + continue + value = _NONE + for place in _attr_resolution_order: + value = getattr(place, name, _NONE) + if value is not _NONE: + break + + if value is _NONE: + __extra__.remove(name) + else: + globals()[name] = value + +del _attr_resolution_order +__all__ = __implements__ + __imports__ +# Some other things we want to document +for _x in ('run', 'CompletedProcess', 'TimeoutExpired'): + if _x not in __all__: + __all__.append(_x) + + + +mswindows = WIN +if mswindows: + import msvcrt # pylint: disable=import-error + class Handle(int): + closed = False + + def Close(self): + if not self.closed: + self.closed = True + _winapi.CloseHandle(self) + + def Detach(self): + if not self.closed: + self.closed = True + return int(self) + raise ValueError("already closed") + + def __repr__(self): + return "Handle(%d)" % int(self) + + __del__ = Close + __str__ = __repr__ +else: + import fcntl + import pickle + from gevent import monkey + fork = monkey.get_original('os', 'fork') + from gevent.os import fork_and_watch + +STDOUT = __subprocess__.STDOUT # static analysis + + +def call(*popenargs, **kwargs): + """ + call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> returncode + + Run command with arguments. Wait for command to complete or + timeout, then return the returncode attribute. + + The arguments are the same as for the Popen constructor. Example:: + + retcode = call(["ls", "-l"]) + + .. versionchanged:: 1.2a1 + The ``timeout`` keyword argument is now accepted on all supported + versions of Python (not just Python 3) and if it expires will raise a + :exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`). + """ + timeout = kwargs.pop('timeout', None) + with Popen(*popenargs, **kwargs) as p: + try: + return p.wait(timeout=timeout, _raise_exc=True) + except: + p.kill() + p.wait() + raise + +def check_call(*popenargs, **kwargs): + """ + check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> 0 + + Run command with arguments. Wait for command to complete. If + the exit code was zero then return, otherwise raise + :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the + return code in the returncode attribute. + + The arguments are the same as for the Popen constructor. Example:: + + retcode = check_call(["ls", "-l"]) + """ + retcode = call(*popenargs, **kwargs) + if retcode: + cmd = kwargs.get("args") + if cmd is None: + cmd = popenargs[0] + raise CalledProcessError(retcode, cmd) # pylint:disable=undefined-variable + return 0 + +def check_output(*popenargs, **kwargs): + r""" + check_output(args, *, input=None, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None) -> output + + Run command with arguments and return its output. + + If the exit code was non-zero it raises a :exc:`CalledProcessError`. The + ``CalledProcessError`` object will have the return code in the returncode + attribute and output in the output attribute. + + + The arguments are the same as for the Popen constructor. Example:: + + >>> check_output(["ls", "-1", "/dev/null"]) + '/dev/null\n' + + The ``stdout`` argument is not allowed as it is used internally. + + To capture standard error in the result, use ``stderr=STDOUT``:: + + >>> output = check_output(["/bin/sh", "-c", + ... "ls -l non_existent_file ; exit 0"], + ... stderr=STDOUT).decode('ascii').strip() + >>> print(output.rsplit(':', 1)[1].strip()) + No such file or directory + + There is an additional optional argument, "input", allowing you to + pass a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it too will be used internally. Example:: + + >>> check_output(["sed", "-e", "s/foo/bar/"], + ... input=b"when in the course of fooman events\n") + 'when in the course of barman events\n' + + If ``universal_newlines=True`` is passed, the return value will be a + string rather than bytes. + + .. versionchanged:: 1.2a1 + The ``timeout`` keyword argument is now accepted on all supported + versions of Python (not just Python 3) and if it expires will raise a + :exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`). + .. versionchanged:: 1.2a1 + The ``input`` keyword argument is now accepted on all supported + versions of Python, not just Python 3 + .. versionchanged:: 22.08.0 + Passing the ``check`` keyword argument is forbidden, just as in Python 3.11. + """ + timeout = kwargs.pop('timeout', None) + if 'stdout' in kwargs: + raise ValueError('stdout argument not allowed, it will be overridden.') + if 'check' in kwargs: + raise ValueError('check argument not allowed, it will be overridden.') + if 'input' in kwargs: + if 'stdin' in kwargs: + raise ValueError('stdin and input arguments may not both be used.') + inputdata = kwargs['input'] + del kwargs['input'] + kwargs['stdin'] = PIPE + else: + inputdata = None + + with Popen(*popenargs, stdout=PIPE, **kwargs) as process: + try: + output, unused_err = process.communicate(inputdata, timeout=timeout) + except TimeoutExpired: + process.kill() + output, unused_err = process.communicate() + raise TimeoutExpired(process.args, timeout, output=output) + except: + process.kill() + process.wait() + raise + retcode = process.poll() + if retcode: + # pylint:disable=undefined-variable + raise CalledProcessError(retcode, process.args, output=output) + return output + +_PLATFORM_DEFAULT_CLOSE_FDS = object() + +if 'TimeoutExpired' not in globals(): + # Python 2 + + # Make TimeoutExpired inherit from _Timeout so it can be caught + # the way we used to throw things (except Timeout), but make sure it doesn't + # init a timer. Note that we can't have a fake 'SubprocessError' that inherits + # from exception, because we need TimeoutExpired to just be a BaseException for + # bwc. + from gevent.timeout import Timeout as _Timeout + + class TimeoutExpired(_Timeout): + """ + This exception is raised when the timeout expires while waiting for + a child process in `communicate`. + + Under Python 2, this is a gevent extension with the same name as the + Python 3 class for source-code forward compatibility. However, it extends + :class:`gevent.timeout.Timeout` for backwards compatibility (because + we used to just raise a plain ``Timeout``); note that ``Timeout`` is a + ``BaseException``, *not* an ``Exception``. + + .. versionadded:: 1.2a1 + """ + + def __init__(self, cmd, timeout, output=None): + _Timeout.__init__(self, None) + self.cmd = cmd + self.seconds = timeout + self.output = output + + @property + def timeout(self): + return self.seconds + + def __str__(self): + return ("Command '%s' timed out after %s seconds" % + (self.cmd, self.timeout)) + + +if hasattr(os, 'set_inheritable'): + _set_inheritable = os.set_inheritable +else: + _set_inheritable = lambda i, v: True + + +def FileObject(*args, **kwargs): + # Defer importing FileObject until we need it + # to allow it to be configured more easily. + from gevent.fileobject import FileObject as _FileObject + globals()['FileObject'] = _FileObject + return _FileObject(*args) + + +class _CommunicatingGreenlets(object): + # At most, exactly one of these objects may be created + # for a given Popen object. This ensures that only one background + # greenlet at a time will be reading from the file object. This matters because + # if a timeout exception is raised, the user may call back into communicate() to + # get the output (usually after killing the process; see run()). We must not + # lose output in that case (Python 3 specifically documents that raising a timeout + # doesn't lose output). Also, attempting to read from a pipe while it's already + # being read from results in `RuntimeError: reentrant call in io.BufferedReader`; + # the same thing happens if you attempt to close() it while that's in progress. + __slots__ = ( + 'stdin', + 'stdout', + 'stderr', + '_all_greenlets', + ) + + def __init__(self, popen, input_data): + self.stdin = self.stdout = self.stderr = None + if popen.stdin: # Even if no data, we need to close + self.stdin = spawn(self._write_and_close, popen.stdin, input_data) + + # If the timeout parameter is used, and the caller calls back after + # getting a TimeoutExpired exception, we can wind up with multiple + # greenlets trying to run and read from and close stdout/stderr. + # That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'. + # We can't just kill the previous greenlets when a timeout happens, + # though, because we risk losing the output collected by that greenlet + # (and Python 3, where timeout is an official parameter, explicitly says + # that no output should be lost in the event of a timeout.) Instead, we're + # watching for the exception and ignoring it. It's not elegant, + # but it works + if popen.stdout: + self.stdout = spawn(self._read_and_close, popen.stdout) + + if popen.stderr: + self.stderr = spawn(self._read_and_close, popen.stderr) + + all_greenlets = [] + for g in self.stdin, self.stdout, self.stderr: + if g is not None: + all_greenlets.append(g) + self._all_greenlets = tuple(all_greenlets) + + def __iter__(self): + return iter(self._all_greenlets) + + def __bool__(self): + return bool(self._all_greenlets) + + __nonzero__ = __bool__ + + def __len__(self): + return len(self._all_greenlets) + + @staticmethod + def _write_and_close(fobj, data): + try: + if data: + fobj.write(data) + if hasattr(fobj, 'flush'): + # 3.6 started expecting flush to be called. + fobj.flush() + except OSError as ex: + # Test cases from the stdlib can raise BrokenPipeError + # without setting an errno value. This matters because + # Python 2 doesn't have a BrokenPipeError. + if isinstance(ex, BrokenPipeError) and ex.errno is None: + ex.errno = errno.EPIPE + if ex.errno not in (errno.EPIPE, errno.EINVAL): + raise + finally: + try: + fobj.close() + except EnvironmentError: + pass + + @staticmethod + def _read_and_close(fobj): + try: + return fobj.read() + finally: + try: + fobj.close() + except EnvironmentError: + pass + + +class Popen(object): + """ + The underlying process creation and management in this module is + handled by the Popen class. It offers a lot of flexibility so that + developers are able to handle the less common cases not covered by + the convenience functions. + + .. seealso:: :class:`subprocess.Popen` + This class should have the same interface as the standard library class. + + .. caution:: + + The default values of some arguments, notably ``buffering``, differ + between Python 2 and Python 3. For the most consistent behaviour across + versions, it's best to explicitly pass the desired values. + + .. caution:: + + On Python 2, the ``read`` method of the ``stdout`` and ``stderr`` attributes + will not be buffered unless buffering is explicitly requested (e.g., `bufsize=-1`). + This is different than the ``read`` method of the standard library attributes, + which will buffer internally even if no buffering has been requested. This + matches the Python 3 behaviour. For portability, please explicitly request + buffering if you want ``read(n)`` to return all ``n`` bytes, making more than + one system call if needed. See `issue 1701 `_ + for more context. + + .. versionchanged:: 1.2a1 + Instances can now be used as context managers under Python 2.7. Previously + this was restricted to Python 3. + + .. versionchanged:: 1.2a1 + Instances now save the ``args`` attribute under Python 2.7. Previously this was + restricted to Python 3. + + .. versionchanged:: 1.2b1 + Add the ``encoding`` and ``errors`` parameters for Python 3. + + .. versionchanged:: 1.3a1 + Accept "path-like" objects for the *cwd* parameter on all platforms. + This was added to Python 3.6. Previously with gevent, it only worked + on POSIX platforms on 3.6. + + .. versionchanged:: 1.3a1 + Add the ``text`` argument as a synonym for ``universal_newlines``, + as added on Python 3.7. + + .. versionchanged:: 1.3a2 + Allow the same keyword arguments under Python 2 as Python 3: + ``pass_fds``, ``start_new_session``, ``restore_signals``, ``encoding`` + and ``errors``. Under Python 2, ``encoding`` and ``errors`` are ignored + because native handling of universal newlines is used. + + .. versionchanged:: 1.3a2 + Under Python 2, ``restore_signals`` defaults to ``False``. Previously it + defaulted to ``True``, the same as it did in Python 3. + + .. versionchanged:: 20.6.0 + Add the *group*, *extra_groups*, *user*, and *umask* arguments. These + were added to Python 3.9, but are available in any gevent version, provided + the underlying platform support is present. + + .. versionchanged:: 20.12.0 + On Python 2 only, if unbuffered binary communication is requested, + the ``stdin`` attribute of this object will have a ``write`` method that + actually performs internal buffering and looping, similar to the standard library. + It guarantees to write all the data given to it in a single call (but internally + it may make many system calls and/or trips around the event loop to accomplish this). + See :issue:`1711`. + + .. versionchanged:: 21.12.0 + Added the ``pipesize`` argument for compatibility with Python 3.10. + This is ignored on all platforms. + + .. versionchanged:: 22.08.0 + Added the ``process_group`` and ``check`` arguments for compatibility with + Python 3.11. + + .. versionchanged:: 24.10.1 + To match Python 3.13, ``stdout=STDOUT`` now raises a :exc:`ValueError`. + """ + + if GenericAlias is not None: + # 3.9, annoying typing is creeping everywhere. + __class_getitem__ = classmethod(GenericAlias) + + # The value returned from communicate() when there was nothing to read. + # Changes if we're in text mode or universal newlines mode. + _communicate_empty_value = b'' + + # pylint:disable-next=too-many-positional-arguments + def __init__(self, args, + bufsize=-1, + executable=None, + stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False, + cwd=None, env=None, universal_newlines=None, + startupinfo=None, creationflags=0, + restore_signals=True, start_new_session=False, + pass_fds=(), + # Added in 3.6. These are kept as ivars + encoding=None, errors=None, + # Added in 3.7. Not an ivar directly. + text=None, + # Added in 3.9 + group=None, extra_groups=None, user=None, + umask=-1, + # Added in 3.10, but ignored. + pipesize=-1, + # Added in 3.11 + process_group=None, + # gevent additions + threadpool=None): + + self.encoding = encoding + self.errors = errors + + hub = get_hub() + + if bufsize is None: + # Python 2 doesn't allow None at all, but Python 3 treats + # it the same as the default. We do as well. + bufsize = -1 + if not isinstance(bufsize, integer_types): + raise TypeError("bufsize must be an integer") + + if stdout is STDOUT: + raise ValueError("STDOUT can only be used for stderr") + + if mswindows: + if preexec_fn is not None: + raise ValueError("preexec_fn is not supported on Windows " + "platforms") + + if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: + close_fds = True + + if threadpool is None: + threadpool = hub.threadpool + self.threadpool = threadpool + self._waiting = False + else: + # POSIX + if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: + # close_fds has different defaults on Py3/Py2 + close_fds = True + + if pass_fds and not close_fds: + import warnings + warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) + close_fds = True + if startupinfo is not None: + raise ValueError("startupinfo is only supported on Windows " + "platforms") + if creationflags != 0: + raise ValueError("creationflags is only supported on Windows " + "platforms") + assert threadpool is None + self._loop = hub.loop + + # Validate the combinations of text and universal_newlines + if (text is not None and universal_newlines is not None + and bool(universal_newlines) != bool(text)): + # pylint:disable=undefined-variable + raise SubprocessError('Cannot disambiguate when both text ' + 'and universal_newlines are supplied but ' + 'different. Pass one or the other.') + + self.args = args # Previously this was Py3 only. + self.stdin = None + self.stdout = None + self.stderr = None + self.pid = None + self.returncode = None + self.universal_newlines = universal_newlines + self.result = AsyncResult() + + # Input and output objects. The general principle is like + # this: + # + # Parent Child + # ------ ----- + # p2cwrite ---stdin---> p2cread + # c2pread <--stdout--- c2pwrite + # errread <--stderr--- errwrite + # + # On POSIX, the child objects are file descriptors. On + # Windows, these are Windows file handles. The parent objects + # are file descriptors on both platforms. The parent objects + # are -1 when not using PIPEs. The child objects are -1 + # when not redirecting. + + (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) = self._get_handles(stdin, stdout, stderr) + + # We wrap OS handles *before* launching the child, otherwise a + # quickly terminating child could make our fds unwrappable + # (see #8458). + if mswindows: + if p2cwrite != -1: + p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) + if c2pread != -1: + c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) + if errread != -1: + errread = msvcrt.open_osfhandle(errread.Detach(), 0) + + text_mode = self.encoding or self.errors or universal_newlines or text + if text_mode or universal_newlines: + # Always a native str in universal_newlines mode, even when that + # str type is bytes. Additionally, text_mode is only true under + # Python 3, so it's actually a unicode str + self._communicate_empty_value = '' + + uid, gid, gids = self.__handle_uids(user, group, extra_groups) + + if p2cwrite != -1: + if text_mode: + # Under Python 3, if we left on the 'b' we'd get different results + # depending on whether we used FileObjectPosix or FileObjectThread + self.stdin = FileObject(p2cwrite, 'w', bufsize, + encoding=self.encoding, errors=self.errors) + else: + self.stdin = FileObject(p2cwrite, 'wb', bufsize) + + if c2pread != -1: + if universal_newlines or text_mode: + self.stdout = FileObject(c2pread, 'r', bufsize, + encoding=self.encoding, errors=self.errors) + # NOTE: Universal Newlines are broken on Windows/Py3, at least + # in some cases. This is true in the stdlib subprocess module + # as well; the following line would fix the test cases in + # test__subprocess.py that depend on python_universal_newlines, + # but would be inconsistent with the stdlib: + + else: + self.stdout = FileObject(c2pread, 'rb', bufsize) + if errread != -1: + if universal_newlines or text_mode: + self.stderr = FileObject(errread, 'r', bufsize, + encoding=encoding, errors=errors) + else: + self.stderr = FileObject(errread, 'rb', bufsize) + + self._closed_child_pipe_fds = False + # Convert here for the sake of all platforms. os.chdir accepts + # path-like objects natively under 3.6, but CreateProcess + # doesn't. + cwd = fsdecode(cwd) if cwd is not None else None + try: + self._execute_child(args, executable, preexec_fn, close_fds, + pass_fds, cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite, + restore_signals, + gid, gids, uid, umask, + start_new_session, process_group) + except: + # Cleanup if the child failed starting. + # (gevent: New in python3, but reported as gevent bug in #347. + # Note that under Py2, any error raised below will replace the + # original error so we have to use reraise) + for f in filter(None, (self.stdin, self.stdout, self.stderr)): + try: + f.close() + except OSError: + pass # Ignore EBADF or other errors. + + if not self._closed_child_pipe_fds: + to_close = [] + if stdin == PIPE: + to_close.append(p2cread) + if stdout == PIPE: + to_close.append(c2pwrite) + if stderr == PIPE: + to_close.append(errwrite) + if hasattr(self, '_devnull'): + to_close.append(self._devnull) + for fd in to_close: + try: + os.close(fd) + except OSError: + pass + raise + + def __handle_uids(self, user, group, extra_groups): + gid = None + if group is not None: + if not hasattr(os, 'setregid'): + raise ValueError("The 'group' parameter is not supported on the " + "current platform") + + if isinstance(group, str): + if grp is None: + raise ValueError("The group parameter cannot be a string " + "on systems without the grp module") + + gid = grp.getgrnam(group).gr_gid + elif isinstance(group, int): + gid = group + else: + raise TypeError("Group must be a string or an integer, not {}" + .format(type(group))) + + if gid < 0: + raise ValueError("Group ID cannot be negative, got %s" % gid) + + gids = None + if extra_groups is not None: + if not hasattr(os, 'setgroups'): + raise ValueError("The 'extra_groups' parameter is not " + "supported on the current platform") + + if isinstance(extra_groups, str): + raise ValueError("Groups must be a list, not a string") + + gids = [] + for extra_group in extra_groups: + if isinstance(extra_group, str): + if grp is None: + raise ValueError("Items in extra_groups cannot be " + "strings on systems without the " + "grp module") + + gids.append(grp.getgrnam(extra_group).gr_gid) + elif isinstance(extra_group, int): + if extra_group >= 2**64: + # This check is implicit in the C version of _Py_Gid_Converter. + # + # We actually need access to the C type ``gid_t`` to get + # its actual length. This just makes the test that was added + # for the bug pass. That's OK though, if we guess too big here, + # we should get an OverflowError from the setgroups() + # call we make. The only difference is the type of exception. + # + # See https://bugs.python.org/issue42655 + raise ValueError("Item in extra_groups is too large") + gids.append(extra_group) + else: + raise TypeError("Items in extra_groups must be a string " + "or integer, not {}" + .format(type(extra_group))) + + # make sure that the gids are all positive here so we can do less + # checking in the C code + for gid_check in gids: + if gid_check < 0: + raise ValueError("Group ID cannot be negative, got %s" % (gid_check,)) + + uid = None + if user is not None: + if not hasattr(os, 'setreuid'): + raise ValueError("The 'user' parameter is not supported on " + "the current platform") + + if isinstance(user, str): + if pwd is None: + raise ValueError("The user parameter cannot be a string " + "on systems without the pwd module") + + uid = pwd.getpwnam(user).pw_uid + elif isinstance(user, int): + uid = user + else: + raise TypeError("User must be a string or an integer") + + if uid < 0: + raise ValueError("User ID cannot be negative, got %s" % (uid,)) + + return uid, gid, gids + + def __repr__(self): + return '<%s at 0x%x pid=%r returncode=%r>' % (self.__class__.__name__, id(self), self.pid, self.returncode) + + def _on_child(self, watcher): + watcher.stop() + status = watcher.rstatus + if os.WIFSIGNALED(status): + self.returncode = -os.WTERMSIG(status) + else: + self.returncode = os.WEXITSTATUS(status) + self.result.set(self.returncode) + + def _get_devnull(self): + if not hasattr(self, '_devnull'): + self._devnull = os.open(os.devnull, os.O_RDWR) + return self._devnull + + _communicating_greenlets = None + + def communicate(self, input=None, timeout=None): + """ + Interact with process and return its output and error. + + - Send *input* data to stdin. + - Read data from stdout and stderr, until end-of-file is reached. + - Wait for process to terminate. + + The optional *input* argument should be a + string to be sent to the child process, or None, if no data + should be sent to the child. + + communicate() returns a tuple (stdout, stderr). + + :keyword timeout: Under Python 2, this is a gevent extension; if + given and it expires, we will raise :exc:`TimeoutExpired`, which + extends :exc:`gevent.timeout.Timeout` (note that this only extends :exc:`BaseException`, + *not* :exc:`Exception`) + Under Python 3, this raises the standard :exc:`TimeoutExpired` exception. + + .. versionchanged:: 1.1a2 + Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout` + exception. Previously, we silently returned. + .. versionchanged:: 1.1b5 + Honor a *timeout* even if there's no way to communicate with the child + (stdin, stdout, and stderr are not pipes). + """ + if self._communicating_greenlets is None: + self._communicating_greenlets = _CommunicatingGreenlets(self, input) + greenlets = self._communicating_greenlets + + # If we were given stdin=stdout=stderr=None, we have no way to + # communicate with the child, and thus no greenlets to wait + # on. This is a nonsense case, but it comes up in the test + # case for Python 3.5 (test_subprocess.py + # RunFuncTestCase.test_timeout). Instead, we go directly to + # self.wait + if not greenlets and timeout is not None: + self.wait(timeout=timeout, _raise_exc=True) + + done = joinall(greenlets, timeout=timeout) + # Allow finished greenlets, if any, to raise. This takes priority over + # the timeout exception. + for greenlet in done: + greenlet.get() + if timeout is not None and len(done) != len(self._communicating_greenlets): + raise TimeoutExpired(self.args, timeout) + + # Close only after we're sure that everything is done + # (there was no timeout, or there was, but everything finished). + # There should be no greenlets still running, even from a prior + # attempt. If there are, then this can raise RuntimeError: 'reentrant call'. + # So we ensure that previous greenlets are dead. + for pipe in (self.stdout, self.stderr): + if pipe: + try: + pipe.close() + except RuntimeError: + pass + + self.wait() + + return (None if greenlets.stdout is None else greenlets.stdout.get(), + None if greenlets.stderr is None else greenlets.stderr.get()) + + def poll(self): + """Check if child process has terminated. Set and return :attr:`returncode` attribute.""" + return self._internal_poll() + + def __enter__(self): + return self + + def __exit__(self, t, v, tb): + if self.stdout: + self.stdout.close() + if self.stderr: + self.stderr.close() + try: # Flushing a BufferedWriter may raise an error + if self.stdin: + self.stdin.close() + finally: + # Wait for the process to terminate, to avoid zombies. + # JAM: gevent: If the process never terminates, this + # blocks forever. + self.wait() + + def _gevent_result_wait(self, timeout=None, raise_exc=True): + result = self.result.wait(timeout=timeout) + if raise_exc and timeout is not None and not self.result.ready(): + raise TimeoutExpired(self.args, timeout) + return result + + + if mswindows: + # + # Windows methods + # + def _get_handles(self, stdin, stdout, stderr): + """Construct and return tuple with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + """ + # pylint:disable=undefined-variable + if stdin is None and stdout is None and stderr is None: + return (-1, -1, -1, -1, -1, -1) + + p2cread, p2cwrite = -1, -1 + c2pread, c2pwrite = -1, -1 + errread, errwrite = -1, -1 + + try: + DEVNULL + except NameError: + _devnull = object() + else: + _devnull = DEVNULL + + if stdin is None: + p2cread = GetStdHandle(STD_INPUT_HANDLE) + if p2cread is None: + p2cread, _ = CreatePipe(None, 0) + p2cread = Handle(p2cread) + _winapi.CloseHandle(_) + elif stdin == PIPE: + p2cread, p2cwrite = CreatePipe(None, 0) + p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) + elif stdin == _devnull: + p2cread = msvcrt.get_osfhandle(self._get_devnull()) + elif isinstance(stdin, int): + p2cread = msvcrt.get_osfhandle(stdin) + else: + # Assuming file-like object + p2cread = msvcrt.get_osfhandle(stdin.fileno()) + p2cread = self._make_inheritable(p2cread) + + if stdout is None: + c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) + if c2pwrite is None: + _, c2pwrite = CreatePipe(None, 0) + c2pwrite = Handle(c2pwrite) + _winapi.CloseHandle(_) + elif stdout == PIPE: + c2pread, c2pwrite = CreatePipe(None, 0) + c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) + elif stdout == _devnull: + c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) + elif isinstance(stdout, int): + c2pwrite = msvcrt.get_osfhandle(stdout) + else: + # Assuming file-like object + c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) + c2pwrite = self._make_inheritable(c2pwrite) + + if stderr is None: + errwrite = GetStdHandle(STD_ERROR_HANDLE) + if errwrite is None: + _, errwrite = CreatePipe(None, 0) + errwrite = Handle(errwrite) + _winapi.CloseHandle(_) + elif stderr == PIPE: + errread, errwrite = CreatePipe(None, 0) + errread, errwrite = Handle(errread), Handle(errwrite) + elif stderr == STDOUT: + errwrite = c2pwrite + elif stderr == _devnull: + errwrite = msvcrt.get_osfhandle(self._get_devnull()) + elif isinstance(stderr, int): + errwrite = msvcrt.get_osfhandle(stderr) + else: + # Assuming file-like object + errwrite = msvcrt.get_osfhandle(stderr.fileno()) + errwrite = self._make_inheritable(errwrite) + + return (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + def _make_inheritable(self, handle): + """Return a duplicate of handle, which is inheritable""" + # pylint:disable=undefined-variable + return DuplicateHandle(GetCurrentProcess(), + handle, GetCurrentProcess(), 0, 1, + DUPLICATE_SAME_ACCESS) + + def _find_w9xpopen(self): + """Find and return absolute path to w9xpopen.exe""" + # pylint:disable=undefined-variable + w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), + "w9xpopen.exe") + if not os.path.exists(w9xpopen): + # Eeek - file-not-found - possibly an embedding + # situation - see if we can locate it in sys.exec_prefix + w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), + "w9xpopen.exe") + if not os.path.exists(w9xpopen): + raise RuntimeError("Cannot locate w9xpopen.exe, which is " + "needed for Popen to work with your " + "shell or platform.") + return w9xpopen + + + def _filter_handle_list(self, handle_list): + """Filter out console handles that can't be used + in lpAttributeList["handle_list"] and make sure the list + isn't empty. This also removes duplicate handles.""" + # An handle with it's lowest two bits set might be a special console + # handle that if passed in lpAttributeList["handle_list"], will + # cause it to fail. + # Only works on 3.7+ + return list({handle for handle in handle_list + if handle & 0x3 != 0x3 + or _winapi.GetFileType(handle) != + _winapi.FILE_TYPE_CHAR}) + + + def _execute_child(self, args, executable, preexec_fn, close_fds, + pass_fds, cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite, + unused_restore_signals, + unused_gid, unused_gids, unused_uid, unused_umask, + unused_start_new_session, unused_process_group): + """Execute program (MS Windows version)""" + # pylint:disable=undefined-variable + assert not pass_fds, "pass_fds not supported on Windows." + if isinstance(args, str): + pass + elif isinstance(args, bytes): + if shell: + raise TypeError('bytes args is not allowed on Windows') + args = list2cmdline([args]) + elif isinstance(args, PathLike): + if shell: + raise TypeError('path-like args is not allowed when ' + 'shell is true') + args = list2cmdline([args]) + else: + args = list2cmdline(args) + + if executable is not None: + executable = fsdecode(executable) + + if not isinstance(args, string_types): + args = list2cmdline(args) + + # Process startup details + if startupinfo is None: + startupinfo = STARTUPINFO() + elif hasattr(startupinfo, 'copy'): + # bpo-34044: Copy STARTUPINFO since it is modified below, + # so the caller can reuse it multiple times. + startupinfo = startupinfo.copy() + elif hasattr(startupinfo, '_copy'): + # When the fix was backported to Python 3.7, copy() was + # made private as _copy. + startupinfo = startupinfo._copy() + + use_std_handles = -1 not in (p2cread, c2pwrite, errwrite) + if use_std_handles: + startupinfo.dwFlags |= STARTF_USESTDHANDLES + startupinfo.hStdInput = p2cread + startupinfo.hStdOutput = c2pwrite + startupinfo.hStdError = errwrite + + if hasattr(startupinfo, 'lpAttributeList'): + # Support for Python >= 3.7 + + attribute_list = startupinfo.lpAttributeList + have_handle_list = bool(attribute_list and + "handle_list" in attribute_list and + attribute_list["handle_list"]) + + # If we were given an handle_list or need to create one + if have_handle_list or (use_std_handles and close_fds): + if attribute_list is None: + attribute_list = startupinfo.lpAttributeList = {} + handle_list = attribute_list["handle_list"] = \ + list(attribute_list.get("handle_list", [])) + + if use_std_handles: + handle_list += [int(p2cread), int(c2pwrite), int(errwrite)] + + handle_list[:] = self._filter_handle_list(handle_list) + + if handle_list: + if not close_fds: + import warnings + warnings.warn("startupinfo.lpAttributeList['handle_list'] " + "overriding close_fds", RuntimeWarning) + + # When using the handle_list we always request to inherit + # handles but the only handles that will be inherited are + # the ones in the handle_list + close_fds = False + + if shell: + startupinfo.dwFlags |= STARTF_USESHOWWINDOW + startupinfo.wShowWindow = SW_HIDE + comspec = os.environ.get("COMSPEC", "cmd.exe") + args = '{} /c "{}"'.format(comspec, args) + if GetVersion() >= 0x80000000 or os.path.basename(comspec).lower() == "command.com": + # Win9x, or using command.com on NT. We need to + # use the w9xpopen intermediate program. For more + # information, see KB Q150956 + # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) + w9xpopen = self._find_w9xpopen() + args = '"%s" %s' % (w9xpopen, args) + # Not passing CREATE_NEW_CONSOLE has been known to + # cause random failures on win9x. Specifically a + # dialog: "Your program accessed mem currently in + # use at xxx" and a hopeful warning about the + # stability of your system. Cost is Ctrl+C wont + # kill children. + creationflags |= CREATE_NEW_CONSOLE + + # PyPy 2.7 7.3.6 is now producing these errors. This + # happens automatically on Posix platforms, and is built + # in to the CreateProcess call on CPython 2 & 3. It's not + # clear why we don't pick it up for free from the + # CreateProcess call on PyPy. Currently we don't test PyPy3 on Windows, + # so we don't know for sure if it's built into CreateProcess there. + if PYPY: + def _check_nul(s, err_kind=ValueError): + if not s: + return + nul = b'\0' if isinstance(s, bytes) else '\0' + if nul in s: + # PyPy 2 expects a TypeError; Python 3 raises ValueError always. + raise err_kind("argument must be a string without NUL characters") + def _check_env(): + if not env: + return + for k, v in env.items(): + _check_nul(k) + _check_nul(v) + if '=' in k: + raise ValueError("'=' not allowed in environment keys") + + _check_nul(executable) + _check_nul(args) + _check_env() + + # Start the process + try: + hp, ht, pid, tid = CreateProcess(executable, args, + # no special security + None, None, + int(not close_fds), + creationflags, + env, + cwd, # fsdecode handled earlier + startupinfo) + # except IOError as e: # From 2.6 on, pywintypes.error was defined as IOError + # # Translate pywintypes.error to WindowsError, which is + # # a subclass of OSError. FIXME: We should really + # # translate errno using _sys_errlist (or similar), but + # # how can this be done from Python? + # raise # don't remap here + # raise WindowsError(*e.args) + finally: + # Child is launched. Close the parent's copy of those pipe + # handles that only the child should have open. You need + # to make sure that no handles to the write end of the + # output pipe are maintained in this process or else the + # pipe will not close when the child process exits and the + # ReadFile will hang. + def _close(x): + if x is not None and x != -1: + if hasattr(x, 'Close'): + x.Close() + else: + _winapi.CloseHandle(x) + + _close(p2cread) + _close(c2pwrite) + _close(errwrite) + if hasattr(self, '_devnull'): + os.close(self._devnull) + + # Retain the process handle, but close the thread handle + self._child_created = True + self._handle = Handle(hp) if not hasattr(hp, 'Close') else hp + self.pid = pid + _winapi.CloseHandle(ht) if not hasattr(ht, 'Close') else ht.Close() + + def _internal_poll(self): + """Check if child process has terminated. Returns returncode + attribute. + """ + # pylint:disable=undefined-variable + if self.returncode is None: + if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: + self.returncode = GetExitCodeProcess(self._handle) + self.result.set(self.returncode) + return self.returncode + + def rawlink(self, callback): + if not self.result.ready() and not self._waiting: + self._waiting = True + Greenlet.spawn(self._wait) + self.result.rawlink(linkproxy(callback, self)) + # XXX unlink + + def _blocking_wait(self): + # pylint:disable=undefined-variable + WaitForSingleObject(self._handle, INFINITE) + self.returncode = GetExitCodeProcess(self._handle) + return self.returncode + + def _wait(self): + self.threadpool.spawn(self._blocking_wait).rawlink(self.result) + + def wait(self, timeout=None, _raise_exc=True): + """Wait for child process to terminate. Returns returncode + attribute.""" + if self.returncode is None: + if not self._waiting: + self._waiting = True + self._wait() + return self._gevent_result_wait(timeout, _raise_exc) + + def send_signal(self, sig): + """Send a signal to the process + """ + if sig == signal.SIGTERM: + self.terminate() + elif sig == signal.CTRL_C_EVENT: + os.kill(self.pid, signal.CTRL_C_EVENT) + elif sig == signal.CTRL_BREAK_EVENT: + os.kill(self.pid, signal.CTRL_BREAK_EVENT) + else: + raise ValueError("Unsupported signal: {}".format(sig)) + + def terminate(self): + """Terminates the process + """ + # pylint:disable=undefined-variable + # Don't terminate a process that we know has already died. + if self.returncode is not None: + return + try: + TerminateProcess(self._handle, 1) + except OSError as e: + # ERROR_ACCESS_DENIED (winerror 5) is received when the + # process already died. + if e.winerror != 5: + raise + rc = GetExitCodeProcess(self._handle) + if rc == STILL_ACTIVE: + raise + self.returncode = rc + self.result.set(self.returncode) + + kill = terminate + + else: + # + # POSIX methods + # + + def rawlink(self, callback): + # Not public documented, part of the link protocol + self.result.rawlink(linkproxy(callback, self)) + # XXX unlink + + def _get_handles(self, stdin, stdout, stderr): + """Construct and return tuple with IO objects: + p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite + """ + p2cread, p2cwrite = -1, -1 + c2pread, c2pwrite = -1, -1 + errread, errwrite = -1, -1 + + try: + DEVNULL + except NameError: + _devnull = object() + else: + _devnull = DEVNULL + + if stdin is None: + pass + elif stdin == PIPE: + p2cread, p2cwrite = self.pipe_cloexec() + elif stdin == _devnull: + p2cread = self._get_devnull() + elif isinstance(stdin, int): + p2cread = stdin + else: + # Assuming file-like object + p2cread = stdin.fileno() + + if stdout is None: + pass + elif stdout == PIPE: + c2pread, c2pwrite = self.pipe_cloexec() + elif stdout == _devnull: + c2pwrite = self._get_devnull() + elif isinstance(stdout, int): + c2pwrite = stdout + else: + # Assuming file-like object + c2pwrite = stdout.fileno() + + if stderr is None: + pass + elif stderr == PIPE: + errread, errwrite = self.pipe_cloexec() + elif stderr == STDOUT: # pylint:disable=undefined-variable + if c2pwrite != -1: + errwrite = c2pwrite + else: # child's stdout is not set, use parent's stdout + errwrite = sys.__stdout__.fileno() + elif stderr == _devnull: + errwrite = self._get_devnull() + elif isinstance(stderr, int): + errwrite = stderr + else: + # Assuming file-like object + errwrite = stderr.fileno() + + return (p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite) + + def _set_cloexec_flag(self, fd, cloexec=True): + try: + cloexec_flag = fcntl.FD_CLOEXEC + except AttributeError: + cloexec_flag = 1 + + old = fcntl.fcntl(fd, fcntl.F_GETFD) + if cloexec: + fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) + else: + fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) + + def _remove_nonblock_flag(self, fd): + flags = fcntl.fcntl(fd, fcntl.F_GETFL) & (~os.O_NONBLOCK) + fcntl.fcntl(fd, fcntl.F_SETFL, flags) + + def pipe_cloexec(self): + """Create a pipe with FDs set CLOEXEC.""" + # Pipes' FDs are set CLOEXEC by default because we don't want them + # to be inherited by other subprocesses: the CLOEXEC flag is removed + # from the child's FDs by _dup2(), between fork() and exec(). + # This is not atomic: we would need the pipe2() syscall for that. + r, w = os.pipe() + self._set_cloexec_flag(r) + self._set_cloexec_flag(w) + return r, w + + _POSSIBLE_FD_DIRS = ( + '/proc/self/fd', # Linux + '/dev/fd', # BSD, including macOS + ) + + @classmethod + def _close_fds(cls, keep, errpipe_write): + # From the C code: + # errpipe_write is part of keep. It must be closed at + # exec(), but kept open in the child process until exec() is + # called. + for path in cls._POSSIBLE_FD_DIRS: + if os.path.isdir(path): + return cls._close_fds_from_path(path, keep, errpipe_write) + return cls._close_fds_brute_force(keep, errpipe_write) + + @classmethod + def _close_fds_from_path(cls, path, keep, errpipe_write): + # path names a directory whose only entries have + # names that are ascii strings of integers in base10, + # corresponding to the fds the current process has open + try: + fds = [int(fname) for fname in os.listdir(path)] + except (ValueError, OSError): + cls._close_fds_brute_force(keep, errpipe_write) + else: + for i in keep: + if i == errpipe_write: + continue + _set_inheritable(i, True) + + for fd in fds: + if fd in keep or fd < 3: + continue + try: + os.close(fd) + except: + pass + + @classmethod + def _close_fds_brute_force(cls, keep, errpipe_write): + # `keep` is a set of fds, so we + # use os.closerange from 3 to min(keep) + # and then from max(keep + 1) to MAXFD and + # loop through filling in the gaps. + + # Under new python versions, we need to explicitly set + # passed fds to be inheritable or they will go away on exec + + # XXX: Bug: We implicitly rely on errpipe_write being the largest open + # FD so that we don't change its cloexec flag. + + assert hasattr(os, 'closerange') # Added in 2.7 + keep = sorted(keep) + min_keep = min(keep) + max_keep = max(keep) + os.closerange(3, min_keep) + os.closerange(max_keep + 1, MAXFD) + + for i in xrange(min_keep, max_keep): + if i in keep: + _set_inheritable(i, True) + continue + + try: + os.close(i) + except: + pass + # pylint:disable-next=too-many-positional-arguments + def _execute_child(self, args, executable, preexec_fn, close_fds, + pass_fds, cwd, env, universal_newlines, + startupinfo, creationflags, shell, + p2cread, p2cwrite, + c2pread, c2pwrite, + errread, errwrite, + restore_signals, + gid, gids, uid, umask, + start_new_session, process_group): + """Execute program (POSIX version)""" + + if isinstance(args, (str, bytes)): + args = [args] + elif isinstance(args, PathLike): + if shell: + raise TypeError('path-like args is not allowed when ' + 'shell is true') + args = [fsencode(args)] # os.PathLike -> [str] + else: + args = list(args) + + if shell: + # On Android the default shell is at '/system/bin/sh'. + unix_shell = ( + '/system/bin/sh' if hasattr(sys, 'getandroidapilevel') else '/bin/sh' + ) + args = [unix_shell, "-c"] + args + if executable: + args[0] = executable + + if executable is None: + executable = args[0] + + self._loop.install_sigchld() + + # For transferring possible exec failure from child to parent + # The first char specifies the exception type: 0 means + # OSError, 1 means some other error. + errpipe_read, errpipe_write = self.pipe_cloexec() + # errpipe_write must not be in the standard io 0, 1, or 2 fd range. + low_fds_to_close = [] + while errpipe_write < 3: + low_fds_to_close.append(errpipe_write) + errpipe_write = os.dup(errpipe_write) + for low_fd in low_fds_to_close: + os.close(low_fd) + try: + try: + gc_was_enabled = gc.isenabled() + # Disable gc to avoid bug where gc -> file_dealloc -> + # write to stderr -> hang. http://bugs.python.org/issue1336 + gc.disable() + try: + self.pid = fork_and_watch(self._on_child, self._loop, True, fork) + except: + if gc_was_enabled: + gc.enable() + raise + if self.pid == 0: + # Child + + # In various places on the child side of things, we catch OSError + # and add attributes to it that detail where in the process we failed; + # like all exceptions until we have exec'd, this exception is pickled + # and sent to the parent to raise in the calling process. + # The parent uses this to decide how to treat that exception, + # adjusting certain information about it as needed. + # + # Python 3.11.8 --- yes, a minor patch release --- stopped + # letting the 'filename' parameter get set in the resulting + # exception for many cases. We're not quite interpreting this + # the same way the stdlib is, I'm sure, but this makes the stdlib + # tests pass. + + # XXX: Technically we're doing a lot of stuff here that + # may not be safe to do before a exec(), depending on the OS. + # CPython 3 goes to great lengths to precompute a lot + # of this info before the fork and pass it all to C functions that + # try hard not to call things like malloc(). (Of course, + # CPython 2 pretty much did what we're doing.) + try: + # Close parent's pipe ends + if p2cwrite != -1: + os.close(p2cwrite) + if c2pread != -1: + os.close(c2pread) + if errread != -1: + os.close(errread) + os.close(errpipe_read) + + # When duping fds, if there arises a situation + # where one of the fds is either 0, 1 or 2, it + # is possible that it is overwritten (#12607). + if c2pwrite == 0: + c2pwrite = os.dup(c2pwrite) + _set_inheritable(c2pwrite, False) + while errwrite in (0, 1): + errwrite = os.dup(errwrite) + _set_inheritable(errwrite, False) + + # Dup fds for child + def _dup2(existing, desired): + # dup2() removes the CLOEXEC flag but + # we must do it ourselves if dup2() + # would be a no-op (issue #10806). + if existing == desired: + self._set_cloexec_flag(existing, False) + elif existing != -1: + os.dup2(existing, desired) + try: + self._remove_nonblock_flag(desired) + except OSError: + # Ignore EBADF, it may not actually be + # open yet. + # Tested beginning in 3.7.0b3 test_subprocess.py + pass + _dup2(p2cread, 0) + _dup2(c2pwrite, 1) + _dup2(errwrite, 2) + + # Close pipe fds. Make sure we don't close the + # same fd more than once, or standard fds. + if not True: + closed = set([None]) + for fd in (p2cread, c2pwrite, errwrite): + if fd not in closed and fd > 2: + os.close(fd) + closed.add(fd) + + # Python 3 (with a working set_inheritable): + # We no longer manually close p2cread, + # c2pwrite, and errwrite here as + # _close_open_fds takes care when it is + # not already non-inheritable. + + if cwd is not None: + try: + os.chdir(cwd) + except OSError as e: + e._failed_chdir = True + raise + + # Python 3.9 + if umask >= 0: + os.umask(umask) + # XXX: CPython does _Py_RestoreSignals here. + # Then setsid() based on ??? + try: + if gids: + os.setgroups(gids) + if gid: + os.setregid(gid, gid) + if uid: + os.setreuid(uid, uid) + if process_group is not None: + os.setpgid(0, process_group) + except OSError as e: + e._failed_chuser = True + raise + + if preexec_fn: + preexec_fn() + + # Close all other fds, if asked for. This must be done + # after preexec_fn runs. + if close_fds: + fds_to_keep = set(pass_fds) + fds_to_keep.add(errpipe_write) + self._close_fds(fds_to_keep, errpipe_write) + + if restore_signals: + # restore the documented signals back to sig_dfl; + # not all will be defined on every platform + for sig in 'SIGPIPE', 'SIGXFZ', 'SIGXFSZ': + sig = getattr(signal, sig, None) + if sig is not None: + signal.signal(sig, signal.SIG_DFL) + + if start_new_session: + os.setsid() + + try: + if env is None: + os.execvp(executable, args) + else: + # Python 3.6 started testing for + # bytes values in the env; it also + # started encoding strs using + # fsencode and using a lower-level + # API that takes a list of keys + # and values. We don't have access + # to that API, so we go the reverse direction. + env = {os.fsdecode(k) if isinstance(k, bytes) else k: + os.fsdecode(v) if isinstance(v, bytes) else v + for k, v in env.items()} + os.execvpe(executable, args, env) + except OSError as e: + e._failed_exec = True + raise + except: + exc_type, exc_value, tb = sys.exc_info() + # Save the traceback and attach it to the exception object + exc_lines = traceback.format_exception(exc_type, + exc_value, + tb) + exc_value.child_traceback = ''.join(exc_lines) + os.write(errpipe_write, pickle.dumps(exc_value)) + + finally: + # Make sure that the process exits no matter what. + # The return code does not matter much as it won't be + # reported to the application + os._exit(1) + + # Parent + self._child_created = True + if gc_was_enabled: + gc.enable() + finally: + # be sure the FD is closed no matter what + os.close(errpipe_write) + + # self._devnull is not always defined. + devnull_fd = getattr(self, '_devnull', None) + if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: + os.close(p2cread) + if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: + os.close(c2pwrite) + if errwrite != -1 and errread != -1 and errwrite != devnull_fd: + os.close(errwrite) + if devnull_fd is not None: + os.close(devnull_fd) + # Prevent a double close of these fds from __init__ on error. + self._closed_child_pipe_fds = True + + # Wait for exec to fail or succeed; possibly raising exception + errpipe_read = FileObject(errpipe_read, 'rb') + data = errpipe_read.read() + finally: + try: + if hasattr(errpipe_read, 'close'): + errpipe_read.close() + else: + os.close(errpipe_read) + except OSError: + # Especially on PyPy, we sometimes see the above + # `os.close(errpipe_read)` raise an OSError. + # It's not entirely clear why, but it happens in + # InterprocessSignalTests.test_main sometimes, which must mean + # we have some sort of race condition. + pass + finally: + errpipe_read = -1 + + if data != b"": + self.wait() + child_exception = pickle.loads(data) + for fd in (p2cwrite, c2pread, errread): + if fd is not None and fd != -1: + os.close(fd) + if isinstance(child_exception, OSError): + child_exception.filename = executable + if hasattr(child_exception, '_failed_chdir'): + child_exception.filename = cwd + if getattr(child_exception, '_failed_chuser', False): + child_exception.filename = None + raise child_exception + + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED, + _WSTOPSIG=os.WSTOPSIG): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope. + # (gevent: We don't have a __del__, that's in the CPython implementation.) + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) + elif _WIFSTOPPED(sts): + self.returncode = -_WSTOPSIG(sts) + else: + # Should never happen + raise RuntimeError("Unknown child exit status!") + + def _internal_poll(self): + """Check if child process has terminated. Returns returncode + attribute. + """ + if self.returncode is None: + if get_hub() is not getcurrent(): + sig_pending = getattr(self._loop, 'sig_pending', True) + if sig_pending: + sleep(0.00001) + return self.returncode + + def wait(self, timeout=None, _raise_exc=True): + """ + Wait for child process to terminate. Returns :attr:`returncode` + attribute. + + :keyword timeout: The floating point number of seconds to + wait. Under Python 2, this is a gevent extension, and + we simply return if it expires. Under Python 3, if + this time elapses without finishing the process, + :exc:`TimeoutExpired` is raised. + """ + return self._gevent_result_wait(timeout, _raise_exc) + + def send_signal(self, sig): + """Send a signal to the process + """ + # Skip signalling a process that we know has already died. + if self.returncode is None: + os.kill(self.pid, sig) + + def terminate(self): + """Terminate the process with SIGTERM + """ + self.send_signal(signal.SIGTERM) + + def kill(self): + """Kill the process with SIGKILL + """ + self.send_signal(signal.SIGKILL) + + +def _with_stdout_stderr(exc, stderr): + # Prior to Python 3.5, most exceptions didn't have stdout + # and stderr attributes and can't take the stderr attribute in their + # constructor + exc.stdout = exc.output + exc.stderr = stderr + return exc + +class CompletedProcess(object): + """ + A process that has finished running. + + This is returned by run(). + + Attributes: + - args: The list or str args passed to run(). + - returncode: The exit code of the process, negative for signals. + - stdout: The standard output (None if not captured). + - stderr: The standard error (None if not captured). + + .. versionadded:: 1.2a1 + This first appeared in Python 3.5 and is available to all + Python versions in gevent. + """ + if GenericAlias is not None: + # Sigh, 3.9 spreading typing stuff all over everything + __class_getitem__ = classmethod(GenericAlias) + + def __init__(self, args, returncode, stdout=None, stderr=None): + self.args = args + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + def __repr__(self): + args = ['args={!r}'.format(self.args), + 'returncode={!r}'.format(self.returncode)] + if self.stdout is not None: + args.append('stdout={!r}'.format(self.stdout)) + if self.stderr is not None: + args.append('stderr={!r}'.format(self.stderr)) + return "{}({})".format(type(self).__name__, ', '.join(args)) + + def check_returncode(self): + """Raise CalledProcessError if the exit code is non-zero.""" + if self.returncode: + # pylint:disable=undefined-variable + raise _with_stdout_stderr(CalledProcessError(self.returncode, self.args, self.stdout), self.stderr) + + +def run(*popenargs, **kwargs): + """ + run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False) -> CompletedProcess + + Run command with arguments and return a CompletedProcess instance. + + The returned instance will have attributes args, returncode, stdout and + stderr. By default, stdout and stderr are not captured, and those attributes + will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. + If check is True and the exit code was non-zero, it raises a + CalledProcessError. The CalledProcessError object will have the return code + in the returncode attribute, and output & stderr attributes if those streams + were captured. + + If timeout is given, and the process takes too long, a TimeoutExpired + exception will be raised. + + There is an optional argument "input", allowing you to + pass a string to the subprocess's stdin. If you use this argument + you may not also use the Popen constructor's "stdin" argument, as + it will be used internally. + The other arguments are the same as for the Popen constructor. + If universal_newlines=True is passed, the "input" argument must be a + string and stdout/stderr in the returned object will be strings rather than + bytes. + + .. versionadded:: 1.2a1 + This function first appeared in Python 3.5. It is available on all Python + versions gevent supports. + + .. versionchanged:: 1.3a2 + Add the ``capture_output`` argument from Python 3.7. It automatically sets + ``stdout`` and ``stderr`` to ``PIPE``. It is an error to pass either + of those arguments along with ``capture_output``. + """ + input = kwargs.pop('input', None) + timeout = kwargs.pop('timeout', None) + check = kwargs.pop('check', False) + capture_output = kwargs.pop('capture_output', False) + + if input is not None: + if 'stdin' in kwargs: + raise ValueError('stdin and input arguments may not both be used.') + kwargs['stdin'] = PIPE + + if capture_output: + if ('stdout' in kwargs) or ('stderr' in kwargs): + raise ValueError('stdout and stderr arguments may not be used ' + 'with capture_output.') + kwargs['stdout'] = PIPE + kwargs['stderr'] = PIPE + + with Popen(*popenargs, **kwargs) as process: + try: + stdout, stderr = process.communicate(input, timeout=timeout) + except TimeoutExpired: + process.kill() + stdout, stderr = process.communicate() + raise _with_stdout_stderr(TimeoutExpired(process.args, timeout, output=stdout), stderr) + except: + process.kill() + process.wait() + raise + retcode = process.poll() + if check and retcode: + # pylint:disable=undefined-variable + raise _with_stdout_stderr(CalledProcessError(retcode, process.args, stdout), stderr) + + return CompletedProcess(process.args, retcode, stdout, stderr) + +def _gevent_did_monkey_patch(target_module, *_args, **_kwargs): + # Beginning on 3.8 on Mac, the 'spawn' method became the default + # start method. That doesn't fire fork watchers and we can't + # easily patch to make it do so: multiprocessing uses the private + # c accelerated _subprocess module to implement this. Instead we revert + # back to using fork. + from gevent._compat import MAC + + if MAC: + import multiprocessing + if hasattr(multiprocessing, 'set_start_method'): + multiprocessing.set_start_method('fork', force=True) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0081c21882219f7a1076bf7af627cb58c7ca9efe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/__init__.py @@ -0,0 +1,187 @@ +# Copyright (c) 2008-2009 AG Projects +# Copyright 2018 gevent community +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + + +import unittest + +# pylint:disable=unused-import + +# It's important to do this ASAP, because if we're monkey patched, +# then importing things like the standard library test.support can +# need to construct the hub (to check for IPv6 support using a socket). +# We can't do it in the testrunner, as the testrunner spawns new, unrelated +# processes. +from .hub import QuietHub +import gevent.hub +gevent.hub.set_default_hub_class(QuietHub) + +try: + import faulthandler +except ImportError: + # The backport isn't installed. + pass +else: + # Enable faulthandler for stack traces. We have to do this here + # for the same reasons as above. + faulthandler.enable() + +try: + from gevent.libuv import _corecffi +except ImportError: + pass +else: + _corecffi.lib.gevent_test_setup() # pylint:disable=no-member + del _corecffi + +from .sysinfo import VERBOSE +from .sysinfo import WIN +from .sysinfo import LINUX +from .sysinfo import OSX +from .sysinfo import LIBUV +from .sysinfo import CFFI_BACKEND +from .sysinfo import DEBUG +from .sysinfo import RUN_LEAKCHECKS +from .sysinfo import RUN_COVERAGE + +from .sysinfo import PY2 +from .sysinfo import PY3 +from .sysinfo import PY36 +from .sysinfo import PY37 +from .sysinfo import PY38 +from .sysinfo import PY39 +from .sysinfo import PY310 + +from .sysinfo import PYPY +from .sysinfo import PYPY3 +from .sysinfo import CPYTHON + +from .sysinfo import PLATFORM_SPECIFIC_SUFFIXES +from .sysinfo import NON_APPLICABLE_SUFFIXES +from .sysinfo import SHARED_OBJECT_EXTENSION + +from .sysinfo import RUNNING_ON_TRAVIS +from .sysinfo import RUNNING_ON_APPVEYOR +from .sysinfo import RUNNING_ON_CI + +from .sysinfo import RESOLVER_NOT_SYSTEM +from .sysinfo import RESOLVER_DNSPYTHON +from .sysinfo import RESOLVER_ARES +from .sysinfo import resolver_dnspython_available + +from .sysinfo import EXPECT_POOR_TIMER_RESOLUTION + +from .sysinfo import CONN_ABORTED_ERRORS + +from .skipping import skipOnWindows +from .skipping import skipOnAppVeyor +from .skipping import skipOnCI +from .skipping import skipOnPyPy3OnCI +from .skipping import skipOnPyPy +from .skipping import skipOnPyPyOnCI +from .skipping import skipOnPyPyOnWindows +from .skipping import skipOnPyPy3 +from .skipping import skipIf +from .skipping import skipUnless +from .skipping import skipOnLibev +from .skipping import skipOnLibuv +from .skipping import skipOnLibuvOnWin +from .skipping import skipOnLibuvOnCI +from .skipping import skipOnLibuvOnCIOnPyPy +from .skipping import skipOnLibuvOnPyPyOnWin +from .skipping import skipOnPurePython +from .skipping import skipWithCExtensions +from .skipping import skipOnPy37 +from .skipping import skipOnPy310 +from .skipping import skipOnPy312 +from .skipping import skipOnPy3 +from .skipping import skipWithoutResource +from .skipping import skipWithoutExternalNetwork +from .skipping import skipOnManylinux +from .skipping import skipOnMacOnCI + +from .exception import ExpectedException + + +from .leakcheck import ignores_leakcheck + + +from .params import LARGE_TIMEOUT +from .params import DEFAULT_LOCAL_HOST_ADDR +from .params import DEFAULT_LOCAL_HOST_ADDR6 +from .params import DEFAULT_BIND_ADDR +from .params import DEFAULT_BIND_ADDR_TUPLE +from .params import DEFAULT_CONNECT_HOST + + +from .params import DEFAULT_SOCKET_TIMEOUT +from .params import DEFAULT_XPC_SOCKET_TIMEOUT + +main = unittest.main +SkipTest = unittest.SkipTest + + + + +from .sockets import bind_and_listen +from .sockets import tcp_listener + +from .openfiles import get_number_open_files +from .openfiles import get_open_files + +from .testcase import TestCase + +from .modules import walk_modules + +BaseTestCase = unittest.TestCase + +from .flaky import reraiseFlakyTestTimeout +from .flaky import reraiseFlakyTestRaceCondition +from .flaky import reraises_flaky_timeout +from .flaky import reraises_flaky_race_condition + +def gc_collect_if_needed(): + "Collect garbage if necessary for destructors to run" + import gc + if PYPY: # pragma: no cover + gc.collect() + +# Our usage of mock should be limited to '@mock.patch()' +# and other things that are easily...mocked...here on Python 2 +# when mock is not installed. +try: + from unittest import mock +except ImportError: # Python 2 + try: + import mock + except ImportError: # pragma: no cover + # Backport not installed + class mock(object): + + @staticmethod + def patch(reason): + return unittest.skip(reason) + +mock = mock + + +# zope.interface +from zope.interface import verify diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/coveragesite/sitecustomize.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/coveragesite/sitecustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..097dcec1548adba129c1868b06bc4c0675783e09 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/coveragesite/sitecustomize.py @@ -0,0 +1,17 @@ +# When testrunner.py is invoked with --coverage, it puts this first +# on the path as per https://coverage.readthedocs.io/en/coverage-4.0b3/subprocess.html. +# Note that this disables other sitecustomize.py files. +import coverage +try: + coverage.process_startup() +except coverage.CoverageException as e: + if str(e) == "Can't support concurrency=greenlet with PyTracer, only threads are supported": + pass + else: + import traceback + traceback.print_exc() + raise +except: + import traceback + traceback.print_exc() + raise diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/errorhandler.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/errorhandler.py new file mode 100644 index 0000000000000000000000000000000000000000..76cbdaa568f4e0e9f25a70c7d5157084b2988144 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/errorhandler.py @@ -0,0 +1,57 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import print_function +from functools import wraps + + +def wrap_error_fatal(method): + from gevent._hub_local import get_hub_class + system_error = get_hub_class().SYSTEM_ERROR + + @wraps(method) + def fatal_error_wrapper(self, *args, **kwargs): + # XXX should also be able to do gevent.SYSTEM_ERROR = object + # which is a global default to all hubs + get_hub_class().SYSTEM_ERROR = object + try: + return method(self, *args, **kwargs) + finally: + get_hub_class().SYSTEM_ERROR = system_error + return fatal_error_wrapper + + +def wrap_restore_handle_error(method): + from gevent._hub_local import get_hub_if_exists + from gevent import getcurrent + + @wraps(method) + def restore_fatal_error_wrapper(self, *args, **kwargs): + try: + return method(self, *args, **kwargs) + finally: + # Remove any customized handle_error, if set on the + # instance. + try: + del get_hub_if_exists().handle_error + except AttributeError: + pass + if self.peek_error()[0] is not None: + getcurrent().throw(*self.peek_error()[1:]) + return restore_fatal_error_wrapper diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/exception.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..baa9f96ab2251306bef82e88a789d25a003a2902 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/exception.py @@ -0,0 +1,23 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +class ExpectedException(Exception): + """An exception whose traceback should be ignored by the hub""" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/flaky.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/flaky.py new file mode 100644 index 0000000000000000000000000000000000000000..98f9fe8c96ba5aeb9aac6c83bb3abff03e5d981b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/flaky.py @@ -0,0 +1,114 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import sys +import functools +import unittest + +from . import sysinfo +from . import six + +class FlakyAssertionError(AssertionError): + "Re-raised so that we know it's a known-flaky test." + +# The next exceptions allow us to raise them in a highly +# greppable way so that we can debug them later. + +class FlakyTest(unittest.SkipTest): + """ + A unittest exception that causes the test to be skipped when raised. + + Use this carefully, it is a code smell and indicates an undebugged problem. + """ + +class FlakyTestRaceCondition(FlakyTest): + """ + Use this when the flaky test is definitely caused by a race condition. + """ + +class FlakyTestTimeout(FlakyTest): + """ + Use this when the flaky test is definitely caused by an + unexpected timeout. + """ + +class FlakyTestCrashes(FlakyTest): + """ + Use this when the test sometimes crashes. + """ + +def reraiseFlakyTestRaceCondition(): + six.reraise(FlakyAssertionError, + FlakyAssertionError(sys.exc_info()[1]), + sys.exc_info()[2]) + +reraiseFlakyTestTimeout = reraiseFlakyTestRaceCondition +reraiseFlakyTestRaceConditionLibuv = reraiseFlakyTestRaceCondition +reraiseFlakyTestTimeoutLibuv = reraiseFlakyTestRaceCondition + +if sysinfo.RUNNING_ON_CI or (sysinfo.PYPY and sysinfo.WIN): + # pylint: disable=function-redefined + def reraiseFlakyTestRaceCondition(): + # Getting stack traces is incredibly expensive + # in pypy on win, at least in test virtual machines. + # It can take minutes. The traceback consistently looks like + # the following when interrupted: + + # dump_stacks -> traceback.format_stack + # -> traceback.extract_stack -> linecache.checkcache + # -> os.stat -> _structseq.structseq_new + + # Moreover, without overriding __repr__ or __str__, + # the msg doesn't get printed like we would want (its basically + # unreadable, all printed on one line). So skip that. + + #msg = '\n'.join(dump_stacks()) + msg = str(sys.exc_info()[1]) + six.reraise(FlakyTestRaceCondition, + FlakyTestRaceCondition(msg), + sys.exc_info()[2]) + + def reraiseFlakyTestTimeout(): + msg = str(sys.exc_info()[1]) + six.reraise(FlakyTestTimeout, + FlakyTestTimeout(msg), + sys.exc_info()[2]) + + if sysinfo.LIBUV: + reraiseFlakyTestRaceConditionLibuv = reraiseFlakyTestRaceCondition + reraiseFlakyTestTimeoutLibuv = reraiseFlakyTestTimeout + + +def reraises_flaky_timeout(exc_kind=AssertionError, _func=reraiseFlakyTestTimeout): + + def wrapper(f): + @functools.wraps(f) + def m(*args): + try: + f(*args) + except exc_kind: + _func() + return m + + return wrapper + +def reraises_flaky_race_condition(exc_kind=AssertionError): + return reraises_flaky_timeout(exc_kind, _func=reraiseFlakyTestRaceCondition) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/hub.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..09575cbe809a952fc3fbe87145b55f8b3f1f29cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/hub.py @@ -0,0 +1,70 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +from contextlib import contextmanager +from gevent.hub import Hub + +from .exception import ExpectedException + +class QuietHub(Hub): + _resolver = None + _threadpool = None + + EXPECTED_TEST_ERROR = (ExpectedException,) + IGNORE_EXPECTED_TEST_ERROR = False + + @contextmanager + def ignoring_expected_test_error(self): + """ + Code in the body of this context manager will ignore + ``EXPECTED_TEST_ERROR`` objects reported to ``handle_error``; + they will not get a chance to go to the hub's parent. + + This completely changes the semantics of normal error handling + by avoiding some switches (to the main greenlet, and eventually + once a callback is processed, back to the hub). This should be used + in narrow ways for test compatibility for tests that assume + ``ExpectedException`` objects behave this way. + """ + old = self.IGNORE_EXPECTED_TEST_ERROR + self.IGNORE_EXPECTED_TEST_ERROR = True + try: + yield + finally: + self.IGNORE_EXPECTED_TEST_ERROR = old + + def handle_error(self, context, type, value, tb): + type, value, tb = self._normalize_exception(type, value, tb) + # If we check that the ``type`` is a subclass of ``EXPECTED_TEST_ERROR``, + # and return, we completely change the semantics: We avoid raising + # this error in the main greenlet, which cuts out several switches. + # Overall, not good. + if self.IGNORE_EXPECTED_TEST_ERROR and issubclass(type, self.EXPECTED_TEST_ERROR): + # Don't pass these up; avoid switches + return + return Hub.handle_error(self, context, type, value, tb) + + def print_exception(self, context, t, v, tb): + t, v, tb = self._normalize_exception(t, v, tb) + if issubclass(t, self.EXPECTED_TEST_ERROR): + # see handle_error + return + return Hub.print_exception(self, context, t, v, tb) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/leakcheck.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/leakcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..a6212cacb884552406db4ac3cab9e44ae78a5ec4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/leakcheck.py @@ -0,0 +1,231 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import print_function + +import sys +import gc +from functools import wraps +import unittest + +try: + import objgraph +except ImportError: # pragma: no cover + # Optional test dependency + objgraph = None + +import gevent +import gevent.core + + +def ignores_leakcheck(func): + """ + Ignore the given object during leakchecks. + + Can be applied to a method, in which case the method will run, but + will not be subject to leak checks. + + If applied to a class, the entire class will be skipped during leakchecks. This + is intended to be used for classes that are very slow and cause problems such as + test timeouts; typically it will be used for classes that are subclasses of a base + class and specify variants of behaviour (such as pool sizes). + """ + func.ignore_leakcheck = True + return func + +class _RefCountChecker(object): + + # Some builtin things that we ignore. + # For awhile, we also ignored types.FrameType and types.TracebackType, + # but those are important and often involved in leaks. + IGNORED_TYPES = (tuple, dict,) + try: + CALLBACK_KIND = gevent.core.callback + except AttributeError: + # Must be using FFI. + from gevent._ffi.callback import callback as CALLBACK_KIND + + + def __init__(self, testcase, function): + self.testcase = testcase + self.function = function + self.deltas = [] + self.peak_stats = {} + + # The very first time we are called, we have already been + # self.setUp() by the test runner, so we don't need to do it again. + self.needs_setUp = False + + def _ignore_object_p(self, obj): + if obj is self: + return False + try: + # Certain badly written __eq__ and __contains__ methods + # (I'm looking at you, Python 3.10 importlib.metadata._text! + # ``__eq__(self, other): return self.lower() == other.lower()``) + # raise AttributeError which propagates here, and must be caught. + # Similarly, we can get a TypeError + if ( + obj in self.__dict__.values() + or obj == self._ignore_object_p # pylint:disable=comparison-with-callable + ): + return False + except (AttributeError, TypeError): + # `obj` is things like that _text class. Also have seen + # - psycopg2._psycopg.type + # - relstorage.adapters.drivers._ClassDriverFactory + return True + + kind = type(obj) + if kind in self.IGNORED_TYPES: + return False + if kind is self.CALLBACK_KIND and obj.callback is None and obj.args is None: + # these represent callbacks that have been stopped, but + # the event loop hasn't cycled around to run them. The only + # known cause of this is killing greenlets before they get a chance + # to run for the first time. + return False + return True + + def _growth(self): + return objgraph.growth(limit=None, peak_stats=self.peak_stats, filter=self._ignore_object_p) + + def _report_diff(self, growth): + if not growth: + return "" + + lines = [] + width = max(len(name) for name, _, _ in growth) + for name, count, delta in growth: + lines.append('%-*s%9d %+9d' % (width, name, count, delta)) + + diff = '\n'.join(lines) + return diff + + + def _run_test(self, args, kwargs): + gc_enabled = gc.isenabled() + gc.disable() + + if self.needs_setUp: + self.testcase.setUp() + self.testcase.skipTearDown = False + try: + self.function(self.testcase, *args, **kwargs) + finally: + self.testcase.tearDown() + self.testcase.doCleanups() + self.testcase.skipTearDown = True + self.needs_setUp = True + if gc_enabled: + gc.enable() + + def _growth_after(self): + # Grab post snapshot + if 'urlparse' in sys.modules: + sys.modules['urlparse'].clear_cache() + if 'urllib.parse' in sys.modules: + sys.modules['urllib.parse'].clear_cache() # pylint:disable=no-member + + return self._growth() + + def _check_deltas(self, growth): + # Return false when we have decided there is no leak, + # true if we should keep looping, raises an assertion + # if we have decided there is a leak. + + deltas = self.deltas + if not deltas: + # We haven't run yet, no data, keep looping + return True + + if gc.garbage: + raise AssertionError("Generated uncollectable garbage %r" % (gc.garbage,)) + + + # the following configurations are classified as "no leak" + # [0, 0] + # [x, 0, 0] + # [... a, b, c, d] where a+b+c+d = 0 + # + # the following configurations are classified as "leak" + # [... z, z, z] where z > 0 + + if deltas[-2:] == [0, 0] and len(deltas) in (2, 3): + return False + + if deltas[-3:] == [0, 0, 0]: + return False + + if len(deltas) >= 4 and sum(deltas[-4:]) == 0: + return False + + if len(deltas) >= 3 and deltas[-1] > 0 and deltas[-1] == deltas[-2] and deltas[-2] == deltas[-3]: + diff = self._report_diff(growth) + raise AssertionError('refcount increased by %r\n%s' % (deltas, diff)) + + # OK, we don't know for sure yet. Let's search for more + if sum(deltas[-3:]) <= 0 or sum(deltas[-4:]) <= 0 or deltas[-4:].count(0) >= 2: + # this is suspicious, so give a few more runs + limit = 11 + else: + limit = 7 + if len(deltas) >= limit: + raise AssertionError('refcount increased by %r\n%s' + % (deltas, + self._report_diff(growth))) + + # We couldn't decide yet, keep going + return True + + def __call__(self, args, kwargs): + for _ in range(3): + gc.collect() + + # Capture state before; the incremental will be + # updated by each call to _growth_after + growth = self._growth() + + while self._check_deltas(growth): + self._run_test(args, kwargs) + + growth = self._growth_after() + + self.deltas.append(sum((stat[2] for stat in growth))) + + +def wrap_refcount(method): + + if objgraph is None or getattr(method, 'ignore_leakcheck', False): + if objgraph is None: + import warnings + warnings.warn("objgraph not available, leakchecks disabled") + @wraps(method) + def _method_skipped_during_leakcheck(self, *_args, **_kwargs): + self.skipTest("This method ignored during leakchecks") + return _method_skipped_during_leakcheck + + + @wraps(method) + def wrapper(self, *args, **kwargs): # pylint:disable=too-many-branches + if getattr(self, 'ignore_leakcheck', False): + raise unittest.SkipTest("This class ignored during leakchecks") + return _RefCountChecker(self, method)(args, kwargs) + + return wrapper diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/modules.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8549c3bd20fa0a0682987acc9da7c570d9e35e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/modules.py @@ -0,0 +1,137 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import importlib +import os.path +import warnings + +import gevent + +from . import sysinfo +# Avoid importing this at the top level because +# it imports threading and subprocess, and this module +# is always imported in our monkey-patched stdlib unittests, +# and some of them don't like it when those are imported. +# from . import util + + +OPTIONAL_MODULES = frozenset({ + ## Resolvers. + # ares might not be built + 'gevent.resolver_ares', + 'gevent.resolver.ares', + # dnspython might not be installed + 'gevent.resolver.dnspython', + ## Backends + 'gevent.libev', + 'gevent.libev.watcher', + 'gevent.libuv.loop', + 'gevent.libuv.watcher', +}) + +EXCLUDED_MODULES = frozenset({ + '__init__', + 'core', + 'ares', + '_util', + '_semaphore', + 'corecffi', + '_corecffi', + '_corecffi_build', +}) + +def walk_modules( + basedir=None, + modpath=None, + include_so=False, + recursive=False, + check_optional=True, + include_tests=False, + optional_modules=OPTIONAL_MODULES, + excluded_modules=EXCLUDED_MODULES, +): + """ + Find gevent modules, yielding tuples of ``(path, importable_module_name)``. + + :keyword bool check_optional: If true (the default), then if we discover a + module that is known to be optional on this system (such as a backend), + we will attempt to import it; if the import fails, it will not be returned. + If false, then we will not make such an attempt, the caller will need to be prepared + for an `ImportError`; the caller can examine *optional_modules* against + the yielded *importable_module_name*. + """ + # pylint:disable=too-many-branches,too-many-locals + if sysinfo.PYPY: + include_so = False + if basedir is None: + basedir = os.path.dirname(gevent.__file__) + if modpath is None: + modpath = 'gevent.' + else: + if modpath is None: # pylint:disable=else-if-used + modpath = '' + + for fn in sorted(os.listdir(basedir)): + path = os.path.join(basedir, fn) + if os.path.isdir(path): + if not recursive: + continue + if not include_tests and fn in ['testing', 'tests']: + continue + pkg_init = os.path.join(path, '__init__.py') + if os.path.exists(pkg_init): + yield pkg_init, modpath + fn + for p, m in walk_modules( + path, modpath + fn + ".", + include_so=include_so, + recursive=recursive, + check_optional=check_optional, + include_tests=include_tests, + optional_modules=optional_modules, + excluded_modules=excluded_modules, + ): + yield p, m + continue + + if fn.endswith('.py'): + x = fn[:-3] + if x.endswith('_d'): + x = x[:-2] + if x in excluded_modules: + continue + modname = modpath + x + if check_optional and modname in optional_modules: + try: + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + importlib.import_module(modname) + except ImportError: + from . import util + util.debug("Unable to import optional module %s", modname) + continue + yield path, modname + elif include_so and fn.endswith(sysinfo.SHARED_OBJECT_EXTENSION): + if '.pypy-' in fn: + continue + if fn.endswith('_d.so'): + yield path, modpath + fn[:-5] + else: + yield path, modpath + fn[:-3] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/monkey_test.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/monkey_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbebd94081119f4504e5db5ff85a8fc26f212d2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/monkey_test.py @@ -0,0 +1,170 @@ +import sys +import os + + +test_filename = sys.argv[1] +del sys.argv[1] + + + +from gevent import monkey +# Only test the default set of patch arguments. +monkey.patch_all() + +from .patched_tests_setup import disable_tests_in_source +from . import support +from . import resources +from . import SkipTest +from . import util + + + +# This uses the internal built-in function ``_thread._count()``, +# which we don't/can't monkey-patch, so it returns inaccurate information. +def threading_setup(): + return (1, ()) + +# This then tries to wait for that value to return to its original value; +# but if we started worker threads that can never happen. +def threading_cleanup(*_args): + return + +assert support.threading_setup +assert support.threading_cleanup + +support.threading_setup = threading_setup +support.threading_cleanup = threading_cleanup + + +# On all versions of Python 3.6+, this also uses ``_thread._count()``, +# meaning it suffers from inaccuracies, +# and test_socket.py constantly fails with an extra thread +# on some random test. We disable it entirely. +# XXX: Figure out how to make a *definition* in ./support.py actually +# override the original in test.support, without having to +# manually set it +# +import contextlib +@contextlib.contextmanager +def wait_threads_exit(timeout=None): # pylint:disable=unused-argument + # On < 3.10, this is support.wait_threads_exit; + # on >= 3.10, this is threading_helper.wait_threads_exit + yield + +support.wait_threads_exit = wait_threads_exit + +# On Python 3.11, they changed the way that they deal with this, +# meaning that this method no longer works. (Actually, it's not +# clear that any of our patches to `support` are doing anything on +# Python 3 at all? They certainly aren't on 3.11). This was a good +# thing As it led to adding the timeout value for the threadpool +# idle threads. But...the default of 5s meant that many tests in +# test_socket were each taking at least 5s to run, leading to the +# whole thing exceeding the allowed test timeout. We could set the +# GEVENT_THREADPOOL_IDLE_TASK_TIMEOUT env variable to a smaller +# value, and although that might stress the system nicely, it's +# not indicative of what end users see. And it's still hard to get +# a correct value. +# +# So try harder to make sure our patches apply. +# +# If this fails, symptoms are very long running tests that can be resolved +# by setting that TASK_TIMEOUT value small, and/or setting GEVENT_RESOLVER=block. +# Also, some number of warnings about dangling threads, or failures +# from wait_threads_exit +try: + from test import support as ts +except ImportError: + pass +else: + ts.threading_setup = threading_setup + ts.threading_cleanup = threading_cleanup + ts.wait_threads_exit = wait_threads_exit + ts.print_warning = lambda msg: msg + +try: + from test.support import threading_helper +except ImportError: + pass +else: + threading_helper.wait_threads_exit = wait_threads_exit + threading_helper.threading_setup = threading_setup + threading_helper.threading_cleanup = threading_cleanup + + +try: + from test.support import import_helper +except ImportError: + pass +else: + # Importing fresh modules breaks our monkey patches. we can't allow that. + def import_fresh_module(name, *_args, **_kwargs): + import importlib + return importlib.import_module(name) + import_helper.import_fresh_module = import_fresh_module + +# So we don't have to patch test_threading to use our +# version of lock_tests, we patch +from gevent.tests import lock_tests +try: + import test.lock_tests +except ImportError: + pass +else: + test.lock_tests = lock_tests + sys.modules['tests.lock_tests'] = lock_tests + +# Configure allowed resources +resources.setup_resources() + +if not os.path.exists(test_filename) and os.sep not in test_filename: + # A simple filename, given without a path, that doesn't exist. + # So we change to the appropriate directory, if we can find it. + # This happens when copy-pasting the output of the testrunner + for d in util.find_stdlib_tests(): + if os.path.exists(os.path.join(d, test_filename)): + os.chdir(d) + break + +__file__ = os.path.abspath(test_filename) #os.path.join(os.getcwd(), test_filename) +test_name = os.path.splitext(os.path.basename(test_filename))[0] + +print('Running with patch_all(): %s' % (__file__,)) + +with open(test_filename, encoding='utf-8') as module_file: + module_source = module_file.read() +module_source = disable_tests_in_source(module_source, test_name) + +# We write the module source to a file so that tracebacks +# show correctly, since disabling the tests changes line +# numbers. However, note that __file__ must still point to the +# real location so that data files can be found. +# See https://github.com/gevent/gevent/issues/1306 +import tempfile +temp_handle, temp_path = tempfile.mkstemp(prefix=test_name, suffix='.py', text=True) +os.write(temp_handle, module_source.encode('utf-8')) +os.close(temp_handle) +remove_file = not os.environ.get('GEVENT_DEBUG') +try: + module_code = compile(module_source, + temp_path, + 'exec', + dont_inherit=True) + exec(module_code, globals()) + remove_file = True +except SkipTest as e: + remove_file = True + # Some tests can raise test.support.ResourceDenied + # in their main method before the testrunner takes over. + # That's a kind of SkipTest. we can't get a true skip count because it + # hasn't run, though. + print(e) + # Match the regular unittest output, including ending with skipped + print("Ran 0 tests in 0.0s") + print('OK (skipped=0)') +finally: + if remove_file: + try: + os.remove(temp_path) + except OSError: + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/openfiles.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/openfiles.py new file mode 100644 index 0000000000000000000000000000000000000000..3aabaa99c42ffa03bd21deb62860c78349f61642 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/openfiles.py @@ -0,0 +1,227 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import os +import unittest +import re +import gc +import functools + +from . import sysinfo + +# Linux/OS X/BSD platforms /can/ implement this by calling out to lsof. +# However, if psutil is available (it is cross-platform) use that. +# It is *much* faster than shelling out to lsof each time +# (Running 14 tests takes 3.964s with lsof and 0.046 with psutil) +# However, it still doesn't completely solve the issue on Windows: fds are reported +# as -1 there, so we can't fully check those. + +def _collects(func): + # We've seen OSError: No such file or directory /proc/PID/fd/NUM. + # This occurs in the loop that checks open files. It first does + # listdir() and then tries readlink() on each file. But the file + # went away. This must be because of async GC in PyPy running + # destructors at arbitrary times. This became an issue in PyPy 7.2 + # but could theoretically be an issue with any objects caught in a + # cycle. This is one reason we GC before we begin. (The other is + # to clean up outstanding objects that will close files in + # __del__.) + # + # Note that this can hide errors, though, by causing greenlets to get + # collected and drop references and thus close files. We should be deterministic + # and careful about closing things. + @functools.wraps(func) + def f(**kw): + gc.collect() + gc.collect() + enabled = gc.isenabled() + gc.disable() + + try: + return func(**kw) + finally: + if enabled: + gc.enable() + return f + + +if sysinfo.WIN: + def _run_lsof(): + raise unittest.SkipTest("lsof not expected on Windows") +else: + @_collects + def _run_lsof(): + import tempfile + pid = os.getpid() + fd, tmpname = tempfile.mkstemp('get_open_files') + os.close(fd) + lsof_command = 'lsof -p %s > %s' % (pid, tmpname) + if os.system(lsof_command): + # XXX: This prints to the console an annoying message: 'lsof is not recognized' + raise unittest.SkipTest("lsof failed") + + with open(tmpname) as fobj: # pylint:disable=unspecified-encoding + data = fobj.read().strip() + os.remove(tmpname) + return data + +def default_get_open_files(pipes=False, **_kwargs): + data = _run_lsof() + results = {} + for line in data.split('\n'): + line = line.strip() + if not line or line.startswith("COMMAND"): + # Skip header and blank lines + continue + split = re.split(r'\s+', line) + # Note that this needs the real lsof; it won't work with + # the lsof that comes from BusyBox. You'll get parsing errors + # here. + _command, _pid, _user, fd = split[:4] + # Pipes (on OS X, at least) get an fd like "3" while normal files get an fd like "1u" + if fd[:-1].isdigit() or fd.isdigit(): + if not pipes and fd[-1].isdigit(): + continue + fd = int(fd[:-1]) if not fd[-1].isdigit() else int(fd) + if fd in results: + params = (fd, line, split, results.get(fd), data) + raise AssertionError('error when parsing lsof output: duplicate fd=%r\nline=%r\nsplit=%r\nprevious=%r\ndata:\n%s' % params) + results[fd] = line + if not results: + raise AssertionError('failed to parse lsof:\n%s' % (data, )) + results['data'] = data + return results + +@_collects +def default_get_number_open_files(): + if os.path.exists('/proc/'): + # Linux only + fd_directory = '/proc/%d/fd' % os.getpid() + return len(os.listdir(fd_directory)) + + try: + return len(get_open_files(pipes=True)) - 1 + except (OSError, AssertionError, unittest.SkipTest): + return 0 + +lsof_get_open_files = default_get_open_files + +try: + # psutil import subprocess which on Python 3 imports selectors. + # This can expose issues with monkey-patching. + import psutil +except ImportError: + get_open_files = default_get_open_files + get_number_open_files = default_get_number_open_files +else: + class _TrivialOpenFile(object): + __slots__ = ('fd',) + def __init__(self, fd): + self.fd = fd + + @_collects + def get_open_files(count_closing_as_open=True, **_kw): + """ + Return a list of popenfile and pconn objects. + + Note that other than `fd`, they have different attributes. + + .. important:: If you want to find open sockets, on Windows + and linux, it is important that the socket at least be listening + (socket.listen(1)). Unlike the lsof implementation, this will only + return sockets in a state like that. + """ + + results = {} + + for _ in range(3): + try: + if count_closing_as_open and os.path.exists('/proc/'): + # Linux only. + # psutil doesn't always see all connections, even though + # they exist in the filesystem. It's not entirely clear why. + # It sees them on Travis (prior to Ubuntu Bionic, at least) + # but doesn't in the manylinux image or Fedora 33 Rawhide image. + # This happens in test__makefile_ref TestSSL.*; in particular, if a + # ``sslsock.makefile()`` is opened and used to read all data, and the sending + # side shuts down, psutil no longer finds the open file. So we add them + # back in. + # + # Of course, the flip side of this is that we sometimes find connections + # we're not expecting. + # I *think* this has to do with CLOSE_WAIT handling? + fd_directory = '/proc/%d/fd' % os.getpid() + fd_files = os.listdir(fd_directory) + else: + fd_files = [] + process = psutil.Process() + results['data'] = process.open_files() + results['data'] += process.connections('all') + break + except OSError: + pass + else: + # No break executed + raise unittest.SkipTest("Unable to read open files") + + for x in results['data']: + results[x.fd] = x + for fd_str in fd_files: + if fd_str not in results: + fd = int(fd_str) + results[fd] = _TrivialOpenFile(fd) + results['data'] += [('From psutil', process)] + results['data'] += [('fd files', fd_files)] + return results + + @_collects + def get_number_open_files(): + process = psutil.Process() + try: + return process.num_fds() + except AttributeError: + # num_fds is unix only. Is num_handles close enough on Windows? + return 0 + + + +class DoesNotLeakFilesMixin(object): # pragma: no cover + """ + A test case mixin that helps find a method that's leaking an + open file. + + Only mix this in when needed to debug, it slows tests down. + """ + def setUp(self): + self.__open_files_count = get_number_open_files() + super(DoesNotLeakFilesMixin, self).setUp() + + def tearDown(self): + super(DoesNotLeakFilesMixin, self).tearDown() + after = get_number_open_files() + if after > self.__open_files_count: + raise AssertionError( + "Too many open files. Before: %s < After: %s.\n%s" % ( + self.__open_files_count, + after, + get_open_files() + ) + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/params.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/params.py new file mode 100644 index 0000000000000000000000000000000000000000..00097a79ce2adefa0031db2c166485035de0bb0b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/params.py @@ -0,0 +1,68 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +from . import support + +from .sysinfo import PY3 +from .sysinfo import PYPY +from .sysinfo import WIN +from .sysinfo import LIBUV + +from .sysinfo import EXPECT_POOR_TIMER_RESOLUTION + + +# Travis is slow and overloaded; Appveyor used to be faster, but +# as of Dec 2015 it's almost always slower and/or has much worse timer +# resolution +CI_TIMEOUT = 15 +if (PY3 and PYPY) or (PYPY and WIN and LIBUV): + # pypy3 is very slow right now, + # as is PyPy2 on windows (which only has libuv) + CI_TIMEOUT = 20 +if PYPY and LIBUV: + # slow and flaky timeouts + LOCAL_TIMEOUT = CI_TIMEOUT +else: + LOCAL_TIMEOUT = 2 + +LARGE_TIMEOUT = max(LOCAL_TIMEOUT, CI_TIMEOUT) + +# Previously we set this manually to 'localhost' +# and then had some conditions where we changed it to +# 127.0.0.1 (e.g., on Windows or OSX or travis), but Python's test.support says +# # Don't use "localhost", since resolving it uses the DNS under recent +# # Windows versions (see issue #18792). +# and sets it unconditionally to 127.0.0.1. +DEFAULT_LOCAL_HOST_ADDR = support.HOST +DEFAULT_LOCAL_HOST_ADDR6 = support.HOSTv6 +# Not all TCP stacks support dual binding where '' +# binds to both v4 and v6. +# XXX: This is badly named; you often want DEFAULT_BIND_ADDR_TUPLE +DEFAULT_BIND_ADDR = support.HOST + + +DEFAULT_CONNECT_HOST = DEFAULT_CONNECT = DEFAULT_LOCAL_HOST_ADDR +DEFAULT_BIND_ADDR_TUPLE = (DEFAULT_BIND_ADDR, 0) + +# For in-process sockets +DEFAULT_SOCKET_TIMEOUT = 0.1 if not EXPECT_POOR_TIMER_RESOLUTION else 2.0 + +# For cross-process sockets +DEFAULT_XPC_SOCKET_TIMEOUT = 2.0 if not EXPECT_POOR_TIMER_RESOLUTION else 4.0 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/patched_tests_setup.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/patched_tests_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..47780c6d33250ea5f5bafb99f2806abdff0eb525 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/patched_tests_setup.py @@ -0,0 +1,1529 @@ +# pylint:disable=missing-docstring,invalid-name,too-many-lines +from __future__ import print_function, absolute_import, division + +import collections +import contextlib +import functools +import sys +import os +# At least on 3.6+, importing platform +# imports subprocess, which imports selectors. That +# can expose issues with monkey patching. We don't need it +# though. +# import platform +import re + +from .sysinfo import RUNNING_ON_APPVEYOR as APPVEYOR +from .sysinfo import RUNNING_ON_TRAVIS as TRAVIS +from .sysinfo import RESOLVER_NOT_SYSTEM as ARES +from .sysinfo import RESOLVER_ARES +from .sysinfo import RESOLVER_DNSPYTHON +from .sysinfo import RUNNING_ON_CI +from .sysinfo import RUNNING_ON_MUSLLINUX +from .sysinfo import RUN_COVERAGE + + +from .sysinfo import PYPY +from .sysinfo import PYPY3 + +from .sysinfo import PY38 +from .sysinfo import PY39 +from .sysinfo import PY39_EXACTLY +from .sysinfo import PY310 +from .sysinfo import PY311 +from .sysinfo import PY312 +from .sysinfo import PY313 + +from .sysinfo import WIN +from .sysinfo import OSX +from .sysinfo import LINUX + +from .sysinfo import LIBUV +from .sysinfo import CFFI_BACKEND + +from . import flaky + +CPYTHON = not PYPY + +# By default, test cases are expected to switch and emit warnings if there was none +# If a test is found in this list, it's expected not to switch. +no_switch_tests = '''test_patched_select.SelectTestCase.test_error_conditions +test_patched_ftplib.*.test_all_errors +test_patched_ftplib.*.test_getwelcome +test_patched_ftplib.*.test_sanitize +test_patched_ftplib.*.test_set_pasv +#test_patched_ftplib.TestIPv6Environment.test_af +test_patched_socket.TestExceptions.testExceptionTree +test_patched_socket.Urllib2FileobjectTest.testClose +test_patched_socket.TestLinuxAbstractNamespace.testLinuxAbstractNamespace +test_patched_socket.TestLinuxAbstractNamespace.testMaxName +test_patched_socket.TestLinuxAbstractNamespace.testNameOverflow +test_patched_socket.FileObjectInterruptedTestCase.* +test_patched_urllib.* +test_patched_asyncore.HelperFunctionTests.* +test_patched_httplib.BasicTest.* +test_patched_httplib.HTTPSTimeoutTest.test_attributes +test_patched_httplib.HeaderTests.* +test_patched_httplib.OfflineTest.* +test_patched_httplib.HTTPSTimeoutTest.test_host_port +test_patched_httplib.SourceAddressTest.testHTTPSConnectionSourceAddress +test_patched_select.SelectTestCase.test_error_conditions +test_patched_smtplib.NonConnectingTests.* +test_patched_urllib2net.OtherNetworkTests.* +test_patched_wsgiref.* +test_patched_subprocess.HelperFunctionTests.* +''' + +ignore_switch_tests = ''' +test_patched_socket.GeneralModuleTests.* +test_patched_httpservers.BaseHTTPRequestHandlerTestCase.* +test_patched_queue.* +test_patched_signal.SiginterruptTest.* +test_patched_urllib2.* +test_patched_ssl.* +test_patched_signal.BasicSignalTests.* +test_patched_threading_local.* +test_patched_threading.* +''' + + +def make_re(tests): + tests = [x.strip().replace(r'\.', r'\\.').replace('*', '.*?') + for x in tests.split('\n') if x.strip()] + return re.compile('^%s$' % '|'.join(tests)) + + +no_switch_tests = make_re(no_switch_tests) +ignore_switch_tests = make_re(ignore_switch_tests) + + +def get_switch_expected(fullname): + """ + >>> get_switch_expected('test_patched_select.SelectTestCase.test_error_conditions') + False + >>> get_switch_expected('test_patched_socket.GeneralModuleTests.testCrucialConstants') + False + >>> get_switch_expected('test_patched_socket.SomeOtherTest.testHello') + True + >>> get_switch_expected("test_patched_httplib.BasicTest.test_bad_status_repr") + False + """ + # certain pylint versions mistype the globals as + # str, not re. + # pylint:disable=no-member + if ignore_switch_tests.match(fullname) is not None: + return None + if no_switch_tests.match(fullname) is not None: + return False + return True + + +disabled_tests = [ + # Want's __module__ to be 'signal', which of course it isn't once + # monkey-patched. + 'test_signal.GenericTests.test_functions_module_attr', + # XXX: While we debug latest updates. This is leaking + 'test_threading.ThreadTests.test_no_refcycle_through_target', + + # The server side takes awhile to shut down + 'test_httplib.HTTPSTest.test_local_bad_hostname', + # These were previously 3.5+ issues (same as above) + # but have been backported. + 'test_httplib.HTTPSTest.test_local_good_hostname', + 'test_httplib.HTTPSTest.test_local_unknown_cert', + + + 'test_threading.ThreadTests.test_PyThreadState_SetAsyncExc', + # uses some internal C API of threads not available when threads are emulated with greenlets + + 'test_threading.ThreadTests.test_join_nondaemon_on_shutdown', + # asserts that repr(sleep) is '' + + 'test_urllib2net.TimeoutTest.test_ftp_no_timeout', + 'test_urllib2net.TimeoutTest.test_ftp_timeout', + 'test_urllib2net.TimeoutTest.test_http_no_timeout', + 'test_urllib2net.TimeoutTest.test_http_timeout', + # accesses _sock.gettimeout() which is always in non-blocking mode + + 'test_urllib2net.OtherNetworkTests.test_ftp', + # too slow + + 'test_urllib2net.OtherNetworkTests.test_urlwithfrag', + # fails dues to some changes on python.org + + 'test_urllib2net.OtherNetworkTests.test_sites_no_connection_close', + # flaky + + 'test_socket.UDPTimeoutTest.testUDPTimeout', + # has a bug which makes it fail with error: (107, 'Transport endpoint is not connected') + # (it creates a TCP socket, not UDP) + + 'test_socket.GeneralModuleTests.testRefCountGetNameInfo', + # fails with "socket.getnameinfo loses a reference" while the reference is only "lost" + # because it is referenced by the traceback - any Python function would lose a reference like that. + # the original getnameinfo does not "lose" it because it's in C. + + 'test_socket.NetworkConnectionNoServer.test_create_connection_timeout', + # replaces socket.socket with MockSocket and then calls create_connection. + # this unfortunately does not work with monkey patching, because gevent.socket.create_connection + # is bound to gevent.socket.socket and updating socket.socket does not affect it. + # this issues also manifests itself when not monkey patching DNS: http://code.google.com/p/gevent/issues/detail?id=54 + # create_connection still uses gevent.socket.getaddrinfo while it should be using socket.getaddrinfo + + 'test_asyncore.BaseTestAPI.test_handle_expt', + # sends some OOB data and expect it to be detected as such; gevent.select.select does not support that + + # This one likes to check its own filename, but we rewrite + # the file to a temp location during patching. + 'test_asyncore.HelperFunctionTests.test_compact_traceback', + + # expects time.sleep() to return prematurely in case of a signal; + # gevent.sleep() is better than that and does not get interrupted + # (unless signal handler raises an error) + 'test_signal.WakeupSignalTests.test_wakeup_fd_early', + + # expects select.select() to raise select.error(EINTR'interrupted + # system call') gevent.select.select() does not get interrupted + # (unless signal handler raises an error) maybe it should? + 'test_signal.WakeupSignalTests.test_wakeup_fd_during', + + # these rely on os.read raising EINTR which never happens with gevent.os.read + 'test_signal.SiginterruptTest.test_without_siginterrupt', + 'test_signal.SiginterruptTest.test_siginterrupt_on', + 'test_signal.SiginterruptTest.test_siginterrupt_off', + # This one takes forever and relies on threading details + 'test_signal.StressTest.test_stress_modifying_handlers', + # This uses an external file, and launches it. This means that it's not + # actually testing gevent because there's no monkey-patch. + 'test_signal.PosixTests.test_interprocess_signal', + + 'test_subprocess.ProcessTestCase.test_leak_fast_process_del_killed', + 'test_subprocess.ProcessTestCase.test_zombie_fast_process_del', + # relies on subprocess._active which we don't use + + # Very slow, tries to open lots and lots of subprocess and files, + # tends to timeout on CI. + 'test_subprocess.ProcessTestCase.test_no_leaking', + + # This test is also very slow, and has been timing out on Travis + # since November of 2016 on Python 3, but now also seen on Python 2/Pypy. + 'test_subprocess.ProcessTestCase.test_leaking_fds_on_error', + + # Added between 3.6.0 and 3.6.3, uses _testcapi and internals + # of the subprocess module. Backported to Python 2.7.16. + 'test_subprocess.POSIXProcessTestCase.test_stopped', + + 'test_ssl.ThreadedTests.test_default_ciphers', + 'test_ssl.ThreadedTests.test_empty_cert', + 'test_ssl.ThreadedTests.test_malformed_cert', + 'test_ssl.ThreadedTests.test_malformed_key', + 'test_ssl.NetworkedTests.test_non_blocking_connect_ex', + # XXX needs investigating + + 'test_ssl.NetworkedTests.test_algorithms', + # The host this wants to use, sha256.tbs-internet.com, is not resolvable + # right now (2015-10-10), and we need to get Windows wheels + + # This started timing out randomly on Travis in oct/nov 2018. It appears + # to be something with random number generation taking too long. + 'test_ssl.BasicSocketTests.test_random_fork', + + # Relies on the repr of objects (Py3) + 'test_ssl.BasicSocketTests.test_dealloc_warn', + + # Takes forever + 'test_ssl.BasicSocketTests.test_connect_ex_error', + + 'test_urllib2.HandlerTests.test_cookie_redirect', + # this uses cookielib which we don't care about + + 'test_thread.ThreadRunningTests.test__count', + 'test_thread.TestForkInThread.test_forkinthread', + # XXX needs investigating + + 'test_subprocess.POSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes', + # Does not exist in the test suite until 2.7.4+. Subclasses Popen, and overrides + # _execute_child. But our version has a different parameter list than the + # version that comes with PyPy/CPython, so fails with a TypeError. + + # This one crashes the interpreter if it has a bug parsing the + # invalid data. + 'test_ssl.BasicSocketTests.test_parse_cert_CVE_2019_5010', + # We had to copy in a newer version of the test file for SSL fixes + # and this doesn't work reliably on all versions. + 'test_httplib.HeaderTests.test_headers_debuglevel', + + # On Appveyor with Python 3.8.0 and 3.7.5, this test + # for __class_getitem__ fails. Presumably this was added + # in a patch release (it's not in the PEP.) Sigh. + # https://bugs.python.org/issue38979 + 'test_context.ContextTest.test_contextvar_getitem', + # The same patch that fixed that removed this test, + # because it would now fail. + 'test_context.ContextTest.test_context_var_new_2', + + + # The C queue objects are immune to monkey patching, disable them + 'test_queue.CLifoQueueTest', + 'test_queue.CPriorityQueueTest', + 'test_queue.CQueueTest', + 'test_queue.CSimpleQueueTest', + 'test_queue.CFailingQueueTest', + + # (These will actually catch tests for many different queue types.) + # They needs to be disabled because it uses tight loops in "threads" + # calling ``q.get(False)`` which doesn't allow any other greenlet to + # make progress, so the shutdown request never gets through. + 'test_queue.PyLifoQueueTest.test_shutdown_all_methods_in_many_threads', + 'test_queue.PyLifoQueueTest.test_shutdown_immediate_all_methods_in_many_threads', + +] + + +if OSX: + disabled_tests += [ + # These are timing dependent, and sometimes run into the OS X + # kernel bug leading to 'Protocol wrong type for socket'. + # See discussion at https://github.com/benoitc/gunicorn/issues/1487 + 'test_ssl.SimpleBackgroundTests.test_connect_capath', + 'test_ssl.SimpleBackgroundTests.test_connect_with_context', + ] + +if PYPY: + disabled_tests += [ + # The exact error message the code code checks for is different + # (possibly just on macOS?). Plain PyPy3 fails as well. + 'test_signal.WakeupSignalTests.test_wakeup_write_error', + ] + +if 'thread' in os.getenv('GEVENT_FILE', ''): + disabled_tests += [ + 'test_subprocess.ProcessTestCase.test_double_close_on_error' + # Fails with "OSError: 9 invalid file descriptor"; expect GC/lifetime issues + ] + + +if LIBUV: + # epoll appears to work with these just fine in some cases; + # kqueue (at least on OS X, the only tested kqueue system) + # never does (failing with abort()) + # (epoll on Raspbian 8.0/Debian Jessie/Linux 4.1.20 works; + # on a VirtualBox image of Ubuntu 15.10/Linux 4.2.0 both tests fail; + # Travis CI Ubuntu 12.04 precise/Linux 3.13 causes one of these tests to hang forever) + # XXX: Retry this with libuv 1.12+ + disabled_tests += [ + # A 2.7 test. Tries to fork, and libuv cannot fork + 'test_signal.InterProcessSignalTests.test_main', + # Likewise, a forking problem + 'test_signal.SiginterruptTest.test_siginterrupt_off', + ] + + disabled_tests += [ + # This test wants to pass an arbitrary fileno + # to a socket and do things with it. libuv doesn't like this, + # it raises EPERM. It is disabled on windows already. + # It depends on whether we had a fd already open and multiplexed with + 'test_socket.GeneralModuleTests.test_unknown_socket_family_repr', + # And yes, there's a typo in some versions. + 'test_socket.GeneralModuleTests.test_uknown_socket_family_repr', + # This test sometimes fails at line 358. It's apparently + # extremely sensitive to timing. + 'test_selectors.PollSelectorTestCase.test_timeout', + ] + + if OSX: + disabled_tests += [ + # XXX: Starting when we upgraded from libuv 1.18.0 + # to 1.19.2, this sometimes (usually) started having + # a series of calls ('select.poll(0)', 'select.poll(-1)') + # take longer than the allowed 0.5 seconds. Debugging showed that + # it was the second call that took longer, for no apparent reason. + # There doesn't seem to be a change in the source code to libuv that + # would affect this. + # XXX-XXX: This actually disables too many tests :( + 'test_selectors.PollSelectorTestCase.test_timeout', + ] + + if RUN_COVERAGE: + + disabled_tests += [ + # Starting with #1145 this test (actually + # TestTLS_FTPClassMixin) becomes sensitive to timings + # under coverage. + 'test_ftplib.TestFTPClass.test_storlines', + ] + + + if sys.platform.startswith('linux'): + disabled_tests += [ + # crashes with EPERM, which aborts the epoll loop, even + # though it was allowed in in the first place. + 'test_asyncore.FileWrapperTest.test_dispatcher', + ] + + + if PYPY: + disabled_tests += [ + # appears to timeout? + 'test_threading.ThreadTests.test_finalize_with_trace', + 'test_asyncore.DispatcherWithSendTests_UsePoll.test_send', + 'test_asyncore.DispatcherWithSendTests.test_send', + + # More unexpected timeouts + 'test_ssl.ContextTests.test__https_verify_envvar', + 'test_subprocess.ProcessTestCase.test_check_output', + 'test_telnetlib.ReadTests.test_read_eager_A', + + # But on Windows, our gc fix for that doesn't work anyway + # so we have to disable it. + 'test_urllib2_localnet.TestUrlopen.test_https_with_cafile', + + # These tests hang. see above. + 'test_threading.ThreadJoinOnShutdown.test_1_join_on_shutdown', + 'test_threading.ThreadingExceptionTests.test_print_exception', + + # Our copy of these in test__subprocess.py also hangs. + # Anything that uses Popen.communicate or directly uses + # Popen.stdXXX.read hangs. It's not clear why. + 'test_subprocess.ProcessTestCase.test_communicate', + 'test_subprocess.ProcessTestCase.test_cwd', + 'test_subprocess.ProcessTestCase.test_env', + 'test_subprocess.ProcessTestCase.test_stderr_pipe', + 'test_subprocess.ProcessTestCase.test_stdout_pipe', + 'test_subprocess.ProcessTestCase.test_stdout_stderr_pipe', + 'test_subprocess.ProcessTestCase.test_stderr_redirect_with_no_stdout_redirect', + 'test_subprocess.ProcessTestCase.test_stdout_filedes_of_stdout', + 'test_subprocess.ProcessTestcase.test_stdout_none', + 'test_subprocess.ProcessTestcase.test_universal_newlines', + 'test_subprocess.ProcessTestcase.test_writes_before_communicate', + 'test_subprocess.Win32ProcessTestCase._kill_process', + 'test_subprocess.Win32ProcessTestCase._kill_dead_process', + 'test_subprocess.Win32ProcessTestCase.test_shell_sequence', + 'test_subprocess.Win32ProcessTestCase.test_shell_string', + 'test_subprocess.CommandsWithSpaces.with_spaces', + ] + + + if WIN: + + disabled_tests += [ + # This test winds up hanging a long time. + # Inserting GCs doesn't fix it. + 'test_ssl.ThreadedTests.test_handshake_timeout', + + # These sometimes raise LoopExit, for no apparent reason, + # mostly but not exclusively on Python 2. Sometimes (often?) + # this happens in the setUp() method when we attempt to get a client + # connection + 'test_socket.BufferIOTest.testRecvFromIntoBytearray', + 'test_socket.BufferIOTest.testRecvFromIntoArray', + 'test_socket.BufferIOTest.testRecvIntoArray', + 'test_socket.BufferIOTest.testRecvIntoMemoryview', + 'test_socket.BufferIOTest.testRecvFromIntoEmptyBuffer', + 'test_socket.BufferIOTest.testRecvFromIntoMemoryview', + 'test_socket.BufferIOTest.testRecvFromIntoSmallBuffer', + 'test_socket.BufferIOTest.testRecvIntoBytearray', + ] + + if PYPY: + + if TRAVIS: + + disabled_tests += [ + # This sometimes causes a segfault for no apparent reason. + # See https://travis-ci.org/gevent/gevent/jobs/327328704 + # Can't reproduce locally. + 'test_subprocess.ProcessTestCase.test_universal_newlines_communicate', + ] + +if RUN_COVERAGE and CFFI_BACKEND: + disabled_tests += [ + # This test hangs in this combo for some reason + 'test_socket.GeneralModuleTests.test_sendall_interrupted', + # This can get a timeout exception instead of the Alarm + 'test_socket.TCPTimeoutTest.testInterruptedTimeout', + + # This test sometimes gets the wrong answer (due to changed timing?) + 'test_socketserver.SocketServerTest.test_ForkingUDPServer', + + # Timing and signals are off, so a handler exception doesn't get raised. + # Seen under libev + 'test_signal.InterProcessSignalTests.test_main', + ] + + +if PYPY and sys.pypy_version_info[:2] == (7, 3): # pylint:disable=no-member + + if OSX: + disabled_tests += [ + # This is expected to produce an SSLError, but instead it appears to + # actually work. See above for when it started failing the same on + # Travis. + 'test_ssl.ThreadedTests.test_alpn_protocols', + # This fails, presumably due to the OpenSSL it's compiled with. + 'test_ssl.ThreadedTests.test_default_ecdh_curve', + ] + +if PYPY3 and TRAVIS: + disabled_tests += [ + # If socket.SOCK_CLOEXEC is defined, this creates a socket + # and tests its type with ``sock.type & socket.SOCK_CLOEXEC`` + # We have a ``@property`` for ``type`` that takes care of + # ``SOCK_NONBLOCK`` on Linux, but otherwise it's just a pass-through. + # This started failing with PyPy 7.3.1 and it's not clear why. + 'test_socket.InheritanceTest.test_SOCK_CLOEXEC', + ] + +if PYPY3 and WIN: + disabled_tests += [ + # test_httpservers.CGIHTTPServerTestCase all seem to hang. + # There seem to be some general subprocess issues. This is + # ignored entirely from known_failures.py + + # This produces: + # + # OSError: [Errno 10014] The system detected an invalid + # pointer address in attempting to use a pointer argument in + # a call + # + # When calling socket.socket(fileno=fd) when we actually + # call ``self._socket =self._gevent_sock_class()``. + 'test_socket.GeneralModuleTests.test_socket_fileno', + + # This doesn't respect the scope properly + # + # self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex)) + # AssertionError: Tuples differ: ('ff02::1de:c0:face:8d%42', 1234, 0, 42) != ('ff02::1de:c0:face:8d', 1234, 0, 42 + # + 'test_socket.GeneralModuleTests.test_getaddrinfo_ipv6_scopeid_numeric', + + # self.assertEqual(newsock.get_inheritable(), False) + # AssertionError: True != False + 'test_socket.InheritanceTest.test_dup', + ] + +def _make_run_with_original(mod_name, func_name): + @contextlib.contextmanager + def with_orig(): + mod = __import__(mod_name) + now = getattr(mod, func_name) + from gevent.monkey import get_original + orig = get_original(mod_name, func_name) + try: + setattr(mod, func_name, orig) + yield + finally: + setattr(mod, func_name, now) + return with_orig + +@contextlib.contextmanager +def _gc_at_end(): + try: + yield + finally: + import gc + gc.collect() + gc.collect() + +@contextlib.contextmanager +def _flaky_socket_timeout(): + import socket + try: + yield + except socket.timeout: + flaky.reraiseFlakyTestTimeout() + +# Map from FQN to a context manager that will be wrapped around +# that test. +wrapped_tests = { +} + + + +class _PatchedTest(object): + def __init__(self, test_fqn): + self._patcher = wrapped_tests[test_fqn] + + def __call__(self, orig_test_fn): + + @functools.wraps(orig_test_fn) + def test(*args, **kwargs): + with self._patcher(): + return orig_test_fn(*args, **kwargs) + return test + + +if OSX: + disabled_tests += [ + 'test_subprocess.POSIXProcessTestCase.test_run_abort', + # causes Mac OS X to show "Python crashes" dialog box which is annoying + ] + +if WIN: + disabled_tests += [ + # Issue with Unix vs DOS newlines in the file vs from the server + 'test_ssl.ThreadedTests.test_socketserver', + # This sometimes hangs (only on appveyor) + 'test_ssl.ThreadedTests.test_asyncore_server', + # On appveyor, this sometimes produces 'A non-blocking socket + # operation could not be completed immediately', followed by + # 'No connection could be made because the target machine + # actively refused it' + 'test_socket.NonBlockingTCPTests.testAccept', + + # On appveyor, this test has been seen to fail on 3.9 and 3.8 + ] + + if sys.version_info[:2] <= (3, 9): + disabled_tests += [ + 'test_context.HamtTest.test_hamt_collision_3', + # Sometimes fails:: + # + # self.assertIn('got more than ', str(cm.exception)) + # AssertionError: 'got more than ' not found in + # 'Remote end closed connection without response' + # + 'test_httplib.BasicTest.test_overflowing_header_limit_after_100', + + ] + + # These are a problem on 3.5; on 3.6+ they wind up getting (accidentally) disabled. + wrapped_tests.update({ + 'test_socket.SendfileUsingSendTest.testWithTimeout': _flaky_socket_timeout, + 'test_socket.SendfileUsingSendTest.testOffset': _flaky_socket_timeout, + 'test_socket.SendfileUsingSendTest.testRegularFile': _flaky_socket_timeout, + 'test_socket.SendfileUsingSendTest.testCount': _flaky_socket_timeout, + }) + +if PYPY: + disabled_tests += [ + # Does not exist in the CPython test suite, tests for a specific bug + # in PyPy's forking. Only runs on linux and is specific to the PyPy + # implementation of subprocess (possibly explains the extra parameter to + # _execut_child) + 'test_subprocess.ProcessTestCase.test_failed_child_execute_fd_leak', + # On some platforms, this returns "zlib_compression", but the test is looking for + # "ZLIB" + 'test_ssl.ThreadedTests.test_compression', + + # These are flaxy, apparently a race condition? Began with PyPy 2.7-7 and 3.6-7 + 'test_asyncore.TestAPI_UsePoll.test_handle_error', + 'test_asyncore.TestAPI_UsePoll.test_handle_read', + ] + + if WIN: + disabled_tests += [ + # Starting in 7.3.1 on Windows, this stopped raising ValueError; it appears to + # be a bug in PyPy. + 'test_signal.WakeupFDTests.test_invalid_fd', + # Likewise for 7.3.1. See the comments for PY35 + 'test_socket.GeneralModuleTests.test_sock_ioctl', + ] + + + disabled_tests += [ + # These are flaky, beginning in 3.6-alpha 7.0, not finding some flag + # set, apparently a race condition + 'test_asyncore.TestAPI_UveIPv6Poll.test_handle_accept', + 'test_asyncore.TestAPI_UveIPv6Poll.test_handle_accepted', + 'test_asyncore.TestAPI_UveIPv6Poll.test_handle_close', + 'test_asyncore.TestAPI_UveIPv6Poll.test_handle_write', + + 'test_asyncore.TestAPI_UseIPV6Select.test_handle_read', + + # These are reporting 'ssl has no attribute ...' + # This could just be an OSX thing + 'test_ssl.ContextTests.test__create_stdlib_context', + 'test_ssl.ContextTests.test_create_default_context', + 'test_ssl.ContextTests.test_get_ciphers', + 'test_ssl.ContextTests.test_options', + 'test_ssl.ContextTests.test_constants', + + # These tend to hang for some reason, probably not properly + # closed sockets. + 'test_socketserver.SocketServerTest.test_write', + + # This uses ctypes to do funky things including using ptrace, + # it hangs + 'test_subprocess.ProcessTestcase.test_child_terminated_in_stopped_state', + + # Certificate errors; need updated test + 'test_urllib2_localnet.TestUrlopen.test_https', + ] + +# Generic Python 3 + + + +disabled_tests += [ + # Triggers the crash reporter + 'test_threading.SubinterpThreadingTests.test_daemon_threads_fatal_error', + + # Relies on an implementation detail, Thread._tstate_lock + 'test_threading.ThreadTests.test_tstate_lock', + # Relies on an implementation detail (reprs); we have our own version + 'test_threading.ThreadTests.test_various_ops', + 'test_threading.ThreadTests.test_various_ops_large_stack', + 'test_threading.ThreadTests.test_various_ops_small_stack', + + # Relies on Event having a _cond and an _reset_internal_locks() + # XXX: These are commented out in the source code of test_threading because + # this doesn't work. + # 'lock_tests.EventTests.test_reset_internal_locks', + + # Python bug 13502. We may or may not suffer from this as its + # basically a timing race condition. + # XXX Same as above + # 'lock_tests.EventTests.test_set_and_clear', + + # These tests want to assert on the type of the class that implements + # `Popen.stdin`; we use a FileObject, but they expect different subclasses + # from the `io` module + 'test_subprocess.ProcessTestCase.test_io_buffered_by_default', + 'test_subprocess.ProcessTestCase.test_io_unbuffered_works', + + # 3.3 exposed the `endtime` argument to wait accidentally. + # It is documented as deprecated and not to be used since 3.4 + # This test in 3.6.3 wants to use it though, and we don't have it. + 'test_subprocess.ProcessTestCase.test_wait_endtime', + + # These all want to inspect the string value of an exception raised + # by the exec() call in the child. The _posixsubprocess module arranges + # for better exception handling and printing than we do. + 'test_subprocess.POSIXProcessTestCase.test_exception_bad_args_0', + 'test_subprocess.POSIXProcessTestCase.test_exception_bad_executable', + 'test_subprocess.POSIXProcessTestCase.test_exception_cwd', + # Relies on a 'fork_exec' attribute that we don't provide + 'test_subprocess.POSIXProcessTestCase.test_exception_errpipe_bad_data', + 'test_subprocess.POSIXProcessTestCase.test_exception_errpipe_normal', + + # Python 3 fixed a bug if the stdio file descriptors were closed; + # we still have that bug + 'test_subprocess.POSIXProcessTestCase.test_small_errpipe_write_fd', + + # Relies on implementation details (some of these tests were added in 3.4, + # but PyPy3 is also shipping them.) + 'test_socket.GeneralModuleTests.test_SocketType_is_socketobject', + 'test_socket.GeneralModuleTests.test_dealloc_warn', + 'test_socket.GeneralModuleTests.test_repr', + 'test_socket.GeneralModuleTests.test_str_for_enums', + 'test_socket.GeneralModuleTests.testGetaddrinfo', + +] +if TRAVIS: + disabled_tests += [ + # test_cwd_with_relative_executable tends to fail + # on Travis...it looks like the test processes are stepping + # on each other and messing up their temp directories. We tend to get things like + # saved_dir = os.getcwd() + # FileNotFoundError: [Errno 2] No such file or directory + 'test_subprocess.ProcessTestCase.test_cwd_with_relative_arg', + 'test_subprocess.ProcessTestCaseNoPoll.test_cwd_with_relative_arg', + 'test_subprocess.ProcessTestCase.test_cwd_with_relative_executable', + + # In 3.7 and 3.8 on Travis CI, this appears to take the full 3 seconds. + # Can't reproduce it locally. We have our own copy of this that takes + # timing on CI into account. + 'test_subprocess.RunFuncTestCase.test_run_with_shell_timeout_and_capture_output', + ] + +disabled_tests += [ + # XXX: BUG: We simply don't handle this correctly. On CPython, + # we wind up raising a BlockingIOError and then + # BrokenPipeError and then some random TypeErrors, all on the + # server. CPython 3.5 goes directly to socket.send() (via + # socket.makefile), whereas CPython 3.6 uses socket.sendall(). + # On PyPy, the behaviour is much worse: we hang indefinitely, perhaps exposing a problem + # with our signal handling. + + # In actuality, though, this test doesn't fully test the EINTR it expects + # to under gevent (because if its EWOULDBLOCK retry behaviour.) + # Instead, the failures were all due to `pthread_kill` trying to send a signal + # to a greenlet instead of a real thread. The solution is to deliver the signal + # to the real thread by letting it get the correct ID, and we previously + # used make_run_with_original to make it do that. + # + # But now that we have disabled our wrappers around Thread.join() in favor + # of the original implementation, that causes problems: + # background.join() thinks that it is the current thread, and won't let it + # be joined. + 'test_wsgiref.IntegrationTests.test_interrupted_write', +] + +# PyPy3 3.5.5 v5.8-beta + +if PYPY3: + + + disabled_tests += [ + # This raises 'RuntimeError: reentrant call' when exiting the + # process tries to close the stdout stream; no other platform does this. + # Seen in both 3.3 and 3.5 (5.7 and 5.8) + 'test_signal.SiginterruptTest.test_siginterrupt_off', + ] + + disabled_tests += [ + # This fails to close all the FDs, at least on CI. On OS X, many of the + # POSIXProcessTestCase fd tests have issues. + 'test_subprocess.POSIXProcessTestCase.test_close_fds_when_max_fd_is_lowered', + + # This has the wrong constants in 5.8 (but worked in 5.7), at least on + # OS X. It finds "zlib compression" but expects "ZLIB". + 'test_ssl.ThreadedTests.test_compression', + + # The below are new with 5.10.1 + # This gets an EOF in violation of protocol; again, even without gevent + # (at least on OS X; it's less consistent about that on travis) + 'test_ssl.NetworkedBIOTests.test_handshake', + + # This passes various "invalid" strings and expects a ValueError. not sure why + # we don't see errors on CPython. + 'test_subprocess.ProcessTestCase.test_invalid_env', + ] + + if OSX: + disabled_tests += [ + # These all fail with "invalid_literal for int() with base 10: b''" + 'test_subprocess.POSIXProcessTestCase.test_close_fds', + 'test_subprocess.POSIXProcessTestCase.test_close_fds_after_preexec', + 'test_subprocess.POSIXProcessTestCase.test_pass_fds', + 'test_subprocess.POSIXProcessTestCase.test_pass_fds_inheritable', + 'test_subprocess.POSIXProcessTestCase.test_pipe_cloexec', + + + # The below are new with 5.10.1 + # These fail with 'OSError: received malformed or improperly truncated ancillary data' + 'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen0', + 'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen0Plus1', + 'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen1', + 'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen2Minus1', + + # Using the provided High Sierra binary, these fail with + # 'ValueError: invalid protocol version _SSLMethod.PROTOCOL_SSLv3'. + # gevent code isn't involved and running them unpatched has the same issue. + 'test_ssl.ContextTests.test_constructor', + 'test_ssl.ContextTests.test_protocol', + 'test_ssl.ContextTests.test_session_stats', + 'test_ssl.ThreadedTests.test_echo', + 'test_ssl.ThreadedTests.test_protocol_sslv23', + 'test_ssl.ThreadedTests.test_protocol_sslv3', + 'test_ssl.ThreadedTests.test_protocol_tlsv1', + 'test_ssl.ThreadedTests.test_protocol_tlsv1_1', + # Similar, they fail without monkey-patching. + 'test_ssl.TestPostHandshakeAuth.test_pha_no_pha_client', + 'test_ssl.TestPostHandshakeAuth.test_pha_optional', + 'test_ssl.TestPostHandshakeAuth.test_pha_required', + + # This gets None instead of http1.1, even without gevent + 'test_ssl.ThreadedTests.test_npn_protocols', + + # This fails to decode a filename even without gevent, + # at least on High Sierra. Newer versions of the tests actually skip this. + 'test_httpservers.SimpleHTTPServerTestCase.test_undecodable_filename', + ] + + disabled_tests += [ + # This seems to be a buffering issue? Something isn't + # getting flushed. (The output is wrong). Under PyPy3 5.7, + # I couldn't reproduce locally in Ubuntu 16 in a VM + # or a laptop with OS X. Under 5.8.0, I can reproduce it, but only + # when run by the testrunner, not when run manually on the command line, + # so something is changing in stdout buffering in those situations. + 'test_threading.ThreadJoinOnShutdown.test_2_join_in_forked_process', + 'test_threading.ThreadJoinOnShutdown.test_1_join_in_forked_process', + ] + + if TRAVIS: + disabled_tests += [ + # Likewise, but I haven't produced it locally. + 'test_threading.ThreadJoinOnShutdown.test_1_join_on_shutdown', + ] + +if PYPY: + + wrapped_tests.update({ + # XXX: gevent: The error that was raised by that last call + # left a socket open on the server or client. The server gets + # to http/server.py(390)handle_one_request and blocks on + # self.rfile.readline which apparently is where the SSL + # handshake is done. That results in the exception being + # raised on the client above, but apparently *not* on the + # server. Consequently it sits trying to read from that + # socket. On CPython, when the client socket goes out of scope + # it is closed and the server raises an exception, closing the + # socket. On PyPy, we need a GC cycle for that to happen. + # Without the socket being closed and exception being raised, + # the server cannot be stopped (it runs each request in the + # same thread that would notice it had been stopped), and so + # the cleanup method added by start_https_server to stop the + # server blocks "forever". + + # This is an important test, so rather than skip it in patched_tests_setup, + # we do the gc before we return. + 'test_urllib2_localnet.TestUrlopen.test_https_with_cafile': _gc_at_end, + + 'test_httpservers.BaseHTTPServerTestCase.test_command': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_handler': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_head_keep_alive': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_head_via_send_error': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_header_close': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_internal_key_error': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_request_line_trimming': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_return_custom_status': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_return_header_keep_alive': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_send_blank': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_send_error': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_version_bogus': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_version_digits': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_version_invalid': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_version_none': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_version_none_get': _gc_at_end, + 'test_httpservers.BaseHTTPServerTestCase.test_get': _gc_at_end, + 'test_httpservers.SimpleHTTPServerTestCase.test_get': _gc_at_end, + 'test_httpservers.SimpleHTTPServerTestCase.test_head': _gc_at_end, + 'test_httpservers.SimpleHTTPServerTestCase.test_invalid_requests': _gc_at_end, + 'test_httpservers.SimpleHTTPServerTestCase.test_path_without_leading_slash': _gc_at_end, + 'test_httpservers.CGIHTTPServerTestCase.test_invaliduri': _gc_at_end, + 'test_httpservers.CGIHTTPServerTestCase.test_issue19435': _gc_at_end, + + 'test_httplib.TunnelTests.test_connect': _gc_at_end, + 'test_httplib.SourceAddressTest.testHTTPConnectionSourceAddress': _gc_at_end, + + # Unclear + 'test_urllib2_localnet.ProxyAuthTests.test_proxy_with_bad_password_raises_httperror': _gc_at_end, + 'test_urllib2_localnet.ProxyAuthTests.test_proxy_with_no_password_raises_httperror': _gc_at_end, + }) + + + +disabled_tests += [ + 'test_subprocess.ProcessTestCase.test_threadsafe_wait', + # XXX: It seems that threading.Timer is not being greened properly, possibly + # due to a similar issue to what gevent.threading documents for normal threads. + # In any event, this test hangs forever + + + 'test_subprocess.POSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes', + # Subclasses Popen, and overrides _execute_child. Expects things to be done + # in a particular order in an exception case, but we don't follow that + # exact order + + + 'test_selectors.PollSelectorTestCase.test_above_fd_setsize', + # This test attempts to open many many file descriptors and + # poll on them, expecting them all to be ready at once. But + # libev limits the number of events it will return at once. Specifically, + # on linux with epoll, it returns a max of 64 (ev_epoll.c). + + # XXX: Hangs (Linux only) + 'test_socket.NonBlockingTCPTests.testInitNonBlocking', + # We don't handle the Linux-only SOCK_NONBLOCK option + 'test_socket.NonblockConstantTest.test_SOCK_NONBLOCK', + + # Tries to use multiprocessing which doesn't quite work in + # monkey_test module (Windows only) + 'test_socket.TestSocketSharing.testShare', + + # Windows-only: Sockets have a 'ioctl' method in Python 3 + # implemented in the C code. This test tries to check + # for the presence of the method in the class, which we don't + # have because we don't inherit the C implementation. But + # it should be found at runtime. + 'test_socket.GeneralModuleTests.test_sock_ioctl', + + # XXX This fails for an unknown reason + 'test_httplib.HeaderTests.test_parse_all_octets', +] + +if OSX: + disabled_tests += [ + # These raise "OSError: 12 Cannot allocate memory" on both + # patched and unpatched runs + 'test_socket.RecvmsgSCMRightsStreamTest.testFDPassEmpty', + ] + + if TRAVIS: + # This has been seen to produce "Inconsistency detected by + # ld.so: dl-open.c: 231: dl_open_worker: Assertion + # `_dl_debug_initialize (0, args->nsid)->r_state == + # RT_CONSISTENT' failed!" and fail. + disabled_tests += [ + 'test_threading.ThreadTests.test_is_alive_after_fork', + # This has timing constraints that are strict and do not always + # hold. + 'test_selectors.PollSelectorTestCase.test_timeout', + ] + +if TRAVIS: + disabled_tests += [ + 'test_subprocess.ProcessTestCase.test_double_close_on_error', + # This test is racy or OS-dependent. It passes locally (sufficiently fast machine) + # but fails under Travis + ] + + +disabled_tests += [ + # XXX: Hangs + 'test_ssl.ThreadedTests.test_nonblocking_send', + 'test_ssl.ThreadedTests.test_socketserver', + # Uses direct sendfile, doesn't properly check for it being enabled + 'test_socket.GeneralModuleTests.test__sendfile_use_sendfile', + + + # Relies on the regex of the repr having the locked state (TODO: it'd be nice if + # we did that). + # XXX: These are commented out in the source code of test_threading because + # this doesn't work. + # 'lock_tests.LockTests.lest_locked_repr', + # 'lock_tests.LockTests.lest_repr', + + + # This test opens a socket, creates a new socket with the same fileno, + # closes the original socket (and hence fileno) and then + # expects that the calling setblocking() on the duplicate socket + # will raise an error. Our implementation doesn't work that way because + # setblocking() doesn't actually touch the file descriptor. + # That's probably OK because this was a GIL state error in CPython + # see https://github.com/python/cpython/commit/fa22b29960b4e683f4e5d7e308f674df2620473c + 'test_socket.TestExceptions.test_setblocking_invalidfd', +] + + +if ARES: + disabled_tests += [ + # These raise different errors or can't resolve + # the IP address correctly + 'test_socket.GeneralModuleTests.test_host_resolution', + 'test_socket.GeneralModuleTests.test_getnameinfo', + ] + + +disabled_tests += [ + 'test_threading.MiscTestCase.test__all__', +] + +# We don't actually implement socket._sendfile_use_sendfile, +# so these tests, which think they're using that and os.sendfile, +# fail. +disabled_tests += [ + 'test_socket.SendfileUsingSendfileTest.testCount', + 'test_socket.SendfileUsingSendfileTest.testCountSmall', + 'test_socket.SendfileUsingSendfileTest.testCountWithOffset', + 'test_socket.SendfileUsingSendfileTest.testOffset', + 'test_socket.SendfileUsingSendfileTest.testRegularFile', + 'test_socket.SendfileUsingSendfileTest.testWithTimeout', + 'test_socket.SendfileUsingSendfileTest.testEmptyFileSend', + 'test_socket.SendfileUsingSendfileTest.testNonBlocking', + 'test_socket.SendfileUsingSendfileTest.test_errors', +] + +# Ditto +disabled_tests += [ + 'test_socket.GeneralModuleTests.test__sendfile_use_sendfile', +] + +disabled_tests += [ + # This test requires Linux >= 4.3. When we were running 'dist: + # trusty' on the 4.4 kernel, it passed (~July 2017). But when + # trusty became the default dist in September 2017 and updated + # the kernel to 4.11.6, it begain failing. It fails on `res = + # op.recv(assoclen + len(plain) + taglen)` (where 'op' is the + # client socket) with 'OSError: [Errno 22] Invalid argument' + # for unknown reasons. This is *after* having successfully + # called `op.sendmsg_afalg`. Post 3.6.0, what we test with, + # the test was changed to require Linux 4.9 and the data was changed, + # so this is not our fault. We should eventually update this when we + # update our 3.6 version. + # See https://bugs.python.org/issue29324 + 'test_socket.LinuxKernelCryptoAPI.test_aead_aes_gcm', +] + + +disabled_tests += [ + # These want to use the private '_communicate' method, which + # our Popen doesn't have. + 'test_subprocess.MiscTests.test_call_keyboardinterrupt_no_kill', + 'test_subprocess.MiscTests.test_context_manager_keyboardinterrupt_no_kill', + 'test_subprocess.MiscTests.test_run_keyboardinterrupt_no_kill', + + # This wants to check that the underlying fileno is blocking, + # but it isn't. + 'test_socket.NonBlockingTCPTests.testSetBlocking', + + # 3.7b2 made it impossible to instantiate SSLSocket objects + # directly, and this tests for that, but we don't follow that change. + 'test_ssl.BasicSocketTests.test_private_init', + + # 3.7b2 made a change to this test that on the surface looks incorrect, + # but it passes when they run it and fails when we do. It's not + # clear why. + 'test_ssl.ThreadedTests.test_check_hostname_idn', + + # These appear to hang, haven't investigated why + 'test_ssl.SimpleBackgroundTests.test_get_server_certificate', + # Probably the same as NetworkConnectionNoServer.test_create_connection_timeout + 'test_socket.NetworkConnectionNoServer.test_create_connection', + + # Internals of the threading module that change. + 'test_threading.ThreadTests.test_finalization_shutdown', + 'test_threading.ThreadTests.test_shutdown_locks', + # Expects a deprecation warning we don't raise + 'test_threading.ThreadTests.test_old_threading_api', + # This tries to use threading.interrupt_main() from a new Thread; + # but of course that's actually the same thread and things don't + # work as expected. + 'test_threading.InterruptMainTests.test_interrupt_main_subthread', + 'test_threading.InterruptMainTests.test_interrupt_main_noerror', + + # TLS1.3 seems flaky + 'test_ssl.ThreadedTests.test_wrong_cert_tls13', +] + + +if APPVEYOR: + disabled_tests += [ + # This sometimes produces ``self.assertEqual(1, len(s.select(0))): 1 != 0``. + # Probably needs to spin the loop once. + 'test_selectors.BaseSelectorTestCase.test_timeout', + # AssertionError: OSError not raised + 'test_socket.PurePythonSocketPairTest.test_injected_authentication_failure', + # subprocess.TimeoutExpired: Command '('C:\\Program Files\\Git\\usr\\bin\\true.EXE',)' + # timed out after -1 seconds + # Seen on 3.12.5 and 3.13.0rc1 + # Perhaps they changed handling of negative timeouts? Doesn't + # affect any other platforms though. + 'test_subprocess.ProcessTestCase.test_wait_negative_timeout', + ] + + +disabled_tests += [ + # This one seems very strict: doesn't want a pathlike + # first argument when shell is true. + 'test_subprocess.RunFuncTestCase.test_run_with_pathlike_path', + # This tests for a warning we don't raise. + 'test_subprocess.RunFuncTestCase.test_bufsize_equal_one_binary_mode', + + # This compares the output of threading.excepthook with + # data constructed in Python. But excepthook is implemented in C + # and can't see the patched threading.get_ident() we use, so the + # output doesn't match. + 'test_threading.ExceptHookTests.test_excepthook_thread_None', +] + +if sys.version_info[:3] < (3, 8, 1): + disabled_tests += [ + # Earlier versions parse differently so the newer test breaks + 'test_ssl.BasicSocketTests.test_parse_all_sans', + 'test_ssl.BasicSocketTests.test_parse_cert_CVE_2013_4238', + ] + +if sys.version_info[:3] < (3, 8, 10): + disabled_tests += [ + # These were added for fixes sometime between 3.8.1 and 3.8.10 + 'test_ftplib.TestFTPClass.test_makepasv_issue43285_security_disabled', + 'test_ftplib.TestFTPClass.test_makepasv_issue43285_security_enabled_default', + 'test_httplib.BasicTest.test_dir_with_added_behavior_on_status', + 'test_httplib.TunnelTests.test_tunnel_connect_single_send_connection_setup', + 'test_ssl.TestSSLDebug.test_msg_callback_deadlock_bpo43577', + # This one fails with the updated certs + 'test_ssl.ContextTests.test_load_verify_cadata', + # This one times out on 3.7.1 on Appveyor + 'test_ftplib.TestTLS_FTPClassMixin.test_retrbinary_rest', + ] + +if RESOLVER_DNSPYTHON: + disabled_tests += [ + # This does two things DNS python doesn't. First, it sends it + # capital letters and expects them to be returned lowercase. + # Second, it expects the symbolic scopeid to be stripped from the end. + 'test_socket.GeneralModuleTests.test_getaddrinfo_ipv6_scopeid_symbolic', + ] + +# if 'signalfd' in os.environ.get('GEVENT_BACKEND', ''): +# # tests that don't interact well with signalfd +# disabled_tests.extend([ +# 'test_signal.SiginterruptTest.test_siginterrupt_off', +# 'test_socketserver.SocketServerTest.test_ForkingTCPServer', +# 'test_socketserver.SocketServerTest.test_ForkingUDPServer', +# 'test_socketserver.SocketServerTest.test_ForkingUnixStreamServer']) + +# LibreSSL reports OPENSSL_VERSION_INFO (2, 0, 0, 0, 0) regardless of its version, +# so this is known to fail on some distros. We don't want to detect this because we +# don't want to trigger the side-effects of importing ssl prematurely if we will +# be monkey-patching, so we skip this test everywhere. It doesn't do much for us +# anyway. +disabled_tests += [ + 'test_ssl.BasicSocketTests.test_openssl_version' +] + +if OSX: + + disabled_tests += [ + # This sometimes produces OSError: Errno 40: Message too long + 'test_socket.RecvmsgIntoTCPTest.testRecvmsgIntoGenerator', + + # These sometime timeout. Cannot reproduce locally. + 'test_ftp.TestTLS_FTPClassMixin.test_mlsd', + 'test_ftp.TestTLS_FTPClassMixin.test_retrlines_too_long', + 'test_ftp.TestTLS_FTPClassMixin.test_storlines', + 'test_ftp.TestTLS_FTPClassMixin.test_retrbinary_rest', + ] + + if RESOLVER_ARES and PY38 and not RUNNING_ON_CI: + disabled_tests += [ + # When updating to 1.16.0 this was seen locally, but not on CI. + # Tuples differ: ('ff02::1de:c0:face:8d', 1234, 0, 0) + # != ('ff02::1de:c0:face:8d', 1234, 0, 1) + 'test_socket.GeneralModuleTests.test_getaddrinfo_ipv6_scopeid_symbolic', + ] + +if PY39: + + disabled_tests += [ + # Depends on exact details of the repr. Eww. + 'test_subprocess.ProcessTestCase.test_repr', + # Tries to wait for the process without using Popen APIs, and expects the + # ``returncode`` attribute to stay None. But we have already hooked SIGCHLD, so + # we see and set the ``returncode``; there is no way to wait that doesn't do that. + 'test_subprocess.POSIXProcessTestTest.test_send_signal_race', + ] + + if sys.version_info[:3] < (3, 9, 5): + disabled_tests += [ + # These were added for fixes sometime between 3.9.1 and 3.9.5 + 'test_ftplib.TestFTPClass.test_makepasv_issue43285_security_disabled', + 'test_ftplib.TestFTPClass.test_makepasv_issue43285_security_enabled_default', + 'test_httplib.BasicTest.test_dir_with_added_behavior_on_status', + 'test_httplib.TunnelTests.test_tunnel_connect_single_send_connection_setup', + 'test_ssl.TestSSLDebug.test_msg_callback_deadlock_bpo43577', + # This one fails with the updated certs + 'test_ssl.ContextTests.test_load_verify_cadata', + # These time out on 3.9.1 on Appveyor + 'test_ftplib.TestTLS_FTPClassMixin.test_retrbinary_rest', + 'test_ftplib.TestTLS_FTPClassMixin.test_retrlines_too_long', + ] + +if PY39_EXACTLY: + if OSX: + disabled_tests += [ + ] + + if APPVEYOR: + disabled_tests += [ + # On 3.9.13, this has been seen to cause + # + # SystemError: returned + # NULL without setting an error + # + # But this isn't even our code! That's a CPython function. Must be flaky. + 'test_socket.GeneralModuleTests.testInvalidInterfaceIndexToName', + ] + +if PY310: + disabled_tests += [ + # They arbitrarily made some types so that they can't be created; + # that's an implementation detail we're not going to follow ( + # it would require them to be factory functions). + 'test_select.SelectTestCase.test_disallow_instantiation', + 'test_threading.ThreadTests.test_disallow_instantiation', + # This wants two true threads to work, but a CPU bound loop + # in a greenlet can't be interrupted. + 'test_threading.InterruptMainTests.test_can_interrupt_tight_loops', + # We don't currently implement pipesize. + 'test_subprocess.ProcessTestCase.test_pipesize_default', + 'test_subprocess.ProcessTestCase.test_pipesizes', + # Unknown + 'test_signal.SiginterruptTest.test_siginterrupt_off', + ] + + if TRAVIS: + disabled_tests += [ + # The mixing of subinterpreters (with threads) and gevent apparently + # leads to a segfault on Ubuntu/GitHubActions/3.10rc1. Not clear why. + # But that's not a great use case for gevent. + 'test_threading.SubinterpThreadingTests.test_threads_join', + 'test_threading.SubinterpThreadingTests.test_threads_join_2', + ] + +if PY311: + disabled_tests += [ + # CPython issue #27718: This wants to require all objects to + # have a __module__ of 'signal' because pydoc. Obviously our patches don't. + 'test_signal.GenericTests.test_functions_module_attr', + # 3.11 added subprocess._USE_VFORK and subprocess._USE_POSIX_SPAWN. + # We don't support either of those (although USE_VFORK might be possible?) + 'test_subprocess.ProcessTestCase.test__use_vfork', + # This test only runs if threading has not been imported already + # when the subprocess runs its script. But locally, and on CI, + # threading is already imported. It's not clear how, because getting the backtrace just + # shows all the internal frozen importlib modules, no actual calling code. + # The closest we get is this: + # + # (626)() + # (609)main() + # (541)venv() + # (394)addsitepackages() + # (236)addsitedir() + # (195)addpackage() + # (1)() + # + # which makes it appear like it's one of the .pth files? + # + # The monkey_test.py runner adds some ``gevent.testing`` + # imports to the top of ``test_threading.py``, and those do + # ultimately import threading, but that shouldn't affect the + # Python subprocess that runs the script being tested. + # + # Locally, I had a .pythonrc that was importing threading + # (``rich.traceback`` -> ``pygments.lexers`` -> + # ``pygments.plugin`` -> ``importlib.metadata`` -> ``zipfile`` + # -> ``importlib.util`` -> ``threading``). + # + # That provided the clue we needed. ``importlib._bootstrap`` + # imports ``importlib.util``, which imports threading. No idea + # how this test gets to pass on the CPython test suite. + 'test_threading.ThreadTests.test_import_from_another_thread', + ] + + if sys.version_info[:3] < (3, 11, 8): + # New tests in that version that won't pass on earlier versions. + disabled_tests += [ + 'test_threading.ThreadTests.test_main_thread_after_fork_from_dummy_thread', + 'tets_ssl.TestPreHandshakeClose.test_preauth_data_to_tls_client', + 'test_ssl.TestPreHandshakeClose.test_preauth_data_to_tls_server', + 'test_signal.PosixTests.test_no_repr_is_called_on_signal_handler', + 'test_socket.GeneralModuleTests.testInvalidInterfaceIndexToName', + ] + + if WIN: + disabled_tests += [ + 'test_subprocess.ProcessTestCase.test_win32_duplicate_envs', + 'test_ssl.SimpleBackgroundTests.test_transport_eof', + 'test_ssl.SimpleBackgroundTests.test_bio_read_write_data', + 'test_ssl.SimpleBackgroundTests.test_bio_handshake', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_readline_without_limit', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_readline', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1_unbounded', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1_bounded', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1', + 'test_httplib.HeaderTests.test_ipv6host_header', + ] + +if PY312: + disabled_tests += [ + # This test is new in 3.12.1; it appears to essentially rely + # on blocking sockets to fully read data in one call, and our + # version delivers a short initial read. + 'test_ssl.ThreadedTests.test_recv_into_buffer_protocol_len', + ] + + if sys.version_info[:3] < (3, 12, 1): + # Appveyor still has 3.12.0 when we added the 3.12.1 tests. + # Some of them depend on changes to the stdlib/interpreter. + disabled_tests += [ + 'test_httplib.HeaderTests.test_ipv6host_header', + 'test_interpreters.TestInterpreterClose.test_subthreads_still_running', + 'test_interpreters.TestInterpreterIsRunning.test_main', + 'test_interpreters.TestInterpreterIsRunning.test_with_only_background_threads', + 'test_interpreters.TestInterpreterRun.test_with_background_threads_still_running', + 'test_interpreters.FinalizationTests.test_gh_109793', + 'test_interpreters.StartupTests.test_sys_path_0', + 'test_threading.SubinterpThreadingTests.test_threads_join_with_no_main', + 'test_threading.MiscTestCase.test_gh112826_missing__thread__is_main_interpreter', + ] + + if RUN_COVERAGE: + disabled_tests += [ + # This test wants to look for installed tracing functions, and + # having a coverage tracer function installed breaks it. + 'test_threading.ThreadTests.test_gettrace_all_threads', + ] + + if WIN: + disabled_tests += [ + # These three are looking for an error string that matches, + # and ours differs very slightly + 'test_socket.BasicHyperVTest.testCreateHyperVSocketAddrNotTupleFailure', + 'test_socket.BasicHyperVTest.testCreateHyperVSocketAddrServiceIdNotValidUUIDFailure', + 'test_socket.BasicHyperVTest.testCreateHyperVSocketAddrVmIdNotValidUUIDFailure', + ] + # Like the case for 3.12.1, these need VM or stdlib updates. + if sys.version_info[:3] < (3, 12, 2): + disabled_tests += [ + 'test_socket.GeneralModuleTests.testInvalidInterfaceIndexToName', + 'test_subprocess.ProcessTestCase.test_win32_duplicate_envs', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_readline_without_limit', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_readline', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1_unbounded', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1_bounded', + 'test_httplib.ExtendedReadTestContentLengthKnown.test_read1', + ] + + if LINUX and RUNNING_ON_CI: + disabled_tests += [ + # These two try to forcibly close a socket, preventing some data + # from reaching its destination. That works OK on some platforms, but + # in this set of circumstances, because of the event loop, gevent is + # able to send that data. + 'test_ssl.TestPreHandshakeClose.test_preauth_data_to_tls_client', + 'test_ssl.TestPreHandshakeClose.test_preauth_data_to_tls_server', + ] + + if ARES: + disabled_tests += [ + # c-ares doesn't like the IPv6 syntax it uses here. + 'test_socket.GeneralModuleTests.test_getaddrinfo_ipv6_scopeid_symbolic', + ] + + +if PY313: + disabled_tests += [ + # Creates a fork bomb because all the threads that have been created in the + # parent process continue running in each child process. + 'test_threading.ThreadJoinOnShutdown.test_reinit_tls_after_fork', + ] + + if OSX and RUNNING_ON_CI: + disabled_tests += [ + # Sometimes times out. Cannot reproduce locally. + 'test_signal.ItimerTest.test_itimer_virtual', + ] + + if APPVEYOR: + disabled_tests += [ + ] + +if TRAVIS: + disabled_tests += [ + # These tests frequently break when we try to use newer Travis CI images, + # due to different versions of OpenSSL being available. See above for some + # specific examples. Usually the tests catch up, eventually (e.g., at this writing, + # the 3.9b1 tests are fine on Ubuntu Bionic, but all other versions fail). + 'test_ssl.ContextTests.test_options', + 'test_ssl.ThreadedTests.test_alpn_protocols', + 'test_ssl.ThreadedTests.test_default_ecdh_curve', + 'test_ssl.ThreadedTests.test_shared_ciphers', + + ] + +if RUNNING_ON_MUSLLINUX: + disabled_tests += [ + # This is supposed to *not* crash, but on the muslilnux image, it + # does crash (exitcode -11, ie, SIGSEGV) + 'test_threading.ThreadingExceptionTests.test_recursion_limit', + ] + + +# Now build up the data structure we'll use to actually find disabled tests +# to avoid a linear scan for every file (it seems the list could get quite large) +# (First, freeze the source list to make sure it isn't modified anywhere) + +def _build_test_structure(sequence_of_tests): + + _disabled_tests = frozenset(sequence_of_tests) + + disabled_tests_by_file = collections.defaultdict(set) + for file_case_meth in _disabled_tests: + file_name, _rest = file_case_meth.split('.', 1) + + by_file = disabled_tests_by_file[file_name] + + by_file.add(file_case_meth) + + return disabled_tests_by_file + +_disabled_tests_by_file = _build_test_structure(disabled_tests) + +_wrapped_tests_by_file = _build_test_structure(wrapped_tests) + + +def disable_tests_in_source(source, filename): + # Source and filename are both native strings. + + if filename.startswith('./'): + # turn "./test_socket.py" (used for auto-complete) into "test_socket.py" + filename = filename[2:] + + if filename.endswith('.py'): + filename = filename[:-3] + + + # XXX ignoring TestCase class name (just using function name). + # Maybe we should do this with the AST, or even after the test is + # imported. + my_disabled_tests = _disabled_tests_by_file.get(filename, ()) + my_wrapped_tests = _wrapped_tests_by_file.get(filename, {}) + + + if my_disabled_tests or my_wrapped_tests: + # Insert our imports early in the file. + # If we do it on a def-by-def basis, we can break syntax + # if the function is already decorated + pattern = r'^import .*' + replacement = r'from gevent.testing import patched_tests_setup as _GEVENT_PTS;' + replacement += r'import unittest as _GEVENT_UTS;' + replacement += r'\g<0>' + source, n = re.subn(pattern, replacement, source, + count=1, flags=re.MULTILINE) + + print("Added imports", n) + + # Test cases will always be indented some, + # so use [ \t]+. Without indentation, test_main, commonly used as the + # __main__ function at the top level, could get matched. \s matches + # newlines even in MULTILINE mode so it would still match that. + my_disabled_testcases = set() + for test in my_disabled_tests: + # test will be: + # test_module.TestClass.test_method + # or + # test_module.TestClass + if test.count('.') == 1: + _module, class_name = test.split('.') + # disabling a class. + # + # class CLifoTest(BaseCLass): + # -> + # class _GEVENT_DISABLE_ClifoTest: + # + # Unittest discover finds subclasses of TestCase, + # so make that not be true. This will fail if the definition + # crosses multiple lines... + pattern = r"class " + class_name + r'.*\):' + no_test_class_name = class_name.replace("Test", "") + replacement = 'class _GEVENT_DISABLE_' + no_test_class_name + ":" + source, n = re.subn(pattern, replacement, source, + flags=re.MULTILINE) + else: + testcase = test.split('.')[-1] + my_disabled_testcases.add(testcase) + # def foo_bar(self) + # -> + # @_GEVENT_UTS.skip('Removed by patched_tests_setup') + # def foo_bar(self) + pattern = r"^([ \t]+)def " + testcase + replacement = r"\1@_GEVENT_UTS.skip('Removed by patched_tests_setup: %s')\n" % (test,) + replacement += r"\g<0>" + source, n = re.subn(pattern, replacement, source, + flags=re.MULTILINE) + print('Skipped %s (%d)' % (test, n), file=sys.stderr) + + + for test in my_wrapped_tests: + testcase = test.split('.')[-1] + if testcase in my_disabled_testcases: + print("Not wrapping %s because it is skipped" % (test,)) + continue + + # def foo_bar(self) + # -> + # @_GEVENT_PTS._PatchedTest('file.Case.name') + # def foo_bar(self) + pattern = r"^([ \t]+)def " + testcase + replacement = r"\1@_GEVENT_PTS._PatchedTest('%s')\n" % (test,) + replacement += r"\g<0>" + + source, n = re.subn(pattern, replacement, source, 0, re.MULTILINE) + print('Wrapped %s (%d)' % (testcase, n), file=sys.stderr) + + return source diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/resources.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..547087e3d5860626de2323dcff6f6de6926ad7fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/resources.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +""" +Test environment setup. + +This establishes the resources that are available for use, +which are tested with `support.is_resource_enabled`. + +""" +from __future__ import absolute_import, division, print_function + +# This file may be imported early, so it should take care not to import +# things it doesn't need, which means deferred imports. + + +def get_ALL_RESOURCES(): + "Return a fresh list of resource names." + # RESOURCE_NAMES is the list of all known resources, including those that + # shouldn't be enabled by default or when asking for "all" resources. + # ALL_RESOURCES is the list of resources enabled by default or with "all" resources. + + try: + # 3.6 and 3.7 + from test.libregrtest import ALL_RESOURCES + except ImportError: + # 2.7 through 3.5 + + # Don't do this: + ## from test.regrtest import ALL_RESOURCES + + # On Python 2.7 to 3.5, importing regrtest iterates + # sys.modules and does modifications. That doesn't work well + # when it's imported from another module at module scope. + # Also, it makes some assumptions about module __file__ that + # may not hold true (at least on 2.7), especially when six or + # other module proxy objects are involved. + # So we hardcode the list. This is from 2.7, which is a superset + # of the defined resources through 3.5. + + ALL_RESOURCES = ( + 'audio', 'curses', 'largefile', 'network', 'bsddb', + 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui', + 'xpickle' + ) + + return list(ALL_RESOURCES) + [ + # Do we test the stdlib monkey-patched? + 'gevent_monkey', + ] + + +def parse_resources(resource_str=None): + # str -> Sequence[str] + + # Parse it like libregrtest.cmdline documents: + + # -u is used to specify which special resource intensive tests to run, + # such as those requiring large file support or network connectivity. + # The argument is a comma-separated list of words indicating the + # resources to test. Currently only the following are defined: + + # all - Enable all special resources. + # + # none - Disable all special resources (this is the default). + # + # network - It is okay to run tests that use external network + # resource, e.g. testing SSL support for sockets. + # + # + # subprocess Run all tests for the subprocess module. + # + # + # To enable all resources except one, use '-uall,-'. For + # example, to run all the tests except for the gui tests, give the + # option '-uall,-gui'. + + # We make a change though: we default to 'all' resources, instead of + # 'none'. Encountering either of those later in the string resets + # it, for ease of working with appending to environment variables. + + if resource_str is None: + import os + resource_str = os.environ.get('GEVENTTEST_USE_RESOURCES') + + resources = get_ALL_RESOURCES() + + if not resource_str: + return resources + + requested_resources = resource_str.split(',') + + for requested_resource in requested_resources: + # empty strings are ignored; this can happen when working with + # the environment variable if not already set: + # ENV=$ENV,-network + if not requested_resource: + continue + if requested_resource == 'all': + resources = get_ALL_RESOURCES() + elif requested_resource == 'none': + resources = [] + elif requested_resource.startswith('-'): + if requested_resource[1:] in resources: + resources.remove(requested_resource[1:]) + else: + # TODO: Produce a warning if it's an unknown resource? + resources.append(requested_resource) + + return resources + +def unparse_resources(resources): + """ + Given a list of enabled resources, produce the correct environment variable + setting to enable (only) that list. + """ + # By default, we assume all resources are enabled, so explicitly + # listing them here doesn't actually disable anything. To do that, we want to + # list the ones that are disabled. This is usually shorter than starting with + # 'none', and manually adding them back in one by one. + # + # 'none' must be special cased because an empty option string + # means 'all'. Still, we're explicit about that. + # + # TODO: Make this produce the minimal output; sometimes 'none' and + # adding would be shorter. + + all_resources = set(get_ALL_RESOURCES()) + enabled = set(resources) + + if enabled == all_resources: + result = 'all' + elif resources: + explicitly_disabled = all_resources - enabled + result = ''.join(sorted('-' + x for x in explicitly_disabled)) + else: + result = 'none' + return result + + +def setup_resources(resources=None): + """ + Call either with a list of resources or a resource string. + + If ``None`` is given, get the resource string from the environment. + """ + + if isinstance(resources, str) or resources is None: + resources = parse_resources(resources) + + from . import support + support.use_resources = list(resources) + support.gevent_has_setup_resources = True + + return resources + +def ensure_setup_resources(): + # Call when you don't know if resources have been setup and you want to + # get the environment variable if needed. + # Returns an object with `is_resource_enabled`. + from . import support + if not support.gevent_has_setup_resources: + setup_resources() + + return support + +def exit_without_resource(resource): + """ + Call this in standalone test modules that can't use unittest.SkipTest. + + Exits with a status of 0 if the resource isn't enabled. + """ + + if not ensure_setup_resources().is_resource_enabled(resource): + print("Skipped: %r not enabled" % (resource,)) + import sys + sys.exit(0) + +def skip_without_resource(resource, reason=''): + requires = 'Requires resource %r' % (resource,) + if not reason: + reason = requires + else: + reason = reason + ' (' + requires + ')' + + if not ensure_setup_resources().is_resource_enabled(resource): + import unittest + raise unittest.SkipTest(reason) + +if __name__ == '__main__': + print(setup_resources()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/six.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/six.py new file mode 100644 index 0000000000000000000000000000000000000000..b73361fe2a48c1fef00e3bbaa924c3e5df9c5b7a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/six.py @@ -0,0 +1,43 @@ +import sys +# pylint:disable=unused-argument,import-error + +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] >= 3 + +if PY3: + import builtins + exec_ = getattr(builtins, "exec") + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + + xrange = range + string_types = (str,) + text_type = str + +else: + def exec_(code, globs=None, locs=None): + """Execute code in a namespace.""" + if globs is None: + frame = sys._getframe(1) + globs = frame.f_globals + if locs is None: + locs = frame.f_locals + del frame + elif locs is None: + locs = globs + exec("""exec code in globs, locs""") + + import __builtin__ as builtins + xrange = builtins.xrange + string_types = (builtins.basestring,) + text_type = builtins.unicode + + exec_("""def reraise(tp, value, tb=None): + try: + raise tp, value, tb + finally: + tb = None +""") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/skipping.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/skipping.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ea3316c2b799720e5de41b6aeccc76e6ed47f4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/skipping.py @@ -0,0 +1,198 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import functools +import unittest + +from . import sysinfo + +def _identity(f): + return f + +def _do_not_skip(reason): + assert reason + return _identity + + +skipOnMac = _do_not_skip +skipOnMacOnCI = _do_not_skip +skipOnWindows = _do_not_skip +skipOnAppVeyor = _do_not_skip +skipOnCI = _do_not_skip +skipOnManylinux = _do_not_skip + +skipOnPyPy = _do_not_skip +skipOnPyPyOnCI = _do_not_skip +skipOnPyPy3OnCI = _do_not_skip +skipOnPyPy3 = _do_not_skip +skipOnPyPyOnWindows = _do_not_skip + +skipOnPy3 = unittest.skip if sysinfo.PY3 else _do_not_skip +skipOnPy37 = unittest.skip if sysinfo.PY37 else _do_not_skip +skipOnPy310 = unittest.skip if sysinfo.PY310 else _do_not_skip +skipOnPy312 = unittest.skip if sysinfo.PY312 else _do_not_skip + +skipOnPurePython = unittest.skip if sysinfo.PURE_PYTHON else _do_not_skip +skipWithCExtensions = unittest.skip if not sysinfo.PURE_PYTHON else _do_not_skip + +skipOnLibuv = _do_not_skip +skipOnLibuvOnWin = _do_not_skip +skipOnLibuvOnCI = _do_not_skip +skipOnLibuvOnCIOnPyPy = _do_not_skip +skipOnLibuvOnPyPyOnWin = _do_not_skip + + +skipOnLibev = _do_not_skip + +if sysinfo.WIN: + skipOnWindows = unittest.skip + +if sysinfo.OSX: + skipOnMac = unittest.skip + +if sysinfo.RUNNING_ON_APPVEYOR: + # See comments scattered around about timeouts and the timer + # resolution available on appveyor (lots of jitter). this + # seems worse with the 62-bit builds. + # Note that we skip/adjust these tests only on AppVeyor, not + # win32---we don't think there's gevent related problems but + # environment related problems. These can be tested and debugged + # separately on windows in a more stable environment. + skipOnAppVeyor = unittest.skip + + +if sysinfo.RUNNING_ON_CI: + skipOnCI = unittest.skip + if sysinfo.OSX: + skipOnMacOnCI = unittest.skip + +if sysinfo.RUNNING_ON_MANYLINUX: + skipOnManylinux = unittest.skip + +if sysinfo.PYPY: + skipOnPyPy = unittest.skip + if sysinfo.RUNNING_ON_CI: + skipOnPyPyOnCI = unittest.skip + + if sysinfo.WIN: + skipOnPyPyOnWindows = unittest.skip + + if sysinfo.PYPY3: + skipOnPyPy3 = unittest.skip + if sysinfo.RUNNING_ON_CI: + # Same as above, for PyPy3.3-5.5-alpha and 3.5-5.7.1-beta and 3.5-5.8 + skipOnPyPy3OnCI = unittest.skip + + +skipUnderCoverage = unittest.skip if sysinfo.RUN_COVERAGE else _do_not_skip + +skipIf = unittest.skipIf +skipUnless = unittest.skipUnless + +_has_psutil_process = None +def _check_psutil(): + global _has_psutil_process + if _has_psutil_process is None: + _has_psutil_process = sysinfo.get_this_psutil_process() is not None + return _has_psutil_process + + +def _make_runtime_skip_decorator(reason, predicate): + def decorator(test_item): + if not isinstance(test_item, type): + f = test_item + @functools.wraps(test_item) + def skip_wrapper(*args, **kwargs): + if not predicate(): + raise unittest.SkipTest(reason) + return f(*args, **kwargs) + test_item = skip_wrapper + else: + # given a class, override setUp() to skip it. + # + # Internally, unittest uses two flags on the class to do this: + # __unittest_skip__ and __unittest_skip_why__. It *appears* + # these are evaluated for each method in the test, so we can safely + # change them at runtime. **This isn't documented.** + # + # If they are set before execution begins, then the class setUpClass + # and tearDownClass are skipped. So changing them at runtime could result + # in something being set up but not torn down. It is substantially + # faster, though, to set them. + base = test_item + base_setUp = base.setUp + @functools.wraps(test_item) + def setUp(self): + if not predicate(): + base.__unittest_skip__ = True + base.__unittest_skip_why__ = reason + raise unittest.SkipTest(reason) + base_setUp(self) + base.setUp = setUp + + return test_item + + return decorator + +def skipWithoutPSUtil(reason): + reason = "psutil not available: " + reason + # Defer the check until runtime to avoid imports + return _make_runtime_skip_decorator(reason, _check_psutil) + +if sysinfo.LIBUV: + skipOnLibuv = unittest.skip + + if sysinfo.RUNNING_ON_CI: + skipOnLibuvOnCI = unittest.skip + if sysinfo.PYPY: + skipOnLibuvOnCIOnPyPy = unittest.skip + + if sysinfo.WIN: + skipOnLibuvOnWin = unittest.skip + if sysinfo.PYPY: + skipOnLibuvOnPyPyOnWin = unittest.skip +else: + skipOnLibev = unittest.skip + + +def skipWithoutResource(resource, reason=''): + requires = 'Requires resource %r' % (resource,) + if not reason: + reason = requires + else: + reason = reason + ' (' + requires + ')' + + # Defer until runtime; resources are established as part + # of test startup. + def predicate(): # This is easily cached if needed + from . import resources + return resources.ensure_setup_resources().is_resource_enabled(resource) + + return _make_runtime_skip_decorator(reason, predicate) + +def skipWithoutExternalNetwork(reason=''): + # Use to decorate test functions or classes that + # need access to external network resources (e.g., DNS, HTTP servers, etc) + # + # Important: If you use this on classes, you must not use the + # two-argument form of super() + + return skipWithoutResource('network', reason) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sockets.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..36046373784e840c2f592c155ede8f9506784d5e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sockets.py @@ -0,0 +1,49 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +from .params import DEFAULT_BIND_ADDR_TUPLE + +def bind_and_listen(sock, address=DEFAULT_BIND_ADDR_TUPLE, backlog=50, reuse_addr=True): + from socket import SOL_SOCKET, SO_REUSEADDR, error + if reuse_addr: + try: + sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, + sock.getsockopt(SOL_SOCKET, SO_REUSEADDR) | 1) + except error: + pass + sock.bind(address) + if backlog is not None: # udp + sock.listen(backlog) + + +def tcp_listener(address=DEFAULT_BIND_ADDR_TUPLE, backlog=50, reuse_addr=True): + """A shortcut to create a TCP socket, bind it and put it into listening state.""" + from gevent import socket + sock = socket.socket() + bind_and_listen(sock, address, backlog=backlog, reuse_addr=reuse_addr) + return sock + +def udp_listener(address=DEFAULT_BIND_ADDR_TUPLE, reuse_addr=True): + """A shortcut to create a UDF socket, bind it and put it into listening state.""" + from gevent import socket + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + bind_and_listen(sock, address, backlog=None, reuse_addr=reuse_addr) + return sock diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/support.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/support.py new file mode 100644 index 0000000000000000000000000000000000000000..f05fbd1199f7101e7e26cc1d68994f491bf6e2fa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/support.py @@ -0,0 +1,142 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +A re-export of the support module from Python's test package, with some +version compatibility shims and overrides. + +The manylinux docker images do not include test.support at all, for space reasons, +so we need to be vaguely functional to run tests in that environment. +""" + +import sys + +# Proxy through, so that changes to this module reflect in the real +# module too. (In 3.7, this is natively supported with __getattr__ at +# module scope.) This breaks static analysis (pylint), so we configure +# pylint to ignore this module. + +class _Default(object): + # A descriptor-like object that will + # only be used if the actual stdlib module + # doesn't have the value. + + def __init__(self, value): + self.value = value + +class _ModuleProxy(object): + + __slots__ = ('_this_mod', '_stdlib_support') + + def __init__(self): + self._this_mod = sys.modules[__name__] + self._stdlib_support = self + + def __get_stdlib_support(self): + if self._stdlib_support is self: + try: + from test import support as stdlib_support + except ImportError: + stdlib_support = None + self._stdlib_support = stdlib_support + + return self._stdlib_support + + def __getattr__(self, name): + try: + local_val = getattr(self._this_mod, name) + except AttributeError: + return getattr(self.__get_stdlib_support(), name) + + if isinstance(local_val, _Default): + try: + return getattr(self.__get_stdlib_support(), name) + except AttributeError: + return local_val.value + return local_val + + def __setattr__(self, name, value): + if name in _ModuleProxy.__slots__: + super(_ModuleProxy, self).__setattr__(name, value) + return + # Setting it deletes it from this module, so that + # we then continue to fall through to the original module. + try: + setattr(self.__get_stdlib_support(), name, value) + except AttributeError: + setattr(self._this_mod, name, value) + else: + try: + delattr(self._this_mod, name) + except AttributeError: + pass + + def __repr__(self): + return repr(self._this_mod) + +HOSTv6 = _Default('::1') +HOST = _Default("localhost") +HOSTv4 = _Default("127.0.0.1") +verbose = _Default(False) + +@_Default +def is_resource_enabled(_): + return False + +@_Default +def bind_port(sock, host=None): # pragma: no cover + import socket + host = host if host is not None else sys.modules[__name__].HOST + if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: + if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) # pylint:disable=no-member + + sock.bind((host, 0)) + port = sock.getsockname()[1] + return port + +@_Default +def find_unused_port(family=None, socktype=None): # pragma: no cover + import socket + family = family or socket.AF_INET + socktype = socktype or socket.SOCK_STREAM + tempsock = socket.socket(family, socktype) + try: + port = sys.modules[__name__].bind_port(tempsock) + finally: + tempsock.close() + del tempsock + return port + +@_Default +def threading_setup(): + return [] + +@_Default +def threading_cleanup(*_): + pass + +@_Default +def reap_children(): + pass + +# Set by resources.setup_resources() +gevent_has_setup_resources = False + +sys.modules[__name__] = _ModuleProxy() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/switching.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/switching.py new file mode 100644 index 0000000000000000000000000000000000000000..d846dc8ca9d03da452dd00cd6fea2669c45e7a78 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/switching.py @@ -0,0 +1,64 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +from functools import wraps + +from gevent.hub import _get_hub + +from .hub import QuietHub + +from .patched_tests_setup import get_switch_expected + +def wrap_switch_count_check(method): + @wraps(method) + def wrapper(self, *args, **kwargs): + initial_switch_count = getattr(_get_hub(), 'switch_count', None) + self.switch_expected = getattr(self, 'switch_expected', True) + if initial_switch_count is not None: + fullname = getattr(self, 'fullname', None) + if self.switch_expected == 'default' and fullname: + self.switch_expected = get_switch_expected(fullname) + result = method(self, *args, **kwargs) + if initial_switch_count is not None and self.switch_expected is not None: + switch_count = _get_hub().switch_count - initial_switch_count + if self.switch_expected is True: + assert switch_count >= 0 + if not switch_count: + raise AssertionError('%s did not switch' % fullname) + elif self.switch_expected is False: + if switch_count: + raise AssertionError('%s switched but not expected to' % fullname) + else: + raise AssertionError('Invalid value for switch_expected: %r' % (self.switch_expected, )) + return result + return wrapper + + + + +class CountingHub(QuietHub): + + switch_count = 0 + + def switch(self, *args): + # pylint:disable=arguments-differ + self.switch_count += 1 + return QuietHub.switch(self, *args) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sysinfo.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sysinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..18704e011b7c1a70011551afe0b7f2dc63bd2a1b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/sysinfo.py @@ -0,0 +1,258 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +import errno +import os +import sys + +import gevent.core +from gevent import _compat as gsysinfo + +VERBOSE = sys.argv.count('-v') > 1 + +# Python implementations +PYPY = gsysinfo.PYPY +CPYTHON = not PYPY + +# Platform/operating system +WIN = gsysinfo.WIN +LINUX = gsysinfo.LINUX +OSX = gsysinfo.OSX + +PURE_PYTHON = gsysinfo.PURE_PYTHON + +get_this_psutil_process = gsysinfo.get_this_psutil_process + +# XXX: Formalize this better +LIBUV = 'libuv' in gevent.core.loop.__module__ # pylint:disable=no-member +CFFI_BACKEND = PYPY or LIBUV or 'cffi' in os.getenv('GEVENT_LOOP', '') + +if '--debug-greentest' in sys.argv: + sys.argv.remove('--debug-greentest') + DEBUG = True +else: + DEBUG = False + +RUN_LEAKCHECKS = os.getenv('GEVENTTEST_LEAKCHECK') +RUN_COVERAGE = os.getenv("COVERAGE_PROCESS_START") or os.getenv("GEVENTTEST_COVERAGE") + +# Generally, ignore the portions that are only implemented +# on particular platforms; they generally contain partial +# implementations completed in different modules. +PLATFORM_SPECIFIC_SUFFIXES = ('2', '279', '3') +if WIN: + PLATFORM_SPECIFIC_SUFFIXES += ('posix',) + +PY2 = False # Never again +PY3 = True +PY35 = None +PY36 = None +PY37 = None +PY38 = None +PY39 = None +PY39_EXACTLY = None +PY310 = None +PY311 = None +PY312 = None +PY313 = None + +NON_APPLICABLE_SUFFIXES = () +if sys.version_info[0] == 3: + # Python 3 + NON_APPLICABLE_SUFFIXES += ('2', '279') + PY2 = False + PY3 = True + if sys.version_info[1] >= 5: + PY35 = True + if sys.version_info[1] >= 6: + PY36 = True + if sys.version_info[1] >= 7: + PY37 = True + if sys.version_info[1] >= 8: + PY38 = True + if sys.version_info[1] >= 9: + PY39 = True + if sys.version_info[:2] == (3, 9): + PY39_EXACTLY = True + if sys.version_info[1] >= 10: + PY310 = True + if sys.version_info[1] >= 11: + PY311 = True + if sys.version_info[1] >= 12: + PY312 = True + if sys.version_info[1] >= 13: + PY313 = True + + +else: # pragma: no cover + # Python 4? + raise ImportError('Unsupported major python version') + +PYPY3 = PYPY and PY3 + +if WIN: + NON_APPLICABLE_SUFFIXES += ("posix",) + # This is intimately tied to FileObjectPosix + NON_APPLICABLE_SUFFIXES += ("fileobject2",) + SHARED_OBJECT_EXTENSION = ".pyd" +else: + SHARED_OBJECT_EXTENSION = ".so" + +# We define GitHub actions to be similar to travis +RUNNING_ON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS') +RUNNING_ON_TRAVIS = os.environ.get('TRAVIS') or RUNNING_ON_GITHUB_ACTIONS +RUNNING_ON_APPVEYOR = os.environ.get('APPVEYOR') +RUNNING_ON_CI = RUNNING_ON_TRAVIS or RUNNING_ON_APPVEYOR +RUNNING_ON_MANYLINUX = os.environ.get('GEVENT_MANYLINUX') +# I'm not sure how to reliably auto-detect this, without +# importing platform, something we don't want to do. +RUNNING_ON_MUSLLINUX = 'musllinux' in os.environ.get('GEVENT_MANYLINUX_NAME', '') + +if RUNNING_ON_APPVEYOR: + # We can't exec corecext on appveyor if we haven't run setup.py in + # 'develop' mode (i.e., we install) + NON_APPLICABLE_SUFFIXES += ('corecext',) + +EXPECT_POOR_TIMER_RESOLUTION = ( + PYPY3 + # Really, this is probably only in VMs. But that's all I test + # Windows with. + or WIN + or (LIBUV and PYPY) + or RUN_COVERAGE + or (OSX and RUNNING_ON_CI) +) + + +CONN_ABORTED_ERRORS = [] +def _make_socket_errnos(*names): + result = [] + for name in names: + try: + x = getattr(errno, name) + except AttributeError: + pass + else: + result.append(x) + return frozenset(result) + +CONN_ABORTED_ERRORS = _make_socket_errnos('WSAECONNABORTED', 'ECONNRESET') +CONN_REFUSED_ERRORS = _make_socket_errnos('WSAECONNREFUSED', 'ECONNREFUSED') + +RESOLVER_ARES = os.getenv('GEVENT_RESOLVER') == 'ares' +RESOLVER_DNSPYTHON = os.getenv('GEVENT_RESOLVER') == 'dnspython' + +RESOLVER_NOT_SYSTEM = RESOLVER_ARES or RESOLVER_DNSPYTHON + +def get_python_version(): + """ + Return a string of the simple python version, + such as '3.8.0b4'. Handles alpha, beta, release candidate, and final releases. + """ + version = '%s.%s.%s' % sys.version_info[:3] + if sys.version_info[3] == 'alpha': + version += 'a%s' % sys.version_info[4] + elif sys.version_info[3] == 'beta': + version += 'b%s' % sys.version_info[4] + elif sys.version_info[3] == 'candidate': + version += 'rc%s' % sys.version_info[4] + + return version + +def _parse_version(ver_str): + try: + from packaging.version import Version + # InvalidVersion is a type of ValueError + except ImportError: + import warnings + warnings.warn('packaging.version not available; assuming no advanced Linux backends') + raise ValueError + + try: + return Version(ver_str) + except ValueError: + import warnings + warnings.warn('Unable to parse version %s' % (ver_str,)) + raise + +def _check_linux_version_at_least(major, minor, error_kind): + # pylint:disable=too-many-return-statements + # ^ Yeah, but this is the most linear and simple way to + # write this. + from platform import system + if system() != 'Linux': + return False + + from platform import release as _release + release = _release() + try: + # Linux versions like '6.8.0-1014-azure' cannot be parsed + # by packaging.version.Version, and distutils.LooseVersion, which + # did handle that, is deprecated. Neither module is guaranteed to be available + # anyway, so do the best we can manually. + ver_strings = (release or '0').split('.', 2) + + if not ver_strings or int(ver_strings[0]) < major: # no way. + return False + + if int(ver_strings[0]) > major: # Way newer! + return True + + assert major == int(ver_strings[0]) # Exactly the major + + if len(ver_strings) < 2: # no minor version, assume no + return False + + if int(ver_strings[1]) < minor: + return False + + assert int(ver_strings[1]) >= minor, (ver_strings[1], minor) + return True + except AssertionError: + raise + except Exception: # pylint:disable=broad-exception-caught + import warnings + warnings.warn('Unable to parse version %r; assuming no %s support' % ( + release, error_kind + )) + return False + +def libev_supports_linux_aio(): + # libev requires kernel 4.19 or above to be able to support + # linux AIO. It can still be compiled in, but will fail to create + # the loop at runtime. + return _check_linux_version_at_least(4, 19, 'aio') + + +def libev_supports_linux_iouring(): + # libev requires kernel XXX to be able to support linux io_uring. + # It fails with the kernel in fedora rawhide (4.19.76) but + # works (doesn't fail catastrophically when asked to create one) + # with kernel 5.3.0 (Ubuntu Bionic) + return _check_linux_version_at_least(5, 3, 'iouring') + + +def resolver_dnspython_available(): + # Try hard not to leave around junk we don't have to. + from importlib import metadata + try: + metadata.distribution('dnspython') + except metadata.PackageNotFoundError: + return False + return True diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testcase.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testcase.py new file mode 100644 index 0000000000000000000000000000000000000000..0cbe87d6c439cf727e0adb5bda8b5f25660c2859 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testcase.py @@ -0,0 +1,480 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +from __future__ import absolute_import, print_function, division + +import sys +import os.path +from contextlib import contextmanager +from unittest import TestCase as BaseTestCase +from functools import wraps + +import gevent +from gevent._util import LazyOnClass +from gevent._compat import perf_counter +from gevent._compat import get_clock_info +from gevent._hub_local import get_hub_if_exists + +from . import sysinfo +from . import params +from . import leakcheck +from . import errorhandler +from . import flaky + +from .patched_tests_setup import get_switch_expected + +class TimeAssertMixin(object): + @flaky.reraises_flaky_timeout() + def assertTimeoutAlmostEqual(self, first, second, places=None, msg=None, delta=None): + try: + self.assertAlmostEqual(first, second, places=places, msg=msg, delta=delta) + except AssertionError: + flaky.reraiseFlakyTestTimeout() + + + if sysinfo.EXPECT_POOR_TIMER_RESOLUTION: + # pylint:disable=unused-argument + def assertTimeWithinRange(self, time_taken, min_time, max_time): + return + else: + def assertTimeWithinRange(self, time_taken, min_time, max_time): + self.assertLessEqual(time_taken, max_time) + self.assertGreaterEqual(time_taken, min_time) + + @contextmanager + def runs_in_given_time(self, expected, fuzzy=None, min_time=None): + if fuzzy is None: + if sysinfo.EXPECT_POOR_TIMER_RESOLUTION or sysinfo.LIBUV: + # The noted timer jitter issues on appveyor/pypy3 + fuzzy = expected * 5.0 + else: + fuzzy = expected / 2.0 + min_time = min_time if min_time is not None else expected - fuzzy + max_time = expected + fuzzy + start = perf_counter() + yield (min_time, max_time) + elapsed = perf_counter() - start + try: + self.assertTrue( + min_time <= elapsed <= max_time, + 'Expected: %r; elapsed: %r; min: %r; max: %r; fuzzy %r; clock_info: %s' % ( + expected, elapsed, min_time, max_time, fuzzy, get_clock_info('perf_counter') + )) + except AssertionError: + flaky.reraiseFlakyTestRaceCondition() + + def runs_in_no_time( + self, + fuzzy=(0.01 if not sysinfo.EXPECT_POOR_TIMER_RESOLUTION and not sysinfo.LIBUV else 1.0)): + return self.runs_in_given_time(0.0, fuzzy) + + +class GreenletAssertMixin(object): + """Assertions related to greenlets.""" + + def assert_greenlet_ready(self, g): + self.assertTrue(g.dead, g) + self.assertTrue(g.ready(), g) + self.assertFalse(g, g) + + def assert_greenlet_not_ready(self, g): + self.assertFalse(g.dead, g) + self.assertFalse(g.ready(), g) + + def assert_greenlet_spawned(self, g): + self.assertTrue(g.started, g) + self.assertFalse(g.dead, g) + + # No difference between spawned and switched-to once + assert_greenlet_started = assert_greenlet_spawned + + def assert_greenlet_finished(self, g): + self.assertFalse(g.started, g) + self.assertTrue(g.dead, g) + + +class StringAssertMixin(object): + """ + Assertions dealing with strings. + """ + + @LazyOnClass + def HEX_NUM_RE(self): + import re + return re.compile('-?0x[0123456789abcdef]+L?', re.I) + + def normalize_addr(self, s, replace='X'): + # https://github.com/PyCQA/pylint/issues/1127 + return self.HEX_NUM_RE.sub(replace, s) # pylint:disable=no-member + + def normalize_module(self, s, module=None, replace='module'): + if module is None: + module = type(self).__module__ + + return s.replace(module, replace) + + def normalize(self, s): + return self.normalize_module(self.normalize_addr(s)) + + def assert_nstr_endswith(self, o, val): + s = str(o) + n = self.normalize(s) + self.assertTrue(n.endswith(val), (s, n)) + + def assert_nstr_startswith(self, o, val): + s = str(o) + n = self.normalize(s) + self.assertTrue(n.startswith(val), (s, n)) + + + +class TestTimeout(gevent.Timeout): + _expire_info = '' + + def __init__(self, timeout, method='Not Given'): + gevent.Timeout.__init__( + self, + timeout, + '%r: test timed out (set class __timeout__ to increase)\n' % (method,), + ref=False + ) + + def _on_expiration(self, prev_greenlet, ex): + from gevent.util import format_run_info + loop = gevent.get_hub().loop + debug_info = 'N/A' + if hasattr(loop, 'debug'): + debug_info = [str(s) for s in loop.debug()] + run_info = format_run_info() + self._expire_info = 'Loop Debug:\n%s\nRun Info:\n%s' % ( + '\n'.join(debug_info), '\n'.join(run_info) + ) + gevent.Timeout._on_expiration(self, prev_greenlet, ex) + + def __str__(self): + s = gevent.Timeout.__str__(self) + s += self._expire_info + return s + +def _wrap_timeout(timeout, method): + if timeout is None: + return method + + @wraps(method) + def timeout_wrapper(self, *args, **kwargs): + with TestTimeout(timeout, method): + return method(self, *args, **kwargs) + + return timeout_wrapper + +def _get_class_attr(classDict, bases, attr, default=AttributeError): + NONE = object() + value = classDict.get(attr, NONE) + if value is not NONE: + return value + for base in bases: + value = getattr(base, attr, NONE) + if value is not NONE: + return value + if default is AttributeError: + raise AttributeError('Attribute %r not found\n%s\n%s\n' % (attr, classDict, bases)) + return default + + +class TestCaseMetaClass(type): + # wrap each test method with + # a) timeout check + # b) fatal error check + # c) restore the hub's error handler (see expect_one_error) + # d) totalrefcount check + def __new__(mcs, classname, bases, classDict): + # pylint and pep8 fight over what this should be called (mcs or cls). + # pylint gets it right, but we cant scope disable pep8, so we go with + # its convention. + # pylint: disable=bad-mcs-classmethod-argument + timeout = classDict.get('__timeout__', 'NONE') + if timeout == 'NONE': + timeout = getattr(bases[0], '__timeout__', None) + if sysinfo.RUN_LEAKCHECKS and timeout is not None: + timeout *= 6 + check_totalrefcount = _get_class_attr(classDict, bases, 'check_totalrefcount', True) + + error_fatal = _get_class_attr(classDict, bases, 'error_fatal', True) + uses_handle_error = _get_class_attr(classDict, bases, 'uses_handle_error', True) + # Python 3: must copy, we mutate the classDict. Interestingly enough, + # it doesn't actually error out, but under 3.6 we wind up wrapping + # and re-wrapping the same items over and over and over. + for key, value in list(classDict.items()): + if key.startswith('test') and callable(value): + classDict.pop(key) + # XXX: When did we stop doing this? + #value = wrap_switch_count_check(value) + value = _wrap_timeout(timeout, value) + error_fatal = getattr(value, 'error_fatal', error_fatal) + if error_fatal: + value = errorhandler.wrap_error_fatal(value) + if uses_handle_error: + value = errorhandler.wrap_restore_handle_error(value) + if check_totalrefcount and sysinfo.RUN_LEAKCHECKS: + value = leakcheck.wrap_refcount(value) + classDict[key] = value + return type.__new__(mcs, classname, bases, classDict) + +def _noop(): + return + +class SubscriberCleanupMixin(object): + + def setUp(self): + super(SubscriberCleanupMixin, self).setUp() + from gevent import events + self.__old_subscribers = events.subscribers[:] + + def addSubscriber(self, sub): + from gevent import events + events.subscribers.append(sub) + + def tearDown(self): + from gevent import events + events.subscribers[:] = self.__old_subscribers + super(SubscriberCleanupMixin, self).tearDown() + + +class TestCase( + # TestCaseMetaClass("NewBase", + # (SubscriberCleanupMixin, + # TimeAssertMixin, + # GreenletAssertMixin, + # StringAssertMixin, + # BaseTestCase,), + # {})): + SubscriberCleanupMixin, TimeAssertMixin, GreenletAssertMixin, + StringAssertMixin, BaseTestCase, + metaclass=TestCaseMetaClass +): + __timeout__ = params.LOCAL_TIMEOUT if not sysinfo.RUNNING_ON_CI else params.CI_TIMEOUT + + switch_expected = 'default' + #: Set this to true to cause errors that get reported to the hub to + #: always get propagated to the main greenlet. This can be done at the + #: class or method level. + #: .. caution:: This can hide errors and make it look like exceptions + #: are propagated even if they're not. + error_fatal = True + uses_handle_error = True + close_on_teardown = () + # This is really used by the SubscriberCleanupMixin + __old_subscribers = () # pylint:disable=unused-private-member + + def run(self, *args, **kwargs): # pylint:disable=signature-differs + if self.switch_expected == 'default': + self.switch_expected = get_switch_expected(self.fullname) + return super(TestCase, self).run(*args, **kwargs) + + def setUp(self): + super(TestCase, self).setUp() + # Especially if we're running in leakcheck mode, where + # the same test gets executed repeatedly, we need to update the + # current time. Tests don't always go through the full event loop, + # so that doesn't always happen. test__pool.py:TestPoolYYY.test_async + # tends to show timeouts that are too short if we don't. + # XXX: Should some core part of the loop call this? + hub = get_hub_if_exists() + if hub and hub.loop: + hub.loop.update_now() + self.close_on_teardown = [] + self.addCleanup(self._tearDownCloseOnTearDown) + + def _callTestMethod(self, method): + # 3.12 started raising a stupid warning about returning + # non-None from ``test_...()`` being deprecated. Since the + # test framework never cares about the return value anyway, + # this is an utterly pointless annoyance. Override the method + # that raises that deprecation. (Are the maintainers planning + # to make the return value _mean_ something someday? That's + # the only valid reason for them to do this. Answer: No, no + # they're not. They're just trying to protect people from + # writing broken tests that accidentally turn into generators + # or something. Which...if people don't notice their tests + # aren't working...well. Now, perhaps this got worse in the + # era of asyncio where *everything* is a generator. But that's + # not our problem; we have better ways of dealing with the + # shortcomings of asyncio, namely, don't use it. + # https://bugs.python.org/issue41322) + method() + + def tearDown(self): + if getattr(self, 'skipTearDown', False): + del self.close_on_teardown[:] + return + + cleanup = getattr(self, 'cleanup', _noop) + cleanup() + self._error = self._none + super(TestCase, self).tearDown() + + def _tearDownCloseOnTearDown(self): + while self.close_on_teardown: + x = self.close_on_teardown.pop() + close = getattr(x, 'close', x) + try: + close() + except Exception: # pylint:disable=broad-except + pass + + def _close_on_teardown(self, resource): + """ + *resource* either has a ``close`` method, or is a + callable. + """ + self.close_on_teardown.append(resource) + return resource + + @property + def testname(self): + return getattr(self, '_testMethodName', '') or getattr(self, '_TestCase__testMethodName') + + @property + def testcasename(self): + return self.__class__.__name__ + '.' + self.testname + + @property + def modulename(self): + return os.path.basename(sys.modules[self.__class__.__module__].__file__).rsplit('.', 1)[0] + + @property + def fullname(self): + return os.path.splitext(os.path.basename(self.modulename))[0] + '.' + self.testcasename + + _none = (None, None, None) + # (context, kind, value) + _error = _none + + def expect_one_error(self): + self.assertEqual(self._error, self._none) + gevent.get_hub().handle_error = self._store_error + + def _store_error(self, where, t, value, tb): + del tb + if self._error != self._none: + gevent.get_hub().parent.throw(t, value) + else: + self._error = (where, t, value) + + def peek_error(self): + return self._error + + def get_error(self): + try: + return self._error + finally: + self._error = self._none + + def assert_error(self, kind=None, value=None, error=None, where_type=None): + if error is None: + error = self.get_error() + econtext, ekind, evalue = error + if kind is not None: + self.assertIsInstance(kind, type) + self.assertIsNotNone( + ekind, + "Error must not be none %r" % (error,)) + assert issubclass(ekind, kind), error + if value is not None: + if isinstance(value, str): + self.assertEqual(str(evalue), value) + else: + self.assertIs(evalue, value) + if where_type is not None: + self.assertIsInstance(econtext, where_type) + return error + + def assertMonkeyPatchedFuncSignatures(self, mod_name, func_names=(), exclude=()): + # If inspect.getfullargspec is not available, + # We use inspect.getargspec because it's the only thing available + # in Python 2.7, but it is deprecated + # pylint:disable=deprecated-method,too-many-locals + import inspect + import warnings + from gevent.monkey import get_original + # XXX: Very similar to gevent.monkey.patch_module. Should refactor? + gevent_module = getattr(__import__('gevent.' + mod_name), mod_name) + module_name = getattr(gevent_module, '__target__', mod_name) + + funcs_given = True + if not func_names: + funcs_given = False + func_names = getattr(gevent_module, '__implements__') + + for func_name in func_names: + if func_name in exclude: + continue + gevent_func = getattr(gevent_module, func_name) + if not inspect.isfunction(gevent_func) and not funcs_given: + continue + + func = get_original(module_name, func_name) + + try: + with warnings.catch_warnings(): + getfullargspec = inspect.getfullargspec + gevent_sig = getfullargspec(gevent_func) + sig = getfullargspec(func) + except TypeError: + if funcs_given: + raise + # Can't do this one. If they specifically asked for it, + # it's an error, otherwise it's not. + # Python 3 can check a lot more than Python 2 can. + continue + self.assertEqual(sig.args, gevent_sig.args, func_name) + # The next two might not actually matter? + self.assertEqual(sig.varargs, gevent_sig.varargs, func_name) + self.assertEqual(sig.defaults, gevent_sig.defaults, func_name) + if hasattr(sig, 'keywords'): # the old version + msg = (func_name, sig.keywords, gevent_sig.keywords) + try: + self.assertEqual(sig.keywords, gevent_sig.keywords, msg) + except AssertionError: + # Ok, if we take `kwargs` and the original function doesn't, + # that's OK. We have to do that as a compatibility hack sometimes to + # work across multiple python versions. + self.assertIsNone(sig.keywords, msg) + self.assertEqual('kwargs', gevent_sig.keywords) + else: + # The new hotness. Unfortunately, we can't actually check these things + # until we drop Python 2 support from the shared code. The only known place + # this is a problem is python 3.11 socket.create_connection(), which we manually + # ignore. So the checks all pass as is. + self.assertEqual(sig.kwonlyargs, gevent_sig.kwonlyargs, func_name) + self.assertEqual(sig.kwonlydefaults, gevent_sig.kwonlydefaults, func_name) + # Should deal with others: https://docs.python.org/3/library/inspect.html#inspect.getfullargspec + + def assertEqualFlakyRaceCondition(self, a, b): + try: + self.assertEqual(a, b) + except AssertionError: + flaky.reraiseFlakyTestRaceCondition() + + def assertStartsWith(self, it, has_prefix): + self.assertTrue(it.startswith(has_prefix), (it, has_prefix)) + + def assertNotMonkeyPatched(self): + from gevent import monkey + self.assertFalse(monkey.is_anything_patched()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testrunner.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testrunner.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6159dd4b87def4ea3bdcb8a4032ff930b3325f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/testrunner.py @@ -0,0 +1,991 @@ +# -*- coding: utf-8 -*- + +import re +import sys +import os +import glob +import operator +import traceback +import importlib + +from contextlib import contextmanager +from datetime import timedelta +from multiprocessing.pool import ThreadPool +from multiprocessing import cpu_count + +from gevent._util import Lazy + +from . import util +from .resources import parse_resources +from .resources import setup_resources +from .resources import unparse_resources +from .sysinfo import RUNNING_ON_CI +from .sysinfo import PYPY +from .sysinfo import PY2 +from .sysinfo import RESOLVER_ARES +from .sysinfo import RUN_LEAKCHECKS +from .sysinfo import OSX +from . import six +from . import travis + +# Import this while we're probably single-threaded/single-processed +# to try to avoid issues with PyPy 5.10. +# See https://bitbucket.org/pypy/pypy/issues/2769/systemerror-unexpected-internal-exception +try: + __import__('_testcapi') +except (ImportError, OSError): + # This can raise a wide variety of errors + pass + +TIMEOUT = 100 # seconds +AVAIL_NWORKERS = cpu_count() - 1 +DEFAULT_NWORKERS = int(os.environ.get('NWORKERS') or max(AVAIL_NWORKERS, 4)) +if DEFAULT_NWORKERS > 15: + DEFAULT_NWORKERS = 10 + + +if RUN_LEAKCHECKS: + # Capturing the stats takes time, and we run each + # test at least twice + TIMEOUT = 200 + +DEFAULT_RUN_OPTIONS = { + 'timeout': TIMEOUT +} + + +if RUNNING_ON_CI: + # Too many and we get spurious timeouts + DEFAULT_NWORKERS = 4 if not OSX else 2 + + +def _package_relative_filename(filename, package): + if not os.path.isfile(filename) and package: + # Ok, try to locate it as a module in the package + package_dir = _dir_from_package_name(package) + return os.path.join(package_dir, filename) + return filename + +def _dir_from_package_name(package): + package_mod = importlib.import_module(package) + package_dir = os.path.dirname(package_mod.__file__) + return package_dir + + +class ResultCollector(object): + + def __init__(self): + self.total = 0 + self.failed = {} + self.passed = {} + self.total_cases = 0 + self.total_skipped = 0 + # Every RunResult reported: failed, passed, rerun + self._all_results = [] + self.reran = {} + + def __iadd__(self, result): + self._all_results.append(result) + + if not result: + self.failed[result.name] = result #[cmd, kwargs] + else: + self.passed[result.name] = True + self.total_cases += result.run_count + self.total_skipped += result.skipped_count + return self + + def __ilshift__(self, result): + """ + collector <<= result + + Stores the result, but does not count it towards + the number of cases run, skipped, passed or failed. + """ + self._all_results.append(result) + self.reran[result.name] = result + return self + + @property + def longest_running_tests(self): + """ + A new list of RunResult objects, sorted from longest running + to shortest running. + """ + return sorted(self._all_results, + key=operator.attrgetter('run_duration'), + reverse=True) + + +class FailFast(Exception): + pass + +class Runner(object): + + TIME_WAIT_REAP = 0.1 + TIME_WAIT_SPAWN = 0.05 + + def __init__(self, + tests, + *, + allowed_return_codes=(), + configured_failing_tests=(), + failfast=False, + quiet=False, + configured_run_alone_tests=(), + worker_count=DEFAULT_NWORKERS, + second_chance=False): + """ + :keyword allowed_return_codes: Return codes other than + 0 that are counted as a success. Needed because some versions + of Python give ``unittest`` weird return codes. + :keyword quiet: Set to True or False to explicitly choose. Set to + `None` to use the default, which may come from the environment variable + ``GEVENTTEST_QUIET``. + """ + self._tests = tests + self._configured_failing_tests = configured_failing_tests + self._quiet = quiet + self._configured_run_alone_tests = configured_run_alone_tests + + assert not (failfast and second_chance) + self._failfast = failfast + self._second_chance = second_chance + + self.results = ResultCollector() + self.results.total = len(self._tests) + self._running_jobs = [] + + self._worker_count = min(len(tests), worker_count) or 1 + self._allowed_return_codes = allowed_return_codes + + def _run_one(self, cmd, **kwargs): + kwargs['allowed_return_codes'] = self._allowed_return_codes + if self._quiet is not None: + kwargs['quiet'] = self._quiet + result = util.run(cmd, **kwargs) + if not result and self._second_chance: + self.results <<= result + util.log("> %s", result.name, color='warning') + result = util.run(cmd, **kwargs) + if not result and self._failfast: + # Under Python 3.9 (maybe older versions?), raising the + # SystemExit here (a background thread belonging to the + # pool) doesn't seem to work well. It gets stuck waiting + # for a lock? The job never shows up as finished. + raise FailFast(cmd) + self.results += result + + def _reap(self): + "Clean up the list of running jobs, returning how many are still outstanding." + for r in self._running_jobs[:]: + if not r.ready(): + continue + if r.successful(): + self._running_jobs.remove(r) + else: + r.get() + sys.exit('Internal error in testrunner.py: %r' % (r, )) + return len(self._running_jobs) + + def _reap_all(self): + util.log("Reaping %d jobs", len(self._running_jobs), color="debug") + while self._running_jobs: + if not self._reap(): + break + util.sleep(self.TIME_WAIT_REAP) + + def _spawn(self, pool, cmd, options): + while True: + if self._reap() < self._worker_count: + job = pool.apply_async(self._run_one, (cmd, ), options or {}) + self._running_jobs.append(job) + return + + util.sleep(self.TIME_WAIT_SPAWN) + + def __call__(self): + util.log("Running tests in parallel with concurrency %s %s." % ( + self._worker_count, + util._colorize('number', '(concurrency available: %d)' % AVAIL_NWORKERS) + ),) + # Setting global state, in theory we can be used multiple times. + # This is fine as long as we are single threaded and call these + # sequentially. + util.BUFFER_OUTPUT = self._worker_count > 1 or self._quiet + + start = util.perf_counter() + try: + self._run_tests() + except KeyboardInterrupt: + self._report(util.perf_counter() - start, exit=False) + util.log('(partial results)\n') + raise + except: + traceback.print_exc() + raise + + self._reap_all() + self._report(util.perf_counter() - start, exit=True) + + def _run_tests(self): + "Runs the tests, produces no report." + run_alone = [] + + tests = self._tests + pool = ThreadPool(self._worker_count) + try: + for cmd, options in tests: + options = options or {} + if matches(self._configured_run_alone_tests, cmd): + run_alone.append((cmd, options)) + else: + self._spawn(pool, cmd, options) + pool.close() + pool.join() + + if run_alone: + util.log("Running tests marked standalone") + for cmd, options in run_alone: + self._run_one(cmd, **options) + except KeyboardInterrupt: + try: + util.log('Waiting for currently running to finish...') + self._reap_all() + except KeyboardInterrupt: + pool.terminate() + raise + except: + pool.terminate() + raise + + def _report(self, elapsed_time, exit=False): + results = self.results + report( + results, + exit=exit, + took=elapsed_time, + configured_failing_tests=self._configured_failing_tests, + ) + + +class TravisFoldingRunner(object): + + def __init__(self, runner, travis_fold_msg): + self._runner = runner + self._travis_fold_msg = travis_fold_msg + self._travis_fold_name = str(int(util.perf_counter())) + + # A zope-style acquisition proxy would be convenient here. + run_tests = runner._run_tests + + def _run_tests(): + self._begin_fold() + try: + run_tests() + finally: + self._end_fold() + + runner._run_tests = _run_tests + + def _begin_fold(self): + travis.fold_start(self._travis_fold_name, + self._travis_fold_msg) + + def _end_fold(self): + travis.fold_end(self._travis_fold_name) + + def __call__(self): + return self._runner() + + +class Discovery(object): + package_dir = None + package = None + + def __init__( + self, + tests=None, + ignore_files=None, + ignored=(), + coverage=False, + package=None, + config=None, + allow_combine=True, + ): + self.config = config or {} + self.ignore = set(ignored or ()) + self.tests = tests + self.configured_test_options = config.get('TEST_FILE_OPTIONS', set()) + self.allow_combine = allow_combine + if ignore_files: + ignore_files = ignore_files.split(',') + for f in ignore_files: + self.ignore.update(set(load_list_from_file(f, package))) + + if coverage: + self.ignore.update(config.get('IGNORE_COVERAGE', set())) + + if package: + self.package = package + self.package_dir = _dir_from_package_name(package) + + class Discovered(object): + def __init__(self, package, configured_test_options, ignore, config, allow_combine): + self.orig_dir = os.getcwd() + self.configured_run_alone = config['RUN_ALONE'] + self.configured_failing_tests = config['FAILING_TESTS'] + self.package = package + self.configured_test_options = configured_test_options + self.allow_combine = allow_combine + self.ignore = ignore + + self.to_import = [] + self.std_monkey_patch_files = [] + self.no_monkey_patch_files = [] + + self.commands = [] + + @staticmethod + def __makes_simple_monkey_patch( + contents, + _patch_present=re.compile(br'[^#].*patch_all\(\)'), + _patch_indented=re.compile(br' .*patch_all\(\)') + ): + return ( + # A non-commented patch_all() call is present + bool(_patch_present.search(contents)) + # that is not indented (because that implies its not at the top-level, + # so some preconditions are being set) + and not _patch_indented.search(contents) + ) + + @staticmethod + def __file_allows_monkey_combine(contents): + return b'testrunner-no-monkey-combine' not in contents + + @staticmethod + def __file_allows_combine(contents): + return b'testrunner-no-combine' not in contents + + @staticmethod + def __calls_unittest_main_toplevel( + contents, + _greentest_main=re.compile(br' greentest.main\(\)'), + _unittest_main=re.compile(br' unittest.main\(\)'), + _import_main=re.compile(br'from gevent.testing import.*main'), + _main=re.compile(br' main\(\)'), + ): + # TODO: Add a check that this comes in a line directly after + # if __name__ == __main__. + return ( + _greentest_main.search(contents) + or _unittest_main.search(contents) + or (_import_main.search(contents) and _main.search(contents)) + ) + + def __has_config(self, filename): + return ( + RUN_LEAKCHECKS + or filename in self.configured_test_options + or filename in self.configured_run_alone + or matches(self.configured_failing_tests, filename) + ) + + def __can_monkey_combine(self, filename, contents): + return ( + self.allow_combine + and not self.__has_config(filename) + and self.__makes_simple_monkey_patch(contents) + and self.__file_allows_monkey_combine(contents) + and self.__file_allows_combine(contents) + and self.__calls_unittest_main_toplevel(contents) + ) + + @staticmethod + def __makes_no_monkey_patch(contents, _patch_present=re.compile(br'[^#].*patch_\w*\(')): + return not _patch_present.search(contents) + + def __can_nonmonkey_combine(self, filename, contents): + return ( + self.allow_combine + and not self.__has_config(filename) + and self.__makes_no_monkey_patch(contents) + and self.__file_allows_combine(contents) + and self.__calls_unittest_main_toplevel(contents) + ) + + def __begin_command(self): + cmd = [sys.executable, '-u'] + # XXX: -X track-resources is broken. This happened when I updated to + # PyPy 7.3.2. It started failing to even start inside the virtual environment + # with + # + # debug: OperationError: + # debug: operror-type: ImportError + # debug: operror-value: No module named traceback + # + # I don't know if this is PyPy's problem or a problem in virtualenv: + # + # virtualenv==20.0.35 + # virtualenv-clone==0.5.4 + # virtualenvwrapper==4.8.4 + # + # Deferring investigation until I need this... + + # if PYPY and PY2: + # # Doesn't seem to be an env var for this. + # # XXX: track-resources is broken in virtual environments + # # on 7.3.2. + # cmd.extend(('-X', 'track-resources')) + return cmd + + + def __add_test(self, qualified_name, filename, contents): + if b'TESTRUNNER' in contents: # test__monkey_patching.py + # XXX: Rework this to avoid importing. + # XXX: Rework this to allow test combining (it could write the files out and return + # them directly; we would use 'python -m gevent.monkey --module unittest ...) + self.to_import.append(qualified_name) + elif self.__can_monkey_combine(filename, contents): + self.std_monkey_patch_files.append(qualified_name if self.package else filename) + elif self.__can_nonmonkey_combine(filename, contents): + self.no_monkey_patch_files.append(qualified_name if self.package else filename) + else: + # XXX: For simple python module tests, try this with + # `runpy.run_module`, very similar to the way we run + # things for monkey patching. The idea here is that we + # can perform setup ahead of time (e.g., + # setup_resources()) in each test without having to do + # it manually or force calls or modifications to those + # tests. + cmd = self.__begin_command() + if self.package: + # Using a package is the best way to work with coverage 5 + # when we specify 'source = ' + cmd.append('-m' + qualified_name) + else: + cmd.append(filename) + + options = DEFAULT_RUN_OPTIONS.copy() + options.update(self.configured_test_options.get(filename, {})) + self.commands.append((cmd, options)) + + @staticmethod + def __remove_options(lst): + return [x for x in lst if x and not x.startswith('-')] + + def __expand_imports(self): + for qualified_name in self.to_import: + module = importlib.import_module(qualified_name) + for cmd, options in module.TESTRUNNER(): + if self.__remove_options(cmd)[-1] in self.ignore: + continue + self.commands.append((cmd, options)) + del self.to_import[:] + + def __combine_commands(self, files, group_size=5): + if not files: + return + + from itertools import groupby + cnt = [0, 0] + def make_group(_): + if cnt[0] > group_size: + cnt[0] = 0 + cnt[1] += 1 + cnt[0] += 1 + return cnt[1] + + for _, group in groupby(files, make_group): + + cmd = self.__begin_command() + cmd.append('-m') + cmd.append('unittest') + # cmd.append('-v') + for name in group: + cmd.append(name) + self.commands.insert(0, (cmd, DEFAULT_RUN_OPTIONS.copy())) + + del files[:] + + + def visit_file(self, filename): + # Support either 'gevent.tests.foo' or 'gevent/tests/foo.py' + if filename.startswith('gevent.tests'): + # XXX: How does this interact with 'package'? Probably not well + qualified_name = module_name = filename + filename = filename[len('gevent.tests') + 1:] + filename = filename.replace('.', os.sep) + '.py' + else: + module_name = os.path.splitext(filename)[0] + qualified_name = self.package + '.' + module_name if self.package else module_name + + # Also allow just 'foo' as a shortcut for 'gevent.tests.foo' + abs_filename = os.path.abspath(filename) + if ( + not os.path.exists(abs_filename) + and not filename.endswith('.py') + and os.path.exists(abs_filename + '.py') ): + abs_filename += '.py' + + with open(abs_filename, 'rb') as f: + # Some of the test files (e.g., test__socket_dns) are + # UTF8 encoded. Depending on the environment, Python 3 may + # try to decode those as ASCII, which fails with UnicodeDecodeError. + # Thus, be sure to open and compare in binary mode. + # Open the absolute path to make errors more clear, + # but we can't store the absolute path, our configuration is based on + # relative file names. + contents = f.read() + + self.__add_test(qualified_name, filename, contents) + + def visit_files(self, filenames): + for filename in filenames: + self.visit_file(filename) + with Discovery._in_dir(self.orig_dir): + self.__expand_imports() + self.__combine_commands(self.std_monkey_patch_files) + self.__combine_commands(self.no_monkey_patch_files) + + @staticmethod + @contextmanager + def _in_dir(package_dir): + olddir = os.getcwd() + if package_dir: + os.chdir(package_dir) + try: + yield + finally: + os.chdir(olddir) + + @Lazy + def discovered(self): + tests = self.tests + discovered = self.Discovered(self.package, self.configured_test_options, + self.ignore, self.config, self.allow_combine) + + # We need to glob relative names, our config is based on filenames still + with self._in_dir(self.package_dir): + if not tests: + tests = set(glob.glob('test_*.py')) - set(['test_support.py']) + else: + tests = set(tests) + + if self.ignore: + # Always ignore the designated list, even if tests + # were specified on the command line. This fixes a + # nasty interaction with + # test__threading_vs_settrace.py being run under + # coverage when 'grep -l subprocess test*py' is used + # to list the tests to run. + tests -= self.ignore + tests = sorted(tests) + discovered.visit_files(tests) + + return discovered + + def __iter__(self): + return iter(self.discovered.commands) # pylint:disable=no-member + + def __len__(self): + return len(self.discovered.commands) # pylint:disable=no-member + +def load_list_from_file(filename, package): + result = [] + if filename: + # pylint:disable=unspecified-encoding + with open(_package_relative_filename(filename, package)) as f: + for x in f: + x = x.split('#', 1)[0].strip() + if x: + result.append(x) + return result + + +def matches(possibilities, command, include_flaky=True): + if isinstance(command, list): + command = ' '.join(command) + for line in possibilities: + if not include_flaky and line.startswith('FLAKY '): + continue + line = line.replace('FLAKY ', '') + # Our configs are still mostly written in terms of file names, + # but the non-monkey tests are now using package names. + # Strip off '.py' from filenames to see if we match a module. + # XXX: This could be much better. Our command needs better structure. + if command.endswith(' ' + line) or command.endswith(line.replace(".py", '')): + return True + if ' ' not in command and command == line: + return True + return False + + +def format_seconds(seconds): + if seconds < 20: + return '%.1fs' % seconds + seconds = str(timedelta(seconds=round(seconds))) + if seconds.startswith('0:'): + seconds = seconds[2:] + return seconds + + +def _show_longest_running(result_collector, how_many=5): + longest_running_tests = result_collector.longest_running_tests + if not longest_running_tests: + return + # The only tricky part is handling repeats. we want to show them, + # but not count them as a distinct entry. + + util.log('\nLongest-running tests:') + length_of_longest_formatted_decimal = len('%.1f' % longest_running_tests[0].run_duration) + + frmt = '%' + str(length_of_longest_formatted_decimal) + '.1f seconds: %s' + seen_names = set() + for result in longest_running_tests: + util.log(frmt, result.run_duration, result.name) + seen_names.add(result.name) + if len(seen_names) >= how_many: + break + + + +def report(result_collector, # type: ResultCollector + exit=True, took=None, + configured_failing_tests=()): + # pylint:disable=redefined-builtin,too-many-branches,too-many-locals + total = result_collector.total + failed = result_collector.failed + passed = result_collector.passed + total_cases = result_collector.total_cases + total_skipped = result_collector.total_skipped + + _show_longest_running(result_collector) + + if took: + took = ' in %s' % format_seconds(took) + else: + took = '' + + failed_expected = [] + failed_unexpected = [] + passed_unexpected = [] + + for name in passed: + if matches(configured_failing_tests, name, include_flaky=False): + passed_unexpected.append(name) + + if passed_unexpected: + util.log('\n%s/%s unexpected passes', len(passed_unexpected), total, color='error') + print_list(passed_unexpected) + + if result_collector.reran: + util.log('\n%s/%s tests rerun', len(result_collector.reran), total, color='warning') + print_list(result_collector.reran) + + if failed: + util.log('\n%s/%s tests failed%s', len(failed), total, took, color='warning') + + for name in failed: + if matches(configured_failing_tests, name, include_flaky=True): + failed_expected.append(name) + else: + failed_unexpected.append(name) + + if failed_expected: + util.log('\n%s/%s expected failures', len(failed_expected), total, color='warning') + print_list(failed_expected) + + if failed_unexpected: + util.log('\n%s/%s unexpected failures', len(failed_unexpected), total, color='error') + print_list(failed_unexpected) + + util.log( + '\nRan %s tests%s in %s files%s', + total_cases, + util._colorize('skipped', " (skipped=%d)" % total_skipped) if total_skipped else '', + total, + took, + ) + + if exit: + if failed_unexpected: + sys.exit(min(100, len(failed_unexpected))) + if passed_unexpected: + sys.exit(101) + if total <= 0: + sys.exit('No tests found.') + + +def print_list(lst): + for name in lst: + util.log(' - %s', name) + +def _setup_environ(debug=False): + def not_set(key): + return not bool(os.environ.get(key)) + + if (not_set('PYTHONWARNINGS') + and (not sys.warnoptions + # Python 3.7 goes from [] to ['default'] for nothing + or sys.warnoptions == ['default'])): + # action:message:category:module:line + + # - when a warning matches + # more than one option, the action for the last matching + # option is performed. + # - action is one of : ignore, default, all, module, once, error + + # Enable default warnings such as ResourceWarning. + # ResourceWarning doesn't exist on Py2, so don't put it + # in there to avoid a warnnig. + defaults = [ + 'default', + 'default::DeprecationWarning', + ] + if not PY2: + defaults.append('default::ResourceWarning') + + os.environ['PYTHONWARNINGS'] = ','.join(defaults + [ + # On Python 3[.6], the system site.py module has + # "open(fullname, 'rU')" which produces the warning that + # 'U' is deprecated, so ignore warnings from site.py + 'ignore:::site:', + # pkgutil on Python 2 complains about missing __init__.py + 'ignore:::pkgutil:', + # importlib/_bootstrap.py likes to spit out "ImportWarning: + # can't resolve package from __spec__ or __package__, falling + # back on __name__ and __path__". I have no idea what that means, but it seems harmless + # and is annoying. + 'ignore:::importlib._bootstrap:', + 'ignore:::importlib._bootstrap_external:', + # importing ABCs from collections, not collections.abc + 'ignore:::pkg_resources._vendor.pyparsing:', + 'ignore:::dns.namedict:', + # dns.hash itself is being deprecated, importing it raises the warning; + # we don't import it, but dnspython still does + 'ignore:::dns.hash:', + # dns.zone uses some raw regular expressions + # without the r'' syntax, leading to DeprecationWarning: invalid + # escape sequence. This is fixed in 2.0 (Python 3 only). + 'ignore:::dns.zone:', + ]) + + if not_set('PYTHONFAULTHANDLER'): + os.environ['PYTHONFAULTHANDLER'] = 'true' + + if not_set('GEVENT_DEBUG') and debug: + os.environ['GEVENT_DEBUG'] = 'debug' + + if not_set('PYTHONTRACEMALLOC') and debug: + # This slows the tests down quite a bit. Reserve + # for debugging. + os.environ['PYTHONTRACEMALLOC'] = '10' + + if not_set('PYTHONDEVMODE'): + # Python 3.7 and above. + os.environ['PYTHONDEVMODE'] = '1' + + if not_set('PYTHONMALLOC') and debug: + # Python 3.6 and above. + # This slows the tests down some, but + # can detect memory corruption. Unfortunately + # it can also be flaky, especially in pre-release + # versions of Python (e.g., lots of crashes on Python 3.8b4). + os.environ['PYTHONMALLOC'] = 'debug' + + if sys.version_info.releaselevel != 'final' and not debug: + os.environ['PYTHONMALLOC'] = 'default' + os.environ['PYTHONDEVMODE'] = '' + + # PYTHONSAFEPATH breaks the assumptions of some tests, notably test_interpreters.py + os.environ.pop('PYTHONSAFEPATH', None) + + interesting_envs = { + k: os.environ[k] + for k in os.environ + if k.startswith(('PYTHON', 'GEVENT')) + } + widest_k = max(len(k) for k in interesting_envs) + for k, v in sorted(interesting_envs.items()): + util.log('%*s\t=\t%s', widest_k, k, v, color="debug") + + +def main(): + # pylint:disable=too-many-locals,too-many-statements,too-many-branches + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--ignore') + parser.add_argument( + '--discover', action='store_true', + help="Only print the tests found." + ) + parser.add_argument( + '--config', default='known_failures.py', + help="The path to the config file containing " + "FAILING_TESTS, IGNORED_TESTS and RUN_ALONE. " + "Defaults to %(default)s." + ) + parser.add_argument( + "--coverage", action="store_true", + help="Enable coverage recording with coverage.py." + ) + # TODO: Quiet and verbose should be mutually exclusive + parser.add_argument( + "--quiet", action="store_true", default=True, + help="Be quiet. Defaults to %(default)s. Also the " + "GEVENTTEST_QUIET environment variable." + ) + parser.add_argument("--verbose", action="store_false", dest='quiet') + + parser.add_argument( + "--debug", action="store_true", default=False, + help="Enable debug settings. If the GEVENT_DEBUG environment variable is not set, " + "this sets it to 'debug'. This can also enable PYTHONTRACEMALLOC and the debug PYTHONMALLOC " + "allocators, if not already set. Defaults to %(default)s." + ) + + parser.add_argument( + "--package", default="gevent.tests", + help="Load tests from the given package. Defaults to %(default)s." + ) + parser.add_argument( + "--processes", "-j", default=DEFAULT_NWORKERS, type=int, + help="Use up to the given number of parallel processes to execute tests. " + "Defaults to %(default)s." + ) + parser.add_argument( + '--no-combine', default=True, action='store_false', + help="Do not combine tests into process groups." + ) + parser.add_argument('-u', '--use', metavar='RES1,RES2,...', + action='store', type=parse_resources, + help='specify which special resource intensive tests ' + 'to run. "all" is the default; "none" may also be used. ' + 'Disable individual resources with a leading -.' + 'For example, "-u-network". GEVENTTEST_USE_RESOURCES is used ' + 'if no argument is given. To only use one resources, specify ' + '"-unone,resource".') + parser.add_argument("--travis-fold", metavar="MSG", + help="Emit Travis CI log fold markers around the output.") + + fail_parser = parser.add_mutually_exclusive_group() + fail_parser.add_argument( + "--second-chance", action="store_true", default=False, + help="Give failed tests a second chance.") + fail_parser.add_argument( + '--failfast', '-x', action='store_true', default=False, + help="Stop running after the first failure.") + + parser.add_argument('tests', nargs='*') + options = parser.parse_args() + # options.use will be either None for not given, or a list + # of the last specified -u argument. + # If not given, use the default, which we'll take from the environment, if set. + options.use = list(set(parse_resources() if options.use is None else options.use)) + + # Whether or not it came from the environment, put it in the + # environment now. + os.environ['GEVENTTEST_USE_RESOURCES'] = unparse_resources(options.use) + setup_resources(options.use) + + + # Set this before any test imports in case of 'from .util import QUIET'; + # not that this matters much because we spawn tests in subprocesses, + # it's the environment setting that matters + util.QUIET = options.quiet + if 'GEVENTTEST_QUIET' not in os.environ: + os.environ['GEVENTTEST_QUIET'] = str(options.quiet) + + FAILING_TESTS = [] + IGNORED_TESTS = [] + RUN_ALONE = [] + + coverage = False + if options.coverage or os.environ.get("GEVENTTEST_COVERAGE"): + if PYPY and RUNNING_ON_CI: + print("Ignoring coverage option on PyPy on CI; slow") + else: + coverage = True + cov_config = os.environ['COVERAGE_PROCESS_START'] = os.path.abspath(".coveragerc") + if PYPY: + cov_config = os.environ['COVERAGE_PROCESS_START'] = os.path.abspath(".coveragerc-pypy") + + this_dir = os.path.dirname(__file__) + site_dir = os.path.join(this_dir, 'coveragesite') + site_dir = os.path.abspath(site_dir) + os.environ['PYTHONPATH'] = site_dir + os.pathsep + os.environ.get("PYTHONPATH", "") + # We change directory often, use an absolute path to keep all the + # coverage files (which will have distinct suffixes because of parallel=true in .coveragerc + # in this directory; makes them easier to combine and use with coverage report) + os.environ['COVERAGE_FILE'] = os.path.abspath(".") + os.sep + ".coverage" + # XXX: Log this with color. Right now, it interferes (buffering) with other early + # output. + print("Enabling coverage to", os.environ['COVERAGE_FILE'], + "with site", site_dir, + "and configuration file", cov_config) + assert os.path.exists(cov_config) + assert os.path.exists(os.path.join(site_dir, 'sitecustomize.py')) + + _setup_environ(debug=options.debug) + + if options.config: + config = {} + options.config = _package_relative_filename(options.config, options.package) + with open(options.config) as f: # pylint:disable=unspecified-encoding + config_data = f.read() + six.exec_(config_data, config) + FAILING_TESTS = config['FAILING_TESTS'] + IGNORED_TESTS = config['IGNORED_TESTS'] + RUN_ALONE = config['RUN_ALONE'] + + tests = Discovery( + options.tests, + ignore_files=options.ignore, + ignored=IGNORED_TESTS, + coverage=coverage, + package=options.package, + config=config, + allow_combine=options.no_combine, + ) + if options.discover: + for cmd, options in tests: + print(util.getname(cmd, env=options.get('env'), setenv=options.get('setenv'))) + print('%s tests found.' % len(tests)) + else: + if PYPY and RESOLVER_ARES: + # XXX: Add a way to force these. + print("Not running tests on pypy with c-ares; not a supported configuration") + return + + if options.package: + # Put this directory on the path so relative imports work. + package_dir = _dir_from_package_name(options.package) + os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', "") + os.pathsep + package_dir + + allowed_return_codes = () + if sys.version_info[:3] >= (3, 12, 1): + # unittest suddenly started failing with this return code + # if all tests in a module are skipped in 3.12.1. + allowed_return_codes += (5,) + + runner = Runner( + tests, + allowed_return_codes=allowed_return_codes, + configured_failing_tests=FAILING_TESTS, + failfast=options.failfast, + quiet=options.quiet, + configured_run_alone_tests=RUN_ALONE, + worker_count=options.processes, + second_chance=options.second_chance, + ) + + if options.travis_fold: + runner = TravisFoldingRunner(runner, options.travis_fold) + + runner() + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/timing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/timing.py new file mode 100644 index 0000000000000000000000000000000000000000..d960710eb1cee87d7b80a62725cd55978034aafc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/timing.py @@ -0,0 +1,138 @@ +# Copyright (c) 2018 gevent community +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import gevent +from gevent._compat import perf_counter + +from . import sysinfo +from . import leakcheck +from .testcase import TestCase + +SMALLEST_RELIABLE_DELAY = 0.001 # 1ms, because of libuv + +SMALL_TICK = 0.01 +SMALL_TICK_MIN_ADJ = SMALLEST_RELIABLE_DELAY +SMALL_TICK_MAX_ADJ = 0.11 +if sysinfo.RUNNING_ON_APPVEYOR: + # Timing resolution is extremely poor on Appveyor + # and subject to jitter. + SMALL_TICK_MAX_ADJ = 1.5 + + +LARGE_TICK = 0.2 +LARGE_TICK_MIN_ADJ = LARGE_TICK / 2.0 +LARGE_TICK_MAX_ADJ = SMALL_TICK_MAX_ADJ + + +class _DelayWaitMixin(object): + + _default_wait_timeout = SMALL_TICK + _default_delay_min_adj = SMALL_TICK_MIN_ADJ + _default_delay_max_adj = SMALL_TICK_MAX_ADJ + + def wait(self, timeout): + raise NotImplementedError('override me in subclass') + + def _check_delay_bounds(self, timeout, delay, + delay_min_adj=None, + delay_max_adj=None): + delay_min_adj = self._default_delay_min_adj if not delay_min_adj else delay_min_adj + delay_max_adj = self._default_delay_max_adj if not delay_max_adj else delay_max_adj + self.assertTimeWithinRange(delay, + timeout - delay_min_adj, + timeout + delay_max_adj) + + def _wait_and_check(self, timeout=None): + if timeout is None: + timeout = self._default_wait_timeout + + # gevent.timer instances have a 'seconds' attribute, + # otherwise it's the raw number + seconds = getattr(timeout, 'seconds', timeout) + + gevent.get_hub().loop.update_now() + start = perf_counter() + try: + result = self.wait(timeout) + finally: + self._check_delay_bounds(seconds, perf_counter() - start, + self._default_delay_min_adj, + self._default_delay_max_adj) + return result + + def test_outer_timeout_is_not_lost(self): + timeout = gevent.Timeout.start_new(SMALLEST_RELIABLE_DELAY, ref=False) + try: + with self.assertRaises(gevent.Timeout) as exc: + self.wait(timeout=1) + self.assertIs(exc.exception, timeout) + finally: + timeout.close() + + +class AbstractGenericWaitTestCase(_DelayWaitMixin, TestCase): + # pylint:disable=abstract-method + + _default_wait_timeout = LARGE_TICK + _default_delay_min_adj = LARGE_TICK_MIN_ADJ + _default_delay_max_adj = LARGE_TICK_MAX_ADJ + + @leakcheck.ignores_leakcheck # waiting checks can be very sensitive to timing + def test_returns_none_after_timeout(self): + result = self._wait_and_check() + # join and wait simply return after timeout expires + self.assertIsNone(result) + + +class AbstractGenericGetTestCase(_DelayWaitMixin, TestCase): + # pylint:disable=abstract-method + + Timeout = gevent.Timeout + + def cleanup(self): + pass + + def test_raises_timeout_number(self): + with self.assertRaises(self.Timeout): + self._wait_and_check(timeout=SMALL_TICK) + # get raises Timeout after timeout expired + self.cleanup() + + def test_raises_timeout_Timeout(self): + timeout = gevent.Timeout(self._default_wait_timeout) + try: + self._wait_and_check(timeout=timeout) + except gevent.Timeout as ex: + self.assertIs(ex, timeout) + finally: + timeout.close() + self.cleanup() + + def test_raises_timeout_Timeout_exc_customized(self): + error = RuntimeError('expected error') + timeout = gevent.Timeout(self._default_wait_timeout, exception=error) + try: + with self.assertRaises(RuntimeError) as exc: + self._wait_and_check(timeout=timeout) + + self.assertIs(exc.exception, error) + self.cleanup() + finally: + timeout.close() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/travis.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/travis.py new file mode 100644 index 0000000000000000000000000000000000000000..81f1800e683a640c5ce644b0ca70aa0c61d21a07 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/travis.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Support functions for travis +# See https://github.com/travis-ci/travis-rubies/blob/9f7962a881c55d32da7c76baefc58b89e3941d91/build.sh + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + + +commands = {} + +def command(func): + commands[func.__name__] = lambda: func(*sys.argv[2:]) + return func + +@command +def fold_start(name, msg): + sys.stdout.write('travis_fold:start:') + sys.stdout.write(name) + sys.stdout.write(chr(0o33)) + sys.stdout.write('[33;1m') + sys.stdout.write(msg) + sys.stdout.write(chr(0o33)) + sys.stdout.write('[33;0m\n') + +@command +def fold_end(name): + sys.stdout.write("\ntravis_fold:end:") + sys.stdout.write(name) + sys.stdout.write("\r\n") + + +def main(): + cmd = sys.argv[1] + commands[cmd]() + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/util.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/util.py new file mode 100644 index 0000000000000000000000000000000000000000..6182e30c607945c6d114a879fcfaa884cb042f64 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/testing/util.py @@ -0,0 +1,655 @@ +""" +.. caution:: + + This module imports `subprocess` and `threading`; this can + break monkey-patched unittests. Specifically, + ``test_threading.ThreadTests.test_import_from_another_thread``. +""" + +import re +import sys +import os +import traceback +import unittest +import threading +import subprocess +from time import sleep + +from . import six +from gevent._config import validate_bool +from gevent._compat import perf_counter +from gevent.monkey import get_original + +# pylint: disable=broad-except,attribute-defined-outside-init + +BUFFER_OUTPUT = False +# This is set by the testrunner, defaulting to true (be quiet) +# But if we're run standalone, default to false +QUIET = validate_bool(os.environ.get('GEVENTTEST_QUIET', '0')) + + +class Popen(subprocess.Popen): + """ + Depending on when we're imported and if the process has been monkey-patched, + this could use cooperative or native Popen. + """ + timer = None # a threading.Timer instance + + def __enter__(self): + return self + + def __exit__(self, *args): + kill(self) + + +# Coloring code based on zope.testrunner + +# These colors are carefully chosen to have enough contrast +# on terminals with both black and white background. +_colorscheme = { + 'normal': 'normal', + 'default': 'default', + + 'actual-output': 'red', + 'character-diffs': 'magenta', + 'debug': 'cyan', + 'diff-chunk': 'magenta', + 'error': 'brightred', + 'error-number': 'brightred', + 'exception': 'red', + 'expected-output': 'green', + 'failed-example': 'cyan', + 'filename': 'lightblue', + 'info': 'normal', + 'lineno': 'lightred', + 'number': 'green', + 'ok-number': 'green', + 'skipped': 'brightyellow', + 'slow-test': 'brightmagenta', + 'suboptimal-behaviour': 'magenta', + 'testname': 'lightcyan', + 'warning': 'cyan', +} + +_prefixes = [ + ('dark', '0;'), + ('light', '1;'), + ('bright', '1;'), + ('bold', '1;'), +] + +_colorcodes = { + 'default': 0, + 'normal': 0, + 'black': 30, + 'red': 31, + 'green': 32, + 'brown': 33, 'yellow': 33, + 'blue': 34, + 'magenta': 35, + 'cyan': 36, + 'grey': 37, 'gray': 37, 'white': 37 +} + +def _color_code(color): + prefix_code = '' + for prefix, code in _prefixes: + if color.startswith(prefix): + color = color[len(prefix):] + prefix_code = code + break + color_code = _colorcodes[color] + return '\033[%s%sm' % (prefix_code, color_code) + +def _color(what): + return _color_code(_colorscheme[what]) + +def _colorize(what, message, normal='normal'): + return _color(what) + message + _color(normal) + +def log(message, *args, **kwargs): + """ + Log a *message* + + :keyword str color: One of the values from _colorscheme + """ + color = kwargs.pop('color', 'normal') + + if args: + string = message % args + else: + string = message + string = _colorize(color, string) + + with output_lock: # pylint:disable=not-context-manager + sys.stderr.write(string + '\n') + +def debug(message, *args, **kwargs): + """ + Log the *message* only if we're not in quiet mode. + """ + if not QUIET: + kwargs.setdefault('color', 'debug') + log(message, *args, **kwargs) + +def killpg(pid): + if not hasattr(os, 'killpg'): + return + try: + return os.killpg(pid, 9) + except OSError as ex: + if ex.errno != 3: + log('killpg(%r, 9) failed: %s: %s', pid, type(ex).__name__, ex) + except Exception as ex: + log('killpg(%r, 9) failed: %s: %s', pid, type(ex).__name__, ex) + + +def kill_processtree(pid): + ignore_msg = 'ERROR: The process "%s" not found.' % pid + err = Popen('taskkill /F /PID %s /T' % pid, stderr=subprocess.PIPE).communicate()[1] + if err and err.strip() not in [ignore_msg, '']: + log('%r', err) + + +def _kill(popen): + if hasattr(popen, 'kill'): + try: + popen.kill() + except OSError as ex: + if ex.errno == 3: # No such process + return + if ex.errno == 13: # Permission denied (translated from windows error 5: "Access is denied") + return + raise + else: + try: + os.kill(popen.pid, 9) + except EnvironmentError: + pass + + +def kill(popen): + if popen.timer is not None: + popen.timer.cancel() + popen.timer = None + if popen.poll() is not None: + return + popen.was_killed = True + try: + if getattr(popen, 'setpgrp_enabled', None): + killpg(popen.pid) + elif sys.platform.startswith('win'): + kill_processtree(popen.pid) + except Exception: + traceback.print_exc() + try: + _kill(popen) + except Exception: + traceback.print_exc() + try: + popen.wait() + except Exception: + traceback.print_exc() + +# A set of environment keys we ignore for printing purposes +IGNORED_GEVENT_ENV_KEYS = { + 'GEVENTTEST_QUIET', + 'GEVENT_DEBUG', + 'GEVENTSETUP_EV_VERIFY', + 'GEVENTSETUP_EMBED', +} + +# A set of (name, value) pairs we ignore for printing purposes. +# These should match the defaults. +IGNORED_GEVENT_ENV_ITEMS = { + ('GEVENT_RESOLVER', 'thread'), + ('GEVENT_RESOLVER_NAMESERVERS', '8.8.8.8'), + ('GEVENTTEST_USE_RESOURCES', 'all'), +} + +def getname(command, env=None, setenv=None): + result = [] + + env = (env or os.environ).copy() + env.update(setenv or {}) + + for key, value in sorted(env.items()): + if not key.startswith('GEVENT'): + continue + if key in IGNORED_GEVENT_ENV_KEYS: + continue + if (key, value) in IGNORED_GEVENT_ENV_ITEMS: + continue + result.append('%s=%s' % (key, value)) + + if isinstance(command, six.string_types): + result.append(command) + else: + result.extend(command) + + return ' '.join(result) + + +def start(command, quiet=False, **kwargs): + timeout = kwargs.pop('timeout', None) + preexec_fn = None + if not os.environ.get('DO_NOT_SETPGRP'): + preexec_fn = getattr(os, 'setpgrp', None) + env = kwargs.pop('env', None) + setenv = kwargs.pop('setenv', None) or {} + name = getname(command, env=env, setenv=setenv) + if preexec_fn is not None: + setenv['DO_NOT_SETPGRP'] = '1' + if setenv: + env = env.copy() if env else os.environ.copy() + env.update(setenv) + + if not quiet: + log('+ %s', name) + popen = Popen(command, preexec_fn=preexec_fn, env=env, **kwargs) + popen.name = name + popen.setpgrp_enabled = preexec_fn is not None + popen.was_killed = False + if timeout is not None: + t = get_original('threading', 'Timer')(timeout, kill, args=(popen, )) + popen.timer = t + t.daemon = True + t.start() + popen.timer = t + return popen + + +class RunResult(object): + """ + The results of running an external command. + + If the command was successful, this has a boolean + value of True; otherwise, a boolean value of false. + + The integer value of this object is the command's exit code. + """ + + def __init__(self, + command, + run_kwargs, + code, + output=None, # type: str + error=None, # type: str + name=None, + run_count=0, skipped_count=0, + run_duration=0, # type: float + ): + self.command = command + self.run_kwargs = run_kwargs + self.code = code + self.output = output + self.error = error + self.name = name + self.run_count = run_count + self.skipped_count = skipped_count + self.run_duration = run_duration + + @property + def output_lines(self): + return self.output.splitlines() + + def __bool__(self): + return not bool(self.code) + + __nonzero__ = __bool__ + + def __int__(self): + return self.code + + def __repr__(self): + return ( + "RunResult of: %r\n" + "Code: %s\n" + "kwargs: %r\n" + "Output:\n" + "----\n" + "%s" + "----\n" + "Error:\n" + "----\n" + "%s" + "----\n" + ) % ( + self.command, + self.code, + self.run_kwargs, + self.output, + self.error + ) + + +def _should_show_warning_output(out): + if 'Warning' in out: + # Strip out some patterns we specifically do not + # care about. + # from test.support for monkey-patched tests + out = out.replace('Warning -- reap_children', 'NADA') + out = out.replace("Warning -- threading_cleanup", 'NADA') + + # The below *could* be done with sophisticated enough warning + # filters passed to the children + + # collections.abc is the new home; setuptools uses the old one, + # as does dnspython + out = out.replace("DeprecationWarning: Using or importing the ABCs", 'NADA') + # libuv poor timer resolution + out = out.replace('UserWarning: libuv only supports', 'NADA') + # Packages on Python 2 + out = out.replace('ImportWarning: Not importing directory', 'NADA') + # Testing that U mode does the same thing + out = out.replace("DeprecationWarning: 'U' mode is deprecated", 'NADA') + out = out.replace("DeprecationWarning: dns.hash module", 'NADA') + return 'Warning' in out + +output_lock = threading.Lock() + +def _find_test_status(took, out): + status = '[took %.1fs%s]' + skipped = '' + run_count = 0 + skipped_count = 0 + if out: + m = re.search(r"Ran (\d+) tests in", out) + if m: + result = out[m.start():m.end()] + status = status.replace('took', result) + run_count = int(out[m.start(1):m.end(1)]) + + m = re.search(r' \(skipped=(\d+)\)$', out) + if m: + skipped = _colorize('skipped', out[m.start():m.end()]) + skipped_count = int(out[m.start(1):m.end(1)]) + status = status % (took, skipped) # pylint:disable=consider-using-augmented-assign + if took > 10: + status = _colorize('slow-test', status) + return status, run_count, skipped_count + + +def run(command, **kwargs): # pylint:disable=too-many-locals + """ + Execute *command*, returning a `RunResult`. + + This blocks until *command* finishes or until it times out. + """ + buffer_output = kwargs.pop('buffer_output', BUFFER_OUTPUT) + quiet = kwargs.pop('quiet', QUIET) + verbose = not quiet + nested = kwargs.pop('nested', False) + allowed_return_codes = kwargs.pop('allowed_return_codes', ()) + if buffer_output: + assert 'stdout' not in kwargs and 'stderr' not in kwargs, kwargs + kwargs['stderr'] = subprocess.STDOUT + kwargs['stdout'] = subprocess.PIPE + popen = start(command, quiet=quiet, **kwargs) + name = popen.name + + try: + time_start = perf_counter() + out, err = popen.communicate() + duration = perf_counter() - time_start + if popen.was_killed or popen.poll() is None: + result = 'TIMEOUT' + else: + result = popen.poll() + finally: + kill(popen) + assert popen.timer is None + + # We don't want to treat return codes that are allowed as failures, + # but we do want to log those specially. That's why we retain the distinction + # between ``failed`` and ``result`` (failed takes the allowed codes into account). + failed = bool(result) and result not in allowed_return_codes + if out: + out = out.strip() + out = out if isinstance(out, str) else out.decode('utf-8', 'ignore') + if out and (failed or verbose or _should_show_warning_output(out)): + out = ' ' + out.replace('\n', '\n ') + out = out.rstrip() + out += '\n' + log('| %s\n%s', name, out) + status, run_count, skipped_count = _find_test_status(duration, out) + if result: + log('! %s [code %s] %s', name, result, status, + color='error' if failed else 'suboptimal-behaviour') + elif not nested: + log('- %s %s', name, status) + + # For everything outside this function, we need to pretend that + # allowed codes are actually successes. + return RunResult( + command, kwargs, + 0 if result in allowed_return_codes else result, + output=out, error=err, + name=name, + run_count=run_count, + skipped_count=skipped_count, + run_duration=duration, + ) + + +class NoSetupPyFound(Exception): + "Raised by find_setup_py_above" + +def find_setup_py_above(a_file): + "Return the directory containing setup.py somewhere above *a_file*" + root = os.path.dirname(os.path.abspath(a_file)) + while not os.path.exists(os.path.join(root, 'setup.py')): + prev, root = root, os.path.dirname(root) + if root == prev: + # Let's avoid infinite loops at root + raise NoSetupPyFound('could not find my setup.py above %r' % (a_file,)) + return root + +def search_for_setup_py(a_file=None, a_module_name=None, a_class=None, climb_cwd=True): + if a_file is not None: + try: + return find_setup_py_above(a_file) + except NoSetupPyFound: + pass + + if a_class is not None: + try: + return find_setup_py_above(sys.modules[a_class.__module__].__file__) + except NoSetupPyFound: + pass + + if a_module_name is not None: + try: + return find_setup_py_above(sys.modules[a_module_name].__file__) + except NoSetupPyFound: + pass + + if climb_cwd: + return find_setup_py_above("./dne") + + raise NoSetupPyFound("After checking %r" % (locals(),)) + +def _version_dir_components(): + directory = '%s.%s' % sys.version_info[:2] + full_directory = '%s.%s.%s' % sys.version_info[:3] + if hasattr(sys, 'pypy_version_info'): + directory += 'pypy' + full_directory += 'pypy' + + return directory, full_directory + +def find_stdlib_tests(): + """ + Return a sequence of directories that could contain + stdlib tests for the running version of Python. + + The most specific tests are at the end of the sequence. + + No checks are performed on existence of the directories. + """ + setup_py = search_for_setup_py(a_file=__file__) + greentest = os.path.join(setup_py, 'src', 'greentest') + + + directory, full_directory = _version_dir_components() + + directory = '%s.%s' % sys.version_info[:2] + full_directory = '%s.%s.%s' % sys.version_info[:3] + if hasattr(sys, 'pypy_version_info'): + directory += 'pypy' + full_directory += 'pypy' + + directory = os.path.join(greentest, directory) + full_directory = os.path.join(greentest, full_directory) + + return directory, full_directory + +def absolute_pythonpath(): + """ + Return the PYTHONPATH environment variable (if set) with each + entry being an absolute path. If not set, returns None. + """ + if 'PYTHONPATH' not in os.environ: + return None + + path = os.environ['PYTHONPATH'] + path = [os.path.abspath(p) for p in path.split(os.path.pathsep)] + return os.path.pathsep.join(path) + +class ExampleMixin(object): + """ + Something that uses the ``examples/`` directory + from the root of the gevent distribution. + + The `cwd` property is set to the root of the gevent distribution. + """ + #: Arguments to pass to the example file. + example_args = [] + before_delay = 3 + after_delay = 0.5 + #: Path of the example Python file, relative to `cwd` + example = None # subclasses define this to be the path to the server.py + #: Keyword arguments to pass to the start or run method. + start_kwargs = None + + def find_setup_py(self): + "Return the directory containing setup.py" + return search_for_setup_py( + a_file=__file__, + a_class=type(self) + ) + + @property + def cwd(self): + try: + root = self.find_setup_py() + except NoSetupPyFound as e: + raise unittest.SkipTest("Unable to locate file/dir to run: %s" % (e,)) + return os.path.join(root, 'examples') + + @property + def setenv(self): + """ + Returns a dictionary of environment variables to set for the + child in addition to (or replacing) the ones already in the + environment. + + Since the child is run in `cwd`, relative paths in ``PYTHONPATH`` + need to be converted to absolute paths. + """ + abs_pythonpath = absolute_pythonpath() + return {'PYTHONPATH': abs_pythonpath} if abs_pythonpath else None + + def _start(self, meth): + if getattr(self, 'args', None): + raise AssertionError("Invalid test", self, self.args) + if getattr(self, 'server', None): + raise AssertionError("Invalid test", self, self.server) + + try: + # These could be or are properties that can raise + server = self.example + server_dir = self.cwd + except NoSetupPyFound as e: + raise unittest.SkipTest("Unable to locate file/dir to run: %s" % (e,)) + + kwargs = self.start_kwargs or {} + setenv = self.setenv + if setenv: + if 'setenv' in kwargs: + kwargs['setenv'].update(setenv) + else: + kwargs['setenv'] = setenv + return meth( + [sys.executable, '-W', 'ignore', '-u', server] + self.example_args, + cwd=server_dir, + **kwargs + ) + + def start_example(self): + return self._start(meth=start) + + def run_example(self):# run() is a unittest method. + return self._start(meth=run) + + +class TestServer(ExampleMixin, + unittest.TestCase): + popen = None + + def running_server(self): + from contextlib import contextmanager + + @contextmanager + def running_server(): + with self.start_example() as popen: + self.popen = popen + self.before() + yield + self.after() + return running_server() + + def test(self): + with self.running_server(): + self._run_all_tests() + + def before(self): + if self.before_delay is not None: + sleep(self.before_delay) + self.assertIsNone(self.popen.poll(), + '%s died with code %s' % ( + self.example, self.popen.poll(), + )) + + def after(self): + if self.after_delay is not None: + sleep(self.after_delay) + self.assertIsNone(self.popen.poll(), + '%s died with code %s' % ( + self.example, self.popen.poll(), + )) + + def _run_all_tests(self): + ran = False + for method in sorted(dir(self)): + if method.startswith('_test'): + function = getattr(self, method) + if callable(function): + function() + ran = True + assert ran + + +class alarm(threading.Thread): + # can't use signal.alarm because of Windows + + def __init__(self, timeout): + threading.Thread.__init__(self) + self.daemon = True + self.timeout = timeout + self.start() + + def run(self): + sleep(self.timeout) + sys.stderr.write('Timeout.\n') + os._exit(5) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/2_7_keycert.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/2_7_keycert.pem new file mode 100644 index 0000000000000000000000000000000000000000..d75a2aa241153f79365006d26b00a1cf726579d8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/2_7_keycert.pem @@ -0,0 +1,81 @@ +-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQChqfmG6uOG95Jb +7uRi6yxohJ8GOR3gi39yX6JB+Xdukvqxy2/vsjH1+CF1i8jKZZO0hJLGT+/GmKIc +1c0XUEjVoQvCNQHIaDTXiUXOGXfkQNKR0vtJH5ZOZn/tvYAKPniYPmHuF3TpAB6H +ouLpyIC55SXdK7pTEbmU7J1aBjugn3O56cu6FzjU1j/0QVUVGloxApLvv57bmINa +X9ygKsh/ug0lhV1RwYLJ9UX57m95FIlcofa98tCuoKi++G+sWsjopDXVmsiTbjZf +s72kcDUTRYKNZbRFRRETORdOVRHxlAIPEn4QFYn/3wVSNFvfeY0j8RI5YcPLU66B +atun6HU+YAs6z8Qc8S1EMElJdoyVeLCqLA07btICzKq2I16TZAOWVng2P7NOtibA +eCzDAxAxJ3Oby+BVikKcu8WmJLxGvRvaPljdD76xjPB5NK6O0J62C3uU3EWhPODX +9H5l/WF+aNRqSccgs0Umddj33N+b/mTJnHn1GpanThrv1UfOFGKfxjemwESz66d1 +iqD7iXvTxt7yZeU7LIMRgDqhVe6zoBpJEeWl9YYyfGPwgIOhwzNVZ5WkzQARs7si +3j3Wkmyca7hEN8qq8DkLWNf1PTcIwo/239wKRbyW3Z+U4IGRrVMdeSoC2JpRAx/e +EXTjuUePQlHCvwW9iiY7jTjDfbIvpwIDAQABAoICAC3CJMTRe3FaZezro210T2+O +Ck0CobhLA9nlw9GUwP9lTtxATwCzmXybrSzOUhknwzUXSUwkmCPIVCqBQbnVmagO +G3vu8QA+rqZLTpzVjJ/o0TFBXKsH681pKdCrELDVmeDN135C2W6SABI4Qq4VeIol +mCAQHn8gxzyl9Kvkk8AVIfZ/fJDBve5Qbm2+iEye1uSEa/68aEST2Kod9B7JvVKZ +4Nq78vwPH+v2JsZlfNvyuiakGWkOb47eHqVfQIyybaebwzkgxKEmUvGnuIfw0rUP +ubI4FVx9/iVIxZYAckHEuQh3HYOD9TmdcK4h79dDWnXP6G6hg3/rwbsT+fR+0aBQ +9rkKnA4uToGikYmplixAQ/jDBwMs3VQqenO+YBIsC4HEZ0fJUbs+l4LEnuUJxYcR +UlAvnVQXa1WGne3Yzb2xONWeiocKfhcdJ2JuQo00UR74+2Qonxn/WpimvlLCBDgI +uKxHCSWOgv5yPpU2kwTPIjORXcy/y2G9K2bnsQCzznPRDyNkZmavQxxG6greFcrO +/0yhRPuBgxKBRvXPO+F5fybKFlU9IPLFehV60jLUybBejab/lMJyxdkh9UMu2Xqy +FVsRGazJt6T6AGp6TFEEcFUQw7qXNhVo9S7zGGaJFJdYc+Vx8QJRoCe8EAYVH7Mp +b/eYGhHaKg6iG7QCjPPxAoIBAQDN54wtuDqpAA+4PmqhiEhQKhabNqAoVmAWUxnJ +Db4Zzvkkc3Fo/Yg0HnQVaT0KmkcxY7397lTdtiwNkWPgJ0f6+g7L4K7PA7xh/q84 +IoXFGvYWwVdiVXLR1l06jorpA20clnba6CsbezwcllTq4bWvNnrAcM8l1YrAlRnV +qqqbPL78Rnba4C8q+VFy8r0d9OGnbvFcV7VWJjhr0a3aZbHQ67jPinNiUWvBVFFx +yGrqPMjkeHyiTLMhqQpaSHH67S88rj0g9RKexBaSUrl18QO7xnQHHSCcFWMQOiSN +shNvFri48dnU+Ms6ZLc3MBHbTK6uzP8xJCVnmsz/MWPGkQZFAoIBAQDI/vj/3/y/ +EpIawyHN7PQAMoto4AQF6sVasrgGd1tRsJnGKrCugH9gILvyke3L7qg0JTV3bDJY +e8+vH1vC3NV7PsOlCFjMtRWG0lRbCh/b7Qe3pCvPu4mbFhJgMT/mz+vbl5zvcdgX +kvne+St/267NKnY5gHBDhqitBwkZwNlTWJ0zVmTecKXn/KwjS9lX1qU3HiT3UFkd +5Y5Nt5lj1IOK/6NCXkxVkgOc4Zjcxx138Cg03VJhIiHTusRq6z9iTSTDubhkaSbi +2nadptFBiQtkVhAJ5G53U7pl/pIhhiJy901bu/v/wrIMJ2l6hiZIcLrbg6VGXxjV +5dB7LDEtKoL7AoIBAQC8+ffA+mX0N9c1nSuWh5L+6DIJUHBbtTLJKonu6gsAeuJU +3xNGbfK1CwI1qHnaolAW91knlrcTKaBy726ACu1YXmp4GgW2f9JFCk/csGqfxaf4 +qIg/+va/ugOku7CoPXnGFB6PuSffOBKqlhrn3DI41kKBHsgwDDYlnHKylMmyYmVS ++oUZS0pfIaXsXvbNaLQ2TG9+9gy7Pabo5e+vE0jI25+p84MEyH+iV3XMfUoLI7Cp +aB/TgZuimBelVvotd8Sz56K4/dSSHJwuvXfz1Dk9/Nz+rnAAcOyTtxlXZwnJGkx9 +iZMIkTNMq6UwJJEu+ckVK5ZHjso5tWzSBo1xcCcVAoIBAQCPL0x1A7zK5VDd7cqE +J1w/U8KKiKN1D6VeElkUiiysyjERwdGxzmpvMYKSsDCGCdMbqrInDBXlgPYXnDBD +ZgxSywiW5ZZU5l+advWPEWxWwMmxoitvxfqmV5fpnMwYAmDUQ3KSBTjaumJ03G6H +nBkvoSMtnXjcMe6xrIRoK0Dmpgb+znn3GKqn1BFQ57TCZW+3DytoX33M1X6FkNie +DINVHv3Pxtt8ThNyzCeYh+RPT+9kkZIhDi6o5bENNd8miSw6nnBkX6BLFTRQ5MjH +dfh+luzAD1I+gZAVHsA9T4/09IXQZt+DeNBb5iu3FB/rlRsYS/UOZ6qKnjfhtz6l +HVbHAoIBAFjNY/UPJDxQ/uG+rMU0nrmSBRGdgBvQkcefjWX/LIZV3MjNilUQ+B2a +lXz5AHGmHRnnwQsBVfN8rf4qQLln8l34Kgm7+cIFavgfg2oqVbNyNgezSlUmRq0J +Ttf3xYJtRgRUx8F+BcgJXMqlNGTMQJY8wawM/ATkwkbmSwGOKe04sBeIkwEycMId +BupvfN5lxDrKqJVPSl1t5Rh4us95CNh22/c5Tq5rsynl02ZB4swlcsVTdv8FSGmM +QVf/MkWXGN/x4lHJhKyklHMGv15GGvys1nlPTstMfUYs55ioWRW46TXQ8vOyzzpg +67xzBKYFEde+hgYk7X1Xeqj8A6bsqro= +-----END PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIIFCzCCAvOgAwIBAgIUePnEKFfhxpt3oypt6nTicAGTFJowDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIxMDcwODExMzQzNVoYDzIxMjEw +NjE0MTEzNDM1WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQChqfmG6uOG95Jb7uRi6yxohJ8GOR3gi39yX6JB+Xdu +kvqxy2/vsjH1+CF1i8jKZZO0hJLGT+/GmKIc1c0XUEjVoQvCNQHIaDTXiUXOGXfk +QNKR0vtJH5ZOZn/tvYAKPniYPmHuF3TpAB6HouLpyIC55SXdK7pTEbmU7J1aBjug +n3O56cu6FzjU1j/0QVUVGloxApLvv57bmINaX9ygKsh/ug0lhV1RwYLJ9UX57m95 +FIlcofa98tCuoKi++G+sWsjopDXVmsiTbjZfs72kcDUTRYKNZbRFRRETORdOVRHx +lAIPEn4QFYn/3wVSNFvfeY0j8RI5YcPLU66Batun6HU+YAs6z8Qc8S1EMElJdoyV +eLCqLA07btICzKq2I16TZAOWVng2P7NOtibAeCzDAxAxJ3Oby+BVikKcu8WmJLxG +vRvaPljdD76xjPB5NK6O0J62C3uU3EWhPODX9H5l/WF+aNRqSccgs0Umddj33N+b +/mTJnHn1GpanThrv1UfOFGKfxjemwESz66d1iqD7iXvTxt7yZeU7LIMRgDqhVe6z +oBpJEeWl9YYyfGPwgIOhwzNVZ5WkzQARs7si3j3Wkmyca7hEN8qq8DkLWNf1PTcI +wo/239wKRbyW3Z+U4IGRrVMdeSoC2JpRAx/eEXTjuUePQlHCvwW9iiY7jTjDfbIv +pwIDAQABo1MwUTAdBgNVHQ4EFgQUTUfShFbaXGMwrWEAkm05sXFH/x4wHwYDVR0j +BBgwFoAUTUfShFbaXGMwrWEAkm05sXFH/x4wDwYDVR0TAQH/BAUwAwEB/zANBgkq +hkiG9w0BAQsFAAOCAgEAe65ORDx0NDxTo1q6EY221KS3vEezUNBdZNaeOQsQeUAY +lEO5iZ+2QLIVlWC5UtvISK96FU2CX0ucgAGfHS2ZB7o8i95fbjG2qrWC+VUH4V/6 +jse9jlfGlYGkPuU5onNIDGcZ7gay3n0prCDiguAmCzV419GnGDWgSSgyVNCp/0tx +b7pR5cVr0kZ5bTZjiysEEprkG2ofAlXzj09VGtTfM8gQvCz9Puj7pGzw2iaIEQVk +hSGjoRWlI5x6+o16JOTHXzv9cYRUfDX6tjw3nQJIeMipuUkR8pkHUFjG3EeJEtO3 +X/GO0G8rwUPaZiskGPiMZj7XqoVclnYL7JtntwUHR/dU5A/EhDfhgEfTXTqT78Oe +cKri+VJE+G/hYxbP0FNYaDtqIwJcX1tsy4HOpKVBncc+K/PvXElVsyQET/+uwH7p +Wm5ymndnuLoiQrWIA4nJC6rVwR4GPijuN0NCKcVdE+8jlOCBs3VBJTWKuu0J80RP +71iZy03AoK1YY4+nHglmE9HetAgSsbGh2fWC7DUS/4JzLSzOBeb+nn74zfmIfMU+ +qUArFXvVGAtjmZZ/63cWzXDMZsp1BZ+O5dx6Gi2QtjgGYhh6DhW7ocQYXDkAeN/O +K1Yzwq/G4AEQA0k0/1I+F0Rdlo41+7tOp+LMCOoZXqUzhM0ZQ2sf3QclubxLX9U= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/__main__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e43891fb1110494e4f78f3b0f23d9d226c2ab559 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/__main__.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python +from __future__ import print_function, absolute_import, division + +if __name__ == '__main__': + from gevent.testing import testrunner + testrunner.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_blocks_at_top_level.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_blocks_at_top_level.py new file mode 100644 index 0000000000000000000000000000000000000000..9f907aa62b5175a33a03f7264664470daccee6fa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_blocks_at_top_level.py @@ -0,0 +1,3 @@ +from gevent import sleep +sleep(0.01) +x = "done" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_import_patch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_import_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..aa85abd62b81ebd7bd7208d241433fa481361298 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_import_patch.py @@ -0,0 +1 @@ +__import__('_import_patch') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_patch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7cc3c3e04a99765ea7b6401dc930337bb235ff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_patch.py @@ -0,0 +1,2 @@ +import gevent.monkey +gevent.monkey.patch_all() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_wait.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_wait.py new file mode 100644 index 0000000000000000000000000000000000000000..80850a54406db3636f1319fe9b80e8b8562394fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_import_wait.py @@ -0,0 +1,26 @@ +# test__import_wait.py calls this via an import statement, +# so all of this is happening with import locks held (especially on py2) +import gevent + + +def fn2(): + return 2 + + +# A blocking function doesn't raise LoopExit +def fn(): + return gevent.wait([gevent.spawn(fn2), gevent.spawn(fn2)]) + +gevent.spawn(fn).get() + + +# Marshalling the traceback across greenlets doesn't +# raise LoopExit +def raise_name_error(): + raise NameError("ThisIsExpected") + +try: + gevent.spawn(raise_name_error).get() + raise AssertionError("Should fail") +except NameError as e: + x = e diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_at_top_level.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_at_top_level.py new file mode 100644 index 0000000000000000000000000000000000000000..d11f66b6e57d86536d975eddb5e86c3f9b414542 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_at_top_level.py @@ -0,0 +1,2 @@ +# We simply import a stdlib module +__import__('netrc') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_imports_at_top_level.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_imports_at_top_level.py new file mode 100644 index 0000000000000000000000000000000000000000..00bbf513509a4986552e5f81259dc9428bc5e194 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/_imports_imports_at_top_level.py @@ -0,0 +1,13 @@ +import gevent + +# For reproducing #728: We spawn a greenlet at import time, +# that itself wants to import, and wait on it at import time. +# If we're the only greenlet running, and locks aren't granular +# enough, this results in a LoopExit (and also a lock deadlock) + + +def f(): + __import__('_imports_at_top_level') + +g = gevent.spawn(f) +g.get() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badcert.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badcert.pem new file mode 100644 index 0000000000000000000000000000000000000000..c4191460f9e5e67b74a0cb8882b90e6751b065e6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badcert.pem @@ -0,0 +1,36 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L +opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH +fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB +AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU +D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA +IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM +oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0 +ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/ +loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j +oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA +z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq +ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV +q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU= +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +Just bad cert data +-----END CERTIFICATE----- +-----BEGIN RSA PRIVATE KEY----- +MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L +opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH +fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB +AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU +D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA +IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM +oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0 +ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/ +loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j +oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA +z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq +ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV +q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU= +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +Just bad cert data +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badkey.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badkey.pem new file mode 100644 index 0000000000000000000000000000000000000000..1c8a9557193c31135e93dc199ad2ede2ede565e0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/badkey.pem @@ -0,0 +1,40 @@ +-----BEGIN RSA PRIVATE KEY----- +Bad Key, though the cert should be OK +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD +VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x +IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT +U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1 +NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl +bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m +dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj +aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh +m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8 +M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn +fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC +AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb +08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx +CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/ +iHkC6gGdBJhogs4= +-----END CERTIFICATE----- +-----BEGIN RSA PRIVATE KEY----- +Bad Key, though the cert should be OK +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD +VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x +IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT +U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1 +NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl +bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m +dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj +aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh +m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8 +M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn +fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC +AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb +08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx +CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/ +iHkC6gGdBJhogs4= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/getaddrinfo_module.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/getaddrinfo_module.py new file mode 100644 index 0000000000000000000000000000000000000000..75a25dff9764642e2bcdc7ce472dff42c9b2b03d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/getaddrinfo_module.py @@ -0,0 +1,4 @@ +import socket +import gevent.socket as gevent_socket + +gevent_socket.getaddrinfo(u'gevent.org', None, socket.AF_INET) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/hosts_file.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/hosts_file.txt new file mode 100644 index 0000000000000000000000000000000000000000..a33da688644030e689b1fe03dbc6a641b235ec58 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/hosts_file.txt @@ -0,0 +1,10351 @@ +## +# Host Database +# +# localhost is used to configure the loopback interface +# when the system is booting. Do not change this entry. +## +127.0.0.1 localhost Localhost localhost.localdomain testsite.mc.com mathcounts.mc.com platform.osu.edu + +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +172.178.0.51 excelsior excelsior.example.com +162.168.8.27 memoryprime.local memoryprime +122.168.9.64 isy.local isy + + +192.168.1.172 drivefoo.local + +172.168.15.95 aragefoo.local +172.168.15.105 livgfoo.local +172.168.16.109 upsirsfoo.local +172.168.15.140 bacorthfoo.local +172.168.15.142 bacouthfoo.local +172.168.16.144 drisfoo.local +172.168.15.152 nghborfoo.local +172.168.15.154 fntfoo.local +172.168.18.151 as.local + +# Internals +146.120.241.22 ds3 +146.120.241.23 ds4 +146.120.241.21 ds2 +146.120.241.20 ds1 + + +# Not blocked by Mar 18 2013 +0.0.0.0 h.ppjol.com +0.0.0.0 s.ppjol.net +0.0.0.0 yayfollowers.com +0.0.0.0 pagead2.googlesyndication.com +0.0.0.0 www.googletagservices.com +0.0.0.0 cdn.teads.tv +0.0.0.0 js.moatads.com +0.0.0.0 cdn2.teads.tv + + +# This hosts file is brought to you by Dan Pollock and can be found at +# http://someonewhocares.org/hosts/zero/ + +# +# For example, to block unpleasant pages, try: +0.0.0.0 goatse.cx # More information on sites such as +0.0.0.0 www.goatse.cx # these can be found in this article +0.0.0.0 oralse.cx # en.wikipedia.org/wiki/List_of_shock_sites +0.0.0.0 www.oralse.cx +0.0.0.0 goatse.ca +0.0.0.0 www.goatse.ca +0.0.0.0 oralse.ca +0.0.0.0 www.oralse.ca +0.0.0.0 goat.cx +0.0.0.0 www.goat.cx +0.0.0.0 goatse.ru +0.0.0.0 www.goatse.ru + +0.0.0.0 1girl1pitcher.com +0.0.0.0 1girl1pitcher.org +0.0.0.0 1guy1cock.com +0.0.0.0 1man1jar.org +0.0.0.0 1man2needles.com +0.0.0.0 1priest1nun.com +0.0.0.0 2girls1cup.com +0.0.0.0 2girls1cup-free.com +0.0.0.0 2girls1cup.nl +0.0.0.0 2girls1cup.ws +0.0.0.0 2girls1finger.com +0.0.0.0 2girls1finger.org +0.0.0.0 2guys1stump.org +0.0.0.0 3guys1hammer.ws +0.0.0.0 4girlsfingerpaint.com +0.0.0.0 4girlsfingerpaint.org +0.0.0.0 bagslap.com +0.0.0.0 ballsack.org +0.0.0.0 bluewaffle.biz +0.0.0.0 bottleguy.com +0.0.0.0 bowlgirl.com +0.0.0.0 cadaver.org +0.0.0.0 clownsong.com +0.0.0.0 copyright-reform.info +0.0.0.0 cshacks.partycat.us +0.0.0.0 cyberscat.com +0.0.0.0 dadparty.com +0.0.0.0 detroithardcore.com +0.0.0.0 donotwatch.org +0.0.0.0 dontwatch.us +0.0.0.0 eelsoup.net +0.0.0.0 fruitlauncher.com +0.0.0.0 fuck.org +0.0.0.0 funnelchair.com +0.0.0.0 goatse.bz +0.0.0.0 goatsegirl.org +0.0.0.0 goatse.ru +0.0.0.0 hai2u.com +0.0.0.0 homewares.org +0.0.0.0 howtotroll.org +0.0.0.0 japscat.org +0.0.0.0 jiztini.com +0.0.0.0 junecleeland.com +0.0.0.0 kids-in-sandbox.com +0.0.0.0 kidsinsandbox.info +0.0.0.0 lemonparty.biz +0.0.0.0 lemonparty.org +0.0.0.0 lolhello.com +0.0.0.0 loltrain.com +0.0.0.0 meatspin.biz +0.0.0.0 meatspin.com +0.0.0.0 merryholidays.org +0.0.0.0 milkfountain.com +0.0.0.0 mudfall.com +0.0.0.0 mudmonster.org +0.0.0.0 nimp.org +0.0.0.0 nobrain.dk +0.0.0.0 nutabuse.com +0.0.0.0 octopusgirl.com +0.0.0.0 on.nimp.org +0.0.0.0 painolympics.info +0.0.0.0 phonejapan.com +0.0.0.0 pressurespot.com +0.0.0.0 prolapseman.com +0.0.0.0 scrollbelow.com +0.0.0.0 selfpwn.org +0.0.0.0 sexitnow.com +0.0.0.0 sourmath.com +0.0.0.0 suckdude.com +0.0.0.0 thatsjustgay.com +0.0.0.0 thatsphucked.com +0.0.0.0 thehomo.org +0.0.0.0 themacuser.org +0.0.0.0 thepounder.com +0.0.0.0 tubgirl.me +0.0.0.0 tubgirl.org +0.0.0.0 turdgasm.com +0.0.0.0 vomitgirl.org +0.0.0.0 walkthedinosaur.com +0.0.0.0 whipcrack.org +0.0.0.0 wormgush.com +0.0.0.0 www.1girl1pitcher.org +0.0.0.0 www.1guy1cock.com +0.0.0.0 www.1man1jar.org +0.0.0.0 www.1man2needles.com +0.0.0.0 www.1priest1nun.com +0.0.0.0 www.2girls1cup-free.com +0.0.0.0 www.2girls1cup.nl +0.0.0.0 www.2girls1cup.ws +0.0.0.0 www.2girls1finger.org +0.0.0.0 www.2guys1stump.org +0.0.0.0 www.3guys1hammer.ws +0.0.0.0 www.4girlsfingerpaint.org +0.0.0.0 www.bagslap.com +0.0.0.0 www.ballsack.org +0.0.0.0 www.bluewaffle.biz +0.0.0.0 www.bottleguy.com +0.0.0.0 www.bowlgirl.com +0.0.0.0 www.cadaver.org +0.0.0.0 www.clownsong.com +0.0.0.0 www.copyright-reform.info +0.0.0.0 www.cshacks.partycat.us +0.0.0.0 www.cyberscat.com +0.0.0.0 www.dadparty.com +0.0.0.0 www.detroithardcore.com +0.0.0.0 www.donotwatch.org +0.0.0.0 www.dontwatch.us +0.0.0.0 www.eelsoup.net +0.0.0.0 www.fruitlauncher.com +0.0.0.0 www.fuck.org +0.0.0.0 www.funnelchair.com +0.0.0.0 www.goatse.bz +0.0.0.0 www.goatsegirl.org +0.0.0.0 www.goatse.ru +0.0.0.0 www.hai2u.com +0.0.0.0 www.homewares.org +0.0.0.0 www.howtotroll.org +0.0.0.0 www.japscat.org +0.0.0.0 www.jiztini.com +0.0.0.0 www.junecleeland.com +0.0.0.0 www.kids-in-sandbox.com +0.0.0.0 www.kidsinsandbox.info +0.0.0.0 www.lemonparty.biz +0.0.0.0 www.lemonparty.org +0.0.0.0 www.lolhello.com +0.0.0.0 www.loltrain.com +0.0.0.0 www.meatspin.biz +0.0.0.0 www.meatspin.com +0.0.0.0 www.merryholidays.org +0.0.0.0 www.milkfountain.com +0.0.0.0 www.mudfall.com +0.0.0.0 www.mudmonster.org +0.0.0.0 www.nimp.org +0.0.0.0 www.nobrain.dk +0.0.0.0 www.nutabuse.com +0.0.0.0 www.octopusgirl.com +0.0.0.0 www.on.nimp.org +0.0.0.0 www.painolympics.info +0.0.0.0 www.phonejapan.com +0.0.0.0 www.pressurespot.com +0.0.0.0 www.prolapseman.com +0.0.0.0 www.punishtube.com +0.0.0.0 www.scrollbelow.com +0.0.0.0 www.selfpwn.org +0.0.0.0 www.sourmath.com +0.0.0.0 www.suckdude.com +0.0.0.0 www.thatsjustgay.com +0.0.0.0 www.thatsphucked.com +0.0.0.0 www.theexgirlfriends.com +0.0.0.0 www.thehomo.org +0.0.0.0 www.themacuser.org +0.0.0.0 www.thepounder.com +0.0.0.0 www.tubgirl.me +0.0.0.0 www.tubgirl.org +0.0.0.0 www.turdgasm.com +0.0.0.0 www.vomitgirl.org +0.0.0.0 www.walkthedinosaur.com +0.0.0.0 www.whipcrack.org +0.0.0.0 www.wormgush.com +0.0.0.0 www.xvideoslive.com +0.0.0.0 www.y8.com +0.0.0.0 www.youaresogay.com +0.0.0.0 www.ypmate.com +0.0.0.0 www.zentastic.com +0.0.0.0 youaresogay.com +0.0.0.0 zentastic.com +# + +0.0.0.0 ads234.com +0.0.0.0 ads345.com +0.0.0.0 www.ads234.com +0.0.0.0 www.ads345.com +# + + +# + +# +0.0.0.0 auto.search.msn.com # Microsoft uses this server to redirect + # mistyped URLs to search engines. They + # log all such errors. +0.0.0.0 sitefinder.verisign.com # Verisign has joined the game +0.0.0.0 sitefinder-idn.verisign.com # of trying to hijack mistyped + # URLs to their site. + # May break iOS Game Center. + +0.0.0.0 s0.2mdn.net # This may interfere with some streaming + # video on sites such as cbc.ca +0.0.0.0 ad.doubleclick.net # This may interefere with www.sears.com + # and potentially other sites. +0.0.0.0 media.fastclick.net # Likewise, this may interfere with some +0.0.0.0 cdn.fastclick.net # sites. +0.0.0.0 ebay.doubleclick.net # may interfere with ebay +#0.0.0.0 google-analytics.com # breaks some sites +#0.0.0.0 ssl.google-analytics.com +#0.0.0.0 www.google-analytics.l.google.com +0.0.0.0 stat.livejournal.com # There are reports that this may mess + # up CSS on livejournal +0.0.0.0 stats.surfaid.ihost.com # This has been known cause + # problems with NPR.org +0.0.0.0 www.google-analytics.com # breaks some sites +0.0.0.0 ads.imeem.com # Seems to interfere with the functioning of imeem.com +# + +0.0.0.0 006.free-counter.co.uk +0.0.0.0 006.freecounters.co.uk +0.0.0.0 06272002-dbase.hitcountz.net # Web bugs in spam +0.0.0.0 123counter.mycomputer.com +0.0.0.0 123counter.superstats.com +0.0.0.0 1ca.cqcounter.com +0.0.0.0 1uk.cqcounter.com +0.0.0.0 1us.cqcounter.com +0.0.0.0 1xxx.cqcounter.com +0.0.0.0 2001-007.com +0.0.0.0 3bc3fd26-91cf-46b2-8ec6-b1559ada0079.statcamp.net +0.0.0.0 3ps.go.com +0.0.0.0 4-counter.com +0.0.0.0 a796faee-7163-4757-a34f-e5b48cada4cb.statcamp.net +0.0.0.0 abscbn.spinbox.net +0.0.0.0 activity.serving-sys.com #eyeblaster.com +0.0.0.0 adadvisor.net +0.0.0.0 adclient.rottentomatoes.com +0.0.0.0 adcodes.aim4media.com +0.0.0.0 adcounter.globeandmail.com +0.0.0.0 adcounter.theglobeandmail.com +0.0.0.0 addfreestats.com +0.0.0.0 ademails.com +0.0.0.0 adlog.com.com # Used by Ziff Davis to serve + # ads and track users across + # the com.com family of sites +0.0.0.0 ad-logics.com +0.0.0.0 admanmail.com +0.0.0.0 adopt.specificclick.net +0.0.0.0 ads.tiscali.com +0.0.0.0 ads.tiscali.it +0.0.0.0 adult.foxcounter.com +0.0.0.0 affiliate.ab1trk.com +0.0.0.0 affiliate.irotracker.com +0.0.0.0 ai062.insightexpress.com +0.0.0.0 ai078.insightexpressai.com +0.0.0.0 ai087.insightexpress.com +0.0.0.0 ai113.insightexpressai.com +0.0.0.0 ai125.insightexpressai.com +0.0.0.0 alpha.easy-hit-counters.com +0.0.0.0 amateur.xxxcounter.com +0.0.0.0 amer.hops.glbdns.microsoft.com +0.0.0.0 amer.rel.msn.com +0.0.0.0 analytics.msnbc.msn.com +0.0.0.0 analytics.prx.org +0.0.0.0 anm.intelli-direct.com +0.0.0.0 ant.conversive.nl +0.0.0.0 apac.rel.msn.com +0.0.0.0 api.bizographics.com +0.0.0.0 apprep.smartscreen.microsoft.com +0.0.0.0 app.yesware.com +0.0.0.0 arbo.hit.gemius.pl +0.0.0.0 au052.insightexpress.com +0.0.0.0 auspice.augur.io +0.0.0.0 au.track.decideinteractive.com +0.0.0.0 a.visualrevenue.com +0.0.0.0 banner.0catch.com +0.0.0.0 banners.webcounter.com +0.0.0.0 beacon-1.newrelic.com +0.0.0.0 beacon.scorecardresearch.com +0.0.0.0 beacons.hottraffic.nl +0.0.0.0 be.sitestat.com +0.0.0.0 best-search.cc #spyware +0.0.0.0 beta.easy-hit-counter.com +0.0.0.0 beta.easy-hit-counters.com +0.0.0.0 beta.easyhitcounters.com +0.0.0.0 bilbo.counted.com +0.0.0.0 bin.clearspring.com +0.0.0.0 birta.stats.is +0.0.0.0 bluekai.com +0.0.0.0 bluestreak.com +0.0.0.0 bookproplus.com +0.0.0.0 broadcastpc.tv +0.0.0.0 report.broadcastpc.tv +0.0.0.0 www.broadcastpc.tv +0.0.0.0 bserver.blick.com +0.0.0.0 bstats.adbrite.com +0.0.0.0 b.stats.paypal.com +0.0.0.0 by.optimost.com +0.0.0.0 c10.statcounter.com +0.0.0.0 c11.statcounter.com +0.0.0.0 c12.statcounter.com +0.0.0.0 c13.statcounter.com +0.0.0.0 c14.statcounter.com +0.0.0.0 c15.statcounter.com +0.0.0.0 c16.statcounter.com +0.0.0.0 c17.statcounter.com +0.0.0.0 c1.statcounter.com +0.0.0.0 c1.thecounter.com +0.0.0.0 c1.thecounter.de +0.0.0.0 c1.xxxcounter.com +0.0.0.0 c2.gostats.com +0.0.0.0 c2.thecounter.com +0.0.0.0 c2.thecounter.de +0.0.0.0 c2.xxxcounter.com +0.0.0.0 c3.gostats.com +0.0.0.0 c3.statcounter.com +0.0.0.0 c3.thecounter.com +0.0.0.0 c3.xxxcounter.com +0.0.0.0 c4.myway.com +0.0.0.0 c4.statcounter.com +0.0.0.0 c5.statcounter.com +0.0.0.0 c6.statcounter.com +0.0.0.0 c7.statcounter.com +0.0.0.0 c8.statcounter.com +0.0.0.0 c9.statcounter.com +0.0.0.0 ca.cqcounter.com +0.0.0.0 cashcounter.com +0.0.0.0 cb1.counterbot.com +0.0.0.0 cdn.krxd.net +0.0.0.0 cdn.oggifinogi.com +0.0.0.0 cdn.taboolasyndication.com +0.0.0.0 cdxbin.vulnerap.com +0.0.0.0 cf.addthis.com +0.0.0.0 cgicounter.onlinehome.de +0.0.0.0 cgicounter.puretec.de +0.0.0.0 cgi.hotstat.nl +0.0.0.0 cgi.sexlist.com +0.0.0.0 ci-mpsnare.iovation.com # See http://www.codingthewheel.com/archives/online-gambling-privacy-iesnare +0.0.0.0 citrix.tradedoubler.com +0.0.0.0 cjt1.net +0.0.0.0 click.atdmt.com +0.0.0.0 clickauditor.net +0.0.0.0 click.fivemtn.com +0.0.0.0 click.investopedia.com +0.0.0.0 click.jve.net +0.0.0.0 clickmeter.com +0.0.0.0 click.payserve.com +0.0.0.0 clicks.emarketmakers.com +0.0.0.0 click.silvercash.com +0.0.0.0 clicks.m4n.nl +0.0.0.0 clicks.natwest.com +0.0.0.0 clickspring.net #used by a spyware product called PurityScan +0.0.0.0 clicks.rbs.co.uk +0.0.0.0 clicktrack.onlineemailmarketing.com +0.0.0.0 clicktracks.webmetro.com +0.0.0.0 clit10.sextracker.com +0.0.0.0 clit13.sextracker.com +0.0.0.0 clit15.sextracker.com +0.0.0.0 clit2.sextracker.com +0.0.0.0 clit4.sextracker.com +0.0.0.0 clit6.sextracker.com +0.0.0.0 clit7.sextracker.com +0.0.0.0 clit8.sextracker.com +0.0.0.0 clit9.sextracker.com +0.0.0.0 clk.aboxdeal.com +0.0.0.0 clk.relestar.com +0.0.0.0 cnn.entertainment.printthis.clickability.com +0.0.0.0 cnt.xcounter.com +0.0.0.0 collector.deepmetrix.com +0.0.0.0 collector.newsx.cc +0.0.0.0 connectionlead.com +0.0.0.0 connexity.net +0.0.0.0 cookies.cmpnet.com +0.0.0.0 count.channeladvisor.com +0.0.0.0 counter10.bravenet.com +0.0.0.0 counter10.sextracker.be +0.0.0.0 counter10.sextracker.com +0.0.0.0 counter11.bravenet.com +0.0.0.0 counter11.sextracker.be +0.0.0.0 counter11.sextracker.com +0.0.0.0 counter.123counts.com +0.0.0.0 counter12.bravenet.com +0.0.0.0 counter12.sextracker.be +0.0.0.0 counter12.sextracker.com +0.0.0.0 counter13.bravenet.com +0.0.0.0 counter13.sextracker.be +0.0.0.0 counter13.sextracker.com +0.0.0.0 counter14.bravenet.com +0.0.0.0 counter14.sextracker.be +0.0.0.0 counter14.sextracker.com +0.0.0.0 counter15.bravenet.com +0.0.0.0 counter15.sextracker.be +0.0.0.0 counter15.sextracker.com +0.0.0.0 counter16.bravenet.com +0.0.0.0 counter16.sextracker.be +0.0.0.0 counter16.sextracker.com +0.0.0.0 counter17.bravenet.com +0.0.0.0 counter18.bravenet.com +0.0.0.0 counter19.bravenet.com +0.0.0.0 counter1.bravenet.com +0.0.0.0 counter1.sextracker.be +0.0.0.0 counter1.sextracker.com +0.0.0.0 counter.1stblaze.com +0.0.0.0 counter20.bravenet.com +0.0.0.0 counter21.bravenet.com +0.0.0.0 counter22.bravenet.com +0.0.0.0 counter23.bravenet.com +0.0.0.0 counter24.bravenet.com +0.0.0.0 counter25.bravenet.com +0.0.0.0 counter26.bravenet.com +0.0.0.0 counter27.bravenet.com +0.0.0.0 counter28.bravenet.com +0.0.0.0 counter29.bravenet.com +0.0.0.0 counter2.bravenet.com +0.0.0.0 counter2.freeware.de +0.0.0.0 counter2.hitslink.com +0.0.0.0 counter2.sextracker.be +0.0.0.0 counter2.sextracker.com +0.0.0.0 counter30.bravenet.com +0.0.0.0 counter31.bravenet.com +0.0.0.0 counter32.bravenet.com +0.0.0.0 counter33.bravenet.com +0.0.0.0 counter34.bravenet.com +0.0.0.0 counter35.bravenet.com +0.0.0.0 counter36.bravenet.com +0.0.0.0 counter37.bravenet.com +0.0.0.0 counter38.bravenet.com +0.0.0.0 counter39.bravenet.com +0.0.0.0 counter3.bravenet.com +0.0.0.0 counter3.sextracker.be +0.0.0.0 counter3.sextracker.com +0.0.0.0 counter40.bravenet.com +0.0.0.0 counter41.bravenet.com +0.0.0.0 counter42.bravenet.com +0.0.0.0 counter43.bravenet.com +0.0.0.0 counter44.bravenet.com +0.0.0.0 counter45.bravenet.com +0.0.0.0 counter46.bravenet.com +0.0.0.0 counter47.bravenet.com +0.0.0.0 counter48.bravenet.com +0.0.0.0 counter49.bravenet.com +0.0.0.0 counter4all.dk +0.0.0.0 counter4.bravenet.com +0.0.0.0 counter4.sextracker.be +0.0.0.0 counter4.sextracker.com +0.0.0.0 counter4u.de +0.0.0.0 counter50.bravenet.com +0.0.0.0 counter5.bravenet.com +0.0.0.0 counter5.sextracker.be +0.0.0.0 counter5.sextracker.com +0.0.0.0 counter6.bravenet.com +0.0.0.0 counter6.sextracker.be +0.0.0.0 counter6.sextracker.com +0.0.0.0 counter7.bravenet.com +0.0.0.0 counter7.sextracker.be +0.0.0.0 counter7.sextracker.com +0.0.0.0 counter8.bravenet.com +0.0.0.0 counter8.sextracker.be +0.0.0.0 counter8.sextracker.com +0.0.0.0 counter9.bravenet.com +0.0.0.0 counter9.sextracker.be +0.0.0.0 counter9.sextracker.com +0.0.0.0 counter.aaddzz.com +0.0.0.0 counterad.de +0.0.0.0 counter.adultcheck.com +0.0.0.0 counter.adultrevenueservice.com +0.0.0.0 counter.advancewebhosting.com +0.0.0.0 counter.aport.ru +0.0.0.0 counteraport.spylog.com +0.0.0.0 counter.asexhound.com +0.0.0.0 counter.avp2000.com +0.0.0.0 counter.bizland.com +0.0.0.0 counter.bloke.com +0.0.0.0 counterbot.com +0.0.0.0 counter.clubnet.ro +0.0.0.0 counter.cnw.cz +0.0.0.0 countercrazy.com +0.0.0.0 counter.credo.ru +0.0.0.0 counter.cz +0.0.0.0 counter.digits.com +0.0.0.0 counter.dreamhost.com +0.0.0.0 counter.e-audit.it +0.0.0.0 counter.execpc.com +0.0.0.0 counter.fateback.com +0.0.0.0 counter.gamespy.com +0.0.0.0 counter.hitslink.com +0.0.0.0 counter.hitslinks.com +0.0.0.0 counter.htmlvalidator.com +0.0.0.0 counter.impressur.com +0.0.0.0 counter.inetusa.com +0.0.0.0 counter.inti.fr +0.0.0.0 counter.kaspersky.com +0.0.0.0 counter.letssingit.com +0.0.0.0 counter.mtree.com +0.0.0.0 counter.mycomputer.com +0.0.0.0 counter.netmore.net +0.0.0.0 counter.nope.dk +0.0.0.0 counter.nowlinux.com +0.0.0.0 counter.pcgames.de +0.0.0.0 counter.rambler.ru +0.0.0.0 counters.auctionhelper.com # comment these +0.0.0.0 counters.auctionwatch.com # out to allow +0.0.0.0 counters.auctiva.com # tracking by +0.0.0.0 counters.honesty.com # ebay users +0.0.0.0 counter.search.bg +0.0.0.0 counter.sexhound.nl +0.0.0.0 counters.gigya.com +0.0.0.0 counter.sparklit.com +0.0.0.0 counter.superstats.com +0.0.0.0 counter.surfcounters.com +0.0.0.0 counters.xaraonline.com +0.0.0.0 counter.times.lv +0.0.0.0 counter.topping.com.ua +0.0.0.0 counter.tripod.com +0.0.0.0 counter.uq.edu.au +0.0.0.0 counter.w3open.com +0.0.0.0 counter.webcom.com +0.0.0.0 counter.webmedia.pl +0.0.0.0 counter.webtrends.com +0.0.0.0 counter.webtrends.net +0.0.0.0 counter.xxxcool.com +0.0.0.0 counter.yadro.ru +0.0.0.0 count.paycounter.com +0.0.0.0 count.xhit.com +0.0.0.0 cs.sexcounter.com +0.0.0.0 c.statcounter.com +0.0.0.0 c.thecounter.de +0.0.0.0 cw.nu +0.0.0.0 cyseal.cyveillance.com +0.0.0.0 cz3.clickzs.com +0.0.0.0 cz6.clickzs.com +0.0.0.0 da.ce.bd.a9.top.list.ru +0.0.0.0 da.newstogram.com +0.0.0.0 data2.perf.overture.com +0.0.0.0 data.coremetrics.com +0.0.0.0 data.webads.co.nz +0.0.0.0 dclk.haaretz.co.il +0.0.0.0 dclk.themarker.com +0.0.0.0 dclk.themarketer.com +0.0.0.0 delivery.loopingclick.com +0.0.0.0 de.sitestat.com +0.0.0.0 didtheyreadit.com # email bugs +0.0.0.0 digistats.westjet.com +0.0.0.0 dimeprice.com # "spam bugs" +0.0.0.0 directads.mcafee.com +0.0.0.0 dotcomsecrets.com +0.0.0.0 dpbolvw.net +0.0.0.0 ds.247realmedia.com +0.0.0.0 ds.amateurmatch.com +0.0.0.0 dwclick.com +0.0.0.0 e-2dj6wfk4ehd5afq.stats.esomniture.com +0.0.0.0 e-2dj6wfk4ggdzkbo.stats.esomniture.com +0.0.0.0 e-2dj6wfk4gkcpiep.stats.esomniture.com +0.0.0.0 e-2dj6wfk4skdpogo.stats.esomniture.com +0.0.0.0 e-2dj6wfkiakdjgcp.stats.esomniture.com +0.0.0.0 e-2dj6wfkiepczoeo.stats.esomniture.com +0.0.0.0 e-2dj6wfkikjd5glq.stats.esomniture.com +0.0.0.0 e-2dj6wfkiokc5odp.stats.esomniture.com +0.0.0.0 e-2dj6wfkiqjcpifp.stats.esomniture.com +0.0.0.0 e-2dj6wfkocjczedo.stats.esomniture.com +0.0.0.0 e-2dj6wfkokjajseq.stats.esomniture.com +0.0.0.0 e-2dj6wfkowkdjokp.stats.esomniture.com +0.0.0.0 e-2dj6wfkykpazskq.stats.esomniture.com +0.0.0.0 e-2dj6wflicocjklo.stats.esomniture.com +0.0.0.0 e-2dj6wfligpd5iap.stats.esomniture.com +0.0.0.0 e-2dj6wflikgdpodo.stats.esomniture.com +0.0.0.0 e-2dj6wflikiajslo.stats.esomniture.com +0.0.0.0 e-2dj6wflioldzoco.stats.esomniture.com +0.0.0.0 e-2dj6wfliwpczolp.stats.esomniture.com +0.0.0.0 e-2dj6wfloenczmkq.stats.esomniture.com +0.0.0.0 e-2dj6wflokmajedo.stats.esomniture.com +0.0.0.0 e-2dj6wfloqgc5mho.stats.esomniture.com +0.0.0.0 e-2dj6wfmysgdzobo.stats.esomniture.com +0.0.0.0 e-2dj6wgkigpcjedo.stats.esomniture.com +0.0.0.0 e-2dj6wgkisnd5abo.stats.esomniture.com +0.0.0.0 e-2dj6wgkoandzieq.stats.esomniture.com +0.0.0.0 e-2dj6wgkycpcpsgq.stats.esomniture.com +0.0.0.0 e-2dj6wgkyepajmeo.stats.esomniture.com +0.0.0.0 e-2dj6wgkyknd5sko.stats.esomniture.com +0.0.0.0 e-2dj6wgkyomdpalp.stats.esomniture.com +0.0.0.0 e-2dj6whkiandzkko.stats.esomniture.com +0.0.0.0 e-2dj6whkiepd5iho.stats.esomniture.com +0.0.0.0 e-2dj6whkiwjdjwhq.stats.esomniture.com +0.0.0.0 e-2dj6wjk4amd5mfp.stats.esomniture.com +0.0.0.0 e-2dj6wjk4kkcjalp.stats.esomniture.com +0.0.0.0 e-2dj6wjk4ukazebo.stats.esomniture.com +0.0.0.0 e-2dj6wjkosodpmaq.stats.esomniture.com +0.0.0.0 e-2dj6wjkouhd5eao.stats.esomniture.com +0.0.0.0 e-2dj6wjkowhd5ggo.stats.esomniture.com +0.0.0.0 e-2dj6wjkowjajcbo.stats.esomniture.com +0.0.0.0 e-2dj6wjkyandpogq.stats.esomniture.com +0.0.0.0 e-2dj6wjkycpdzckp.stats.esomniture.com +0.0.0.0 e-2dj6wjkyqmdzcgo.stats.esomniture.com +0.0.0.0 e-2dj6wjkysndzigp.stats.esomniture.com +0.0.0.0 e-2dj6wjl4qhd5kdo.stats.esomniture.com +0.0.0.0 e-2dj6wjlichdjoep.stats.esomniture.com +0.0.0.0 e-2dj6wjliehcjglp.stats.esomniture.com +0.0.0.0 e-2dj6wjlignajgaq.stats.esomniture.com +0.0.0.0 e-2dj6wjloagc5oco.stats.esomniture.com +0.0.0.0 e-2dj6wjlougazmao.stats.esomniture.com +0.0.0.0 e-2dj6wjlyamdpogo.stats.esomniture.com +0.0.0.0 e-2dj6wjlyckcpelq.stats.esomniture.com +0.0.0.0 e-2dj6wjlyeodjkcq.stats.esomniture.com +0.0.0.0 e-2dj6wjlygkd5ecq.stats.esomniture.com +0.0.0.0 e-2dj6wjmiekc5olo.stats.esomniture.com +0.0.0.0 e-2dj6wjmyehd5mfo.stats.esomniture.com +0.0.0.0 e-2dj6wjmyooczoeo.stats.esomniture.com +0.0.0.0 e-2dj6wjny-1idzkh.stats.esomniture.com +0.0.0.0 e-2dj6wjnyagcpkko.stats.esomniture.com +0.0.0.0 e-2dj6wjnyeocpcdo.stats.esomniture.com +0.0.0.0 e-2dj6wjnygidjskq.stats.esomniture.com +0.0.0.0 e-2dj6wjnyqkajabp.stats.esomniture.com +0.0.0.0 easy-web-stats.com +0.0.0.0 ecestats.theglobeandmail.com +0.0.0.0 economisttestcollect.insightfirst.com +0.0.0.0 ehg.fedex.com +0.0.0.0 eitbglobal.ojdinteractiva.com +0.0.0.0 emea.rel.msn.com +0.0.0.0 engine.cmmeglobal.com +0.0.0.0 enoratraffic.com +0.0.0.0 entry-stats.huffingtonpost.com +0.0.0.0 environmentalgraffiti.uk.intellitxt.com +0.0.0.0 e-n.y-1shz2prbmdj6wvny-1sez2pra2dj6wjmyepdzadpwudj6x9ny-1seq-2-2.stats.esomniture.com +0.0.0.0 e-ny.a-1shz2prbmdj6wvny-1sez2pra2dj6wjny-1jcpgbowsdj6x9ny-1seq-2-2.stats.esomniture.com +0.0.0.0 es.optimost.com +0.0.0.0 fastcounter.bcentral.com +0.0.0.0 fastcounter.com +0.0.0.0 fastcounter.linkexchange.com +0.0.0.0 fastcounter.linkexchange.net +0.0.0.0 fastcounter.linkexchange.nl +0.0.0.0 fastcounter.onlinehoster.net +0.0.0.0 fastwebcounter.com +0.0.0.0 fcstats.bcentral.com +0.0.0.0 fi.sitestat.com +0.0.0.0 fl01.ct2.comclick.com +0.0.0.0 flycast.com +0.0.0.0 forbescollect.247realmedia.com +0.0.0.0 formalyzer.com +0.0.0.0 foxcounter.com +0.0.0.0 free-counter.5u.com +0.0.0.0 freeinvisiblecounters.com +0.0.0.0 freestats.com +0.0.0.0 freewebcounter.com +0.0.0.0 free.xxxcounter.com +0.0.0.0 fs10.fusestats.com +0.0.0.0 ft2.autonomycloud.com +0.0.0.0 gapl.hit.gemius.pl +0.0.0.0 gator.com +0.0.0.0 gcounter.hosting4u.net +0.0.0.0 gd.mlb.com +0.0.0.0 geocounter.net +0.0.0.0 gkkzngresullts.com +0.0.0.0 go-in-search.net +0.0.0.0 goldstats.com +0.0.0.0 googfle.com +0.0.0.0 googletagservices.com +0.0.0.0 gostats.com +0.0.0.0 grafix.xxxcounter.com +0.0.0.0 gtcc1.acecounter.com +0.0.0.0 g-wizzads.net +0.0.0.0 hc2.humanclick.com +0.0.0.0 hit10.hotlog.ru +0.0.0.0 hit2.hotlog.ru +0.0.0.0 hit37.chark.dk +0.0.0.0 hit37.chart.dk +0.0.0.0 hit39.chart.dk +0.0.0.0 hit5.hotlog.ru +0.0.0.0 hit8.hotlog.ru +0.0.0.0 hit.clickaider.com +0.0.0.0 hit-counter.5u.com +0.0.0.0 hit-counter.udub.com +0.0.0.0 hits.guardian.co.uk +0.0.0.0 hits.gureport.co.uk +0.0.0.0 hits.nextstat.com +0.0.0.0 hits.webstat.com +0.0.0.0 hitx.statistics.ro +0.0.0.0 hst.tradedoubler.com +0.0.0.0 htm.freelogs.com +0.0.0.0 http300.edge.ru4.com +0.0.0.0 iccee.com +0.0.0.0 idm.hit.gemius.pl +0.0.0.0 ieplugin.com +0.0.0.0 iesnare.com # See http://www.codingthewheel.com/archives/online-gambling-privacy-iesnare +0.0.0.0 ig.insightgrit.com +0.0.0.0 ih.constantcontacts.com +0.0.0.0 i.kissmetrics.com # http://www.wired.com/epicenter/2011/07/undeletable-cookie/ +0.0.0.0 ilead.itrack.it +0.0.0.0 image.masterstats.com +0.0.0.0 images1.paycounter.com +0.0.0.0 images-aud.freshmeat.net +0.0.0.0 images-aud.slashdot.org +0.0.0.0 images-aud.sourceforge.net +0.0.0.0 images.dailydiscounts.com # "spam bugs" +0.0.0.0 images.itchydawg.com +0.0.0.0 impacts.alliancehub.com # "spam bugs" +0.0.0.0 impch.tradedoubler.com +0.0.0.0 imp.clickability.com +0.0.0.0 impde.tradedoubler.com +0.0.0.0 impdk.tradedoubler.com +0.0.0.0 impes.tradedoubler.com +0.0.0.0 impfr.tradedoubler.com +0.0.0.0 impgb.tradedoubler.com +0.0.0.0 impie.tradedoubler.com +0.0.0.0 impit.tradedouble.com +0.0.0.0 impit.tradedoubler.com +0.0.0.0 impnl.tradedoubler.com +0.0.0.0 impno.tradedoubler.com +0.0.0.0 impse.tradedoubler.com +0.0.0.0 in.paycounter.com +0.0.0.0 insightfirst.com +0.0.0.0 insightxe.looksmart.com +0.0.0.0 int.sitestat.com +0.0.0.0 in.webcounter.cc +0.0.0.0 iprocollect.realmedia.com +0.0.0.0 izitracking.izimailing.com +0.0.0.0 jgoyk.cjt1.net +0.0.0.0 jkearns.freestats.com +0.0.0.0 journalism.uk.smarttargetting.com +0.0.0.0 js.cybermonitor.com +0.0.0.0 jsonlinecollect.247realmedia.com +0.0.0.0 js.revsci.net +0.0.0.0 kissmetrics.com +0.0.0.0 kqzyfj.com +0.0.0.0 kt4.kliptracker.com +0.0.0.0 leadpub.com +0.0.0.0 liapentruromania.ro +0.0.0.0 lin31.metriweb.be +0.0.0.0 linkcounter.com +0.0.0.0 linkcounter.pornosite.com +0.0.0.0 link.masterstats.com +0.0.0.0 linktrack.bravenet.com +0.0.0.0 livestats.atlanta-airport.com +#0.0.0.0 ll.a.hulu.com # Uncomment to block Hulu. +0.0.0.0 loc1.hitsprocessor.com +0.0.0.0 log1.countomat.com +0.0.0.0 log4.quintelligence.com +0.0.0.0 log999.goo.ne.jp +0.0.0.0 loga.xiti.com +0.0.0.0 log.btopenworld.com +0.0.0.0 logc146.xiti.com +0.0.0.0 logc1.xiti.com +0.0.0.0 logc22.xiti.com +0.0.0.0 logc25.xiti.com +0.0.0.0 logc31.xiti.com +0.0.0.0 log.clickstream.co.za +0.0.0.0 log.hankooki.com +0.0.0.0 logi6.xiti.com +0.0.0.0 logi7.xiti.com +0.0.0.0 logi8.xiti.com +0.0.0.0 logp3.xiti.com +0.0.0.0 logs.comics.com +0.0.0.0 logs.eresmas.com +0.0.0.0 logs.eresmas.net +0.0.0.0 log.statistici.ro +0.0.0.0 logv14.xiti.com +0.0.0.0 logv17.xiti.com +0.0.0.0 logv18.xiti.com +0.0.0.0 logv21.xiti.com +0.0.0.0 logv25.xiti.com +0.0.0.0 logv27.xiti.com +0.0.0.0 logv29.xiti.com +0.0.0.0 logv32.xiti.com +0.0.0.0 logv4.xiti.com +0.0.0.0 logv.xiti.com +0.0.0.0 luycos.com +0.0.0.0 lycoscollect.247realmedia.com +0.0.0.0 lycoscollect.realmedia.com +0.0.0.0 m1.nedstatbasic.net +0.0.0.0 m1.webstats4u.com +0.0.0.0 mailcheckisp.biz # "spam bugs" +0.0.0.0 mama128.valuehost.ru +0.0.0.0 marketscore.com +0.0.0.0 mature.xxxcounter.com +0.0.0.0 mbox5.offermatica.com +0.0.0.0 media101.sitebrand.com +0.0.0.0 media.superstats.com +0.0.0.0 mediatrack.revenue.net +0.0.0.0 metric.10best.com +0.0.0.0 metric.infoworld.com +0.0.0.0 metric.nationalgeographic.com +0.0.0.0 metric.nwsource.com +0.0.0.0 metric.olivegarden.com +0.0.0.0 metrics2.pricegrabber.com +0.0.0.0 metrics.accuweather.com +0.0.0.0 metrics.al.com +0.0.0.0 metrics.boston.com +0.0.0.0 metrics.cbc.ca +0.0.0.0 metrics.cleveland.com +0.0.0.0 metrics.cnn.com +0.0.0.0 metrics.csmonitor.com +0.0.0.0 metrics.ctv.ca +0.0.0.0 metrics.dallasnews.com +0.0.0.0 metrics.elle.com +0.0.0.0 metrics.experts-exchange.com +0.0.0.0 metrics.fandome.com +0.0.0.0 metrics.foxnews.com +0.0.0.0 metrics.gap.com +0.0.0.0 metrics.health.com +0.0.0.0 metrics.hrblock.com +0.0.0.0 metrics.ioffer.com +0.0.0.0 metrics.ireport.com +0.0.0.0 metrics.kgw.com +0.0.0.0 metrics.ktvb.com +0.0.0.0 metrics.landolakes.com +0.0.0.0 metrics.lhj.com +0.0.0.0 metrics.maxim.com +0.0.0.0 metrics.mlive.com +0.0.0.0 metrics.mms.mavenapps.net +0.0.0.0 metrics.mpora.com +0.0.0.0 metrics.mysanantonio.com +0.0.0.0 metrics.nba.com +0.0.0.0 metrics.nextgov.com +0.0.0.0 metrics.nfl.com +0.0.0.0 metrics.npr.org +0.0.0.0 metrics.oclc.org +0.0.0.0 metrics.olivegarden.com +0.0.0.0 metrics.oregonlive.com +0.0.0.0 metrics.parallels.com +0.0.0.0 metrics.performancing.com +0.0.0.0 metrics.philly.com +0.0.0.0 metrics.post-gazette.com +0.0.0.0 metrics.premiere.com +0.0.0.0 metrics.rottentomatoes.com +0.0.0.0 metrics.sephora.com +0.0.0.0 metrics.soundandvision.com +0.0.0.0 metrics.soundandvisionmag.com +0.0.0.0 metrics.sun.com +0.0.0.0 metric.starz.com +0.0.0.0 metrics.technologyreview.com +0.0.0.0 metrics.theatlantic.com +0.0.0.0 metrics.thedailybeast.com +0.0.0.0 metrics.thefa.com +0.0.0.0 metrics.thefrisky.com +0.0.0.0 metrics.thenation.com +0.0.0.0 metrics.theweathernetwork.com +#0.0.0.0 metrics.ticketmaster.com # interferes with logging in to ticketmaster.com +0.0.0.0 metrics.tmz.com +0.0.0.0 metrics.toyota.com +0.0.0.0 metrics.tulsaworld.com +0.0.0.0 metrics.washingtonpost.com +0.0.0.0 metrics.whitepages.com +0.0.0.0 metrics.womansday.com +0.0.0.0 metrics.yellowpages.com +0.0.0.0 metrics.yousendit.com +0.0.0.0 metric.thenation.com +0.0.0.0 mng1.clickalyzer.com +0.0.0.0 monster.gostats.com +0.0.0.0 mpsnare.iesnare.com # See http://www.codingthewheel.com/archives/online-gambling-privacy-iesnare +0.0.0.0 msn1.com +0.0.0.0 msnm.com +0.0.0.0 mt122.mtree.com +0.0.0.0 mtcount.channeladvisor.com +0.0.0.0 mtrcs.popcap.com +0.0.0.0 mtv.247realmedia.com +0.0.0.0 multi1.rmuk.co.uk +0.0.0.0 mvs.mediavantage.de +0.0.0.0 mvtracker.com +0.0.0.0 mystats.com +0.0.0.0 nedstat.s0.nl +0.0.0.0 nethit-free.nl +0.0.0.0 net-radar.com +0.0.0.0 network.leadpub.com +0.0.0.0 nextgenstats.com +0.0.0.0 nht-2.extreme-dm.com +0.0.0.0 nl.nedstatbasic.net +0.0.0.0 nl.sitestat.com +0.0.0.0 o.addthis.com +0.0.0.0 objects.tremormedia.com +0.0.0.0 okcounter.com +0.0.0.0 omniture.theglobeandmail.com +0.0.0.0 one.123counters.com +0.0.0.0 oss-crules.marketscore.com +0.0.0.0 oss-survey.marketscore.com +0.0.0.0 ostats.mozilla.com +0.0.0.0 other.xxxcounter.com +0.0.0.0 out.true-counter.com +0.0.0.0 p.addthis.com +0.0.0.0 partner.alerts.aol.com +0.0.0.0 partners.pantheranetwork.com +0.0.0.0 passpport.com +0.0.0.0 paxito.sitetracker.com +0.0.0.0 paycounter.com +0.0.0.0 pei-ads.thesmokingjacket.com +0.0.0.0 perso.estat.com +0.0.0.0 pf.tradedoubler.com +0.0.0.0 pings.blip.tv +0.0.0.0 pix02.revsci.net +0.0.0.0 pix03.revsci.net +0.0.0.0 pix04.revsci.net +0.0.0.0 pixel.invitemedia.com +0.0.0.0 pmg.ad-logics.com +0.0.0.0 pn2.adserver.yahoo.com +0.0.0.0 pointclicktrack.com +0.0.0.0 pong.qubitproducts.com +0.0.0.0 postclick.adcentriconline.com +0.0.0.0 postgazettecollect.247realmedia.com +0.0.0.0 precisioncounter.com +0.0.0.0 p.reuters.com +0.0.0.0 printmail.biz +0.0.0.0 prof.estat.com +0.0.0.0 pro.hit.gemius.pl +0.0.0.0 proxycfg.marketscore.com +0.0.0.0 proxy.ia2.marketscore.com +0.0.0.0 proxy.ia3.marketscore.com +0.0.0.0 proxy.ia4.marketscore.com +0.0.0.0 proxy.or3.marketscore.com +0.0.0.0 proxy.or4.marketscore.com +0.0.0.0 proxy.sj3.marketscore.com +0.0.0.0 proxy.sj4.marketscore.com +0.0.0.0 quantserve.com #: Ad Tracking, JavaScript, etc. +0.0.0.0 quareclk.com +0.0.0.0 raw.oggifinogi.com +0.0.0.0 r.clickdensity.com +0.0.0.0 remotrk.com +0.0.0.0 rightmedia.net +0.0.0.0 rightstats.com +0.0.0.0 roskatrack.roskadirect.com +0.0.0.0 rr1.xxxcounter.com +0.0.0.0 rr2.xxxcounter.com +0.0.0.0 rr3.xxxcounter.com +0.0.0.0 rr4.xxxcounter.com +0.0.0.0 rr5.xxxcounter.com +0.0.0.0 rr7.xxxcounter.com +0.0.0.0 rts.pgmediaserve.com +0.0.0.0 rts.phn.doublepimp.com +0.0.0.0 s10.histats.com +0.0.0.0 s10.sitemeter.com +0.0.0.0 s11.sitemeter.com +0.0.0.0 s12.sitemeter.com +0.0.0.0 s13.sitemeter.com +0.0.0.0 s14.sitemeter.com +0.0.0.0 s15.sitemeter.com +0.0.0.0 s16.sitemeter.com +0.0.0.0 s17.sitemeter.com +0.0.0.0 s18.sitemeter.com +0.0.0.0 s19.sitemeter.com +0.0.0.0 s1.shinystat.it +0.0.0.0 s1.thecounter.com +0.0.0.0 s20.sitemeter.com +0.0.0.0 s21.sitemeter.com +0.0.0.0 s22.sitemeter.com +0.0.0.0 s23.sitemeter.com +0.0.0.0 s24.sitemeter.com +0.0.0.0 s25.sitemeter.com +0.0.0.0 s26.sitemeter.com +0.0.0.0 s27.sitemeter.com +0.0.0.0 s28.sitemeter.com +0.0.0.0 s29.sitemeter.com +0.0.0.0 s2.statcounter.com +0.0.0.0 s2.youtube.com +0.0.0.0 s30.sitemeter.com +0.0.0.0 s31.sitemeter.com +0.0.0.0 s32.sitemeter.com +0.0.0.0 s33.sitemeter.com +0.0.0.0 s34.sitemeter.com +0.0.0.0 s35.sitemeter.com +0.0.0.0 s36.sitemeter.com +0.0.0.0 s37.sitemeter.com +0.0.0.0 s38.sitemeter.com +0.0.0.0 s39.sitemeter.com +0.0.0.0 s3.hit.stat.pl +0.0.0.0 s41.sitemeter.com +0.0.0.0 s42.sitemeter.com +0.0.0.0 s43.sitemeter.com +0.0.0.0 s44.sitemeter.com +0.0.0.0 s45.sitemeter.com +0.0.0.0 s46.sitemeter.com +0.0.0.0 s47.sitemeter.com +0.0.0.0 s48.sitemeter.com +0.0.0.0 s4.histats.com +0.0.0.0 s4.shinystat.com +0.0.0.0 s.clickability.com +0.0.0.0 scorecardresearch.com +0.0.0.0 scribe.twitter.com +0.0.0.0 scrooge.channelcincinnati.com +0.0.0.0 scrooge.channeloklahoma.com +0.0.0.0 scrooge.click10.com +0.0.0.0 scrooge.clickondetroit.com +0.0.0.0 scrooge.nbc11.com +0.0.0.0 scrooge.nbc4columbus.com +0.0.0.0 scrooge.nbc4.com +0.0.0.0 scrooge.nbcsandiego.com +0.0.0.0 scrooge.newsnet5.com +0.0.0.0 scrooge.thebostonchannel.com +0.0.0.0 scrooge.thedenverchannel.com +0.0.0.0 scrooge.theindychannel.com +0.0.0.0 scrooge.thekansascitychannel.com +0.0.0.0 scrooge.themilwaukeechannel.com +0.0.0.0 scrooge.theomahachannel.com +0.0.0.0 scrooge.wesh.com +0.0.0.0 scrooge.wftv.com +0.0.0.0 scrooge.wnbc.com +0.0.0.0 scrooge.wsoctv.com +0.0.0.0 scrooge.wtov9.com +0.0.0.0 sdc.rbistats.com +0.0.0.0 searchadv.com +0.0.0.0 sekel.ch +0.0.0.0 servedby.valuead.com +0.0.0.0 server10.opentracker.net +0.0.0.0 server11.opentracker.net +0.0.0.0 server12.opentracker.net +0.0.0.0 server13.opentracker.net +0.0.0.0 server14.opentracker.net +0.0.0.0 server15.opentracker.net +0.0.0.0 server16.opentracker.net +0.0.0.0 server17.opentracker.net +0.0.0.0 server18.opentracker.net +0.0.0.0 server1.opentracker.net +0.0.0.0 server2.opentracker.net +0.0.0.0 server3.opentracker.net +0.0.0.0 server3.web-stat.com +0.0.0.0 server4.opentracker.net +0.0.0.0 server5.opentracker.net +0.0.0.0 server6.opentracker.net +0.0.0.0 server7.opentracker.net +0.0.0.0 server8.opentracker.net +0.0.0.0 server9.opentracker.net +0.0.0.0 service.bfast.com +0.0.0.0 services.krxd.net +0.0.0.0 se.sitestat.com +0.0.0.0 sexcounter.com +0.0.0.0 seznam.hit.gemius.pl +0.0.0.0 showads.pubmatic.com +0.0.0.0 showcount.honest.com +0.0.0.0 sideshow.directtrack.com +0.0.0.0 sitestat.com +0.0.0.0 sitestats.tiscali.co.uk +0.0.0.0 sm1.sitemeter.com +0.0.0.0 sm2.sitemeter.com +0.0.0.0 sm3.sitemeter.com +0.0.0.0 sm4.sitemeter.com +0.0.0.0 sm5.sitemeter.com +0.0.0.0 sm6.sitemeter.com +0.0.0.0 sm7.sitemeter.com +0.0.0.0 sm8.sitemeter.com +0.0.0.0 sm9.sitemeter.com +0.0.0.0 smartstats.com +0.0.0.0 softcore.xxxcounter.com +0.0.0.0 sostats.mozilla.com +0.0.0.0 sovereign.sitetracker.com +0.0.0.0 spinbox.maccentral.com +0.0.0.0 spinbox.versiontracker.com +0.0.0.0 spklds.com +0.0.0.0 s.statistici.ro +0.0.0.0 s.stats.wordpress.com +0.0.0.0 ss.tiscali.com +0.0.0.0 ss.tiscali.it +0.0.0.0 st1.hit.gemius.pl +0.0.0.0 stags.peer39.net +0.0.0.0 stast2.gq.com +0.0.0.0 stat1.z-stat.com +0.0.0.0 stat3.cybermonitor.com +0.0.0.0 stat.4u.pl +0.0.0.0 stat.alibaba.com +0.0.0.0 statcounter.com +0.0.0.0 stat-counter.tass-online.ru +0.0.0.0 stat.discogs.com +0.0.0.0 static.kibboko.com +0.0.0.0 static.smni.com # Santa Monica - popunders +0.0.0.0 statik.topica.com +0.0.0.0 statistics.dynamicsitestats.com +0.0.0.0 statistics.elsevier.nl +0.0.0.0 statistics.reedbusiness.nl +0.0.0.0 statistics.theonion.com +0.0.0.0 statistik-gallup.net +0.0.0.0 stat.netmonitor.fi +0.0.0.0 stat.onestat.com +0.0.0.0 stats1.clicktracks.com +0.0.0.0 stats1.corusradio.com +0.0.0.0 stats1.in +0.0.0.0 stats.24ways.org +0.0.0.0 stats2.clicktracks.com +0.0.0.0 stats2.gourmet.com +0.0.0.0 stats2.newyorker.com +0.0.0.0 stats2.rte.ie +0.0.0.0 stats2.unrulymedia.com +0.0.0.0 stats2.vanityfair.com +0.0.0.0 stats4all.com +0.0.0.0 stats5.lightningcast.com +0.0.0.0 stats6.lightningcast.net +0.0.0.0 stats.absol.co.za +0.0.0.0 stats.adbrite.com +0.0.0.0 stats.adotube.com +0.0.0.0 stats.adultswim.com +0.0.0.0 stats.airfarewatchdog.com +0.0.0.0 stats.allliquid.com +0.0.0.0 stats.askmen.com +0.0.0.0 stats.bbc.co.uk +0.0.0.0 stats.becu.org +0.0.0.0 stats.big-boards.com +0.0.0.0 stats.blogoscoop.net +0.0.0.0 stats.bonzaii.no +0.0.0.0 stats.break.com +0.0.0.0 stats.brides.com +0.0.0.0 stats.buysellads.com +0.0.0.0 stats.cafepress.com +0.0.0.0 stats.canalblog.com +0.0.0.0 stats.cartoonnetwork.com +0.0.0.0 stats.channel4.com +0.0.0.0 stats.clickability.com +0.0.0.0 stats.concierge.com +0.0.0.0 stats.cts-bv.nl +0.0.0.0 stats.darkbluesea.com +0.0.0.0 stats.datahjaelp.net +0.0.0.0 stats.directnic.com +0.0.0.0 stats.dziennik.pl +0.0.0.0 stats.economist.com +0.0.0.0 stats.epicurious.com +0.0.0.0 statse.webtrendslive.com # Fortune.com among others +0.0.0.0 stats.examiner.com +0.0.0.0 stats.fairmont.com +0.0.0.0 stats.fastcompany.com +0.0.0.0 stats.foxcounter.com +0.0.0.0 stats.free-rein.net +0.0.0.0 stats.f-secure.com +0.0.0.0 stats.ft.com +0.0.0.0 stats.gamestop.com +0.0.0.0 stats.globesports.com +0.0.0.0 stats.groupninetyfour.com +0.0.0.0 stats.idsoft.com +0.0.0.0 stats.ign.com +0.0.0.0 stats.ilsemedia.nl +0.0.0.0 stats.independent.co.uk +0.0.0.0 stats.indexstats.com +0.0.0.0 stats.indextools.com +0.0.0.0 stats.investors.com +0.0.0.0 stats.iwebtrack.com +0.0.0.0 stats.jippii.com +0.0.0.0 stats.klsoft.com +0.0.0.0 stats.ladotstats.nl +0.0.0.0 stats.macworld.com +0.0.0.0 stats.magnify.net +0.0.0.0 stats.manticoretechnology.com +0.0.0.0 stats.mbamupdates.com +0.0.0.0 stats.millanusa.com +0.0.0.0 stats.nowpublic.com +0.0.0.0 stats.paycounter.com +0.0.0.0 stats.platinumbucks.com +0.0.0.0 stats.popscreen.com +0.0.0.0 stats.reinvigorate.net +0.0.0.0 stats.resellerratings.com +0.0.0.0 stats.revenue.net +0.0.0.0 stats.searchles.com +0.0.0.0 stats.ssa.gov +0.0.0.0 stats.superstats.com +0.0.0.0 stats.telegraph.co.uk +0.0.0.0 stats.thoughtcatalog.com +0.0.0.0 stats.townnews.com +0.0.0.0 stats.ultimate-webservices.com +0.0.0.0 stats.unionleader.com +0.0.0.0 stats.video.search.yahoo.com +0.0.0.0 stats.vodpod.com +0.0.0.0 stats.wordpress.com +0.0.0.0 stats.www.ibm.com +0.0.0.0 stats.yourminis.com +0.0.0.0 stat.webmedia.pl +0.0.0.0 stat.www.fi +0.0.0.0 stat.yellowtracker.com +0.0.0.0 stat.youku.com +0.0.0.0 stl.p.a1.traceworks.com +0.0.0.0 straighttangerine.cz.cc +0.0.0.0 st.sageanalyst.net +0.0.0.0 sugoicounter.com +0.0.0.0 superstats.com +0.0.0.0 s.youtube.com +#0.0.0.0 t2.hulu.com # Uncomment to block Hulu. +0.0.0.0 tagging.outrider.com +0.0.0.0 talkcity.realtracker.com +0.0.0.0 targetnet.com +0.0.0.0 tates.freestats.com +0.0.0.0 tcookie.usatoday.com +0.0.0.0 tcr.tynt.com # See http://daringfireball.net/2010/05/tynt_copy_paste_jerks +0.0.0.0 tgpcounter.freethumbnailgalleries.com +0.0.0.0 thecounter.com +0.0.0.0 the-counter.net +0.0.0.0 themecounter.com +0.0.0.0 the.sextracker.com +0.0.0.0 tipsurf.com +0.0.0.0 toolbarpartner.com +0.0.0.0 tools.spylog.ru +0.0.0.0 top.mail.ru +0.0.0.0 topstats.com +0.0.0.0 topstats.net +0.0.0.0 torstarcollect.247realmedia.com +0.0.0.0 track2.mybloglog.com +0.0.0.0 track.adform.com +0.0.0.0 track.adform.net +0.0.0.0 track.did-it.com +0.0.0.0 track.directleads.com +0.0.0.0 track.domainsponsor.com +0.0.0.0 track.effiliation.com +0.0.0.0 tracker.bonnint.net +0.0.0.0 tracker.clicktrade.com +0.0.0.0 tracker.idg.co.uk +0.0.0.0 tracker.mattel.com +0.0.0.0 tracker.netklix.com +0.0.0.0 tracker.tradedoubler.com +0.0.0.0 track.exclusivecpa.com +0.0.0.0 track.ft.com +0.0.0.0 track.gawker.com +0.0.0.0 track.homestead.com +#0.0.0.0 track.hulu.com # Uncomment to block Hulu. +0.0.0.0 tracking.10e20.com +0.0.0.0 tracking.adjug.com +0.0.0.0 tracking.allposters.com +0.0.0.0 tracking.foxnews.com +0.0.0.0 tracking.iol.co.za +0.0.0.0 tracking.msadcenter.msn.com +0.0.0.0 tracking.oggifinogi.com +0.0.0.0 tracking.percentmobile.com +0.0.0.0 tracking.publicidees.com +0.0.0.0 tracking.quisma.com +0.0.0.0 tracking.rangeonlinemedia.com +0.0.0.0 tracking.searchmarketing.com +0.0.0.0 tracking.summitmedia.co.uk +0.0.0.0 tracking.trafficjunky.net +0.0.0.0 tracking.trutv.com +0.0.0.0 tracking.vindicosuite.com +0.0.0.0 track.lfstmedia.com +0.0.0.0 track.mybloglog.com +0.0.0.0 track.omg2.com +0.0.0.0 track.roiservice.com +0.0.0.0 track.searchignite.com +0.0.0.0 tracksurf.daooda.com +0.0.0.0 track.webgains.com +0.0.0.0 tradedoubler.com +0.0.0.0 tradedoubler.sonvideopro.com +0.0.0.0 tr.adinterax.com +0.0.0.0 traffic-stats.streamsolutions.co.uk +0.0.0.0 trax.gamespot.com +0.0.0.0 trc.taboolasyndication.com +0.0.0.0 trk.kissmetrics.com +0.0.0.0 trk.tidaltv.com +0.0.0.0 true-counter.com +0.0.0.0 truehits1.gits.net.th +0.0.0.0 t.senaluno.com +0.0.0.0 tu.connect.wunderloop.net +0.0.0.0 tynt.com +0.0.0.0 u1817.16.spylog.com +0.0.0.0 u3102.47.spylog.com +0.0.0.0 u3305.71.spylog.com +0.0.0.0 u3608.20.spylog.com +0.0.0.0 u4056.56.spylog.com +0.0.0.0 u432.77.spylog.com +0.0.0.0 u4396.79.spylog.com +0.0.0.0 u4443.84.spylog.com +0.0.0.0 u4556.11.spylog.com +0.0.0.0 u5234.87.spylog.com +0.0.0.0 u5234.98.spylog.com +0.0.0.0 u5687.48.spylog.com +0.0.0.0 u574.07.spylog.com +0.0.0.0 u604.41.spylog.com +0.0.0.0 u6762.46.spylog.com +0.0.0.0 u6905.71.spylog.com +0.0.0.0 u7748.16.spylog.com +0.0.0.0 u810.15.spylog.com +0.0.0.0 u920.31.spylog.com +0.0.0.0 u977.40.spylog.com +0.0.0.0 udc.msn.com +0.0.0.0 uk.cqcounter.com +0.0.0.0 uk.sitestat.com +0.0.0.0 ultimatecounter.com +0.0.0.0 us.2.cqcounter.com +0.0.0.0 usa.nedstat.net +0.0.0.0 us.cqcounter.com +0.0.0.0 v1.nedstatbasic.net +0.0.0.0 v7.stats.load.com +0.0.0.0 valueclick.com +0.0.0.0 valueclick.net +0.0.0.0 vertical-stats.huffpost.com +0.0.0.0 video-stats.video.google.com +0.0.0.0 vip.clickzs.com +0.0.0.0 virtualbartendertrack.beer.com +0.0.0.0 visit.theglobeandmail.com # Visits to theglobeandmail.com +0.0.0.0 vis.sexlist.com +0.0.0.0 voken.eyereturn.com +0.0.0.0 vs.dmtracker.com +0.0.0.0 vsii.spinbox.net +0.0.0.0 vsii.spindox.net +0.0.0.0 w1.tcr112.tynt.com +0.0.0.0 warlog.info +0.0.0.0 wau.tynt.com +0.0.0.0 web1.realtracker.com +0.0.0.0 web2.realtracker.com +0.0.0.0 web3.realtracker.com +0.0.0.0 web4.realtracker.com +0.0.0.0 webanalytics.globalthoughtz.com +0.0.0.0 webbug.seatreport.com # web bugs +0.0.0.0 web-counter.5u.com +0.0.0.0 webcounter.com +0.0.0.0 webcounter.goweb.de +0.0.0.0 webcounter.together.net +0.0.0.0 webhit.aftenposten.no +0.0.0.0 webhit.afterposten.no +0.0.0.0 webmasterkai.sitetracker.com +0.0.0.0 webpdp.gator.com +0.0.0.0 webstat.channel4.com +0.0.0.0 webtrends.telenet.be +0.0.0.0 webtrends.thisis.co.uk +0.0.0.0 webtrends.townhall.com +0.0.0.0 wtnj.worldnow.com +0.0.0.0 www.0stats.com +0.0.0.0 www101.coolsavings.com +0.0.0.0 www.123count.com +0.0.0.0 www.123counter.superstats.com +0.0.0.0 www.123stat.com +0.0.0.0 www1.addfreestats.com +0.0.0.0 www1.counter.bloke.com +0.0.0.0 www.1quickclickrx.com +0.0.0.0 www1.tynt.com +0.0.0.0 www.2001-007.com +0.0.0.0 www2.addfreestats.com +0.0.0.0 www2.counter.bloke.com +0.0.0.0 www2.pagecount.com +0.0.0.0 www3.addfreestats.com +0.0.0.0 www3.click-fr.com +0.0.0.0 www3.counter.bloke.com +0.0.0.0 www.3dstats.com +0.0.0.0 www4.addfreestats.com +0.0.0.0 www4.counter.bloke.com +0.0.0.0 www5.addfreestats.com +0.0.0.0 www5.counter.bloke.com +0.0.0.0 www60.valueclick.com +0.0.0.0 www6.addfreestats.com +0.0.0.0 www6.click-fr.com +0.0.0.0 www6.counter.bloke.com +0.0.0.0 www7.addfreestats.com +0.0.0.0 www7.counter.bloke.com +0.0.0.0 www8.addfreestats.com +0.0.0.0 www8.counter.bloke.com +0.0.0.0 www9.counter.bloke.com +0.0.0.0 www.addfreecounter.com +0.0.0.0 www.addfreestats.com +0.0.0.0 www.ademails.com +0.0.0.0 www.affiliatesuccess.net +0.0.0.0 www.bar.ry2002.02-ry014.snpr.hotmx.hair.zaam.net # In spam +0.0.0.0 www.belstat.nl +0.0.0.0 www.betcounter.com +0.0.0.0 www.bigbadted.com +0.0.0.0 www.bluestreak.com +0.0.0.0 www.c1.thecounter.de +0.0.0.0 www.c2.thecounter.de +0.0.0.0 www.clickclick.com +0.0.0.0 www.clickspring.net #used by a spyware product called PurityScan +0.0.0.0 www.clixgalore.com +0.0.0.0 www.connectionlead.com +0.0.0.0 www.counter10.sextracker.be +0.0.0.0 www.counter11.sextracker.be +0.0.0.0 www.counter12.sextracker.be +0.0.0.0 www.counter13.sextracker.be +0.0.0.0 www.counter14.sextracker.be +0.0.0.0 www.counter15.sextracker.be +0.0.0.0 www.counter16.sextracker.be +0.0.0.0 www.counter1.sextracker.be +0.0.0.0 www.counter2.sextracker.be +0.0.0.0 www.counter3.sextracker.be +0.0.0.0 www.counter4all.com +0.0.0.0 www.counter4all.de +0.0.0.0 www.counter4.sextracker.be +0.0.0.0 www.counter5.sextracker.be +0.0.0.0 www.counter6.sextracker.be +0.0.0.0 www.counter7.sextracker.be +0.0.0.0 www.counter8.sextracker.be +0.0.0.0 www.counter9.sextracker.be +0.0.0.0 www.counter.bloke.com +0.0.0.0 www.counterguide.com +0.0.0.0 www.counter.sexhound.nl +0.0.0.0 www.counter.superstats.com +0.0.0.0 www.c.thecounter.de +0.0.0.0 www.cw.nu +0.0.0.0 www.directgrowthhormone.com +0.0.0.0 www.dpbolvw.net +0.0.0.0 www.dwclick.com +0.0.0.0 www.easycounter.com +0.0.0.0 www.emaildeals.biz +0.0.0.0 www.estats4all.com +0.0.0.0 www.fastcounter.linkexchange.nl +0.0.0.0 www.formalyzer.com +0.0.0.0 www.foxcounter.com +0.0.0.0 www.freestats.com +0.0.0.0 www.fxcounters.com +0.0.0.0 www.gator.com +0.0.0.0 www.googkle.com +0.0.0.0 www.googletagservices.com +0.0.0.0 www.hitstats.co.uk +0.0.0.0 www.iccee.com +0.0.0.0 www.iesnare.com # See http://www.codingthewheel.com/archives/online-gambling-privacy-iesnare +0.0.0.0 www.jellycounter.com +0.0.0.0 www.kqzyfj.com +0.0.0.0 www.leadpub.com +0.0.0.0 www.linkcounter.com +0.0.0.0 www.marketscore.com +0.0.0.0 www.megacounter.de +0.0.0.0 www.metareward.com # web bugs in spam +0.0.0.0 www.naturalgrowthstore.biz +0.0.0.0 www.nedstat.com +0.0.0.0 www.nextgenstats.com +0.0.0.0 www.ntsearch.com +0.0.0.0 www.onestat.com +0.0.0.0 www.originalicons.com # installs IE extension +0.0.0.0 www.paycounter.com +0.0.0.0 www.pointclicktrack.com +0.0.0.0 www.popuptrafic.com +0.0.0.0 www.precisioncounter.com +0.0.0.0 www.premiumsmail.net +0.0.0.0 www.printmail.biz +0.0.0.0 www.quantserve.com #: Ad Tracking, JavaScript, etc. +0.0.0.0 www.quareclk.com +0.0.0.0 www.remotrk.com +0.0.0.0 www.rightmedia.net +0.0.0.0 www.rightstats.com +0.0.0.0 www.searchadv.com +0.0.0.0 www.sekel.ch +0.0.0.0 www.shockcounter.com +0.0.0.0 www.simplecounter.net +0.0.0.0 www.specificclick.com +0.0.0.0 www.specificpop.com +0.0.0.0 www.spklds.com +0.0.0.0 www.statcount.com +0.0.0.0 www.statcounter.com +0.0.0.0 www.statsession.com +0.0.0.0 www.stattrax.com +0.0.0.0 www.stiffnetwork.com +0.0.0.0 www.testracking.com +0.0.0.0 www.thecounter.com +0.0.0.0 www.the-counter.net +0.0.0.0 www.toolbarcounter.com +0.0.0.0 www.tradedoubler.com +0.0.0.0 www.tradedoubler.com.ar +0.0.0.0 www.trafficmagnet.net # web bugs in spam +0.0.0.0 www.trafic.ro +0.0.0.0 www.trendcounter.com +0.0.0.0 www.true-counter.com +0.0.0.0 www.tynt.com +0.0.0.0 www.ultimatecounter.com +0.0.0.0 www.v61.com +0.0.0.0 www.webcounter.com +0.0.0.0 www.web-stat.com +0.0.0.0 www.webstat.com +0.0.0.0 www.whereugetxxx.com +0.0.0.0 www.xxxcounter.com +0.0.0.0 x.cb.kount.com +0.0.0.0 xcnn.com +0.0.0.0 xxxcounter.com +0.0.0.0 xyz.freelogs.com +0.0.0.0 zz.cqcounter.com +# +# + +# sites with known trojans, phishing, or other malware +0.0.0.0 05tz2e9.com +0.0.0.0 09killspyware.com +0.0.0.0 11398.onceedge.ru +0.0.0.0 2006mindfreaklike.blogspot.com # Facebook trojan +0.0.0.0 20-yrs-1.info +0.0.0.0 59-106-20-39.r-bl100.sakura.ne.jp +0.0.0.0 662bd114b7c9.onceedge.ru +0.0.0.0 a15172379.alturo-server.de +0.0.0.0 aaukqiooaseseuke.org +0.0.0.0 abetterinternet.com +0.0.0.0 abruzzoinitaly.co.uk +0.0.0.0 acglgoa.com +0.0.0.0 acim.moqhixoz.cn +0.0.0.0 adshufffle.com +0.0.0.0 adwitty.com +0.0.0.0 adwords.google.lloymlincs.com +0.0.0.0 afantispy.com +0.0.0.0 afdbande.cn +0.0.0.0 allhqpics.com # Facebook trojan +0.0.0.0 alphabirdnetwork.com +0.0.0.0 antispywareexpert.com +0.0.0.0 antivirus-online-scan5.com +0.0.0.0 antivirus-scanner8.com +0.0.0.0 antivirus-scanner.com +0.0.0.0 a.oix.com +0.0.0.0 a.oix.net +0.0.0.0 armsart.com +0.0.0.0 articlefuns.cn +0.0.0.0 articleidea.cn +0.0.0.0 asianread.com +0.0.0.0 autohipnose.com +0.0.0.0 a.webwise.com +0.0.0.0 a.webwise.net +0.0.0.0 a.webwise.org +0.0.0.0 beloysoff.ru +0.0.0.0 binsservicesonline.info +0.0.0.0 blackhat.be +0.0.0.0 blenz-me.net +0.0.0.0 bnvxcfhdgf.blogspot.com.es +0.0.0.0 b.oix.com +0.0.0.0 b.oix.net +0.0.0.0 BonusCashh.com +0.0.0.0 brunga.at # Facebook phishing attempt +0.0.0.0 bt.webwise.com +0.0.0.0 bt.webwise.net +0.0.0.0 bt.webwise.org +0.0.0.0 b.webwise.com +0.0.0.0 b.webwise.net +0.0.0.0 b.webwise.org +0.0.0.0 callawaypos.com +0.0.0.0 callbling.com +0.0.0.0 cambonanza.com +0.0.0.0 ccudl.com +0.0.0.0 changduk26.com # Facebook trojan +0.0.0.0 chelick.net # Facebook trojan +0.0.0.0 cioco-froll.com +0.0.0.0 cira.login.cqr.ssl.igotmyloverback.com +0.0.0.0 cleanchain.net +0.0.0.0 click.get-answers-fast.com +0.0.0.0 clien.net +0.0.0.0 cnbc.com-article906773.us +0.0.0.0 co8vd.cn +0.0.0.0 c.oix.com +0.0.0.0 c.oix.net +0.0.0.0 conduit.com +0.0.0.0 cra-arc-gc-ca.noads.biz +0.0.0.0 custom3hurricanedigitalmedia.com +0.0.0.0 c.webwise.com +0.0.0.0 c.webwise.net +0.0.0.0 c.webwise.org +0.0.0.0 dbios.org +0.0.0.0 dhauzja511.co.cc +0.0.0.0 dietpharmacyrx.net +0.0.0.0 download.abetterinternet.com +0.0.0.0 drc-group.net +0.0.0.0 dubstep.onedumb.com +0.0.0.0 east.05tz2e9.com +0.0.0.0 e-kasa.w8w.pl +0.0.0.0 en.likefever.org # Facebook trojan +0.0.0.0 enteryouremail.net +0.0.0.0 eviboli576.o-f.com +0.0.0.0 facebook-repto1040s2.ahlamountada.com +0.0.0.0 faceboook-replyei0ki.montadalitihad.com +0.0.0.0 facemail.com +0.0.0.0 faggotry.com +0.0.0.0 familyupport1.com +0.0.0.0 feaecebook.com +0.0.0.0 fengyixin.com +0.0.0.0 filosvybfimpsv.ru.gg +0.0.0.0 froling.bee.pl +0.0.0.0 fromru.su +0.0.0.0 ftdownload.com +0.0.0.0 fu.golikeus.net # Facebook trojan +0.0.0.0 gamelights.ru +0.0.0.0 gasasthe.freehostia.com +0.0.0.0 get-answers-fast.com +0.0.0.0 gglcash4u.info # twitter worm +0.0.0.0 girlownedbypolicelike.blogspot.com # Facebook trojan +0.0.0.0 goggle.com +0.0.0.0 greatarcadehits.com +0.0.0.0 gyros.es +0.0.0.0 h1317070.stratoserver.net +0.0.0.0 hackerz.ir +0.0.0.0 hakerzy.net +0.0.0.0 hatrecord.ru # Facebook trojan +0.0.0.0 hellwert.biz +0.0.0.0 hotchix.servepics.com +0.0.0.0 hsb-canada.com # phishing site for hsbc.ca +0.0.0.0 hsbconline.ca # phishing site for hsbc.ca +0.0.0.0 icecars.com +0.0.0.0 idea21.org +0.0.0.0 Iframecash.biz +0.0.0.0 infopaypal.com +0.0.0.0 installmac.com +0.0.0.0 ipadzu.net +0.0.0.0 ircleaner.com +0.0.0.0 itwititer.com +0.0.0.0 ity.elusmedic.ru +0.0.0.0 jajajaj-thats-you-really.com +0.0.0.0 janezk.50webs.co +0.0.0.0 jujitsu-ostrava.info +0.0.0.0 jump.ewoss.net +0.0.0.0 juste.ru # Twitter trojan +0.0.0.0 kczambians.com +0.0.0.0 keybinary.com +0.0.0.0 kirgo.at # Facebook phishing attempt +0.0.0.0 klowns4phun.com +0.0.0.0 konflow.com # Facebook trojan +0.0.0.0 kplusd.far.ru +0.0.0.0 kpremium.com +0.0.0.0 lank.ru +0.0.0.0 lighthouse2k.com +0.0.0.0 like.likewut.net +0.0.0.0 likeportal.com # Facebook trojan +0.0.0.0 likespike.com # Facebook trojan +0.0.0.0 likethislist.biz # Facebook trojan +0.0.0.0 likethis.mbosoft.com # Facebook trojan +0.0.0.0 loseweight.asdjiiw.com +0.0.0.0 lucibad.home.ro +0.0.0.0 luxcart.ro +0.0.0.0 m01.oix.com +0.0.0.0 m01.oix.net +0.0.0.0 m01.webwise.com +0.0.0.0 m01.webwise.net +0.0.0.0 m01.webwise.org +0.0.0.0 m02.oix.com +0.0.0.0 m02.oix.net +0.0.0.0 m02.webwise.com +0.0.0.0 m02.webwise.net +0.0.0.0 m02.webwise.org +0.0.0.0 mail.cyberh.fr +0.0.0.0 malware-live-pro-scanv1.com +0.0.0.0 maxi4.firstvds.ru +0.0.0.0 megasurfin.com +0.0.0.0 monkeyball.osa.pl +0.0.0.0 movies.701pages.com +0.0.0.0 mplayerdownloader.com +0.0.0.0 murcia-ban.es +0.0.0.0 mylike.co.uk # Facebook trojan +0.0.0.0 nactx.com +0.0.0.0 natashyabaydesign.com +0.0.0.0 new-dating-2012.info +0.0.0.0 new-vid-zone-1.blogspot.com.au +0.0.0.0 newwayscanner.info +0.0.0.0 novemberrainx.com +0.0.0.0 ns1.oix.com +0.0.0.0 ns1.oix.net +0.0.0.0 ns1.webwise.com +0.0.0.0 ns1.webwise.net +0.0.0.0 ns1.webwise.org +0.0.0.0 ns2.oix.com +0.0.0.0 ns2.oix.net +0.0.0.0 ns2.webwise.com +0.0.0.0 ns2.webwise.net +0.0.0.0 ns2.webwise.org +0.0.0.0 nufindings.info +0.0.0.0 office.officenet.co.kr +0.0.0.0 oix.com +0.0.0.0 oix.net +0.0.0.0 oj.likewut.net +0.0.0.0 online-antispym4.com +0.0.0.0 oo-na-na-pics.com +0.0.0.0 ordersildenafil.com +0.0.0.0 otsserver.com +0.0.0.0 outerinfo.com +0.0.0.0 paincake.yoll.net +0.0.0.0 pc-scanner16.com +0.0.0.0 personalantispy.com +0.0.0.0 phatthalung.go.th +0.0.0.0 picture-uploads.com +0.0.0.0 pilltabletsrxbargain.net +0.0.0.0 powabcyfqe.com +0.0.0.0 premium-live-scan.com +0.0.0.0 products-gold.net +0.0.0.0 proflashdata.com # Facebook trojan +0.0.0.0 protectionupdatecenter.com +0.0.0.0 pv.wantsfly.com +0.0.0.0 qip.ru +0.0.0.0 qy.corrmedic.ru +0.0.0.0 rd.alphabirdnetwork.com +0.0.0.0 rickrolling.com +0.0.0.0 roifmd.info +0.0.0.0 russian-sex.com +0.0.0.0 s4d.in +0.0.0.0 scan.antispyware-free-scanner.com +0.0.0.0 scanner.best-click-av1.info +0.0.0.0 scanner.best-protect.info +0.0.0.0 scottishstuff-online.com # Canadian bank phishing site +0.0.0.0 sc-spyware.com +0.0.0.0 search.conduit.com +0.0.0.0 securedliveuploads.com +0.0.0.0 securityandroidupdate.dinamikaprinting.com +0.0.0.0 securityscan.us +0.0.0.0 sexymarissa.net +0.0.0.0 shell.xhhow4.com +0.0.0.0 shoppstop.comood.opsource.net +0.0.0.0 shop.skin-safety.com +0.0.0.0 signin-ebay-com-ws-ebayisapi-dll-signin-webscr.ocom.pl +0.0.0.0 sinera.org +0.0.0.0 sjguild.com +0.0.0.0 smarturl.it +0.0.0.0 smile-angel.com +0.0.0.0 software-updates.co +0.0.0.0 software-wenc.co.cc +0.0.0.0 someonewhocares.com +0.0.0.0 sousay.info +0.0.0.0 start.qip.ru +0.0.0.0 superegler.net +0.0.0.0 supernaturalart.com +0.0.0.0 superprotection10.com +0.0.0.0 sverd.net +0.0.0.0 tahoesup.com +0.0.0.0 tattooshaha.info # Facebook trojan +0.0.0.0 test.ishvara-yoga.com +0.0.0.0 TheBizMeet.com +0.0.0.0 thedatesafe.com # Facebook trojan +0.0.0.0 themoneyclippodcast.com +0.0.0.0 themusicnetwork.co.uk +0.0.0.0 thinstall.abetterinternet.com +0.0.0.0 tivvitter.com +0.0.0.0 tomorrownewstoday.com # I'm not sure what it does, but it seems to be associated with a phishing attempt on Facebook +0.0.0.0 toolbarbest.biz +0.0.0.0 toolbarbucks.biz +0.0.0.0 toolbarcool.biz +0.0.0.0 toolbardollars.biz +0.0.0.0 toolbarmoney.biz +0.0.0.0 toolbarnew.biz +0.0.0.0 toolbarsale.biz +0.0.0.0 toolbarweb.biz +0.0.0.0 traffic.adwitty.com +0.0.0.0 trialreg.com +0.0.0.0 tvshowslist.com +0.0.0.0 twitter.login.kevanshome.org +0.0.0.0 twitter.secure.bzpharma.net +0.0.0.0 uawj.moqhixoz.cn +0.0.0.0 ughmvqf.spitt.ru +0.0.0.0 uqz.com +0.0.0.0 users16.jabry.com +0.0.0.0 utenti.lycos.it +0.0.0.0 vcipo.info +0.0.0.0 videos.dskjkiuw.com +0.0.0.0 videos.twitter.secure-logins01.com # twitter worm (http://mashable.com/2009/09/23/twitter-worm-dms/) +0.0.0.0 vxiframe.biz +0.0.0.0 waldenfarms.com +0.0.0.0 weblover.info +0.0.0.0 webpaypal.com +0.0.0.0 webwise.com +0.0.0.0 webwise.net +0.0.0.0 webwise.org +0.0.0.0 west.05tz2e9.com +0.0.0.0 wewillrocknow.com +0.0.0.0 willysy.com +0.0.0.0 wm.maxysearch.info +0.0.0.0 womo.corrmedic.ru +0.0.0.0 www1.bmo.com.hotfrio.com.br +0.0.0.0 www1.firesavez5.com +0.0.0.0 www1.firesavez6.com +0.0.0.0 www1.realsoft34.com +0.0.0.0 www4.gy7k.net +0.0.0.0 www.abetterinternet.com +0.0.0.0 www.adshufffle.com +0.0.0.0 www.adwords.google.lloymlincs.com +0.0.0.0 www.afantispy.com +0.0.0.0 www.akoneplatit.sk +0.0.0.0 www.allhqpics.com # Facebook trojan +0.0.0.0 www.alrpost69.com +0.0.0.0 www.anatol.com +0.0.0.0 www.articlefuns.cn +0.0.0.0 www.articleidea.cn +0.0.0.0 www.asianread.com +0.0.0.0 www.backsim.ru +0.0.0.0 www.bankofamerica.com.ok.am +0.0.0.0 www.be4life.ru +0.0.0.0 www.blenz-me.net +0.0.0.0 www.cambonanza.com +0.0.0.0 www.chelick.net # Facebook trojan +0.0.0.0 www.didata.bw +0.0.0.0 www.dietsecret.ru +0.0.0.0 www.eroyear.ru +0.0.0.0 www.exbays.com +0.0.0.0 www.faggotry.com +0.0.0.0 www.feaecebook.com +0.0.0.0 www.fictioncinema.com +0.0.0.0 www.fischereszter.hu +0.0.0.0 www.froling.bee.pl +0.0.0.0 www.gns-consola.com +0.0.0.0 www.goggle.com +0.0.0.0 www.grouphappy.com +0.0.0.0 www.hakerzy.net +0.0.0.0 www.haoyunlaid.com +0.0.0.0 www.icecars.com +0.0.0.0 www.indesignstudioinfo.com +0.0.0.0 www.infopaypal.com +0.0.0.0 www.keybinary.com +0.0.0.0 www.kinomarathon.ru +0.0.0.0 www.kpremium.com +0.0.0.0 www.likeportal.com # Facebook trojan +0.0.0.0 www.likespike.com # Facebook trojan +0.0.0.0 www.likethislist.biz # Facebook trojan +0.0.0.0 www.likethis.mbosoft.com # Facebook trojan +0.0.0.0 www.lomalindasda.org # Facebook trojan +0.0.0.0 www.lovecouple.ru +0.0.0.0 www.lovetrust.ru +0.0.0.0 www.mikras.nl +0.0.0.0 www.monkeyball.osa.pl +0.0.0.0 www.monsonis.net +0.0.0.0 www.movie-port.ru +0.0.0.0 www.mplayerdownloader.com +0.0.0.0 www.mylike.co.uk # Facebook trojan +0.0.0.0 www.mylovecards.com +0.0.0.0 www.nine2rack.in +0.0.0.0 www.novemberrainx.com +0.0.0.0 www.nu26.com +0.0.0.0 www.oix.com +0.0.0.0 www.oix.net +0.0.0.0 www.onlyfreeoffersonline.com +0.0.0.0 www.oreidofitilho.com.br +0.0.0.0 www.otsserver.com +0.0.0.0 www.pay-pal.com-cgibin-canada.4mcmeta4v.cn +0.0.0.0 www.picture-uploads.com +0.0.0.0 www.portaldimensional.com +0.0.0.0 www.poxudeli.ru +0.0.0.0 www.proflashdata.com # Facebook trojan +0.0.0.0 www.rickrolling.com +0.0.0.0 www.russian-sex.com +0.0.0.0 www.scotiaonline.scotiabank.salferreras.com +0.0.0.0 www.sdlpgift.com +0.0.0.0 www.securityscan.us +0.0.0.0 www.servertasarimbu.com +0.0.0.0 www.sexytiger.ru +0.0.0.0 www.shinilchurch.net # domain was hacked and had a trojan installed +0.0.0.0 www.sinera.org +0.0.0.0 www.someonewhocares.com +0.0.0.0 www.tanger.com.br +0.0.0.0 www.tattooshaha.info # Facebook trojan +0.0.0.0 www.te81.net +0.0.0.0 www.thedatesafe.com # Facebook trojan +0.0.0.0 www.trucktirehotline.com +0.0.0.0 www.tvshowslist.com +0.0.0.0 www.upi6.pillsstore-c.com # Facebook trojan +0.0.0.0 www.uqz.com +0.0.0.0 www.via99.org +0.0.0.0 www.videolove.clanteam.com +0.0.0.0 www.videostan.ru +0.0.0.0 www.vippotexa.ru +0.0.0.0 www.wantsfly.com +0.0.0.0 www.webpaypal.com +0.0.0.0 www.webwise.com +0.0.0.0 www.webwise.net +0.0.0.0 www.webwise.org +0.0.0.0 www.wewillrocknow.com +0.0.0.0 www.willysy.com +0.0.0.0 xfotosx01.fromru.su +0.0.0.0 xponlinescanner.com +0.0.0.0 xvrxyzba253.hotmail.ru +0.0.0.0 yrwap.cn +0.0.0.0 zarozinski.info +0.0.0.0 zettapetta.com +0.0.0.0 zfotos.fromru.su +0.0.0.0 zip.er.cz +0.0.0.0 ztrf.net +0.0.0.0 zviframe.biz +# + +# + +0.0.0.0 3ad.doubleclick.net +0.0.0.0 ad2.doubleclick.net +0.0.0.0 ad.3au.doubleclick.net +0.0.0.0 ad.ae.doubleclick.net +0.0.0.0 ad.au.doubleclick.net +0.0.0.0 ad.be.doubleclick.net +0.0.0.0 ad.br.doubleclick.net +0.0.0.0 ad.de.doubleclick.net +0.0.0.0 ad.dk.doubleclick.net +0.0.0.0 ad-emea.doubleclick.net +0.0.0.0 ad.es.doubleclick.net +0.0.0.0 ad.fi.doubleclick.net +0.0.0.0 ad.fr.doubleclick.net +0.0.0.0 ad-g.doubleclick.net +0.0.0.0 ad.it.doubleclick.net +0.0.0.0 ad.jp.doubleclick.net +0.0.0.0 ad.mo.doubleclick.net +0.0.0.0 ad.n2434.doubleclick.net +0.0.0.0 ad.nl.doubleclick.net +0.0.0.0 ad.no.doubleclick.net +0.0.0.0 ad.nz.doubleclick.net +0.0.0.0 ad.pl.doubleclick.net +0.0.0.0 ad.se.doubleclick.net +0.0.0.0 ad.sg.doubleclick.net +0.0.0.0 ad.uk.doubleclick.net +0.0.0.0 ad.ve.doubleclick.net +0.0.0.0 ad-yt-bfp.doubleclick.net +0.0.0.0 ad.za.doubleclick.net +0.0.0.0 amn.doubleclick.net +0.0.0.0 creative.cc-dt.com +0.0.0.0 doubleclick.de +0.0.0.0 doubleclick.net +0.0.0.0 ebaycn.doubleclick.net +0.0.0.0 ebaytw.doubleclick.net +0.0.0.0 exnjadgda1.doubleclick.net +0.0.0.0 exnjadgda2.doubleclick.net +0.0.0.0 exnjadgds1.doubleclick.net +0.0.0.0 exnjmdgda1.doubleclick.net +0.0.0.0 exnjmdgds1.doubleclick.net +0.0.0.0 feedads.g.doubleclick.net +0.0.0.0 fls.doubleclick.net +0.0.0.0 gd10.doubleclick.net +0.0.0.0 gd11.doubleclick.net +0.0.0.0 gd12.doubleclick.net +0.0.0.0 gd13.doubleclick.net +0.0.0.0 gd14.doubleclick.net +0.0.0.0 gd15.doubleclick.net +0.0.0.0 gd16.doubleclick.net +0.0.0.0 gd17.doubleclick.net +0.0.0.0 gd18.doubleclick.net +0.0.0.0 gd19.doubleclick.net +0.0.0.0 gd1.doubleclick.net +0.0.0.0 gd20.doubleclick.net +0.0.0.0 gd21.doubleclick.net +0.0.0.0 gd22.doubleclick.net +0.0.0.0 gd23.doubleclick.net +0.0.0.0 gd24.doubleclick.net +0.0.0.0 gd25.doubleclick.net +0.0.0.0 gd26.doubleclick.net +0.0.0.0 gd27.doubleclick.net +0.0.0.0 gd28.doubleclick.net +0.0.0.0 gd29.doubleclick.net +0.0.0.0 gd2.doubleclick.net +0.0.0.0 gd30.doubleclick.net +0.0.0.0 gd31.doubleclick.net +0.0.0.0 gd3.doubleclick.net +0.0.0.0 gd4.doubleclick.net +0.0.0.0 gd5.doubleclick.net +0.0.0.0 gd7.doubleclick.net +0.0.0.0 gd8.doubleclick.net +0.0.0.0 gd9.doubleclick.net +0.0.0.0 googleads.g.doubleclick.net +0.0.0.0 iv.doubleclick.net +0.0.0.0 ln.doubleclick.net +0.0.0.0 m1.2mdn.net +0.0.0.0 m1.ae.2mdn.net +0.0.0.0 m1.au.2mdn.net +0.0.0.0 m1.be.2mdn.net +0.0.0.0 m1.br.2mdn.net +0.0.0.0 m1.ca.2mdn.net +0.0.0.0 m1.cn.2mdn.net +0.0.0.0 m1.de.2mdn.net +0.0.0.0 m1.dk.2mdn.net +0.0.0.0 m1.doubleclick.net +0.0.0.0 m1.es.2mdn.net +0.0.0.0 m1.fi.2mdn.net +0.0.0.0 m1.fr.2mdn.net +0.0.0.0 m1.it.2mdn.net +0.0.0.0 m1.jp.2mdn.net +0.0.0.0 m1.nl.2mdn.net +0.0.0.0 m1.no.2mdn.net +0.0.0.0 m1.nz.2mdn.net +0.0.0.0 m1.pl.2mdn.net +0.0.0.0 m1.se.2mdn.net +0.0.0.0 m1.sg.2mdn.net +0.0.0.0 m1.uk.2mdn.net +0.0.0.0 m1.ve.2mdn.net +0.0.0.0 m1.za.2mdn.net +0.0.0.0 m2.ae.2mdn.net +0.0.0.0 m2.au.2mdn.net +0.0.0.0 m2.be.2mdn.net +0.0.0.0 m2.br.2mdn.net +0.0.0.0 m2.ca.2mdn.net +0.0.0.0 m2.cn.2mdn.net +0.0.0.0 m2.cn.doubleclick.net +0.0.0.0 m2.de.2mdn.net +0.0.0.0 m2.dk.2mdn.net +0.0.0.0 m2.doubleclick.net +0.0.0.0 m2.es.2mdn.net +0.0.0.0 m2.fi.2mdn.net +0.0.0.0 m2.fr.2mdn.net +0.0.0.0 m2.it.2mdn.net +0.0.0.0 m2.jp.2mdn.net +0.0.0.0 m.2mdn.net +0.0.0.0 m2.nl.2mdn.net +0.0.0.0 m2.no.2mdn.net +0.0.0.0 m2.nz.2mdn.net +0.0.0.0 m2.pl.2mdn.net +0.0.0.0 m2.se.2mdn.net +0.0.0.0 m2.sg.2mdn.net +0.0.0.0 m2.uk.2mdn.net +0.0.0.0 m2.ve.2mdn.net +0.0.0.0 m2.za.2mdn.net +0.0.0.0 m3.ae.2mdn.net +0.0.0.0 m3.au.2mdn.net +0.0.0.0 m3.be.2mdn.net +0.0.0.0 m3.br.2mdn.net +0.0.0.0 m3.ca.2mdn.net +0.0.0.0 m3.cn.2mdn.net +0.0.0.0 m3.de.2mdn.net +0.0.0.0 m3.dk.2mdn.net +0.0.0.0 m3.doubleclick.net +0.0.0.0 m3.es.2mdn.net +0.0.0.0 m3.fi.2mdn.net +0.0.0.0 m3.fr.2mdn.net +0.0.0.0 m3.it.2mdn.net +0.0.0.0 m3.jp.2mdn.net +0.0.0.0 m3.nl.2mdn.net +0.0.0.0 m3.no.2mdn.net +0.0.0.0 m3.nz.2mdn.net +0.0.0.0 m3.pl.2mdn.net +0.0.0.0 m3.se.2mdn.net +0.0.0.0 m3.sg.2mdn.net +0.0.0.0 m3.uk.2mdn.net +0.0.0.0 m3.ve.2mdn.net +0.0.0.0 m3.za.2mdn.net +0.0.0.0 m4.ae.2mdn.net +0.0.0.0 m4.au.2mdn.net +0.0.0.0 m4.be.2mdn.net +0.0.0.0 m4.br.2mdn.net +0.0.0.0 m4.ca.2mdn.net +0.0.0.0 m4.cn.2mdn.net +0.0.0.0 m4.de.2mdn.net +0.0.0.0 m4.dk.2mdn.net +0.0.0.0 m4.doubleclick.net +0.0.0.0 m4.es.2mdn.net +0.0.0.0 m4.fi.2mdn.net +0.0.0.0 m4.fr.2mdn.net +0.0.0.0 m4.it.2mdn.net +0.0.0.0 m4.jp.2mdn.net +0.0.0.0 m4.nl.2mdn.net +0.0.0.0 m4.no.2mdn.net +0.0.0.0 m4.nz.2mdn.net +0.0.0.0 m4.pl.2mdn.net +0.0.0.0 m4.se.2mdn.net +0.0.0.0 m4.sg.2mdn.net +0.0.0.0 m4.uk.2mdn.net +0.0.0.0 m4.ve.2mdn.net +0.0.0.0 m4.za.2mdn.net +0.0.0.0 m5.ae.2mdn.net +0.0.0.0 m5.au.2mdn.net +0.0.0.0 m5.be.2mdn.net +0.0.0.0 m5.br.2mdn.net +0.0.0.0 m5.ca.2mdn.net +0.0.0.0 m5.cn.2mdn.net +0.0.0.0 m5.de.2mdn.net +0.0.0.0 m5.dk.2mdn.net +0.0.0.0 m5.doubleclick.net +0.0.0.0 m5.es.2mdn.net +0.0.0.0 m5.fi.2mdn.net +0.0.0.0 m5.fr.2mdn.net +0.0.0.0 m5.it.2mdn.net +0.0.0.0 m5.jp.2mdn.net +0.0.0.0 m5.nl.2mdn.net +0.0.0.0 m5.no.2mdn.net +0.0.0.0 m5.nz.2mdn.net +0.0.0.0 m5.pl.2mdn.net +0.0.0.0 m5.se.2mdn.net +0.0.0.0 m5.sg.2mdn.net +0.0.0.0 m5.uk.2mdn.net +0.0.0.0 m5.ve.2mdn.net +0.0.0.0 m5.za.2mdn.net +0.0.0.0 m6.ae.2mdn.net +0.0.0.0 m6.au.2mdn.net +0.0.0.0 m6.be.2mdn.net +0.0.0.0 m6.br.2mdn.net +0.0.0.0 m6.ca.2mdn.net +0.0.0.0 m6.cn.2mdn.net +0.0.0.0 m6.de.2mdn.net +0.0.0.0 m6.dk.2mdn.net +0.0.0.0 m6.doubleclick.net +0.0.0.0 m6.es.2mdn.net +0.0.0.0 m6.fi.2mdn.net +0.0.0.0 m6.fr.2mdn.net +0.0.0.0 m6.it.2mdn.net +0.0.0.0 m6.jp.2mdn.net +0.0.0.0 m6.nl.2mdn.net +0.0.0.0 m6.no.2mdn.net +0.0.0.0 m6.nz.2mdn.net +0.0.0.0 m6.pl.2mdn.net +0.0.0.0 m6.se.2mdn.net +0.0.0.0 m6.sg.2mdn.net +0.0.0.0 m6.uk.2mdn.net +0.0.0.0 m6.ve.2mdn.net +0.0.0.0 m6.za.2mdn.net +0.0.0.0 m7.ae.2mdn.net +0.0.0.0 m7.au.2mdn.net +0.0.0.0 m7.be.2mdn.net +0.0.0.0 m7.br.2mdn.net +0.0.0.0 m7.ca.2mdn.net +0.0.0.0 m7.cn.2mdn.net +0.0.0.0 m7.de.2mdn.net +0.0.0.0 m7.dk.2mdn.net +0.0.0.0 m7.doubleclick.net +0.0.0.0 m7.es.2mdn.net +0.0.0.0 m7.fi.2mdn.net +0.0.0.0 m7.fr.2mdn.net +0.0.0.0 m7.it.2mdn.net +0.0.0.0 m7.jp.2mdn.net +0.0.0.0 m7.nl.2mdn.net +0.0.0.0 m7.no.2mdn.net +0.0.0.0 m7.nz.2mdn.net +0.0.0.0 m7.pl.2mdn.net +0.0.0.0 m7.se.2mdn.net +0.0.0.0 m7.sg.2mdn.net +0.0.0.0 m7.uk.2mdn.net +0.0.0.0 m7.ve.2mdn.net +0.0.0.0 m7.za.2mdn.net +0.0.0.0 m8.ae.2mdn.net +0.0.0.0 m8.au.2mdn.net +0.0.0.0 m8.be.2mdn.net +0.0.0.0 m8.br.2mdn.net +0.0.0.0 m8.ca.2mdn.net +0.0.0.0 m8.cn.2mdn.net +0.0.0.0 m8.de.2mdn.net +0.0.0.0 m8.dk.2mdn.net +0.0.0.0 m8.doubleclick.net +0.0.0.0 m8.es.2mdn.net +0.0.0.0 m8.fi.2mdn.net +0.0.0.0 m8.fr.2mdn.net +0.0.0.0 m8.it.2mdn.net +0.0.0.0 m8.jp.2mdn.net +0.0.0.0 m8.nl.2mdn.net +0.0.0.0 m8.no.2mdn.net +0.0.0.0 m8.nz.2mdn.net +0.0.0.0 m8.pl.2mdn.net +0.0.0.0 m8.se.2mdn.net +0.0.0.0 m8.sg.2mdn.net +0.0.0.0 m8.uk.2mdn.net +0.0.0.0 m8.ve.2mdn.net +0.0.0.0 m8.za.2mdn.net +0.0.0.0 m9.ae.2mdn.net +0.0.0.0 m9.au.2mdn.net +0.0.0.0 m9.be.2mdn.net +0.0.0.0 m9.br.2mdn.net +0.0.0.0 m9.ca.2mdn.net +0.0.0.0 m9.cn.2mdn.net +0.0.0.0 m9.de.2mdn.net +0.0.0.0 m9.dk.2mdn.net +0.0.0.0 m9.doubleclick.net +0.0.0.0 m9.es.2mdn.net +0.0.0.0 m9.fi.2mdn.net +0.0.0.0 m9.fr.2mdn.net +0.0.0.0 m9.it.2mdn.net +0.0.0.0 m9.jp.2mdn.net +0.0.0.0 m9.nl.2mdn.net +0.0.0.0 m9.no.2mdn.net +0.0.0.0 m9.nz.2mdn.net +0.0.0.0 m9.pl.2mdn.net +0.0.0.0 m9.se.2mdn.net +0.0.0.0 m9.sg.2mdn.net +0.0.0.0 m9.uk.2mdn.net +0.0.0.0 m9.ve.2mdn.net +0.0.0.0 m9.za.2mdn.net +0.0.0.0 m.de.2mdn.net +0.0.0.0 m.doubleclick.net +0.0.0.0 n3302ad.doubleclick.net +0.0.0.0 n3349ad.doubleclick.net +0.0.0.0 n4061ad.doubleclick.net +0.0.0.0 n4403ad.doubleclick.net +0.0.0.0 n479ad.doubleclick.net +0.0.0.0 optimize.doubleclick.net +0.0.0.0 pubads.g.doubleclick.net +0.0.0.0 rd.intl.doubleclick.net +0.0.0.0 securepubads.g.doubleclick.net +0.0.0.0 stats.g.doubleclick.net +0.0.0.0 twx.2mdn.net +0.0.0.0 twx.doubleclick.net +0.0.0.0 ukrpts.net +0.0.0.0 uunyadgda1.doubleclick.net +0.0.0.0 uunyadgds1.doubleclick.net +0.0.0.0 www.ukrpts.net +# + +# + +0.0.0.0 1up.us.intellitxt.com +0.0.0.0 5starhiphop.us.intellitxt.com +0.0.0.0 askmen2.us.intellitxt.com +0.0.0.0 bargainpda.us.intellitxt.com +0.0.0.0 businesspundit.us.intellitxt.com +0.0.0.0 canadafreepress.us.intellitxt.com +0.0.0.0 contactmusic.uk.intellitxt.com +0.0.0.0 ctv.us.intellitxt.com +0.0.0.0 designtechnica.us.intellitxt.com +0.0.0.0 devshed.us.intellitxt.com +0.0.0.0 digitaltrends.us.intellitxt.com +0.0.0.0 dnps.us.intellitxt.com +0.0.0.0 doubleviking.us.intellitxt.com +0.0.0.0 drizzydrake.us.intellitxt.com +0.0.0.0 ehow.us.intellitxt.com +0.0.0.0 entertainment.msnbc.us.intellitxt.com +0.0.0.0 examnotes.us.intellitxt.com +0.0.0.0 excite.us.intellitxt.com +0.0.0.0 experts.us.intellitxt.com +0.0.0.0 extremetech.us.intellitxt.com +0.0.0.0 ferrago.uk.intellitxt.com +0.0.0.0 filmschoolrejects.us.intellitxt.com +0.0.0.0 filmwad.us.intellitxt.com +0.0.0.0 firstshowing.us.intellitxt.com +0.0.0.0 flashmagazine.us.intellitxt.com +0.0.0.0 foxnews.us.intellitxt.com +0.0.0.0 foxtv.us.intellitxt.com +0.0.0.0 freedownloadcenter.uk.intellitxt.com +0.0.0.0 gadgets.fosfor.se.intellitxt.com +0.0.0.0 gamesradar.us.intellitxt.com +0.0.0.0 gannettbroadcast.us.intellitxt.com +0.0.0.0 gonintendo.us.intellitxt.com +0.0.0.0 gorillanation.us.intellitxt.com +0.0.0.0 hackedgadgets.us.intellitxt.com +0.0.0.0 hardcoreware.us.intellitxt.com +0.0.0.0 hardocp.us.intellitxt.com +0.0.0.0 hothardware.us.intellitxt.com +0.0.0.0 hotonlinenews.us.intellitxt.com +0.0.0.0 ign.us.intellitxt.com +0.0.0.0 images.intellitxt.com +0.0.0.0 itxt2.us.intellitxt.com +0.0.0.0 joblo.us.intellitxt.com +0.0.0.0 johnchow.us.intellitxt.com +0.0.0.0 laptopmag.us.intellitxt.com +0.0.0.0 linuxforums.us.intellitxt.com +0.0.0.0 maccity.it.intellitxt.com +0.0.0.0 macnn.us.intellitxt.com +0.0.0.0 macuser.uk.intellitxt.com +0.0.0.0 macworld.uk.intellitxt.com +0.0.0.0 metro.uk.intellitxt.com +0.0.0.0 mobile9.us.intellitxt.com +0.0.0.0 monstersandcritics.uk.intellitxt.com +0.0.0.0 moviesonline.ca.intellitxt.com +0.0.0.0 mustangevolution.us.intellitxt.com +0.0.0.0 neowin.us.intellitxt.com +0.0.0.0 newcarnet.uk.intellitxt.com +0.0.0.0 newlaunches.uk.intellitxt.com +0.0.0.0 nexys404.us.intellitxt.com +0.0.0.0 ohgizmo.us.intellitxt.com +0.0.0.0 pcadvisor.uk.intellitxt.com +0.0.0.0 pcgameshardware.de.intellitxt.com +0.0.0.0 pcmag.us.intellitxt.com +0.0.0.0 pcper.us.intellitxt.com +0.0.0.0 penton.us.intellitxt.com +0.0.0.0 physorg.uk.intellitxt.com +0.0.0.0 physorg.us.intellitxt.com +0.0.0.0 playfuls.uk.intellitxt.com +0.0.0.0 pocketlint.uk.intellitxt.com +0.0.0.0 popularmechanics.us.intellitxt.com +0.0.0.0 postchronicle.us.intellitxt.com +0.0.0.0 projectorreviews.us.intellitxt.com +0.0.0.0 psp3d.us.intellitxt.com +0.0.0.0 pspcave.uk.intellitxt.com +0.0.0.0 qj.us.intellitxt.com +0.0.0.0 rasmussenreports.us.intellitxt.com +0.0.0.0 rawstory.us.intellitxt.com +0.0.0.0 savemanny.us.intellitxt.com +0.0.0.0 sc.intellitxt.com +0.0.0.0 siliconera.us.intellitxt.com +0.0.0.0 slashphone.us.intellitxt.com +0.0.0.0 soft32.us.intellitxt.com +0.0.0.0 softpedia.uk.intellitxt.com +0.0.0.0 somethingawful.us.intellitxt.com +0.0.0.0 splashnews.uk.intellitxt.com +0.0.0.0 spymac.us.intellitxt.com +0.0.0.0 techeblog.us.intellitxt.com +0.0.0.0 technewsworld.us.intellitxt.com +0.0.0.0 technologyreview.us.intellitxt.com +0.0.0.0 techspot.us.intellitxt.com +0.0.0.0 tgdaily.us.intellitxt.com +0.0.0.0 the-gadgeteer.us.intellitxt.com +0.0.0.0 thelastboss.us.intellitxt.com +0.0.0.0 thetechzone.us.intellitxt.com +0.0.0.0 thoughtsmedia.us.intellitxt.com +0.0.0.0 tmcnet.us.intellitxt.com +0.0.0.0 tomsnetworking.us.intellitxt.com +0.0.0.0 toms.us.intellitxt.com +0.0.0.0 tribal.us.intellitxt.com # vibrantmedia.com +0.0.0.0 universetoday.us.intellitxt.com +0.0.0.0 us.intellitxt.com +0.0.0.0 warp2search.us.intellitxt.com +0.0.0.0 wi-fitechnology.uk.intellitxt.com +0.0.0.0 worldnetdaily.us.intellitxt.com +# + +# + +# Red Sheriff and imrworldwide.com -- server side tracking +0.0.0.0 devfw.imrworldwide.com +0.0.0.0 fe1-au.imrworldwide.com +0.0.0.0 fe1-fi.imrworldwide.com +0.0.0.0 fe1-it.imrworldwide.com +0.0.0.0 fe2-au.imrworldwide.com +0.0.0.0 fe3-au.imrworldwide.com +0.0.0.0 fe3-gc.imrworldwide.com +0.0.0.0 fe3-uk.imrworldwide.com +0.0.0.0 fe4-uk.imrworldwide.com +0.0.0.0 fe-au.imrworldwide.com +0.0.0.0 imrworldwide.com +0.0.0.0 lycos-eu.imrworldwide.com +0.0.0.0 ninemsn.imrworldwide.com +0.0.0.0 rc-au.imrworldwide.com +0.0.0.0 redsheriff.com +#0.0.0.0 secure-au.imrworldwide.com +0.0.0.0 secure-jp.imrworldwide.com +0.0.0.0 secure-nz.imrworldwide.com +0.0.0.0 secure-uk.imrworldwide.com +0.0.0.0 secure-us.imrworldwide.com +0.0.0.0 secure-za.imrworldwide.com +0.0.0.0 server-au.imrworldwide.com +0.0.0.0 server-br.imrworldwide.com +0.0.0.0 server-by.imrworldwide.com +0.0.0.0 server-ca.imrworldwide.com +0.0.0.0 server-de.imrworldwide.com +0.0.0.0 server-dk.imrworldwide.com +0.0.0.0 server-ee.imrworldwide.com +0.0.0.0 server-fi.imrworldwide.com +0.0.0.0 server-fr.imrworldwide.com +0.0.0.0 server-hk.imrworldwide.com +0.0.0.0 server-it.imrworldwide.com +0.0.0.0 server-jp.imrworldwide.com +0.0.0.0 server-lt.imrworldwide.com +0.0.0.0 server-lv.imrworldwide.com +0.0.0.0 server-no.imrworldwide.com +0.0.0.0 server-nz.imrworldwide.com +0.0.0.0 server-oslo.imrworldwide.com +0.0.0.0 server-pl.imrworldwide.com +0.0.0.0 server-ru.imrworldwide.com +0.0.0.0 server-se.imrworldwide.com +0.0.0.0 server-sg.imrworldwide.com +0.0.0.0 server-stockh.imrworldwide.com +0.0.0.0 server-ua.imrworldwide.com +0.0.0.0 server-uk.imrworldwide.com +0.0.0.0 server-us.imrworldwide.com +0.0.0.0 server-za.imrworldwide.com +0.0.0.0 survey1-au.imrworldwide.com +0.0.0.0 telstra.imrworldwide.com +0.0.0.0 www.imrworldwide.com +0.0.0.0 www.imrworldwide.com.au +0.0.0.0 www.redsheriff.com +# + +# + +# cydoor -- server side tracking +0.0.0.0 cydoor.com +0.0.0.0 j.2004cms.com # cydoor +0.0.0.0 jbaventures.cjt1.net +0.0.0.0 jbeet.cjt1.net +0.0.0.0 jbit.cjt1.net +0.0.0.0 jcollegehumor.cjt1.net +0.0.0.0 jcontent.bns1.net +0.0.0.0 jdownloadacc.cjt1.net +0.0.0.0 jgen10.cjt1.net +0.0.0.0 jgen11.cjt1.net +0.0.0.0 jgen12.cjt1.net +0.0.0.0 jgen13.cjt1.net +0.0.0.0 jgen14.cjt1.net +0.0.0.0 jgen15.cjt1.net +0.0.0.0 jgen16.cjt1.net +0.0.0.0 jgen17.cjt1.net +0.0.0.0 jgen18.cjt1.net +0.0.0.0 jgen19.cjt1.net +0.0.0.0 jgen1.cjt1.net +0.0.0.0 jgen20.cjt1.net +0.0.0.0 jgen21.cjt1.net +0.0.0.0 jgen22.cjt1.net +0.0.0.0 jgen23.cjt1.net +0.0.0.0 jgen24.cjt1.net +0.0.0.0 jgen25.cjt1.net +0.0.0.0 jgen26.cjt1.net +0.0.0.0 jgen27.cjt1.net +0.0.0.0 jgen28.cjt1.net +0.0.0.0 jgen29.cjt1.net +0.0.0.0 jgen2.cjt1.net +0.0.0.0 jgen30.cjt1.net +0.0.0.0 jgen31.cjt1.net +0.0.0.0 jgen32.cjt1.net +0.0.0.0 jgen33.cjt1.net +0.0.0.0 jgen34.cjt1.net +0.0.0.0 jgen35.cjt1.net +0.0.0.0 jgen36.cjt1.net +0.0.0.0 jgen37.cjt1.net +0.0.0.0 jgen38.cjt1.net +0.0.0.0 jgen39.cjt1.net +0.0.0.0 jgen3.cjt1.net +0.0.0.0 jgen40.cjt1.net +0.0.0.0 jgen41.cjt1.net +0.0.0.0 jgen42.cjt1.net +0.0.0.0 jgen43.cjt1.net +0.0.0.0 jgen44.cjt1.net +0.0.0.0 jgen45.cjt1.net +0.0.0.0 jgen46.cjt1.net +0.0.0.0 jgen47.cjt1.net +0.0.0.0 jgen48.cjt1.net +0.0.0.0 jgen49.cjt1.net +0.0.0.0 jgen4.cjt1.net +0.0.0.0 jgen5.cjt1.net +0.0.0.0 jgen6.cjt1.net +0.0.0.0 jgen7.cjt1.net +0.0.0.0 jgen8.cjt1.net +0.0.0.0 jgen9.cjt1.net +0.0.0.0 jhumour.cjt1.net +0.0.0.0 jmbi58.cjt1.net +0.0.0.0 jnova.cjt1.net +0.0.0.0 jpirate.cjt1.net +0.0.0.0 jsandboxer.cjt1.net +0.0.0.0 jumcna.cjt1.net +0.0.0.0 jwebbsense.cjt1.net +0.0.0.0 www.cydoor.com +# + +#<2o7-sites> + +# 2o7.net -- server side tracking +0.0.0.0 102.112.2o7.net +0.0.0.0 102.122.2o7.net +0.0.0.0 112.2o7.net +0.0.0.0 122.2o7.net +0.0.0.0 192.168.112.2o7.net +0.0.0.0 2o7.net +0.0.0.0 actforvictory.112.2o7.net +0.0.0.0 adbrite.112.2o7.net +0.0.0.0 adbrite.122.2o7.net +0.0.0.0 aehistory.112.2o7.net +0.0.0.0 aetv.112.2o7.net +0.0.0.0 agamgreetingscom.112.2o7.net +0.0.0.0 allbritton.122.2o7.net +0.0.0.0 americanbaby.112.2o7.net +0.0.0.0 ancestrymsn.112.2o7.net +0.0.0.0 ancestryuki.112.2o7.net +0.0.0.0 angiba.112.2o7.net +0.0.0.0 angmar.112.2o7.net +0.0.0.0 angtr.112.2o7.net +0.0.0.0 angts.112.2o7.net +0.0.0.0 angvac.112.2o7.net +0.0.0.0 anm.112.2o7.net +0.0.0.0 aolcareers.122.2o7.net +0.0.0.0 aoldlama.122.2o7.net +0.0.0.0 aoljournals.122.2o7.net +0.0.0.0 aolnsnews.122.2o7.net +0.0.0.0 aolpf.122.2o7.net +0.0.0.0 aolpolls.112.2o7.net +0.0.0.0 aolpolls.122.2o7.net +0.0.0.0 aolsearch.122.2o7.net +0.0.0.0 aolsvc.122.2o7.net +0.0.0.0 aoltmz.122.2o7.net +0.0.0.0 aolturnercnnmoney.112.2o7.net +0.0.0.0 aolturnercnnmoney.122.2o7.net +0.0.0.0 aolturnersi.122.2o7.net +0.0.0.0 aolukglobal.122.2o7.net +0.0.0.0 aolwinamp.122.2o7.net +0.0.0.0 aolwpaim.112.2o7.net +0.0.0.0 aolwpicq.122.2o7.net +0.0.0.0 aolwpmq.112.2o7.net +0.0.0.0 aolwpmqnoban.112.2o7.net +0.0.0.0 apdigitalorg.112.2o7.net +0.0.0.0 apdigitalorgovn.112.2o7.net +0.0.0.0 apnonline.112.2o7.net +#0.0.0.0 appleglobal.112.2o7.net #breaks apple.com +#0.0.0.0 applestoreus.112.2o7.net #breaks apple.com +0.0.0.0 atlassian.122.2o7.net +0.0.0.0 autobytel.112.2o7.net +0.0.0.0 autoweb.112.2o7.net +0.0.0.0 bbcnewscouk.112.2o7.net +0.0.0.0 bellca.112.2o7.net +0.0.0.0 bellglobemediapublishing.122.2o7.net +0.0.0.0 bellglovemediapublishing.122.2o7.net +0.0.0.0 bellserviceeng.112.2o7.net +0.0.0.0 betterhg.112.2o7.net +0.0.0.0 bhgmarketing.112.2o7.net +0.0.0.0 bidentonrccom.122.2o7.net +0.0.0.0 biwwltvcom.112.2o7.net +0.0.0.0 biwwltvcom.122.2o7.net +0.0.0.0 blackpress.122.2o7.net +0.0.0.0 bnkr8dev.112.2o7.net +0.0.0.0 bntbcstglobal.112.2o7.net +0.0.0.0 bosecom.112.2o7.net +0.0.0.0 brightcove.112.2o7.net +0.0.0.0 bulldog.122.2o7.net +0.0.0.0 businessweekpoc.112.2o7.net +0.0.0.0 bzresults.122.2o7.net +0.0.0.0 cablevision.112.2o7.net +0.0.0.0 canwest.112.2o7.net +0.0.0.0 canwestcom.112.2o7.net +0.0.0.0 canwestglobal.112.2o7.net +0.0.0.0 capcityadvcom.112.2o7.net +0.0.0.0 capcityadvcom.122.2o7.net +0.0.0.0 careers.112.2o7.net +0.0.0.0 cartoonnetwork.122.2o7.net +0.0.0.0 cbaol.112.2o7.net +0.0.0.0 cbc.122.2o7.net +0.0.0.0 cbcca.112.2o7.net +0.0.0.0 cbcca.122.2o7.net +0.0.0.0 cbcincinnatienquirer.112.2o7.net +0.0.0.0 cbmsn.112.2o7.net +0.0.0.0 cbs.112.2o7.net +0.0.0.0 cbsncaasports.112.2o7.net +0.0.0.0 cbsnfl.112.2o7.net +0.0.0.0 cbspgatour.112.2o7.net +0.0.0.0 cbsspln.112.2o7.net +0.0.0.0 ccrbudgetca.112.2o7.net +0.0.0.0 ccrgaviscom.112.2o7.net +0.0.0.0 cfrfa.112.2o7.net +0.0.0.0 chicagosuntimes.122.2o7.net +0.0.0.0 chumtv.122.2o7.net +0.0.0.0 classifiedscanada.112.2o7.net +0.0.0.0 classmatescom.112.2o7.net +0.0.0.0 cmpglobalvista.112.2o7.net +0.0.0.0 cnetasiapacific.122.2o7.net +0.0.0.0 cnetaustralia.122.2o7.net +0.0.0.0 cneteurope.122.2o7.net +0.0.0.0 cnetnews.112.2o7.net +0.0.0.0 cnetzdnet.112.2o7.net +0.0.0.0 cnhienid.122.2o7.net +0.0.0.0 cnhimcalesternews.122.2o7.net +0.0.0.0 cnhipicayuneitemv.112.2o7.net +0.0.0.0 cnhitribunestar.122.2o7.net +0.0.0.0 cnhitribunestara.122.2o7.net +0.0.0.0 cnhregisterherald.122.2o7.net +0.0.0.0 cnn.122.2o7.net +0.0.0.0 computerworldcom.112.2o7.net +0.0.0.0 condenast.112.2o7.net +0.0.0.0 coxnetmasterglobal.112.2o7.net +0.0.0.0 coxpalmbeachpost.112.2o7.net +0.0.0.0 csoonlinecom.112.2o7.net +0.0.0.0 ctvcrimelibrary.112.2o7.net +0.0.0.0 ctvsmokinggun.112.2o7.net +0.0.0.0 cxociocom.112.2o7.net +0.0.0.0 denverpost.112.2o7.net +0.0.0.0 diginet.112.2o7.net +0.0.0.0 digitalhomediscountptyltd.122.2o7.net +0.0.0.0 disccglobal.112.2o7.net +0.0.0.0 disccstats.112.2o7.net +0.0.0.0 dischannel.112.2o7.net +0.0.0.0 divx.112.2o7.net +0.0.0.0 dixonslnkcouk.112.2o7.net +0.0.0.0 dogpile.112.2o7.net +0.0.0.0 donval.112.2o7.net +0.0.0.0 dowjones.122.2o7.net +0.0.0.0 dreammates.112.2o7.net +0.0.0.0 eaeacom.112.2o7.net +0.0.0.0 eagamesuk.112.2o7.net +0.0.0.0 earthlnkpsplive.122.2o7.net +0.0.0.0 ebay1.112.2o7.net +0.0.0.0 ebaynonreg.112.2o7.net +0.0.0.0 ebayreg.112.2o7.net +0.0.0.0 ebayus.112.2o7.net +0.0.0.0 ebcom.112.2o7.net +0.0.0.0 ectestlampsplus1.112.2o7.net +0.0.0.0 edietsmain.112.2o7.net +0.0.0.0 edmundsinsideline.112.2o7.net +0.0.0.0 edsa.112.2o7.net +0.0.0.0 ehg-moma.hitbox.com.112.2o7.net +0.0.0.0 emc.122.2o7.net +0.0.0.0 employ22.112.2o7.net +0.0.0.0 employ26.112.2o7.net +0.0.0.0 employment.112.2o7.net +0.0.0.0 enterprisenewsmedia.122.2o7.net +0.0.0.0 epost.122.2o7.net +0.0.0.0 ewsnaples.112.2o7.net +0.0.0.0 ewstcpalm.112.2o7.net +0.0.0.0 examinercom.122.2o7.net +0.0.0.0 execulink.112.2o7.net +0.0.0.0 expedia4.112.2o7.net +0.0.0.0 expedia.ca.112.2o7.net +0.0.0.0 f2ncracker.112.2o7.net +0.0.0.0 f2nsmh.112.2o7.net +0.0.0.0 f2ntheage.112.2o7.net +0.0.0.0 faceoff.112.2o7.net +0.0.0.0 fbkmnr.112.2o7.net +0.0.0.0 forbesattache.112.2o7.net +0.0.0.0 forbesauto.112.2o7.net +0.0.0.0 forbesautos.112.2o7.net +0.0.0.0 forbescom.112.2o7.net +0.0.0.0 ford.112.2o7.net +0.0.0.0 foxcom.112.2o7.net +0.0.0.0 foxsimpsons.112.2o7.net +0.0.0.0 georgewbush.112.2o7.net +0.0.0.0 georgewbushcom.112.2o7.net +0.0.0.0 gettyimages.122.2o7.net +0.0.0.0 gjfastcompanycom.112.2o7.net +0.0.0.0 gmchevyapprentice.112.2o7.net +0.0.0.0 gmhummer.112.2o7.net +0.0.0.0 gntbcstglobal.112.2o7.net +0.0.0.0 gntbcstkxtv.112.2o7.net +0.0.0.0 gntbcstwtsp.112.2o7.net +0.0.0.0 gpaper104.112.2o7.net +0.0.0.0 gpaper105.112.2o7.net +0.0.0.0 gpaper107.112.2o7.net +0.0.0.0 gpaper108.112.2o7.net +0.0.0.0 gpaper109.112.2o7.net +0.0.0.0 gpaper110.112.2o7.net +0.0.0.0 gpaper111.112.2o7.net +0.0.0.0 gpaper112.112.2o7.net +0.0.0.0 gpaper113.112.2o7.net +0.0.0.0 gpaper114.112.2o7.net +0.0.0.0 gpaper115.112.2o7.net +0.0.0.0 gpaper116.112.2o7.net +0.0.0.0 gpaper117.112.2o7.net +0.0.0.0 gpaper118.112.2o7.net +0.0.0.0 gpaper119.112.2o7.net +0.0.0.0 gpaper120.112.2o7.net +0.0.0.0 gpaper121.112.2o7.net +0.0.0.0 gpaper122.112.2o7.net +0.0.0.0 gpaper123.112.2o7.net +0.0.0.0 gpaper124.112.2o7.net +0.0.0.0 gpaper125.112.2o7.net +0.0.0.0 gpaper126.112.2o7.net +0.0.0.0 gpaper127.112.2o7.net +0.0.0.0 gpaper128.112.2o7.net +0.0.0.0 gpaper129.112.2o7.net +0.0.0.0 gpaper131.112.2o7.net +0.0.0.0 gpaper132.112.2o7.net +0.0.0.0 gpaper133.112.2o7.net +0.0.0.0 gpaper138.112.2o7.net +0.0.0.0 gpaper139.112.2o7.net +0.0.0.0 gpaper140.112.2o7.net +0.0.0.0 gpaper141.112.2o7.net +0.0.0.0 gpaper142.112.2o7.net +0.0.0.0 gpaper144.112.2o7.net +0.0.0.0 gpaper145.112.2o7.net +0.0.0.0 gpaper147.112.2o7.net +0.0.0.0 gpaper149.112.2o7.net +0.0.0.0 gpaper151.112.2o7.net +0.0.0.0 gpaper154.112.2o7.net +0.0.0.0 gpaper156.112.2o7.net +0.0.0.0 gpaper157.112.2o7.net +0.0.0.0 gpaper158.112.2o7.net +0.0.0.0 gpaper162.112.2o7.net +0.0.0.0 gpaper164.112.2o7.net +0.0.0.0 gpaper166.112.2o7.net +0.0.0.0 gpaper167.112.2o7.net +0.0.0.0 gpaper169.112.2o7.net +0.0.0.0 gpaper170.112.2o7.net +0.0.0.0 gpaper171.112.2o7.net +0.0.0.0 gpaper172.112.2o7.net +0.0.0.0 gpaper173.112.2o7.net +0.0.0.0 gpaper174.112.2o7.net +0.0.0.0 gpaper176.112.2o7.net +0.0.0.0 gpaper177.112.2o7.net +0.0.0.0 gpaper180.112.2o7.net +0.0.0.0 gpaper183.112.2o7.net +0.0.0.0 gpaper184.112.2o7.net +0.0.0.0 gpaper191.112.2o7.net +0.0.0.0 gpaper192.112.2o7.net +0.0.0.0 gpaper193.112.2o7.net +0.0.0.0 gpaper194.112.2o7.net +0.0.0.0 gpaper195.112.2o7.net +0.0.0.0 gpaper196.112.2o7.net +0.0.0.0 gpaper197.112.2o7.net +0.0.0.0 gpaper198.112.2o7.net +0.0.0.0 gpaper202.112.2o7.net +0.0.0.0 gpaper204.112.2o7.net +0.0.0.0 gpaper205.112.2o7.net +0.0.0.0 gpaper212.112.2o7.net +0.0.0.0 gpaper214.112.2o7.net +0.0.0.0 gpaper219.112.2o7.net +0.0.0.0 gpaper223.112.2o7.net +0.0.0.0 harpo.122.2o7.net +0.0.0.0 hchrmain.112.2o7.net +0.0.0.0 heavycom.112.2o7.net +0.0.0.0 heavycom.122.2o7.net +0.0.0.0 homesclick.112.2o7.net +0.0.0.0 hostdomainpeople.112.2o7.net +0.0.0.0 hostdomainpeopleca.112.2o7.net +0.0.0.0 hostpowermedium.112.2o7.net +0.0.0.0 hpglobal.112.2o7.net +0.0.0.0 hphqglobal.112.2o7.net +0.0.0.0 hphqsearch.112.2o7.net +0.0.0.0 infomart.ca.112.2o7.net +0.0.0.0 infospace.com.112.2o7.net +0.0.0.0 intelcorpcim.112.2o7.net +0.0.0.0 intelglobal.112.2o7.net +0.0.0.0 ivillageglobal.112.2o7.net +0.0.0.0 jijsonline.122.2o7.net +0.0.0.0 jitmj4.122.2o7.net +0.0.0.0 johnlewis.112.2o7.net +0.0.0.0 journalregistercompany.122.2o7.net +0.0.0.0 kddi.122.2o7.net +0.0.0.0 krafteurope.112.2o7.net +0.0.0.0 ktva.112.2o7.net +0.0.0.0 ladieshj.112.2o7.net +0.0.0.0 laptopmag.122.2o7.net +0.0.0.0 laxnws.112.2o7.net +0.0.0.0 laxprs.112.2o7.net +0.0.0.0 laxpsd.112.2o7.net +0.0.0.0 ldsfch.112.2o7.net +0.0.0.0 leeenterprises.112.2o7.net +0.0.0.0 lenovo.112.2o7.net +0.0.0.0 logoworksdev.112.2o7.net +0.0.0.0 losu.112.2o7.net +0.0.0.0 mailtribune.112.2o7.net +0.0.0.0 maxim.122.2o7.net +0.0.0.0 maxvr.112.2o7.net +0.0.0.0 mdamarillo.112.2o7.net +0.0.0.0 mdjacksonville.112.2o7.net +0.0.0.0 mdtopeka.112.2o7.net +0.0.0.0 mdwardmore.112.2o7.net +0.0.0.0 mdwsavannah.112.2o7.net +0.0.0.0 medbroadcast.112.2o7.net +0.0.0.0 mediabistrocom.112.2o7.net +0.0.0.0 mediamatters.112.2o7.net +0.0.0.0 meetupcom.112.2o7.net +0.0.0.0 metacafe.122.2o7.net +0.0.0.0 mgjournalnow.112.2o7.net +0.0.0.0 mgtbo.112.2o7.net +0.0.0.0 mgtimesdispatch.112.2o7.net +0.0.0.0 mgwsls.112.2o7.net +0.0.0.0 mgwspa.112.2o7.net +0.0.0.0 microsoftconsumermarketing.112.2o7.net +0.0.0.0 microsofteup.112.2o7.net +0.0.0.0 microsoftwindows.112.2o7.net +0.0.0.0 midala.112.2o7.net +0.0.0.0 midar.112.2o7.net +0.0.0.0 midsen.112.2o7.net +0.0.0.0 mlbastros.112.2o7.net +0.0.0.0 mlbcolorado.112.2o7.net +0.0.0.0 mlbcom.112.2o7.net +0.0.0.0 mlbglobal08.112.2o7.net +0.0.0.0 mlbglobal.112.2o7.net +0.0.0.0 mlbhouston.112.2o7.net +0.0.0.0 mlbstlouis.112.2o7.net +0.0.0.0 mlbtoronto.112.2o7.net +0.0.0.0 mmsshopcom.112.2o7.net +0.0.0.0 mnfidnahub.112.2o7.net +0.0.0.0 mngidmn.112.2o7.net +0.0.0.0 mngirockymtnnews.112.2o7.net +0.0.0.0 mngislctrib.112.2o7.net +0.0.0.0 mngiyrkdr.112.2o7.net +0.0.0.0 mseuppremain.112.2o7.net +0.0.0.0 msnmercom.112.2o7.net +0.0.0.0 msnportal.112.2o7.net +0.0.0.0 mtvn.112.2o7.net +0.0.0.0 mtvu.112.2o7.net +0.0.0.0 mxmacromedia.112.2o7.net +0.0.0.0 myfamilyancestry.112.2o7.net +0.0.0.0 nasdaq.122.2o7.net +0.0.0.0 natgeoeditco.112.2o7.net +0.0.0.0 natgeoeditcom.112.2o7.net +0.0.0.0 natgeonews.112.2o7.net +0.0.0.0 natgeongmcom.112.2o7.net +0.0.0.0 nationalpost.112.2o7.net +0.0.0.0 nba.112.2o7.net +0.0.0.0 neber.112.2o7.net +0.0.0.0 netrp.112.2o7.net +0.0.0.0 netsdartboards.122.2o7.net +0.0.0.0 newsinteractive.112.2o7.net +0.0.0.0 newstimeslivecom.112.2o7.net +0.0.0.0 nike.112.2o7.net +0.0.0.0 nikeplus.112.2o7.net +0.0.0.0 nmanchorage.112.2o7.net +0.0.0.0 nmbrampton.112.2o7.net +0.0.0.0 nmcommancomedia.112.2o7.net +0.0.0.0 nmfresno.112.2o7.net +0.0.0.0 nmhiltonhead.112.2o7.net +0.0.0.0 nmkawartha.112.2o7.net +0.0.0.0 nmminneapolis.112.2o7.net +0.0.0.0 nmmississauga.112.2o7.net +0.0.0.0 nmnandomedia.112.2o7.net +0.0.0.0 nmraleigh.112.2o7.net +0.0.0.0 nmrockhill.112.2o7.net +0.0.0.0 nmsacramento.112.2o7.net +0.0.0.0 nmtoronto.112.2o7.net +0.0.0.0 nmtricity.112.2o7.net +0.0.0.0 nmyork.112.2o7.net +0.0.0.0 novellcom.112.2o7.net +0.0.0.0 nytbglobe.112.2o7.net +0.0.0.0 nytglobe.112.2o7.net +0.0.0.0 nythglobe.112.2o7.net +0.0.0.0 nytimesglobal.112.2o7.net +0.0.0.0 nytimesnonsampled.112.2o7.net +0.0.0.0 nytimesnoonsampled.112.2o7.net +0.0.0.0 nytmembercenter.112.2o7.net +0.0.0.0 nytrflorence.112.2o7.net +0.0.0.0 nytrgadsden.112.2o7.net +0.0.0.0 nytrgainseville.112.2o7.net +0.0.0.0 nytrhendersonville.112.2o7.net +0.0.0.0 nytrhouma.112.2o7.net +0.0.0.0 nytrlakeland.112.2o7.net +0.0.0.0 nytrsantarosa.112.2o7.net +0.0.0.0 nytrsarasota.112.2o7.net +0.0.0.0 nytrwilmington.112.2o7.net +0.0.0.0 nyttechnology.112.2o7.net +0.0.0.0 omniture.112.2o7.net +0.0.0.0 omnitureglobal.112.2o7.net +0.0.0.0 onlineindigoca.112.2o7.net +0.0.0.0 oracle.112.2o7.net +0.0.0.0 oraclecom.112.2o7.net +0.0.0.0 overstock.com.112.2o7.net +0.0.0.0 overturecomvista.112.2o7.net +0.0.0.0 paypal.112.2o7.net +0.0.0.0 poacprod.122.2o7.net +0.0.0.0 poconorecordcom.112.2o7.net +0.0.0.0 projectorpeople.112.2o7.net +0.0.0.0 publicationsunbound.112.2o7.net +0.0.0.0 pulharktheherald.112.2o7.net +0.0.0.0 pulpantagraph.112.2o7.net +0.0.0.0 rckymtnnws.112.2o7.net +0.0.0.0 recordnetcom.112.2o7.net +0.0.0.0 recordonlinecom.112.2o7.net +0.0.0.0 rey3935.112.2o7.net +0.0.0.0 rezrezwhistler.112.2o7.net +0.0.0.0 riptownmedia.122.2o7.net +0.0.0.0 rncgopcom.122.2o7.net +0.0.0.0 roxio.112.2o7.net +0.0.0.0 salesforce.122.2o7.net +0.0.0.0 santacruzsentinel.112.2o7.net +0.0.0.0 sciamglobal.112.2o7.net +0.0.0.0 scrippsbathvert.112.2o7.net +0.0.0.0 scrippsfoodnet.112.2o7.net +0.0.0.0 scrippswfts.112.2o7.net +0.0.0.0 scrippswxyz.112.2o7.net +0.0.0.0 seacoastonlinecom.112.2o7.net +0.0.0.0 searscom.112.2o7.net +0.0.0.0 smibs.112.2o7.net +0.0.0.0 smwww.112.2o7.net +0.0.0.0 sonycorporate.122.2o7.net +0.0.0.0 sonyglobal.112.2o7.net +0.0.0.0 southcoasttoday.112.2o7.net +0.0.0.0 spiketv.112.2o7.net +0.0.0.0 stpetersburgtimes.122.2o7.net +0.0.0.0 suncom.112.2o7.net +0.0.0.0 sunglobal.112.2o7.net +0.0.0.0 sunonesearch.112.2o7.net +0.0.0.0 survey.112.2o7.net +0.0.0.0 sympmsnsports.112.2o7.net +0.0.0.0 techreview.112.2o7.net +0.0.0.0 thestar.122.2o7.net +0.0.0.0 thestardev.122.2o7.net +0.0.0.0 thinkgeek.112.2o7.net +0.0.0.0 timebus2.112.2o7.net +0.0.0.0 timecom.112.2o7.net +0.0.0.0 timeew.122.2o7.net +0.0.0.0 timefortune.112.2o7.net +0.0.0.0 timehealth.112.2o7.net +0.0.0.0 timeofficepirates.122.2o7.net +0.0.0.0 timepeople.122.2o7.net +0.0.0.0 timepopsci.122.2o7.net +0.0.0.0 timerealsimple.112.2o7.net +0.0.0.0 timewarner.122.2o7.net +0.0.0.0 tmsscion.112.2o7.net +0.0.0.0 tmstoyota.112.2o7.net +0.0.0.0 tnttv.112.2o7.net +0.0.0.0 torstardigital.122.2o7.net +0.0.0.0 travidiathebrick.112.2o7.net +0.0.0.0 tribuneinteractive.122.2o7.net +0.0.0.0 usatoday1.112.2o7.net +0.0.0.0 usnews.122.2o7.net +0.0.0.0 usun.112.2o7.net +0.0.0.0 vanns.112.2o7.net +0.0.0.0 verisignwildcard.112.2o7.net +0.0.0.0 verisonwildcard.112.2o7.net +0.0.0.0 vh1com.112.2o7.net +0.0.0.0 viaatomvideo.112.2o7.net +0.0.0.0 viacomedycentralrl.112.2o7.net +0.0.0.0 viagametrailers.112.2o7.net +0.0.0.0 viamtvcom.112.2o7.net +0.0.0.0 viasyndimedia.112.2o7.net +0.0.0.0 viavh1com.112.2o7.net +0.0.0.0 viay2m.112.2o7.net +0.0.0.0 vintacom.112.2o7.net +0.0.0.0 viralvideo.112.2o7.net +0.0.0.0 walmartcom.112.2o7.net +0.0.0.0 westjet.112.2o7.net +0.0.0.0 wileydumcom.112.2o7.net +0.0.0.0 wmg.112.2o7.net +0.0.0.0 wmgmulti.112.2o7.net +0.0.0.0 workopolis.122.2o7.net +0.0.0.0 wpni.112.2o7.net +0.0.0.0 xhealthmobiletools.112.2o7.net +0.0.0.0 youtube.112.2o7.net +0.0.0.0 yrkeve.112.2o7.net +0.0.0.0 ziffdavisglobal.112.2o7.net +0.0.0.0 ziffdavispennyarcade.112.2o7.net +# + + +# ads +0.0.0.0 0101011.com +0.0.0.0 0427d7.se +0.0.0.0 0d79ed.r.axf8.net +0.0.0.0 104231.dtiblog.com +0.0.0.0 10.im.cz +0.0.0.0 123.fluxads.com +0.0.0.0 123specialgifts.com +#0.0.0.0 140cc.v.fwmrm.net #interferes with Comedy Central videos +0.0.0.0 1.adbrite.com +0.0.0.0 1.forgetstore.com +0.0.0.0 1.httpads.com +0.0.0.0 1.primaryads.com +0.0.0.0 207-87-18-203.wsmg.digex.net +0.0.0.0 247support.adtech.fr +0.0.0.0 247support.adtech.us +0.0.0.0 24ratownik.hit.gemius.pl +0.0.0.0 24trk.com +0.0.0.0 25184.hittail.com +0.0.0.0 2754.btrll.com +0.0.0.0 2912a.v.fwmrm.net +0.0.0.0 2.adbrite.com +0.0.0.0 2-art-coliseum.com +0.0.0.0 312.1d27c9b8fb.com +0.0.0.0 321cba.com +0.0.0.0 32red.it +0.0.0.0 360ads.com +0.0.0.0 3.adbrite.com +0.0.0.0 3.cennter.com +0.0.0.0 3fns.com +0.0.0.0 4.adbrite.com +0.0.0.0 4c28d6.r.axf8.net +0.0.0.0 4qinvite.4q.iperceptions.com +0.0.0.0 7500.com +0.0.0.0 76.a.boom.ro +0.0.0.0 7adpower.com +0.0.0.0 7bpeople.com +0.0.0.0 7bpeople.data.7bpeople.com +0.0.0.0 7cnbcnews.com +0.0.0.0 85103.hittail.com +0.0.0.0 8574dnj3yzjace8c8io6zr9u3n.hop.clickbank.net +0.0.0.0 888casino.com +0.0.0.0 961.com +0.0.0.0 9cf9.v.fwmrm.net +0.0.0.0 a01.gestionpub.com +0.0.0.0 a.0day.kiev.ua +0.0.0.0 a1.greenadworks.net +0.0.0.0 a1.interclick.com +0.0.0.0 a200.yieldoptimizer.com +0.0.0.0 a2.mediagra.com +0.0.0.0 a2.websponsors.com +0.0.0.0 a3.suntimes.com +0.0.0.0 a3.websponsors.com +0.0.0.0 a4.websponsors.com +0.0.0.0 a5.websponsors.com +0.0.0.0 a.admaxserver.com +0.0.0.0 a.adorika.net +0.0.0.0 a.ad.playstation.net +0.0.0.0 a.adready.com +0.0.0.0 a.ads1.msn.com +0.0.0.0 a.ads2.msn.com +0.0.0.0 a.adstome.com +0.0.0.0 aads.treehugger.com +0.0.0.0 aams1.aim4media.com +0.0.0.0 aan.amazon.com +0.0.0.0 aa-nb.marketgid.com +0.0.0.0 aa.newsblock.dt00.net +0.0.0.0 aa.newsblock.marketgid.com +0.0.0.0 a.as-eu.falkag.net +0.0.0.0 a.as-us.falkag.net +0.0.0.0 aax-us-east.amazon-adsystem.com +0.0.0.0 abcnews.footprint.net +0.0.0.0 a.boom.ro +0.0.0.0 abrogatesdv.info +0.0.0.0 abseckw.adtlgc.com +0.0.0.0 a.collective-media.net +0.0.0.0 ac.rnm.ca +0.0.0.0 actiondesk.com +0.0.0.0 actionflash.com +0.0.0.0 action.ientry.net +0.0.0.0 action.mathtag.com +0.0.0.0 action.media6degrees.com +0.0.0.0 actionsplash.com +0.0.0.0 ac.tynt.com +0.0.0.0 acvs.mediaonenetwork.net +0.0.0.0 acvsrv.mediaonenetwork.net +0.0.0.0 ad01.adonspot.com +0.0.0.0 ad01.focalink.com +0.0.0.0 ad01.mediacorpsingapore.com +0.0.0.0 ad02.focalink.com +0.0.0.0 ad03.focalink.com +0.0.0.0 ad04.focalink.com +0.0.0.0 ad05.focalink.com +0.0.0.0 ad06.focalink.com +0.0.0.0 ad07.focalink.com +0.0.0.0 ad08.focalink.com +0.0.0.0 ad09.focalink.com +0.0.0.0 ad0.haynet.com +0.0.0.0 ad101com.adbureau.net +0.0.0.0 ad10.bannerbank.ru +0.0.0.0 ad10.focalink.com +0.0.0.0 ad11.bannerbank.ru +0.0.0.0 ad11.focalink.com +0.0.0.0 ad12.bannerbank.ru +0.0.0.0 ad12.focalink.com +0.0.0.0 ad13.focalink.com +0.0.0.0 ad14.focalink.com +0.0.0.0 ad15.focalink.com +0.0.0.0 ad16.focalink.com +0.0.0.0 ad17.focalink.com +0.0.0.0 ad18.focalink.com +0.0.0.0 ad19.focalink.com +0.0.0.0 ad1.adtitan.net +0.0.0.0 ad1.bannerbank.ru +0.0.0.0 ad1.clickhype.com +0.0.0.0 ad1.emediate.dk +0.0.0.0 ad1.emediate.se +0.0.0.0 ad1.gamezone.com +0.0.0.0 ad1.hotel.com +0.0.0.0 ad1.lbn.ru +0.0.0.0 ad1.peel.com +0.0.0.0 ad1.popcap.com +0.0.0.0 ad1.yomiuri.co.jp +0.0.0.0 ad1.yourmedia.com +0.0.0.0 ad234.prbn.ru +0.0.0.0 ad2.adecn.com +0.0.0.0 ad2.bal.dotandad.com +0.0.0.0 ad2.bannerbank.ru +0.0.0.0 ad2.bannerhost.ru +0.0.0.0 ad2.bbmedia.cz +0.0.0.0 ad2.cooks.com +0.0.0.0 ad2.firehousezone.com +0.0.0.0 ad2games.com +0.0.0.0 ad2.gammae.com +0.0.0.0 ad2.hotel.com +0.0.0.0 ad2.ip.ro +0.0.0.0 ad2.lbn.ru +0.0.0.0 ad2.nationalreview.com +0.0.0.0 ad2.pamedia.com +0.0.0.0 ad2.parom.hu +0.0.0.0 ad2.peel.com +0.0.0.0 ad2.pl +0.0.0.0 ad2.pl.mediainter.net +0.0.0.0 ad2.sbisec.co.jp +0.0.0.0 ad2.smni.com +0.0.0.0 ad.360yield.com +0.0.0.0 ad3.adfarm1.adition.com +0.0.0.0 ad3.bannerbank.ru +0.0.0.0 ad3.bb.ru +0.0.0.0 ad.3dnews.ru +0.0.0.0 ad3.lbn.ru +0.0.0.0 ad3.nationalreview.com +0.0.0.0 ad3.rambler.ru +0.0.0.0 ad41.atlas.cz +0.0.0.0 ad4.adfarm1.adition.com +0.0.0.0 ad4.bannerbank.ru +0.0.0.0 ad4.lbn.ru +0.0.0.0 ad4.liverail.com +0.0.0.0 ad4.speedbit.com +0.0.0.0 ad5.bannerbank.ru +0.0.0.0 ad5.lbn.ru +0.0.0.0 ad6.bannerbank.ru +0.0.0.0 ad6.horvitznewspapers.net +0.0.0.0 ad.71i.de +0.0.0.0 ad7.bannerbank.ru +0.0.0.0 ad8.bannerbank.ru +0.0.0.0 ad9.bannerbank.ru +0.0.0.0 ad.abcnews.com +0.0.0.0 ad.aboutwebservices.com +0.0.0.0 ad.adfunky.com +0.0.0.0 ad.adition.de +0.0.0.0 ad.adition.net +0.0.0.0 ad.adlegend.com +0.0.0.0 ad.admarketplace.net +0.0.0.0 ad.adnet.biz +0.0.0.0 ad.adnet.de +0.0.0.0 ad.adnetwork.com.br +0.0.0.0 ad.adnetwork.net +0.0.0.0 ad.adorika.com +0.0.0.0 ad.adperium.com +0.0.0.0 ad.adriver.ru +0.0.0.0 ad.adserve.com +0.0.0.0 ad.adserverplus.com +0.0.0.0 ad.adsmart.net +0.0.0.0 ad.adtegrity.net +0.0.0.0 ad.adtoma.com +0.0.0.0 ad.adverticum.net +0.0.0.0 ad.advertstream.com +0.0.0.0 ad.adview.pl +0.0.0.0 ad.afilo.pl +0.0.0.0 ad.aftenposten.no +0.0.0.0 ad.aftonbladet.se +0.0.0.0 ad.afy11.net +0.0.0.0 ad.agava.tbn.ru +0.0.0.0 adagiobanner.s3.amazonaws.com +0.0.0.0 ad.agkn.com +0.0.0.0 ad.amgdgt.com +0.0.0.0 adap.tv +0.0.0.0 ad.aquamediadirect.com +0.0.0.0 ad.asv.de +0.0.0.0 ad-audit.tubemogul.com +0.0.0.0 ad.auditude.com +0.0.0.0 ad.bannerbank.ru +0.0.0.0 ad.bannerconnect.net +0.0.0.0 adblade.com +0.0.0.0 ad.bnmla.com +0.0.0.0 adbnr.ru +0.0.0.0 adbot.theonion.com +0.0.0.0 adbrite.com +0.0.0.0 adbucks.brandreachsys.com +0.0.0.0 adc2.adcentriconline.com +0.0.0.0 adcache.aftenposten.no +0.0.0.0 adcanadian.com +0.0.0.0 adcash.com +0.0.0.0 adcast.deviantart.com +0.0.0.0 adcentriconline.com +0.0.0.0 adcentric.randomseed.com +0.0.0.0 ad.cibleclick.com +0.0.0.0 ad.clickdistrict.com +0.0.0.0 adclick.hit.gemius.pl +0.0.0.0 ad.clickotmedia.com +0.0.0.0 adclient-af.lp.uol.com.br +0.0.0.0 adclient.uimserv.net +0.0.0.0 adcode.adengage.com +0.0.0.0 adcontent.gamespy.com +0.0.0.0 adcontent.reedbusiness.com +0.0.0.0 adcontent.videoegg.com +0.0.0.0 adcontroller.unicast.com +0.0.0.0 adcount.ohmynews.com +0.0.0.0 adcreative.tribuneinteractive.com +0.0.0.0 adcycle.footymad.net +0.0.0.0 adcycle.icpeurope.net +0.0.0.0 ad.dc2.adtech.de +0.0.0.0 addelivery.thestreet.com +0.0.0.0 ad.designtaxi.com +0.0.0.0 ad.deviantart.com +0.0.0.0 ad.directrev.com +0.0.0.0 addthiscdn.com +0.0.0.0 addthis.com +0.0.0.0 adecn.com +0.0.0.0 ad.egloos.com +0.0.0.0 adengine.rt.ru +0.0.0.0 ad.espn.starwave.com +0.0.0.0 ad.eurosport.com +0.0.0.0 adexpansion.com +0.0.0.0 adexprt.com +0.0.0.0 adexprt.me +0.0.0.0 adexprts.com +0.0.0.0 adext.inkclub.com +0.0.0.0 adfarm1.adition.com +0.0.0.0 adfarm.mserve.ca +0.0.0.0 adfiles.pitchforkmedia.com +0.0.0.0 ad.filmweb.pl +0.0.0.0 ad.firstadsolution.com +0.0.0.0 ad.flux.com +#0.0.0.0 adf.ly +0.0.0.0 adforce.ads.imgis.com +0.0.0.0 adforce.adtech.de +0.0.0.0 adforce.adtech.fr +0.0.0.0 adforce.adtech.us +0.0.0.0 adforce.imgis.com +0.0.0.0 adform.com +0.0.0.0 adfu.blockstackers.com +0.0.0.0 ad.funpic.de +0.0.0.0 adfusion.com +0.0.0.0 ad.garantiarkadas.com +0.0.0.0 adgardener.com +0.0.0.0 ad.gazeta.pl +0.0.0.0 ad.goo.ne.jp +0.0.0.0 adgraphics.theonion.com +0.0.0.0 ad.gra.pl +0.0.0.0 ad.gr.doubleclick.net +0.0.0.0 ad.greenmarquee.com +0.0.0.0 adgroup.naver.com +0.0.0.0 ad.hankooki.com +0.0.0.0 ad.harrenmedianetwork.com +0.0.0.0 adhearus.com +0.0.0.0 adhese.be +0.0.0.0 adhese.com +0.0.0.0 adhitzads.com +0.0.0.0 ad.horvitznewspapers.net +0.0.0.0 ad.host.bannerflow.com +0.0.0.0 ad.howstuffworks.com +0.0.0.0 adhref.pl +#0.0.0.0 ad.hulu.com # Uncomment to block Hulu. +0.0.0.0 ad.iconadserver.com +0.0.0.0 adidm.idmnet.pl +0.0.0.0 adidm.supermedia.pl +0.0.0.0 adimage.asia1.com.sg +0.0.0.0 adimage.asiaone.com +0.0.0.0 adimage.asiaone.com.sg +0.0.0.0 adimage.blm.net +0.0.0.0 adimages.earthweb.com +0.0.0.0 adimages.go.com +0.0.0.0 adimages.mp3.com +0.0.0.0 adimages.watchmygf.net +0.0.0.0 adi.mainichi.co.jp +0.0.0.0 adimg.activeadv.net +0.0.0.0 adimg.com.com +0.0.0.0 adincl.gopher.com +0.0.0.0 ad.insightexpressai.com +0.0.0.0 ad.investopedia.com +0.0.0.0 adipics.com +0.0.0.0 adireland.com +0.0.0.0 ad.ir.ru +0.0.0.0 ad.isohunt.com +0.0.0.0 adition.com +0.0.0.0 ad.iwin.com +0.0.0.0 adj10.thruport.com +0.0.0.0 adj11.thruport.com +0.0.0.0 adj12.thruport.com +0.0.0.0 adj13.thruport.com +0.0.0.0 adj14.thruport.com +0.0.0.0 adj15.thruport.com +0.0.0.0 adj16r1.thruport.com +0.0.0.0 adj16.thruport.com +0.0.0.0 adj17.thruport.com +0.0.0.0 adj18.thruport.com +0.0.0.0 adj19.thruport.com +0.0.0.0 adj1.thruport.com +0.0.0.0 adj22.thruport.com +0.0.0.0 adj23.thruport.com +0.0.0.0 adj24.thruport.com +0.0.0.0 adj25.thruport.com +0.0.0.0 adj26.thruport.com +0.0.0.0 adj27.thruport.com +0.0.0.0 adj28.thruport.com +0.0.0.0 adj29.thruport.com +0.0.0.0 adj2.thruport.com +0.0.0.0 adj30.thruport.com +0.0.0.0 adj31.thruport.com +0.0.0.0 adj32.thruport.com +0.0.0.0 adj33.thruport.com +0.0.0.0 adj34.thruport.com +0.0.0.0 adj35.thruport.com +0.0.0.0 adj36.thruport.com +0.0.0.0 adj37.thruport.com +0.0.0.0 adj38.thruport.com +0.0.0.0 adj39.thruport.com +0.0.0.0 adj3.thruport.com +0.0.0.0 adj40.thruport.com +0.0.0.0 adj41.thruport.com +0.0.0.0 adj43.thruport.com +0.0.0.0 adj44.thruport.com +0.0.0.0 adj45.thruport.com +0.0.0.0 adj46.thruport.com +0.0.0.0 adj47.thruport.com +0.0.0.0 adj48.thruport.com +0.0.0.0 adj49.thruport.com +0.0.0.0 adj4.thruport.com +0.0.0.0 adj50.thruport.com +0.0.0.0 adj51.thruport.com +0.0.0.0 adj52.thruport.com +0.0.0.0 adj53.thruport.com +0.0.0.0 adj54.thruport.com +0.0.0.0 adj55.thruport.com +0.0.0.0 adj56.thruport.com +0.0.0.0 adj5.thruport.com +0.0.0.0 adj6.thruport.com +0.0.0.0 adj7.thruport.com +0.0.0.0 adj8.thruport.com +0.0.0.0 adj9.thruport.com +0.0.0.0 ad.jamba.net +0.0.0.0 ad.jamster.ca +0.0.0.0 adjmps.com +0.0.0.0 adjuggler.net +0.0.0.0 adjuggler.yourdictionary.com +0.0.0.0 ad.kataweb.it +0.0.0.0 ad.kat.ph +0.0.0.0 adkontekst.pl +0.0.0.0 ad.krutilka.ru +0.0.0.0 ad.leadcrunch.com +0.0.0.0 ad.lgappstv.com +0.0.0.0 ad.linkexchange.com +0.0.0.0 ad.linksynergy.com +0.0.0.0 admanager1.collegepublisher.com +0.0.0.0 admanager2.broadbandpublisher.com +0.0.0.0 admanager3.collegepublisher.com +0.0.0.0 admanager.adam4adam.com +0.0.0.0 admanager.beweb.com +0.0.0.0 admanager.btopenworld.com +0.0.0.0 admanager.collegepublisher.com +0.0.0.0 adman.freeze.com +0.0.0.0 adman.in.gr +0.0.0.0 ad.mastermedia.ru +0.0.0.0 admatcher.videostrip.com #http://admatcher.videostrip.com/?puid=23940627&host=www.dumpert.nl&categories=default +0.0.0.0 admatch-syndication.mochila.com +0.0.0.0 admax.quisma.com +0.0.0.0 ad.media-servers.net +0.0.0.0 admedia.xoom.com +0.0.0.0 admeld.com +0.0.0.0 admeta.vo.llnwd.net +#0.0.0.0 adm.fwmrm.net #may interfere with nhl.com +0.0.0.0 admin.digitalacre.com +0.0.0.0 admin.hotkeys.com +0.0.0.0 admin.inq.com +0.0.0.0 admonkey.dapper.net +0.0.0.0 ad.moscowtimes.ru +0.0.0.0 adm.shacknews.com +0.0.0.0 adms.physorg.com +0.0.0.0 ad.my.doubleclick.net +0.0.0.0 ad.nate.com +0.0.0.0 adn.ebay.com +0.0.0.0 adnet.asahi.com +0.0.0.0 adnet.biz +0.0.0.0 adnet.chicago.tribune.com +0.0.0.0 adnet.com +0.0.0.0 adnet.de +0.0.0.0 ad.network60.com +0.0.0.0 adnetwork.nextgen.net +0.0.0.0 adnetwork.rovicorp.com +0.0.0.0 adnetxchange.com +0.0.0.0 adng.ascii24.com +0.0.0.0 adn.kinkydollars.com +0.0.0.0 ad.nozonedata.com +0.0.0.0 adnxs.com +0.0.0.0 adnxs.revsci.net +0.0.0.0 adobee.com +0.0.0.0 adobe.tt.omtrdc.net +0.0.0.0 adocean.pl +0.0.0.0 ad.ohmynews.com +0.0.0.0 adopt.euroclick.com +0.0.0.0 adopt.precisead.com +0.0.0.0 adotube.com +0.0.0.0 ad.parom.hu +0.0.0.0 ad.partis.si +0.0.0.0 adpepper.dk +0.0.0.0 adp.gazeta.pl +0.0.0.0 ad.ph-prt.tbn.ru +0.0.0.0 adpick.switchboard.com +0.0.0.0 ad.pravda.ru +0.0.0.0 ad.preferences.com +0.0.0.0 ad.pro-advertising.com +0.0.0.0 ad.propellerads.com +0.0.0.0 ad.prv.pl +0.0.0.0 adpulse.ads.targetnet.com +0.0.0.0 adpush.dreamscape.com +0.0.0.0 adq.nextag.com +0.0.0.0 adremote.pathfinder.com +0.0.0.0 adremote.timeinc.aol.com +0.0.0.0 adremote.timeinc.net +0.0.0.0 ad.repubblica.it +0.0.0.0 adriver.ru +0.0.0.0 adroll.com +0.0.0.0 adrotate.se +0.0.0.0 adrotator.se +0.0.0.0 ad.ru.doubleclick.net +0.0.0.0 ads01.focalink.com +0.0.0.0 ads01.hyperbanner.net +0.0.0.0 ads02.focalink.com +0.0.0.0 ads02.hyperbanner.net +0.0.0.0 ads03.focalink.com +0.0.0.0 ads03.hyperbanner.net +0.0.0.0 ads04.focalink.com +0.0.0.0 ads04.hyperbanner.net +0.0.0.0 ads05.focalink.com +0.0.0.0 ads05.hyperbanner.net +0.0.0.0 ads06.focalink.com +0.0.0.0 ads06.hyperbanner.net +0.0.0.0 ads07.focalink.com +0.0.0.0 ads07.hyperbanner.net +0.0.0.0 ads08.focalink.com +0.0.0.0 ads08.hyperbanner.net +0.0.0.0 ads09.focalink.com +0.0.0.0 ads09.hyperbanner.net +0.0.0.0 ads0.okcupid.com +0.0.0.0 ads10.focalink.com +0.0.0.0 ads10.hyperbanner.net +0.0.0.0 ads10.speedbit.com +0.0.0.0 ads10.udc.advance.net +0.0.0.0 ads11.focalink.com +0.0.0.0 ads11.hyperbanner.net +0.0.0.0 ads11.udc.advance.net +0.0.0.0 ads12.focalink.com +0.0.0.0 ads12.hyperbanner.net +0.0.0.0 ads12.udc.advance.net +0.0.0.0 ads13.focalink.com +0.0.0.0 ads13.hyperbanner.net +0.0.0.0 ads13.udc.advance.net +0.0.0.0 ads14.bpath.com +0.0.0.0 ads14.focalink.com +0.0.0.0 ads14.hyperbanner.net +0.0.0.0 ads14.udc.advance.net +0.0.0.0 ads15.bpath.com +0.0.0.0 ads15.focalink.com +0.0.0.0 ads15.hyperbanner.net +0.0.0.0 ads15.udc.advance.net +0.0.0.0 ads16.advance.net +0.0.0.0 ads16.focalink.com +0.0.0.0 ads16.hyperbanner.net +0.0.0.0 ads16.udc.advance.net +0.0.0.0 ads17.focalink.com +0.0.0.0 ads17.hyperbanner.net +0.0.0.0 ads18.focalink.com +0.0.0.0 ads18.hyperbanner.net +0.0.0.0 ads19.focalink.com +0.0.0.0 ads1.activeagent.at +0.0.0.0 ads1.ad-flow.com +0.0.0.0 ads1.admedia.ro +0.0.0.0 ads1.advance.net +0.0.0.0 ads1.advertwizard.com +0.0.0.0 ads1.ami-admin.com +0.0.0.0 ads1.canoe.ca +0.0.0.0 ads1.destructoid.com +0.0.0.0 ads1.empiretheatres.com +0.0.0.0 ads1.erotism.com +0.0.0.0 ads1.eudora.com +0.0.0.0 ads1.globeandmail.com +0.0.0.0 ads1.itadnetwork.co.uk +0.0.0.0 ads1.jev.co.za +0.0.0.0 ads1.msads.net +0.0.0.0 ads1.msn.com +0.0.0.0 ads1.perfadbrite.com.akadns.net +0.0.0.0 ads1.performancingads.com +0.0.0.0 ads1.realcities.com +0.0.0.0 ads1.revenue.net +0.0.0.0 ads1.sptimes.com +0.0.0.0 ads1.theglobeandmail.com +0.0.0.0 ads1.ucomics.com +0.0.0.0 ads1.udc.advance.net +0.0.0.0 ads1.updated.com +0.0.0.0 ads1.virtumundo.com +0.0.0.0 ads1.zdnet.com +0.0.0.0 ads20.focalink.com +0.0.0.0 ads21.focalink.com +0.0.0.0 ads22.focalink.com +0.0.0.0 ads23.focalink.com +0.0.0.0 ads24.focalink.com +0.0.0.0 ads25.focalink.com +0.0.0.0 ads2.adbrite.com +0.0.0.0 ads2.ad-flow.com +0.0.0.0 ads2.advance.net +0.0.0.0 ads2.advertwizard.com +0.0.0.0 ads2.canoe.ca +0.0.0.0 ads2.clearchannel.com +0.0.0.0 ads2.clickad.com +0.0.0.0 ads2.collegclub.com +0.0.0.0 ads2.collegeclub.com +0.0.0.0 ads2.contentabc.com +0.0.0.0 ads2.drivelinemedia.com +0.0.0.0 ads2.emeraldcoast.com +0.0.0.0 ads2.exhedra.com +0.0.0.0 ads2.firingsquad.com +0.0.0.0 ads2.gamecity.net +0.0.0.0 ads2.jubii.dk +0.0.0.0 ads2.ljworld.com +0.0.0.0 ads2.msn.com +0.0.0.0 ads2.newtimes.com +0.0.0.0 ads2.osdn.com +0.0.0.0 ads2.pittsburghlive.com +0.0.0.0 ads2.realcities.com +0.0.0.0 ads2.revenue.net +0.0.0.0 ads2.rp.pl +0.0.0.0 ads2srv.com +0.0.0.0 ads2.theglobeandmail.com +0.0.0.0 ads2.udc.advance.net +0.0.0.0 ads2.virtumundo.com +0.0.0.0 ads2.weblogssl.com +0.0.0.0 ads2.zdnet.com +0.0.0.0 ads2.zeusclicks.com +0.0.0.0 ads360.com +0.0.0.0 ads36.hyperbanner.net +0.0.0.0 ads3.ad-flow.com +0.0.0.0 ads3.adman.gr +0.0.0.0 ads3.advance.net +0.0.0.0 ads3.advertwizard.com +0.0.0.0 ads3.canoe.ca +0.0.0.0 ads3.freebannertrade.com +0.0.0.0 ads3.gamecity.net +0.0.0.0 ads3.jubii.dk +0.0.0.0 ads3.realcities.com +0.0.0.0 ads3.udc.advance.net +0.0.0.0 ads3.virtumundo.com +0.0.0.0 ads3.zdnet.com +0.0.0.0 ads4.ad-flow.com +0.0.0.0 ads4.advance.net +0.0.0.0 ads4.advertwizard.com +0.0.0.0 ads4.canoe.ca +0.0.0.0 ads4.clearchannel.com +0.0.0.0 ads4.gamecity.net +0.0.0.0 ads4homes.com +0.0.0.0 ads4.realcities.com +0.0.0.0 ads4.udc.advance.net +0.0.0.0 ads4.virtumundo.com +0.0.0.0 ads5.ad-flow.com +0.0.0.0 ads5.advance.net +0.0.0.0 ads5.advertwizard.com +0.0.0.0 ads5.canoe.ca +0.0.0.0 ads.5ci.lt +0.0.0.0 ads5.fxdepo.com +0.0.0.0 ads5.mconetwork.com +0.0.0.0 ads5.udc.advance.net +0.0.0.0 ads5.virtumundo.com +0.0.0.0 ads6.ad-flow.com +0.0.0.0 ads6.advance.net +0.0.0.0 ads6.advertwizard.com +0.0.0.0 ads6.gamecity.net +0.0.0.0 ads6.udc.advance.net +0.0.0.0 ads7.ad-flow.com +0.0.0.0 ads7.advance.net +0.0.0.0 ads7.advertwizard.com +0.0.0.0 ads.7days.ae +0.0.0.0 ads7.gamecity.net +0.0.0.0 ads7.speedbit.com +0.0.0.0 ads7.udc.advance.net +0.0.0.0 ads.8833.com +0.0.0.0 ads8.ad-flow.com +0.0.0.0 ads8.advertwizard.com +0.0.0.0 ads8.com +0.0.0.0 ads8.udc.advance.net +0.0.0.0 ads9.ad-flow.com +0.0.0.0 ads9.advertwizard.com +0.0.0.0 ads9.udc.advance.net +0.0.0.0 ads.abs-cbn.com +0.0.0.0 ads.accelerator-media.com +0.0.0.0 ads.aceweb.net +0.0.0.0 ads.activeagent.at +0.0.0.0 ads.active.com +0.0.0.0 ads.ad4game.com +0.0.0.0 ads.adap.tv +0.0.0.0 ads.adbrite.com +0.0.0.0 ads.adbroker.de +0.0.0.0 ads.adcorps.com +0.0.0.0 ads.addesktop.com +0.0.0.0 ads.addynamix.com +0.0.0.0 ads.adengage.com +0.0.0.0 ads.ad-flow.com +0.0.0.0 ads.adfox.ru +0.0.0.0 ads.adgoto.com +0.0.0.0 ads.adhall.com +0.0.0.0 ads.adhearus.com +0.0.0.0 ads.adhostingsolutions.com +0.0.0.0 ads.admarvel.com +0.0.0.0 ads.admaximize.com +0.0.0.0 adsadmin.aspentimes.com +0.0.0.0 adsadmin.corusradionetwork.com +0.0.0.0 adsadmin.vaildaily.com +0.0.0.0 ads.admonitor.net +0.0.0.0 ads.adn.com +0.0.0.0 ads.adroar.com +0.0.0.0 ads.adsag.com +0.0.0.0 ads.adsbookie.com +0.0.0.0 ads.adshareware.net +0.0.0.0 ads.adsinimages.com +0.0.0.0 ads.adsonar.com +0.0.0.0 ads.adsrvmedia.com +0.0.0.0 ads.adtegrity.net +0.0.0.0 ads.adtiger.de +0.0.0.0 ads.adultfriendfinder.com +0.0.0.0 ads.adultswim.com +0.0.0.0 ads.advance.net +0.0.0.0 ads.adverline.com +0.0.0.0 ads.adviva.net +0.0.0.0 ads.advolume.com +0.0.0.0 ads.adworldnetwork.com +0.0.0.0 ads.adx.nu +0.0.0.0 ads.adxpansion.com +0.0.0.0 ads.adxpose.com +0.0.0.0 ads.adxpose.mpire.akadns.net +0.0.0.0 ads.affiliates.match.com +0.0.0.0 ads.aftonbladet.se +0.0.0.0 ads.ah-ha.com +0.0.0.0 ads.aintitcool.com +0.0.0.0 ads.airamericaradio.com +0.0.0.0 ads.ak.facebook.com +0.0.0.0 ads.albawaba.com +0.0.0.0 ads.al.com +0.0.0.0 ads.allsites.com +0.0.0.0 ads.allvertical.com +0.0.0.0 ads.amarillo.com +0.0.0.0 ads.amateurmatch.com +0.0.0.0 ads.amazingmedia.com +0.0.0.0 ads.amgdgt.com +0.0.0.0 ads.ami-admin.com +0.0.0.0 ads.anm.co.uk +0.0.0.0 ads.anvato.com +0.0.0.0 ads.aol.com +0.0.0.0 ads.apartmenttherapy.com +0.0.0.0 ads.apn.co.nz +0.0.0.0 ads.apn.co.za +0.0.0.0 ads.appleinsider.com +0.0.0.0 ads.arcadechain.com +0.0.0.0 ads.aroundtherings.com +0.0.0.0 ads.as4x.tmcs.net +0.0.0.0 ads.as4x.tmcs.ticketmaster.ca +0.0.0.0 ads.as4x.tmcs.ticketmaster.com +0.0.0.0 ads.asia1.com +0.0.0.0 ads.asia1.com.sg +0.0.0.0 ads.aspalliance.com +0.0.0.0 ads.aspentimes.com +0.0.0.0 ads.asp.net +0.0.0.0 ads.associatedcontent.com +0.0.0.0 ads.astalavista.us +0.0.0.0 ads.atlantamotorspeedway.com +0.0.0.0 adsatt.abcnews.starwave.com +0.0.0.0 adsatt.espn.go.com +0.0.0.0 adsatt.espn.starwave.com +0.0.0.0 ads.auctionads.com +0.0.0.0 ads.auctioncity.co.nz +0.0.0.0 ads.auctions.yahoo.com +0.0.0.0 ads.augusta.com +0.0.0.0 ads.aversion2.com +0.0.0.0 ads.aws.sitepoint.com +0.0.0.0 ads.azjmp.com +0.0.0.0 ads.baazee.com +0.0.0.0 ads.bangkokpost.co.th +0.0.0.0 ads.banner.t-online.de +0.0.0.0 ads.barnonedrinks.com +0.0.0.0 ads.battle.net +0.0.0.0 ads.bauerpublishing.com +0.0.0.0 ads.baventures.com +0.0.0.0 ads.bbcworld.com +0.0.0.0 ads.bcnewsgroup.com +0.0.0.0 ads.beeb.com +0.0.0.0 ads.beliefnet.com +0.0.0.0 ads.belointeractive.com +0.0.0.0 ads.beta.itravel2000.com +0.0.0.0 ads.betanews.com +0.0.0.0 ads.bfast.com +0.0.0.0 ads.bfm.valueclick.net +0.0.0.0 ads.bianca.com +0.0.0.0 ads.bidclix.com +0.0.0.0 ads.bidvertiser.com +0.0.0.0 ads.bigcitytools.com +0.0.0.0 ads.biggerboat.com +0.0.0.0 ads.bitsonthewire.com +0.0.0.0 ads.bizhut.com +0.0.0.0 ads.blixem.nl +0.0.0.0 ads.blog.com +0.0.0.0 ads.blogherads.com +0.0.0.0 ads.bloomberg.com +0.0.0.0 ads.blp.calueclick.net +0.0.0.0 ads.blp.valueclick.net +0.0.0.0 ads.bluelithium.com +0.0.0.0 ads.bluemountain.com +0.0.0.0 ads.bonnint.net +0.0.0.0 ads.box.sk +0.0.0.0 ads.brabys.com +0.0.0.0 ads.brand.net +0.0.0.0 ads.bridgetrack.com +0.0.0.0 ads.britishexpats.com +0.0.0.0 ads.buscape.com.br +0.0.0.0 ads.businessclick.com +0.0.0.0 ads.businessweek.com +0.0.0.0 ads.calgarysun.com +0.0.0.0 ads.callofdutyblackopsforum.net +0.0.0.0 ads.camrecord.com +0.0.0.0 ads.canoe.ca +0.0.0.0 ads.cardea.se +0.0.0.0 ads.cardplayer.com +0.0.0.0 ads.carltononline.com +0.0.0.0 ads.carocean.co.uk +0.0.0.0 ads.casinocity.com +0.0.0.0 ads.catholic.org +0.0.0.0 ads.cavello.com +0.0.0.0 ads.cbc.ca +0.0.0.0 ads.cdfreaks.com +0.0.0.0 ads.cdnow.com +0.0.0.0 adscendmedia.com +0.0.0.0 ads.centraliprom.com +0.0.0.0 ads.cgchannel.com +0.0.0.0 ads.chalomumbai.com +0.0.0.0 ads.champs-elysees.com +0.0.0.0 ads.channel4.com +0.0.0.0 ads.checkm8.co.za +0.0.0.0 ads.chipcenter.com +0.0.0.0 adscholar.com +0.0.0.0 ads.chumcity.com +0.0.0.0 ads.cjonline.com +0.0.0.0 ads.clamav.net +0.0.0.0 ads.clara.net +0.0.0.0 ads.clearchannel.com +0.0.0.0 ads.cleveland.com +0.0.0.0 ads.clickability.com +0.0.0.0 ads.clickad.com.pl +0.0.0.0 ads.clickagents.com +0.0.0.0 ads.clickhouse.com +0.0.0.0 ads.clicksor.com +0.0.0.0 ads.clickthru.net +0.0.0.0 ads.clicmanager.fr +0.0.0.0 ads.clubzone.com +0.0.0.0 ads.cluster01.oasis.zmh.zope.net +0.0.0.0 ads.cmediaworld.com +0.0.0.0 ads.cmg.valueclick.net +0.0.0.0 ads.cnn.com +0.0.0.0 ads.cnngo.com +0.0.0.0 ads.cobrad.com +0.0.0.0 ads.collegclub.com +0.0.0.0 ads.collegehumor.com +0.0.0.0 ads.collegemix.com +0.0.0.0 ads.com.com +0.0.0.0 ads.comediagroup.hu +0.0.0.0 ads.comicbookresources.com +0.0.0.0 ads.contactmusic.com +0.0.0.0 ads.contentabc.com +0.0.0.0 ads.coopson.com +0.0.0.0 ads.corusradionetwork.com +0.0.0.0 ads.courierpostonline.com +0.0.0.0 ads.cpsgsoftware.com +0.0.0.0 ads.crakmedia.com +0.0.0.0 ads.crapville.com +0.0.0.0 ads.creative-serving.com +0.0.0.0 ads.crosscut.com +0.0.0.0 ads.ctvdigital.net +0.0.0.0 ads.currantbun.com +0.0.0.0 ads.cyberfight.ru +0.0.0.0 ads.cybersales.cz +0.0.0.0 ads.cybertrader.com +0.0.0.0 ads.dada.it +0.0.0.0 ads.danworld.net +0.0.0.0 adsdaq.com +0.0.0.0 ads.dbforums.com +0.0.0.0 ads.ddj.com +0.0.0.0 ads.dealnews.com +0.0.0.0 ads.democratandchronicle.com +0.0.0.0 ads.dennisnet.co.uk +0.0.0.0 ads.designboom.com +0.0.0.0 ads.designtaxi.com +0.0.0.0 ads.desmoinesregister.com +0.0.0.0 ads-de.spray.net +0.0.0.0 ads.detelefoongids.nl +0.0.0.0 ads.developershed.com +0.0.0.0 ads.deviantart.com +0.0.0.0 ads-dev.youporn.com +0.0.0.0 ads.digitalacre.com +0.0.0.0 ads.digital-digest.com +0.0.0.0 ads.digitalhealthcare.com +0.0.0.0 ads.digitalmedianet.com +0.0.0.0 ads.digitalpoint.com +0.0.0.0 ads.dimcab.com +0.0.0.0 ads.directionsmag.com +0.0.0.0 ads-direct.prodigy.net +0.0.0.0 ads.discovery.com +0.0.0.0 ads.dk +0.0.0.0 ads.doclix.com +0.0.0.0 ads.domeus.com +0.0.0.0 ads.dontpanicmedia.com +0.0.0.0 ads.dothads.com +0.0.0.0 ads.doubleviking.com +0.0.0.0 ads.drf.com +0.0.0.0 ads.drivelinemedia.com +0.0.0.0 ads.drugs.com +0.0.0.0 ads.dumpalink.com +0.0.0.0 adsearch.adkontekst.pl +0.0.0.0 adsearch.pl +0.0.0.0 adsearch.wp.pl +0.0.0.0 ads.ecircles.com +0.0.0.0 ads.economist.com +0.0.0.0 ads.ecosalon.com +0.0.0.0 ads.edirectme.com +0.0.0.0 ads.einmedia.com +0.0.0.0 ads.eircom.net +0.0.0.0 ads.emeraldcoast.com +0.0.0.0 ads.enliven.com +0.0.0.0 ad.sensismediasmart.com.au +0.0.0.0 adsentnetwork.com +0.0.0.0 adserer.ihigh.com +0.0.0.0 ads.erotism.com +0.0.0.0 adserv001.adtech.de +0.0.0.0 adserv001.adtech.fr +0.0.0.0 adserv001.adtech.us +0.0.0.0 adserv002.adtech.de +0.0.0.0 adserv002.adtech.fr +0.0.0.0 adserv002.adtech.us +0.0.0.0 adserv003.adtech.de +0.0.0.0 adserv003.adtech.fr +0.0.0.0 adserv003.adtech.us +0.0.0.0 adserv004.adtech.de +0.0.0.0 adserv004.adtech.fr +0.0.0.0 adserv004.adtech.us +0.0.0.0 adserv005.adtech.de +0.0.0.0 adserv005.adtech.fr +0.0.0.0 adserv005.adtech.us +0.0.0.0 adserv006.adtech.de +0.0.0.0 adserv006.adtech.fr +0.0.0.0 adserv006.adtech.us +0.0.0.0 adserv007.adtech.de +0.0.0.0 adserv007.adtech.fr +0.0.0.0 adserv007.adtech.us +0.0.0.0 adserv008.adtech.de +0.0.0.0 adserv008.adtech.fr +0.0.0.0 adserv008.adtech.us +0.0.0.0 adserv2.bravenet.com +0.0.0.0 adserv.aip.org +0.0.0.0 adservant.guj.de +0.0.0.0 adserv.bravenet.com +0.0.0.0 adserve5.nikkeibp.co.jp +0.0.0.0 adserve.adtoll.com +0.0.0.0 adserve.canadawidemagazines.com +0.0.0.0 adserve.city-ad.com +0.0.0.0 adserve.ehpub.com +0.0.0.0 adserve.gossipgirls.com +0.0.0.0 adserve.mizzenmedia.com +0.0.0.0 adserv.entriq.net +0.0.0.0 adserve.podaddies.com +0.0.0.0 adserve.profit-smart.com +0.0.0.0 adserver01.ancestry.com +0.0.0.0 adserver.100free.com +0.0.0.0 adserver.163.com +0.0.0.0 adserver1.adserver.com.pl +0.0.0.0 adserver1.adtech.com.tr +0.0.0.0 adserver1.backbeatmedia.com +0.0.0.0 adserver1.economist.com +0.0.0.0 adserver1.eudora.com +0.0.0.0 adserver1.harvestadsdepot.com +0.0.0.0 adserver1.hookyouup.com +0.0.0.0 adserver1-images.backbeatmedia.com +0.0.0.0 adserver1.isohunt.com +0.0.0.0 adserver1.lokitorrent.com +0.0.0.0 adserver1.mediainsight.de +0.0.0.0 adserver1.ogilvy-interactive.de +0.0.0.0 adserver1.realtracker.com +0.0.0.0 adserver1.sonymusiceurope.com +0.0.0.0 adserver1.teracent.net +0.0.0.0 adserver1.wmads.com +0.0.0.0 adserver.2618.com +0.0.0.0 adserver2.adserver.com.pl +0.0.0.0 adserver2.atman.pl +0.0.0.0 adserver2.christianitytoday.com +0.0.0.0 adserver2.condenast.co.uk +0.0.0.0 adserver2.creative.com +0.0.0.0 adserver2.eudora.com +0.0.0.0 adserver-2.ig.com.br +0.0.0.0 adserver2.mediainsight.de +0.0.0.0 adserver2.news-journalonline.com +0.0.0.0 adserver2.popdata.de +0.0.0.0 adserver2.realtracker.com +0.0.0.0 adserver2.teracent.net +0.0.0.0 adserver.3digit.de +0.0.0.0 adserver3.eudora.com +0.0.0.0 adserver-3.ig.com.br +0.0.0.0 adserver4.eudora.com +0.0.0.0 adserver-4.ig.com.br +0.0.0.0 adserver-5.ig.com.br +0.0.0.0 adserver.71i.de +0.0.0.0 adserver9.contextad.com +0.0.0.0 adserver.ad-it.dk +0.0.0.0 adserver.adreactor.com +0.0.0.0 adserver.adremedy.com +0.0.0.0 adserver.ads360.com +0.0.0.0 adserver.adserver.com.pl +0.0.0.0 adserver.adsincontext.com +0.0.0.0 adserver.adtech.de +0.0.0.0 adserver.adtech.fr +0.0.0.0 adserver.adtech.us +0.0.0.0 adserver.adtechus.com +0.0.0.0 adserver.adultfriendfinder.com +0.0.0.0 adserver.advertist.com +0.0.0.0 adserver.affiliatemg.com +0.0.0.0 adserver.affiliation.com +0.0.0.0 adserver.aim4media.com +0.0.0.0 adserver.a.in.monster.com +0.0.0.0 adserver.airmiles.ca +0.0.0.0 adserver.akqa.net +0.0.0.0 adserver.allheadlinenews.com +0.0.0.0 adserver.amnews.com +0.0.0.0 adserver.ancestry.com +0.0.0.0 adserver.anemo.com +0.0.0.0 adserver.anm.co.uk +0.0.0.0 adserver.aol.fr +0.0.0.0 adserver.archant.co.uk +0.0.0.0 adserver.artempireindustries.com +0.0.0.0 adserver.arttoday.com +0.0.0.0 adserver.atari.net +0.0.0.0 adserverb.conjelco.com +0.0.0.0 adserver.betandwin.de +0.0.0.0 adserver.billiger-surfen.de +0.0.0.0 adserver.billiger-telefonieren.de +0.0.0.0 adserver.bizland-inc.net +0.0.0.0 adserver.bluereactor.com +0.0.0.0 adserver.bluereactor.net +0.0.0.0 adserver.bluewin.ch +0.0.0.0 adserver.buttonware.com +0.0.0.0 adserver.buttonware.net +0.0.0.0 adserver.cams.com +0.0.0.0 adserver.cantv.net +0.0.0.0 adserver.cebu-online.com +0.0.0.0 adserver.cheatplanet.com +0.0.0.0 adserver.chickclick.com +0.0.0.0 adserver.click4cash.de +0.0.0.0 adserver.clubic.com +0.0.0.0 adserver.clundressed.com +0.0.0.0 adserver.co.il +0.0.0.0 adserver.colleges.com +0.0.0.0 adserver.com +0.0.0.0 adserver.comparatel.fr +0.0.0.0 adserver.com-solutions.com +0.0.0.0 adserver.conjelco.com +0.0.0.0 adserver.corusradionetwork.com +0.0.0.0 adserver.creative-asia.com +0.0.0.0 adserver.creativeinspire.com +0.0.0.0 adserver.dayrates.com +0.0.0.0 adserver.dbusiness.com +0.0.0.0 adserver.developersnetwork.com +0.0.0.0 adserver.devx.com +0.0.0.0 adserver.digitalpartners.com +0.0.0.0 adserver.digitoday.com +0.0.0.0 adserver.directforce.com +0.0.0.0 adserver.directforce.net +0.0.0.0 adserver.dnps.com +0.0.0.0 adserver.dotcommedia.de +0.0.0.0 adserver.dotmusic.com +0.0.0.0 adserver.eham.net +0.0.0.0 adserver.emapadserver.com +0.0.0.0 adserver.emporis.com +0.0.0.0 adserver.emulation64.com +0.0.0.0 adserver-espnet.sportszone.net +0.0.0.0 adserver.eudora.com +0.0.0.0 adserver.eva2000.com +0.0.0.0 adserver.expatica.nxs.nl +0.0.0.0 adserver.ezzhosting.com +0.0.0.0 adserver.filefront.com +0.0.0.0 adserver.fmpub.net +0.0.0.0 adserver.fr.adtech.de +0.0.0.0 adserver.freecity.de +0.0.0.0 adserver.freenet.de +0.0.0.0 adserver.friendfinder.com +0.0.0.0 adserver.gameparty.net +0.0.0.0 adserver.gamesquad.net +0.0.0.0 adserver.garden.com +0.0.0.0 adserver.gorillanation.com +0.0.0.0 adserver.gr +0.0.0.0 adserver.gunaxin.com +0.0.0.0 adserver.hardsextube.com +0.0.0.0 adserver.hardwareanalysis.com +0.0.0.0 adserver.harktheherald.com +0.0.0.0 adserver.harvestadsdepot.com +0.0.0.0 adserver.hellasnet.gr +0.0.0.0 adserver.hg-computer.de +0.0.0.0 adserver.hi-m.de +0.0.0.0 adserver.hispavista.com +0.0.0.0 adserver.hk.outblaze.com +0.0.0.0 adserver.home.pl +0.0.0.0 adserver.hostinteractive.com +0.0.0.0 adserver.humanux.com +0.0.0.0 adserver.hwupgrade.it +0.0.0.0 adserver.ifmagazine.com +0.0.0.0 adserver.ig.com.br +0.0.0.0 adserver.ign.com +0.0.0.0 adserver.ilounge.com +0.0.0.0 adserver.infinit.net +0.0.0.0 adserver.infotiger.com +0.0.0.0 adserver.interfree.it +0.0.0.0 adserver.inwind.it +0.0.0.0 adserver.ision.de +0.0.0.0 adserver.isonews.com +0.0.0.0 adserver.ixm.co.uk +0.0.0.0 adserver.jacotei.com.br +0.0.0.0 adserver.janes.com +0.0.0.0 adserver.janes.net +0.0.0.0 adserver.janes.org +0.0.0.0 adserver.jolt.co.uk +0.0.0.0 adserver.journalinteractive.com +0.0.0.0 adserver.juicyads.com +0.0.0.0 adserver.kcilink.com +0.0.0.0 adserver.killeraces.com +0.0.0.0 adserver.kylemedia.com +0.0.0.0 adserver.lanacion.com.ar +0.0.0.0 adserver.lanepress.com +0.0.0.0 adserver.latimes.com +0.0.0.0 adserver.legacy-network.com +0.0.0.0 adserver.libero.it +0.0.0.0 adserver.linktrader.co.uk +0.0.0.0 adserver.livejournal.com +0.0.0.0 adserver.lostreality.com +0.0.0.0 adserver.lunarpages.com +0.0.0.0 adserver.lycos.co.jp +0.0.0.0 adserver.m2kcore.com +0.0.0.0 adserver.magazyn.pl +0.0.0.0 adserver.matchcraft.com +0.0.0.0 adserver.merc.com +0.0.0.0 adserver.mindshare.de +0.0.0.0 adserver.mobsmith.com +0.0.0.0 adserver.monster.com +0.0.0.0 adserver.monstersandcritics.com +0.0.0.0 adserver.motonews.pl +0.0.0.0 adserver.myownemail.com +0.0.0.0 adserver.netcreators.nl +0.0.0.0 adserver.netshelter.net +0.0.0.0 adserver.newdigitalgroup.com +0.0.0.0 adserver.newmassmedia.net +0.0.0.0 adserver.news.com +0.0.0.0 adserver.news.com.au +0.0.0.0 adserver.news-journalonline.com +0.0.0.0 adserver.newtimes.com +0.0.0.0 adserver.ngz-network.de +0.0.0.0 adserver.nydailynews.com +0.0.0.0 adserver.nzoom.com +0.0.0.0 adserver.o2.pl +0.0.0.0 adserver.onwisconsin.com +0.0.0.0 adserver.passion.com +0.0.0.0 adserver.phatmax.net +0.0.0.0 adserver.phillyburbs.com +0.0.0.0 adserver.pl +0.0.0.0 adserver.planet-multiplayer.de +0.0.0.0 adserver.plhb.com +0.0.0.0 adserver.pollstar.com +0.0.0.0 adserver.portalofevil.com +0.0.0.0 adserver.portal.pl +0.0.0.0 adserver.portugalmail.pt +0.0.0.0 adserver.prodigy.net +0.0.0.0 adserver.proteinos.com +0.0.0.0 adserver.radio-canada.ca +0.0.0.0 adserver.ratestar.net +0.0.0.0 adserver.revver.com +0.0.0.0 adserver.ro +0.0.0.0 adserver.sabc.co.za +0.0.0.0 adserver.sabcnews.co.za +0.0.0.0 adserver.sanomawsoy.fi +0.0.0.0 adserver.scmp.com +0.0.0.0 adserver.securityfocus.com +0.0.0.0 adserver.sextracker.com +0.0.0.0 adserver.sharewareonline.com +0.0.0.0 adserver.singnet.com +0.0.0.0 adserver.sl.kharkov.ua +0.0.0.0 adserver.smashtv.com +0.0.0.0 adserver.snowball.com +0.0.0.0 adserver.softonic.com +0.0.0.0 adserver.soloserver.com +0.0.0.0 adserversolutions.com +0.0.0.0 adserver.swiatobrazu.pl +0.0.0.0 adserver.synergetic.de +0.0.0.0 adserver.telalink.net +0.0.0.0 adserver.te.pt +0.0.0.0 adserver.teracent.net +0.0.0.0 adserver.terra.com.br +0.0.0.0 adserver.terra.es +0.0.0.0 adserver.theknot.com +0.0.0.0 adserver.theonering.net +0.0.0.0 adserver.thirty4.com +0.0.0.0 adserver.thisislondon.co.uk +0.0.0.0 adserver.tilted.net +0.0.0.0 adserver.tqs.ca +0.0.0.0 adserver.track-star.com +0.0.0.0 adserver.trader.ca +0.0.0.0 adserver.trafficsyndicate.com +0.0.0.0 adserver.trb.com +0.0.0.0 adserver.tribuneinteractive.com +0.0.0.0 adserver.tsgadv.com +0.0.0.0 adserver.tulsaworld.com +0.0.0.0 adserver.tweakers.net +0.0.0.0 adserver.twitpic.com +0.0.0.0 adserver.ugo.com +0.0.0.0 adserver.ugo.nl +0.0.0.0 adserver.ukplus.co.uk +0.0.0.0 adserver.uproxx.com +0.0.0.0 adserver.usermagnet.com +0.0.0.0 adserver.van.net +0.0.0.0 adserver.virginmedia.com +0.0.0.0 adserver.virgin.net +0.0.0.0 adserver.virtualminds.nl +0.0.0.0 adserver.virtuous.co.uk +0.0.0.0 adserver.voir.ca +0.0.0.0 adserver.webads.co.uk +0.0.0.0 adserver.webads.nl +0.0.0.0 adserver.wemnet.nl +0.0.0.0 adserver.x3.hu +0.0.0.0 adserver.ya.com +0.0.0.0 adserver.yahoo.com +0.0.0.0 adserver.zaz.com.br +0.0.0.0 adserver.zeads.com +0.0.0.0 adserve.shopzilla.com +0.0.0.0 adserve.splicetoday.com +0.0.0.0 adserve.viaarena.com +0.0.0.0 adserv.free6.com +0.0.0.0 adserv.geocomm.com +0.0.0.0 adserv.iafrica.com +0.0.0.0 adservices.google.com +0.0.0.0 adservices.picadmedia.com +0.0.0.0 adservingcentral.com +0.0.0.0 adserving.cpxinteractive.com +0.0.0.0 adserv.internetfuel.com +0.0.0.0 adserv.jupiter.com +0.0.0.0 adserv.lwmn.net +0.0.0.0 adserv.maineguide.com +0.0.0.0 adserv.muchosucko.com +0.0.0.0 adserv.mywebtimes.com +0.0.0.0 adserv.pitchforkmedia.com +0.0.0.0 adserv.postbulletin.com +0.0.0.0 adserv.qconline.com +0.0.0.0 adserv.quality-channel.de +0.0.0.0 adserv.usps.com +0.0.0.0 adserwer.o2.pl +0.0.0.0 ads.espn.adsonar.com +0.0.0.0 ads.eudora.com +0.0.0.0 ads.eu.msn.com +0.0.0.0 ads.euniverseads.com +0.0.0.0 adseu.novem.pl +0.0.0.0 ads.examiner.net +0.0.0.0 ads.exhedra.com +0.0.0.0 ads.expedia.com +0.0.0.0 ads.expekt.com +0.0.0.0 ads.ezboard.com +0.0.0.0 adsfac.eu +0.0.0.0 adsfac.net +0.0.0.0 adsfac.us +0.0.0.0 ads.fairfax.com.au +0.0.0.0 ads.fark.com +0.0.0.0 ads.fayettevillenc.com +0.0.0.0 ads.filecloud.com +0.0.0.0 ads.fileindexer.com +0.0.0.0 ads.filmup.com +0.0.0.0 ads.first-response.be +0.0.0.0 ads.flabber.nl +0.0.0.0 ads.flashgames247.com +0.0.0.0 ads.fling.com +0.0.0.0 ads.floridatoday.com +0.0.0.0 ads.fool.com +0.0.0.0 ads.forbes.com +0.0.0.0 ads.forbes.net +0.0.0.0 ads.fortunecity.com +0.0.0.0 ads.fredericksburg.com +0.0.0.0 ads.freebannertrade.com +0.0.0.0 ads.freshmeat.net +0.0.0.0 ads.fresnobee.com +0.0.0.0 ads.friendfinder.com +0.0.0.0 ads.ft.com +0.0.0.0 ads.gamblinghit.com +0.0.0.0 ads.gamecity.net +0.0.0.0 ads.gamecopyworld.no +0.0.0.0 ads.gameinformer.com +0.0.0.0 ads.game.net +0.0.0.0 ads.gamershell.com +0.0.0.0 ads.gamespy.com +0.0.0.0 ads.gamespyid.com +0.0.0.0 ads.gateway.com +0.0.0.0 ads.gawker.com +0.0.0.0 ads.gettools.com +0.0.0.0 ads.gigaom.com.php5-12.websitetestlink.com +0.0.0.0 ads.globeandmail.com +0.0.0.0 ads.gmg.valueclick.net +0.0.0.0 ads.gmodules.com +0.0.0.0 ads.god.co.uk +0.0.0.0 ads.gorillanation.com +0.0.0.0 ads.gplusmedia.com +0.0.0.0 ads.granadamedia.com +0.0.0.0 ads.greenbaypressgazette.com +0.0.0.0 ads.greenvilleonline.com +0.0.0.0 ads.guardian.co.uk +0.0.0.0 ads.guardianunlimited.co.uk +0.0.0.0 ads.gunaxin.com +0.0.0.0 ads.halogennetwork.com +0.0.0.0 ads.hamptonroads.com +0.0.0.0 ads.hamtonroads.com +0.0.0.0 ads.hardwarezone.com +0.0.0.0 ads.harpers.org +0.0.0.0 ads.hbv.de +0.0.0.0 ads.hearstmags.com +0.0.0.0 ads.heartlight.org +0.0.0.0 ads.herald-mail.com +0.0.0.0 ads.heraldnet.com +0.0.0.0 ads.heraldonline.com +0.0.0.0 ads.heraldsun.com +0.0.0.0 ads.heroldonline.com +0.0.0.0 ads.he.valueclick.net +0.0.0.0 ads.hitcents.com +0.0.0.0 ads.hlwd.valueclick.net +0.0.0.0 ads.hollandsentinel.com +0.0.0.0 ads.hollywood.com +0.0.0.0 ads.hooqy.com +0.0.0.0 ads.hothardware.com +0.0.0.0 ad.showbizz.net +0.0.0.0 ads.hulu.com.edgesuite.net +#0.0.0.0 ads.hulu.com # Uncomment to block Hulu. +0.0.0.0 ads.humorbua.no +0.0.0.0 ads.i12.de +0.0.0.0 ads.i33.com +0.0.0.0 ads.iafrica.com +0.0.0.0 ads.i-am-bored.com +0.0.0.0 ads.iboost.com +0.0.0.0 ads.icq.com +0.0.0.0 ads.iforex.com +0.0.0.0 ads.ign.com +0.0.0.0 ads.illuminatednation.com +0.0.0.0 ads.imdb.com +0.0.0.0 ads.imgur.com +0.0.0.0 ads.imposibil.ro +0.0.0.0 ads.indiatimes.com +0.0.0.0 ads.indya.com +0.0.0.0 ads.indystar.com +0.0.0.0 ads.inedomedia.com +0.0.0.0 ads.inetdirectories.com +0.0.0.0 ads.inetinteractive.com +0.0.0.0 ads.infi.net +0.0.0.0 ads.infospace.com +0.0.0.0 adsinimages.com +0.0.0.0 ads.injersey.com +0.0.0.0 ads.insidehighered.com +0.0.0.0 ads.intellicast.com +0.0.0.0 ads.internic.co.il +0.0.0.0 ads.inthesidebar.com +0.0.0.0 adsintl.starwave.com +0.0.0.0 ads.iol.co.il +0.0.0.0 ads.ipowerweb.com +0.0.0.0 ads.ireport.com +0.0.0.0 ads.isat-tech.com +0.0.0.0 ads.isoftmarketing.com +0.0.0.0 ads.isum.de +0.0.0.0 ads.itv.com +0.0.0.0 ads.iwon.com +0.0.0.0 ads.jacksonville.com +0.0.0.0 ads.jeneauempire.com +0.0.0.0 ads.jetpackdigital.com +0.0.0.0 ads.jetphotos.net +0.0.0.0 ads.jewcy.com +0.0.0.0 ads.jimworld.com +0.0.0.0 ads.joetec.net +0.0.0.0 ads.jokaroo.com +0.0.0.0 ads.jornadavirtual.com.mx +0.0.0.0 ads.jossip.com +0.0.0.0 ads.jpost.com +0.0.0.0 ads.jubii.dk +0.0.0.0 ads.juicyads.com +0.0.0.0 ads.juneauempire.com +0.0.0.0 ads.jwtt3.com +0.0.0.0 ads.kazaa.com +0.0.0.0 ads.keywordblocks.com +0.0.0.0 ads.kixer.com +0.0.0.0 ads.kleinman.com +0.0.0.0 ads.kmpads.com +0.0.0.0 ads.koreanfriendfinder.com +0.0.0.0 ads.ksl.com +0.0.0.0 ad.slashgear.com +0.0.0.0 ads.leo.org +0.0.0.0 ads.lfstmedia.com +0.0.0.0 ads.lilengine.com +0.0.0.0 ads.link4ads.com +0.0.0.0 ads.linksponsor.com +0.0.0.0 ads.linktracking.net +0.0.0.0 ads.linuxjournal.com +0.0.0.0 ads.linuxsecurity.com +0.0.0.0 ads.list-universe.com +0.0.0.0 ads.live365.com +0.0.0.0 ads.ljworld.com +0.0.0.0 ads.lnkworld.com +0.0.0.0 ads.localnow.com +0.0.0.0 ads-local.sixapart.com +0.0.0.0 ads.lubbockonline.com +0.0.0.0 ads.lucidmedia.com +0.0.0.0 ads.lucidmedia.com.gslb.com +0.0.0.0 ads.lycos.com +0.0.0.0 ads.lycos-europe.com +0.0.0.0 ads.lzjl.com +0.0.0.0 ads.macnews.de +0.0.0.0 ads.macupdate.com +0.0.0.0 ads.madisonavenue.com +0.0.0.0 ads.madison.com +0.0.0.0 ads.magnetic.is +0.0.0.0 ads.mail.com +0.0.0.0 ads.mambocommunities.com +0.0.0.0 ad.sma.punto.net +0.0.0.0 ads.mariuana.it +0.0.0.0 adsmart.com +0.0.0.0 adsmart.co.uk +0.0.0.0 adsmart.net +0.0.0.0 ads.mcafee.com +0.0.0.0 ads.mdchoice.com +0.0.0.0 ads.mediamayhemcorp.com +0.0.0.0 ads.mediaodyssey.com +0.0.0.0 ads.mediaturf.net +0.0.0.0 ads.mefeedia.com +0.0.0.0 ads.megaproxy.com +0.0.0.0 ads.metblogs.com +0.0.0.0 ads.mgnetwork.com +0.0.0.0 ads.mindsetnetwork.com +0.0.0.0 ads.miniclip.com +0.0.0.0 ads.mininova.org +0.0.0.0 ads.mircx.com +0.0.0.0 ads.mixtraffic.com +0.0.0.0 ads.mlive.com +0.0.0.0 ads.mm.ap.org +0.0.0.0 ads.mndaily.com +0.0.0.0 ad.smni.com +0.0.0.0 ads.mobiledia.com +0.0.0.0 ads.mobygames.com +0.0.0.0 ads.modbee.com +0.0.0.0 ads.mofos.com +0.0.0.0 ads.money.pl +0.0.0.0 ads.monster.com +0.0.0.0 ads.mouseplanet.com +0.0.0.0 ads.movieweb.com +0.0.0.0 ads.mp3searchy.com +0.0.0.0 adsm.soush.com +0.0.0.0 ads.mt.valueclick.net +0.0.0.0 ads.mtv.uol.com.br +0.0.0.0 ads.multimania.lycos.fr +0.0.0.0 ads.musiccity.com +0.0.0.0 ads.mustangworks.com +0.0.0.0 ads.mysimon.com +0.0.0.0 ads.mytelus.com +0.0.0.0 ads.nandomedia.com +0.0.0.0 ads.nationalreview.com +0.0.0.0 ads.nativeinstruments.de +0.0.0.0 ads.neoseeker.com +0.0.0.0 ads.neowin.net +0.0.0.0 ads.nerve.com +0.0.0.0 ads.netmechanic.com +0.0.0.0 ads.networkwcs.net +0.0.0.0 ads.networldmedia.net +0.0.0.0 ads.neudesicmediagroup.com +0.0.0.0 ads.newcity.com +0.0.0.0 ads.newcitynet.com +0.0.0.0 ads.newdream.net +0.0.0.0 ads.newgrounds.com +0.0.0.0 ads.newsint.co.uk +0.0.0.0 ads.newsminerextra.com +0.0.0.0 ads.newsobserver.com +0.0.0.0 ads.newsquest.co.uk +0.0.0.0 ads.newtention.net +0.0.0.0 ads.newtimes.com +0.0.0.0 adsnew.userfriendly.org +0.0.0.0 ads.ngenuity.com +0.0.0.0 ads.ninemsn.com.au +0.0.0.0 adsniper.ru +0.0.0.0 ads.nola.com +0.0.0.0 ads.northjersey.com +0.0.0.0 ads.novem.pl +0.0.0.0 ads.nowrunning.com +0.0.0.0 ads.npr.valueclick.net +0.0.0.0 ads.ntadvice.com +0.0.0.0 ads.nudecards.com +0.0.0.0 ads.nwsource.com +0.0.0.0 ads.nwsource.com.edgesuite.net +0.0.0.0 ads.nyi.net +0.0.0.0 ads.nyjournalnews.com +0.0.0.0 ads.nypost.com +0.0.0.0 ads.nytimes.com +0.0.0.0 ads.o2.pl +0.0.0.0 adsoftware.com +0.0.0.0 adsoldier.com +0.0.0.0 ads.ole.com +0.0.0.0 ads.omaha.com +0.0.0.0 adsonar.com +0.0.0.0 adson.awempire.com +0.0.0.0 ads.onlineathens.com +0.0.0.0 ads.online.ie +0.0.0.0 ads.onvertise.com +0.0.0.0 ads.ookla.com +0.0.0.0 ads.open.pl +0.0.0.0 ads.opensubtitles.org +0.0.0.0 ads.oregonlive.com +0.0.0.0 ads.orsm.net +0.0.0.0 ads.osdn.com +0.0.0.0 ad-souk.com +0.0.0.0 adspaces.ero-advertising.com +0.0.0.0 ads.parrysound.com +0.0.0.0 ads.partner2profit.com +0.0.0.0 ads.pastemagazine.com +0.0.0.0 ads.paxnet.co.kr +0.0.0.0 ads.pcper.com +0.0.0.0 ads.pdxguide.com +0.0.0.0 ads.peel.com +0.0.0.0 ads.peninsulaclarion.com +0.0.0.0 ads.penny-arcade.com +0.0.0.0 ads.pennyweb.com +0.0.0.0 ads.people.com.cn +0.0.0.0 ads.pg.valueclick.net +0.0.0.0 ads.pheedo.com +0.0.0.0 ads.phillyburbs.com +0.0.0.0 ads.phpclasses.org +0.0.0.0 ads.pilotonline.com +0.0.0.0 adspirit.net +0.0.0.0 adspiro.pl +0.0.0.0 ads.pitchforkmedia.com +0.0.0.0 ads.pittsburghlive.com +0.0.0.0 ads.pixiq.com +0.0.0.0 ads.place1.com +0.0.0.0 ads.planet-f1.com +0.0.0.0 ads.plantyours.com +0.0.0.0 ads.pni.com +0.0.0.0 ads.pno.net +0.0.0.0 ads.poconorecord.com +0.0.0.0 ads.pointroll.com +0.0.0.0 ads.portlandmercury.com +0.0.0.0 ads.premiumnetwork.com +0.0.0.0 ads.premiumnetwork.net +0.0.0.0 ads.pressdemo.com +0.0.0.0 ads.pricescan.com +0.0.0.0 ads.primaryclick.com +0.0.0.0 ads.primeinteractive.net +0.0.0.0 ads.prisacom.com +0.0.0.0 ads.profitsdeluxe.com +0.0.0.0 ads.profootballtalk.com +0.0.0.0 ads.program3.com +0.0.0.0 ads.pro-market.net +0.0.0.0 ads.pro-market.net.edgesuite.net +0.0.0.0 ads.prospect.org +0.0.0.0 ads.pubmatic.com +0.0.0.0 ads.queendom.com +0.0.0.0 ads.quicken.com +0.0.0.0 adsr3pg.com.br +0.0.0.0 ads.rackshack.net +0.0.0.0 ads.rasmussenreports.com +0.0.0.0 ads.ratemyprofessors.com +0.0.0.0 adsrc.bankrate.com +0.0.0.0 ads.rcgroups.com +0.0.0.0 ads.rdstore.com +0.0.0.0 ads.realcastmedia.com +0.0.0.0 ads.realcities.com +0.0.0.0 ads.realmedia.de +0.0.0.0 ads.realtechnetwork.net +0.0.0.0 ads.reason.com +0.0.0.0 ads.rediff.com +0.0.0.0 ads.redorbit.com +0.0.0.0 ads.register.com +0.0.0.0 adsremote.scripps.com +0.0.0.0 adsremote.scrippsnetwork.com +0.0.0.0 ads.revenews.com +0.0.0.0 ads.revenue.net +0.0.0.0 adsrevenue.net +0.0.0.0 ads.revsci.net +0.0.0.0 ads.rim.co.uk +0.0.0.0 ads-rm.looksmart.com +0.0.0.0 ads.roanoke.com +0.0.0.0 ads.rockstargames.com +0.0.0.0 ads.rodale.com +0.0.0.0 ads.roiserver.com +0.0.0.0 ads.rondomondo.com +0.0.0.0 ads.rootzoo.com +0.0.0.0 ads.rottentomatoes.com +0.0.0.0 ads.rp-online.de +0.0.0.0 ads.ruralpress.com +0.0.0.0 adsrv2.wilmingtonstar.com +0.0.0.0 adsrv.bankrate.com +0.0.0.0 adsrv.dispatch.com +0.0.0.0 adsrv.emporis.com +0.0.0.0 adsrv.heraldtribune.com +0.0.0.0 adsrv.hpg.com.br +0.0.0.0 adsrv.iol.co.za +0.0.0.0 adsrv.lua.pl +0.0.0.0 adsrv.news.com.au +0.0.0.0 adsrvr.com +0.0.0.0 adsrv.tuscaloosanews.com +0.0.0.0 adsrv.wilmingtonstar.com +0.0.0.0 ads.sacbee.com +0.0.0.0 ads.satyamonline.com +0.0.0.0 ads.savannahnow.com +0.0.0.0 ads.scabee.com +0.0.0.0 ads.schwabtrader.com +0.0.0.0 ads.scifi.com +0.0.0.0 ads.seattletimes.com +0.0.0.0 ads.sfusion.com +0.0.0.0 ads.shizmoo.com +0.0.0.0 ads.shoppingads.com +0.0.0.0 ads.shoutfile.com +0.0.0.0 ads.sify.com +0.0.0.0 ads.simtel.com +0.0.0.0 ads.simtel.net +0.0.0.0 ads.sitemeter.com +0.0.0.0 ads.sixapart.com +0.0.0.0 adssl01.adtech.de +0.0.0.0 adssl01.adtech.fr +0.0.0.0 adssl01.adtech.us +0.0.0.0 adssl02.adtech.de +0.0.0.0 adssl02.adtech.fr +0.0.0.0 adssl02.adtech.us +0.0.0.0 ads.sl.interpals.net +0.0.0.0 ads.smartclick.com +0.0.0.0 ads.smartclicks.com +0.0.0.0 ads.smartclicks.net +0.0.0.0 ads.snowball.com +0.0.0.0 ads.socialmedia.com +0.0.0.0 ads.sohh.com +0.0.0.0 ads.somethingawful.com +0.0.0.0 ads.space.com +0.0.0.0 adsspace.net +0.0.0.0 ads.specificclick.com +0.0.0.0 ads.specificmedia.com +0.0.0.0 ads.specificpop.com +0.0.0.0 ads.sptimes.com +0.0.0.0 ads.spymac.net +0.0.0.0 ads.stackoverflow.com +0.0.0.0 ads.starbanner.com +0.0.0.0 ads.stephensmedia.com +0.0.0.0 ads.stileproject.com +0.0.0.0 ads.stupid.com +0.0.0.0 ads.sunjournal.com +0.0.0.0 ads.sup.com +0.0.0.0 ads.swiftnews.com +0.0.0.0 ads.switchboard.com +0.0.0.0 ads.teamyehey.com +0.0.0.0 ads.technoratimedia.com +0.0.0.0 ads.techtv.com +0.0.0.0 ads.techvibes.com +0.0.0.0 ads.techweb.com +0.0.0.0 ads.telegraaf.nl +0.0.0.0 ads.telegraph.co.uk +0.0.0.0 ads.the15thinternet.com +0.0.0.0 ads.theawl.com +0.0.0.0 ads.thebugs.ws +0.0.0.0 ads.thecoolhunter.net +0.0.0.0 ads.thecrimson.com +0.0.0.0 ads.thefrisky.com +0.0.0.0 ads.thegauntlet.com +0.0.0.0 ads.theglobeandmail.com +0.0.0.0 ads.theindependent.com +0.0.0.0 ads.theolympian.com +0.0.0.0 ads.thesmokinggun.com +0.0.0.0 ads.thestar.com #Toronto Star +0.0.0.0 ads.thestranger.com +0.0.0.0 ads.thewebfreaks.com +0.0.0.0 adstil.indiatimes.com +0.0.0.0 ads.timesunion.com +0.0.0.0 ads.tiscali.fr +0.0.0.0 ads.tmcs.net +0.0.0.0 ads.tnt.tv +0.0.0.0 adstogo.com +0.0.0.0 adstome.com +0.0.0.0 ads.top500.org #TOP500 SuperComputer Site +0.0.0.0 ads.top-banners.com +0.0.0.0 ads.toronto.com +0.0.0.0 ads.townhall.com +0.0.0.0 ads.track.net +0.0.0.0 ads.traderonline.com +0.0.0.0 ads.traffichaus.com +0.0.0.0 ads.trafficjunky.net +0.0.0.0 ads.traffikings.com +0.0.0.0 adstream.cardboardfish.com +0.0.0.0 adstreams.org +0.0.0.0 ads.treehugger.com +0.0.0.0 ads.tricityherald.com +0.0.0.0 ads.trinitymirror.co.uk +0.0.0.0 ads.tripod.com +0.0.0.0 ads.tripod.lycos.co.uk +0.0.0.0 ads.tripod.lycos.de +0.0.0.0 ads.tripod.lycos.es +0.0.0.0 ads.tromaville.com +0.0.0.0 ads-t.ru +0.0.0.0 ads.trutv.com +0.0.0.0 ads.tucows.com +0.0.0.0 ads.tw.adsonar.com +0.0.0.0 ads.ucomics.com +0.0.0.0 ads.uigc.net +0.0.0.0 ads.undertone.com +0.0.0.0 ads.unixathome.org +0.0.0.0 ads.update.com +0.0.0.0 ad.suprnova.org +0.0.0.0 ads.uproar.com +0.0.0.0 ads.urbandictionary.com +0.0.0.0 ads.usatoday.com +0.0.0.0 ads.us.e-planning.ne +0.0.0.0 ads.us.e-planning.net +0.0.0.0 ads.userfriendly.org +0.0.0.0 ads.v3.com +0.0.0.0 ads.v3exchange.com +0.0.0.0 ads.vaildaily.com +0.0.0.0 ads.valuead.com +0.0.0.0 ads.vegas.com +0.0.0.0 ads.veloxia.com +0.0.0.0 ads.ventivmedia.com +0.0.0.0 ads.veoh.com +0.0.0.0 ads.verkata.com +0.0.0.0 ads.vesperexchange.com +0.0.0.0 ads.vg.basefarm.net +0.0.0.0 ads.viddler.com +0.0.0.0 ads.videoadvertising.com +0.0.0.0 ads.viewlondon.co.uk +0.0.0.0 ads.virginislandsdailynews.com +0.0.0.0 ads.virtualcountries.com +0.0.0.0 ads.vnuemedia.com +0.0.0.0 adsvr.adknowledge.com +0.0.0.0 ads.vs.co +0.0.0.0 ads.vs.com +0.0.0.0 ads.wanadooregie.com +0.0.0.0 ads.warcry.com +0.0.0.0 ads.watershed-publishing.com +0.0.0.0 ads.wave.si +0.0.0.0 ads.weather.ca +0.0.0.0 ads.weather.com +0.0.0.0 ads.web21.com +0.0.0.0 ads.web.alwayson-network.com +0.0.0.0 ads.web.aol.com +0.0.0.0 ads.webattack.com +0.0.0.0 ads.web.compuserve.com +0.0.0.0 ads.webcoretech.com +0.0.0.0 ads.web.cs.com +0.0.0.0 ads.web.de +0.0.0.0 ads.webfeat.com +0.0.0.0 ads.webheat.com +0.0.0.0 ads.webhosting.info +0.0.0.0 ads.webindia123.com +0.0.0.0 ads-web.mail.com +0.0.0.0 ads.webmd.com +0.0.0.0 ads.webnet.advance.net +0.0.0.0 ads.websponsors.com +0.0.0.0 adsweb.tiscali.cz +0.0.0.0 ads.weissinc.com +0.0.0.0 ads.whaleads.com +0.0.0.0 ads.whi.co.nz +0.0.0.0 ads.winsite.com +0.0.0.0 ads.wnd.com +0.0.0.0 ads.wunderground.com +0.0.0.0 ads.x10.com +0.0.0.0 ads.x10.net +0.0.0.0 ads.x17online.com +0.0.0.0 ads.xboxic.com +0.0.0.0 ads.xbox-scene.com +0.0.0.0 ads.xposed.com +0.0.0.0 ads.xtra.ca +0.0.0.0 ads.xtra.co.nz +0.0.0.0 ads.xtramsn.co.nz +0.0.0.0 ads.yahoo.com +0.0.0.0 ads.yimg.com +0.0.0.0 ads.yimg.com.edgesuite.net +0.0.0.0 ads.yldmgrimg.net +0.0.0.0 adsyndication.msn.com +0.0.0.0 adsyndication.yelldirect.com +0.0.0.0 adsynergy.com +0.0.0.0 ads.youporn.com +0.0.0.0 ads.youtube.com +0.0.0.0 adsys.townnews.com +0.0.0.0 ads.zap2it.com +0.0.0.0 ads.zdnet.com +0.0.0.0 adtag.msn.ca +0.0.0.0 adtag.sympatico.ca +0.0.0.0 adtaily.com +0.0.0.0 adtaily.pl +0.0.0.0 ad.tbn.ru +0.0.0.0 adtcp.ru +0.0.0.0 adtech.de +0.0.0.0 ad.technoramedia.com +0.0.0.0 adtech.panthercustomer.com +0.0.0.0 adtechus.com +0.0.0.0 adtegrity.spinbox.net +0.0.0.0 adtext.pl +0.0.0.0 ad.text.tbn.ru +0.0.0.0 ad.tgdaily.com +0.0.0.0 ad.thehill.com +0.0.0.0 ad.thetyee.ca +0.0.0.0 ad.thewheelof.com +0.0.0.0 adthru.com +0.0.0.0 adtigerpl.adspirit.net +0.0.0.0 ad.tiscali.com +0.0.0.0 adtlgc.com +0.0.0.0 adtology3.com +0.0.0.0 ad.tomshardware.com +0.0.0.0 adtotal.pl +0.0.0.0 adtracking.vinden.nl +0.0.0.0 adtrader.com +0.0.0.0 ad.trafficmp.com +0.0.0.0 adtrak.net +0.0.0.0 ad.turn.com +0.0.0.0 ad.tv2.no +0.0.0.0 ad.twitchguru.com +0.0.0.0 ad.ubnm.co.kr +0.0.0.0 ad.uk.tangozebra.com +0.0.0.0 ad-uk.tiscali.com +0.0.0.0 adultadworld.com +0.0.0.0 ad.usatoday.com +0.0.0.0 adv0005.247realmedia.com +0.0.0.0 adv0035.247realmedia.com +0.0.0.0 adv.440net.com +0.0.0.0 adv.adgates.com +0.0.0.0 adv.adtotal.pl +0.0.0.0 adv.adview.pl +0.0.0.0 adv.bannercity.ru +0.0.0.0 adv.bbanner.it +0.0.0.0 adv.bookclubservices.ca +0.0.0.0 adveng.hiasys.com +0.0.0.0 adveraction.pl +0.0.0.0 advert.bayarea.com +0.0.0.0 advertise.com +0.0.0.0 advertisers.federatedmedia.net +0.0.0.0 advertising.aol.com +0.0.0.0 advertisingbay.com +0.0.0.0 advertising.bbcworldwide.com +0.0.0.0 advertising.com +0.0.0.0 advertising.gfxartist.com +0.0.0.0 advertising.hiasys.com +0.0.0.0 advertising.illinimedia.com +0.0.0.0 advertising.online-media24.de +0.0.0.0 advertising.paltalk.com +0.0.0.0 advertising.wellpack.fr +0.0.0.0 advertising.zenit.org +0.0.0.0 advertlets.com +0.0.0.0 advertpro.investorvillage.com +0.0.0.0 advertpro.sitepoint.com +0.0.0.0 adverts.digitalspy.co.uk +0.0.0.0 adverts.ecn.co.uk +0.0.0.0 adverts.freeloader.com +0.0.0.0 adverts.im4ges.com +0.0.0.0 advertstream.com +0.0.0.0 advert.uloz.to +0.0.0.0 adv.federalpost.ru +0.0.0.0 adv.gazeta.pl +0.0.0.0 advicepl.adocean.pl +0.0.0.0 adview.pl +0.0.0.0 adviva.net +0.0.0.0 adv.lampsplus.com +0.0.0.0 advmaker.ru +0.0.0.0 adv.merlin.co.il +0.0.0.0 adv.netshelter.net +0.0.0.0 adv.publy.net +0.0.0.0 adv.surinter.net +0.0.0.0 advt.webindia123.com +0.0.0.0 ad.vurts.com +0.0.0.0 adv.virgilio.it +0.0.0.0 adv.webmd.com +0.0.0.0 adv.wp.pl +0.0.0.0 adv.zapal.ru +0.0.0.0 advzilla.com +0.0.0.0 adware.kogaryu.com +0.0.0.0 adweb2.hornymatches.com +0.0.0.0 ad.webprovider.com +0.0.0.0 adw.sapo.pt +0.0.0.0 ad.wsod.com +0.0.0.0 adx.adrenalinesk.sk +0.0.0.0 adx.gainesvillesun.com +0.0.0.0 adx.gainesvillsun.com +0.0.0.0 adx.groupstate.com +0.0.0.0 adx.hendersonvillenews.com +0.0.0.0 adx.heraldtribune.com +0.0.0.0 adxpose.com +0.0.0.0 adx.starnewsonline.com +0.0.0.0 ad.xtendmedia.com +0.0.0.0 adx.theledger.com +0.0.0.0 ad.yadro.ru +0.0.0.0 ad.yieldmanager.com +0.0.0.0 adz.afterdawn.net +0.0.0.0 ad.zanox.com +0.0.0.0 adzerk.net +0.0.0.0 ad.zodera.hu +0.0.0.0 adzone.ro +0.0.0.0 adzone.stltoday.com +0.0.0.0 adzservice.theday.com +0.0.0.0 ae.goodsblock.marketgid.com +0.0.0.0 afe2.specificclick.net +0.0.0.0 afe.specificclick.net +0.0.0.0 aff.foxtab.com +0.0.0.0 affiliate.a4dtracker.com +0.0.0.0 affiliate.aol.com +0.0.0.0 affiliate.baazee.com +0.0.0.0 affiliate.cfdebt.com +0.0.0.0 affiliate.exabytes.com.my +0.0.0.0 affiliate-fr.com +0.0.0.0 affiliate.fr.espotting.com +0.0.0.0 affiliate.googleusercontent.com +0.0.0.0 affiliate.hbytracker.com +0.0.0.0 affiliate.mlntracker.com +0.0.0.0 affiliates.arvixe.com +0.0.0.0 affiliates.eblastengine.com +0.0.0.0 affiliates.genealogybank.com +0.0.0.0 affiliates.globat.com +0.0.0.0 affiliation-france.com +0.0.0.0 affimg.pop6.com +0.0.0.0 afform.co.uk +0.0.0.0 affpartners.com +0.0.0.0 aff.ringtonepartner.com +0.0.0.0 afi.adocean.pl +0.0.0.0 afilo.pl +0.0.0.0 agkn.com +0.0.0.0 aj.600z.com +0.0.0.0 ajcclassifieds.com +0.0.0.0 akaads-espn.starwave.com +0.0.0.0 aka-cdn.adtechus.com +0.0.0.0 aka-cdn-ns.adtech.de +0.0.0.0 aka-cdn-ns.adtechus.com +0.0.0.0 akamai.invitemedia.com +0.0.0.0 ak.buyservices.com +0.0.0.0 a.kerg.net +0.0.0.0 ak.maxserving.com +0.0.0.0 ako.cc +0.0.0.0 ak.p.openx.net +0.0.0.0 al1.sharethis.com +0.0.0.0 alert.police-patrol-agent.com +0.0.0.0 a.ligatus.com +0.0.0.0 a.ligatus.de +0.0.0.0 alliance.adbureau.net +0.0.0.0 all.orfr.adgtw.orangeads.fr +0.0.0.0 altfarm.mediaplex.com +0.0.0.0 amch.questionmarket.com +0.0.0.0 americansingles.click-url.com +0.0.0.0 a.mktw.net +0.0.0.0 amscdn.btrll.com +0.0.0.0 analysis.fc2.com +0.0.0.0 analytics.kwebsoft.com +0.0.0.0 analytics.percentmobile.com +0.0.0.0 analyzer51.fc2.com +0.0.0.0 ankieta-online.pl +0.0.0.0 annuaire-autosurf.com +0.0.0.0 anrtx.tacoda.net +0.0.0.0 answers.us.intellitxt.com +0.0.0.0 an.tacoda.net +0.0.0.0 an.yandex.ru +0.0.0.0 apex-ad.com +0.0.0.0 api.addthis.com +0.0.0.0 api.affinesystems.com +0.0.0.0 api-public.addthis.com +0.0.0.0 apopt.hbmediapro.com +0.0.0.0 apparelncs.com +0.0.0.0 apparel-offer.com +0.0.0.0 appdev.addthis.com +0.0.0.0 appnexus.com +0.0.0.0 apps5.oingo.com +0.0.0.0 app.scanscout.com +0.0.0.0 ap.read.mediation.pns.ap.orangeads.fr +0.0.0.0 a.prisacom.com +0.0.0.0 apx.moatads.com +0.0.0.0 a.rad.live.com +0.0.0.0 a.rad.msn.com +0.0.0.0 arbomedia.pl +0.0.0.0 arbopl.bbelements.com +0.0.0.0 arsconsole.global-intermedia.com +0.0.0.0 art-music-rewardpath.com +0.0.0.0 art-offer.com +0.0.0.0 art-offer.net +0.0.0.0 art-photo-music-premiumblvd.com +0.0.0.0 art-photo-music-rewardempire.com +0.0.0.0 art-photo-music-savingblvd.com +0.0.0.0 as1.falkag.de +0.0.0.0 as1image1.adshuffle.com +0.0.0.0 as1image2.adshuffle.com +0.0.0.0 as1.inoventiv.com +0.0.0.0 as2.falkag.de +0.0.0.0 as3.falkag.de +0.0.0.0 as4.falkag.de +0.0.0.0 as.5to1.com +0.0.0.0 asa.tynt.com +0.0.0.0 asb.tynt.com +0.0.0.0 as.casalemedia.com +0.0.0.0 as.ebz.io +0.0.0.0 asg01.casalemedia.com +0.0.0.0 asg02.casalemedia.com +0.0.0.0 asg03.casalemedia.com +0.0.0.0 asg04.casalemedia.com +0.0.0.0 asg05.casalemedia.com +0.0.0.0 asg06.casalemedia.com +0.0.0.0 asg07.casalemedia.com +0.0.0.0 asg08.casalemedia.com +0.0.0.0 asg09.casalemedia.com +0.0.0.0 asg10.casalemedia.com +0.0.0.0 asg11.casalemedia.com +0.0.0.0 asg12.casalemedia.com +0.0.0.0 asg13.casalemedia.com +0.0.0.0 ask-gps.ru +0.0.0.0 asklots.com +0.0.0.0 askmen.thruport.com +0.0.0.0 asm2.z1.adserver.com +0.0.0.0 asm3.z1.adserver.com +0.0.0.0 asn.advolution.de +0.0.0.0 asn.cunda.advolution.biz +0.0.0.0 a.ss34.on9mail.com +0.0.0.0 assets.igapi.com +0.0.0.0 assets.kixer.com +0.0.0.0 assets.percentmobile.com +0.0.0.0 as.sexad.net +0.0.0.0 asv.nuggad.net +0.0.0.0 as.vs4entertainment.com +0.0.0.0 as.webmd.com +0.0.0.0 a.tadd.react2media.com +0.0.0.0 at-adserver.alltop.com +0.0.0.0 at.campaigns.f2.com.au +0.0.0.0 at.ceofreehost.com +0.0.0.0 atdmt.com +0.0.0.0 atemda.com +0.0.0.0 athena-ads.wikia.com +0.0.0.0 at.m1.nedstatbasic.net +0.0.0.0 a.total-media.net +0.0.0.0 a.tribalfusion.com +0.0.0.0 a.triggit.com +0.0.0.0 au.adserver.yahoo.com +0.0.0.0 au.ads.link4ads.com +0.0.0.0 aud.pubmatic.com +0.0.0.0 aureate.com +0.0.0.0 auslieferung.commindo-media-ressourcen.de +0.0.0.0 austria1.adverserve.net +0.0.0.0 autocontext.begun.ru +0.0.0.0 automotive-offer.com +0.0.0.0 automotive-rewardpath.com +0.0.0.0 avcounter10.com +0.0.0.0 avpa.dzone.com +0.0.0.0 avpa.javalobby.org +0.0.0.0 a.websponsors.com +0.0.0.0 awesomevipoffers.com +0.0.0.0 awrz.net +0.0.0.0 axp.zedo.com +0.0.0.0 azcentra.app.ur.gcion.com +0.0.0.0 azoogleads.com +0.0.0.0 b1.adbrite.com +0.0.0.0 b1.azjmp.com +0.0.0.0 b2b.filecloud.me +0.0.0.0 babycenter.tt.omtrdc.net +0.0.0.0 b.ads2.msn.com +0.0.0.0 badservant.guj.de +0.0.0.0 b.am15.net +0.0.0.0 bananacashback.com +0.0.0.0 banery.acr.pl +0.0.0.0 banery.netart.pl +0.0.0.0 banery.onet.pl +0.0.0.0 banki.onet.pl +0.0.0.0 bankofamerica.tt.omtrdc.net +0.0.0.0 banman.nepsecure.co.uk +0.0.0.0 banner.1and1.co.uk +0.0.0.0 banner1.pornhost.com +0.0.0.0 banner2.inet-traffic.com +0.0.0.0 bannerads.anytimenews.com +0.0.0.0 bannerads.de +0.0.0.0 bannerads.zwire.com +0.0.0.0 banner.affactive.com +0.0.0.0 banner.betroyalaffiliates.com +0.0.0.0 banner.betwwts.com +0.0.0.0 banner.cdpoker.com +0.0.0.0 banner.clubdicecasino.com +0.0.0.0 bannerconnect.net +0.0.0.0 banner.coza.com +0.0.0.0 banner.diamondclubcasino.com +0.0.0.0 bannerdriven.ru +0.0.0.0 banner.easyspace.com +0.0.0.0 bannerfarm.ace.advertising.com +0.0.0.0 banner.free6.com # www.free6.com +0.0.0.0 bannerhost.egamingonline.com +0.0.0.0 bannerimages.0catch.com +0.0.0.0 banner.joylandcasino.com +0.0.0.0 banner.media-system.de +0.0.0.0 banner.monacogoldcasino.com +0.0.0.0 banner.newyorkcasino.com +0.0.0.0 banner.northsky.com +0.0.0.0 banner.oddcast.com +0.0.0.0 banner.orb.net +0.0.0.0 banner.piratos.de +0.0.0.0 banner.playgatecasino.com +0.0.0.0 bannerpower.com +0.0.0.0 banner.prestigecasino.com +0.0.0.0 banner.publisher.to +0.0.0.0 banner.rbc.ru +0.0.0.0 banner.relcom.ru +0.0.0.0 banners1.linkbuddies.com +0.0.0.0 banners2.castles.org +0.0.0.0 banners3.spacash.com +0.0.0.0 banners.adgoto.com +0.0.0.0 banners.adultfriendfinder.com +0.0.0.0 banners.affiliatefuel.com +0.0.0.0 banners.affiliatefuture.com +0.0.0.0 banners.aftrk.com +0.0.0.0 banners.audioholics.com +0.0.0.0 banners.blogads.com +0.0.0.0 banners.bol.se +0.0.0.0 banners.broadwayworld.com +0.0.0.0 banners.celebritybling.com +0.0.0.0 banners.crisscross.com +0.0.0.0 banners.directnic.com +0.0.0.0 banners.dnastudio.com +0.0.0.0 banners.easydns.com +0.0.0.0 banners.easysolutions.be +0.0.0.0 banners.ebay.com +0.0.0.0 banners.expressindia.com +0.0.0.0 banners.flair.be +0.0.0.0 banners.free6.com # www.free6.com +0.0.0.0 banners.fuifbeest.be +0.0.0.0 banners.globovision.com +0.0.0.0 banners.img.uol.com.br +0.0.0.0 banners.ims.nl +0.0.0.0 banners.iop.org +0.0.0.0 banners.ipotd.com +0.0.0.0 banners.japantoday.com +0.0.0.0 banners.kfmb.com +0.0.0.0 banners.ksl.com +0.0.0.0 banners.linkbuddies.com +0.0.0.0 banners.looksmart.com +0.0.0.0 banners.nbcupromotes.com +0.0.0.0 banners.netcraft.com +0.0.0.0 banners.newsru.com +0.0.0.0 banners.nextcard.com +0.0.0.0 banners.passion.com +0.0.0.0 banners.pennyweb.com +0.0.0.0 banners.primaryclick.com +0.0.0.0 banners.resultonline.com +0.0.0.0 banners.rspworldwide.com +0.0.0.0 banners.sextracker.com +0.0.0.0 banners.spiceworks.com +0.0.0.0 banners.thegridwebmaster.com +0.0.0.0 banners.thestranger.com +0.0.0.0 banners.thgimages.co.uk +0.0.0.0 banners.tribute.ca +0.0.0.0 banners.tucson.com +0.0.0.0 banners.unibet.com +0.0.0.0 bannersurvey.biz +0.0.0.0 banners.valuead.com +0.0.0.0 banners.videosecrets.com +0.0.0.0 banners.webmasterplan.com +0.0.0.0 banners.wunderground.com +0.0.0.0 banners.zbs.ru +0.0.0.0 banner.tattomedia.com +0.0.0.0 banner.techarp.com +0.0.0.0 bannert.ru +0.0.0.0 bannerus1.axelsfun.com +0.0.0.0 bannerus3.axelsfun.com +0.0.0.0 banner.usacasino.com +0.0.0.0 banniere.reussissonsensemble.fr +0.0.0.0 bans.bride.ru +0.0.0.0 banstex.com +0.0.0.0 bansys.onzin.com +0.0.0.0 bargainbeautybuys.com +0.0.0.0 barnesandnoble.bfast.com +0.0.0.0 b.as-us.falkag.net +0.0.0.0 bayoubuzz.advertserve.com +0.0.0.0 bbcdn.go.adlt.bbelements.com +0.0.0.0 bbcdn.go.adnet.bbelements.com +0.0.0.0 bbcdn.go.arbo.bbelements.com +0.0.0.0 bbcdn.go.eu.bbelements.com +0.0.0.0 bbcdn.go.ihned.bbelements.com +0.0.0.0 bbcdn.go.pl.bbelements.com +0.0.0.0 bb.crwdcntrl.net +0.0.0.0 bbnaut.bbelements.com +0.0.0.0 bc685d37-266c-488e-824e-dd95d1c0e98b.statcamp.net +0.0.0.0 bcp.crwdcntrl.net +0.0.0.0 bdnad1.bangornews.com +0.0.0.0 bdv.bidvertiser.com +0.0.0.0 beacon-3.newrelic.com +0.0.0.0 beacons.helium.com +0.0.0.0 bell.adcentriconline.com +0.0.0.0 beseenad.looksmart.com +0.0.0.0 bestgift4you.cn +0.0.0.0 bestshopperrewards.com +0.0.0.0 beta.hotkeys.com +0.0.0.0 bet-at-home.com +0.0.0.0 betterperformance.goldenopps.info +0.0.0.0 bfast.com +0.0.0.0 bidclix.net +0.0.0.0 bid.openx.net +0.0.0.0 bidsystem.com +0.0.0.0 bidtraffic.com +0.0.0.0 bidvertiser.com +0.0.0.0 bigads.guj.de +0.0.0.0 bigbrandpromotions.com +0.0.0.0 bigbrandrewards.com +0.0.0.0 biggestgiftrewards.com +0.0.0.0 billing.speedboink.com +0.0.0.0 bitburg.adtech.de +0.0.0.0 bitburg.adtech.fr +0.0.0.0 bitburg.adtech.us +0.0.0.0 bitcast-d.bitgravity.com +0.0.0.0 bizad.nikkeibp.co.jp +0.0.0.0 biz-offer.com +0.0.0.0 bizopprewards.com +0.0.0.0 blabla4u.adserver.co.il +0.0.0.0 blasphemysfhs.info +0.0.0.0 blatant8jh.info +0.0.0.0 b.liquidustv.com +0.0.0.0 blog.addthis.com +0.0.0.0 blogads.com +0.0.0.0 blogads.ebanner.nl +0.0.0.0 blogvertising.pl +0.0.0.0 bluediamondoffers.com +0.0.0.0 blu.mobileads.msn.com +0.0.0.0 bl.wavecdn.de +0.0.0.0 b.myspace.com +0.0.0.0 bn.bfast.com +0.0.0.0 bnmgr.adinjector.net +0.0.0.0 bnrs.ilm.ee +0.0.0.0 boksy.dir.onet.pl +0.0.0.0 boksy.onet.pl +0.0.0.0 bookclub-offer.com +0.0.0.0 books-media-edu-premiumblvd.com +0.0.0.0 books-media-edu-rewardempire.com +0.0.0.0 books-media-rewardpath.com +0.0.0.0 bostonsubwayoffer.com +0.0.0.0 bp.specificclick.net +0.0.0.0 b.rad.live.com +0.0.0.0 b.rad.msn.com +0.0.0.0 br.adserver.yahoo.com +0.0.0.0 brandrewardcentral.com +0.0.0.0 brandsurveypanel.com +0.0.0.0 bravo.israelinfo.ru +0.0.0.0 bravospots.com +0.0.0.0 br.naked.com +0.0.0.0 broadcast.piximedia.fr +0.0.0.0 broadent.vo.llnwd.net +0.0.0.0 brokertraffic.com +0.0.0.0 bsads.looksmart.com +#0.0.0.0 b.scorecardresearch.com # interferes with Huffington Post slideshows +0.0.0.0 bs.israelinfo.ru +0.0.0.0 bs.serving-sys.com #eyeblaster.com +0.0.0.0 bt.linkpulse.com +0.0.0.0 burns.adtech.de +0.0.0.0 burns.adtech.fr +0.0.0.0 burns.adtech.us +0.0.0.0 business-rewardpath.com +0.0.0.0 bus-offer.com +0.0.0.0 buttcandy.com +0.0.0.0 buttons.googlesyndication.com +0.0.0.0 buzzbox.buzzfeed.com +0.0.0.0 bwp.lastfm.com.com +0.0.0.0 bwp.news.com +0.0.0.0 c1.popads.net +0.0.0.0 c1.teaser-goods.ru +0.0.0.0 c1.zedo.com +0.0.0.0 c2.zedo.com +0.0.0.0 c3.zedo.com +0.0.0.0 c4.maxserving.com +0.0.0.0 c4.zedo.com +0.0.0.0 c5.zedo.com +0.0.0.0 c6.zedo.com +0.0.0.0 c7.zedo.com +0.0.0.0 c8.zedo.com +0.0.0.0 ca.adserver.yahoo.com +0.0.0.0 cache.addthiscdn.com +0.0.0.0 cache.addthis.com +0.0.0.0 cache.blogads.com +0.0.0.0 cache-dev.addthis.com +0.0.0.0 cacheserve.eurogrand.com +0.0.0.0 cacheserve.prestigecasino.com +0.0.0.0 cache.unicast.com +0.0.0.0 c.actiondesk.com +0.0.0.0 c.adroll.com +0.0.0.0 califia.imaginemedia.com +0.0.0.0 c.am10.ru +0.0.0.0 camgeil.com +0.0.0.0 campaign.iitech.dk +0.0.0.0 campaign.indieclick.com +0.0.0.0 campaigns.f2.com.au +0.0.0.0 campaigns.interclick.com +0.0.0.0 capath.com +0.0.0.0 cardgamespidersolitaire.com +0.0.0.0 cards.virtuagirlhd.com +0.0.0.0 careers.canwestad.net +0.0.0.0 careers-rewardpath.com +0.0.0.0 c.ar.msn.com +0.0.0.0 carrier.bz +0.0.0.0 car-truck-boat-bonuspath.com +0.0.0.0 car-truck-boat-premiumblvd.com +0.0.0.0 casalemedia.com +0.0.0.0 cas.clickability.com +0.0.0.0 cashback.co.uk +0.0.0.0 cashbackwow.co.uk +0.0.0.0 cashflowmarketing.com +0.0.0.0 casino770.com +0.0.0.0 c.as-us.falkag.net +0.0.0.0 catalinkcashback.com +0.0.0.0 catchvid.info +0.0.0.0 c.at.msn.com +0.0.0.0 cbanners.virtuagirlhd.com +0.0.0.0 c.be.msn.com +0.0.0.0 c.blogads.com +0.0.0.0 c.br.msn.com +0.0.0.0 c.ca.msn.com +0.0.0.0 c.casalemedia.com +0.0.0.0 ccas.clearchannel.com +0.0.0.0 c.cl.msn.com +0.0.0.0 c.de.msn.com +0.0.0.0 c.dk.msn.com +0.0.0.0 cdn1.adexprt.com +0.0.0.0 cdn1.ads.mofos.com +0.0.0.0 cdn1.eyewonder.com +0.0.0.0 cdn1.rmgserving.com +0.0.0.0 cdn1.traffichaus.com +0.0.0.0 cdn1.xlightmedia.com +0.0.0.0 cdn2.adsdk.com +0.0.0.0 cdn2.amateurmatch.com +0.0.0.0 cdn2.emediate.eu +0.0.0.0 cdn3.adexprts.com +0.0.0.0 cdn3.telemetryverification.net +0.0.0.0 cdn454.telemetryverification.net +0.0.0.0 cdn5.tribalfusion.com +0.0.0.0 cdn6.emediate.eu +0.0.0.0 cdn.adigniter.org +0.0.0.0 cdn.adnxs.com +0.0.0.0 cdnads.cam4.com +0.0.0.0 cdn.ads.ookla.com +0.0.0.0 cdn.amateurmatch.com +0.0.0.0 cdn.amgdgt.com +0.0.0.0 cdn.assets.craveonline.com +0.0.0.0 cdn.banners.scubl.com +0.0.0.0 cdn.cpmstar.com +0.0.0.0 cdn.crowdignite.com +0.0.0.0 cdn.directrev.com +0.0.0.0 cdn.eyewonder.com +0.0.0.0 cdn.go.arbo.bbelements.com +0.0.0.0 cdn.go.arbopl.bbelements.com +0.0.0.0 cdn.go.cz.bbelements.com +0.0.0.0 cdn.go.idmnet.bbelements.com +0.0.0.0 cdn.go.pol.bbelements.com +0.0.0.0 cdn.hadj7.adjuggler.net +0.0.0.0 cdn.innovid.com +0.0.0.0 cdn.krxd.net +0.0.0.0 cdn.mediative.ca +0.0.0.0 cdn.merchenta.com +0.0.0.0 cdn.mobicow.com +0.0.0.0 cdn.nearbyad.com +0.0.0.0 cdn.nsimg.net +0.0.0.0 cdn.onescreen.net +#0.0.0.0 cdns.gigya.com +0.0.0.0 cdns.mydirtyhobby.com +0.0.0.0 cdns.privatamateure.com +0.0.0.0 cdn.stat.easydate.biz +0.0.0.0 cdn.syn.verticalacuity.com +0.0.0.0 cdn.tabnak.ir +0.0.0.0 cdnt.yottos.com +0.0.0.0 cdn.udmserve.net +0.0.0.0 cdn.undertone.com +0.0.0.0 cdn.wg.uproxx.com +0.0.0.0 cdnw.ringtonepartner.com +0.0.0.0 cdn.yottos.com +0.0.0.0 cdn.zeusclicks.com +0.0.0.0 cds.adecn.com +0.0.0.0 cecash.com +0.0.0.0 ced.sascdn.com +0.0.0.0 cell-phone-giveaways.com +0.0.0.0 cellphoneincentives.com +0.0.0.0 cent.adbureau.net +0.0.0.0 c.es.msn.com +0.0.0.0 c.fi.msn.com +0.0.0.0 cf.kampyle.com +0.0.0.0 c.fr.msn.com +0.0.0.0 cgirm.greatfallstribune.com +0.0.0.0 cgm.adbureau.ne +0.0.0.0 cgm.adbureau.net +0.0.0.0 c.gr.msn.com +0.0.0.0 chainsawoffer.com +0.0.0.0 chartbeat.com +0.0.0.0 checkintocash.data.7bpeople.com +0.0.0.0 cherryhi.app.ur.gcion.com +0.0.0.0 c.hk.msn.com +0.0.0.0 chkpt.zdnet.com +0.0.0.0 choicedealz.com +0.0.0.0 choicesurveypanel.com +0.0.0.0 christianbusinessadvertising.com +0.0.0.0 c.id.msn.com +0.0.0.0 c.ie.msn.com +0.0.0.0 c.il.msn.com +0.0.0.0 c.imedia.cz +0.0.0.0 c.in.msn.com +0.0.0.0 cithingy.info +0.0.0.0 citi.bridgetrack.com +0.0.0.0 c.it.msn.com +0.0.0.0 citrix.market2lead.com +0.0.0.0 cityads.telus.net +0.0.0.0 citycash2.blogspot.com +0.0.0.0 c.jp.msn.com +0.0.0.0 cl21.v4.adaction.se +0.0.0.0 cl320.v4.adaction.se +0.0.0.0 claimfreerewards.com +0.0.0.0 clashmediausa.com +0.0.0.0 classicjack.com +0.0.0.0 c.latam.msn.com +0.0.0.0 click1.mainadv.com +0.0.0.0 click1.rbc.magna.ru +0.0.0.0 click2.rbc.magna.ru +0.0.0.0 click3.rbc.magna.ru +0.0.0.0 click4.rbc.magna.ru +0.0.0.0 clickad.eo.pl +0.0.0.0 clickarrows.com +0.0.0.0 click.avenuea.com +0.0.0.0 clickbangpop.com +0.0.0.0 clickcash.webpower.com +0.0.0.0 click.go2net.com +0.0.0.0 click.israelinfo.ru +0.0.0.0 clickit.go2net.com +0.0.0.0 clickmedia.ro +0.0.0.0 click.pulse360.com +0.0.0.0 clicks2.virtuagirl.com +0.0.0.0 clicks.adultplex.com +0.0.0.0 clicks.deskbabes.com +0.0.0.0 click-see-save.com +0.0.0.0 clicksor.com +0.0.0.0 clicksotrk.com +0.0.0.0 clicks.totemcash.com +0.0.0.0 clicks.toteme.com +0.0.0.0 clicks.virtuagirl.com +0.0.0.0 clicks.virtuagirlhd.com +0.0.0.0 clicks.virtuaguyhd.com +0.0.0.0 clicks.walla.co.il +0.0.0.0 clickthru.net +0.0.0.0 clickthrunet.net +0.0.0.0 clickthruserver.com +0.0.0.0 clickthrutraffic.com +0.0.0.0 clicktorrent.info +0.0.0.0 clipserv.adclip.com +0.0.0.0 clkads.com +0.0.0.0 clk.cloudyisland.com +0.0.0.0 clk.tradedoubler.com +0.0.0.0 clkuk.tradedoubler.com +0.0.0.0 c.lomadee.com +0.0.0.0 closeoutproductsreview.com +0.0.0.0 cluster3.adultadworld.com +0.0.0.0 cluster.adultadworld.com +0.0.0.0 cm1359.com +0.0.0.0 cmads.sv.publicus.com +0.0.0.0 cmads.us.publicus.com +0.0.0.0 cmap.am.ace.advertising.com +0.0.0.0 cmap.an.ace.advertising.com +0.0.0.0 cmap.at.ace.advertising.com +0.0.0.0 cmap.dc.ace.advertising.com +0.0.0.0 cmap.ox.ace.advertising.com +0.0.0.0 cmap.pub.ace.advertising.com +0.0.0.0 cmap.rm.ace.advertising.com +0.0.0.0 cmap.rub.ace.advertising.com +0.0.0.0 cmhtml.overture.com +0.0.0.0 cmn1lsm2.beliefnet.com +0.0.0.0 cm.npc-hearst.overture.com +0.0.0.0 cmps.mt50ad.com +0.0.0.0 cm.the-n.overture.com +0.0.0.0 c.my.msn.com +0.0.0.0 cnad1.economicoutlook.net +0.0.0.0 cnad2.economicoutlook.net +0.0.0.0 cnad3.economicoutlook.net +0.0.0.0 cnad4.economicoutlook.net +0.0.0.0 cnad5.economicoutlook.net +0.0.0.0 cnad6.economicoutlook.net +0.0.0.0 cnad7.economicoutlook.net +0.0.0.0 cnad8.economicoutlook.net +0.0.0.0 cnad9.economicoutlook.net +0.0.0.0 cnad.economicoutlook.net +0.0.0.0 cn.adserver.yahoo.com +0.0.0.0 cnf.adshuffle.com +0.0.0.0 c.ninemsn.com.au +0.0.0.0 c.nl.msn.com +0.0.0.0 c.no.msn.com +0.0.0.0 c.novostimira.biz +0.0.0.0 cnt1.xhamster.com +0.0.0.0 code2.adtlgc.com +0.0.0.0 code.adtlgc.com +0.0.0.0 collectiveads.net +0.0.0.0 col.mobileads.msn.com +0.0.0.0 comadverts.bcmpweb.co.nz +0.0.0.0 comcastresidentialservices.tt.omtrdc.net +0.0.0.0 com.cool-premiums-now.com +0.0.0.0 come-see-it-all.com +0.0.0.0 com.htmlwww.youfck.com +0.0.0.0 commerce-offer.com +0.0.0.0 commerce-rewardpath.com +0.0.0.0 commerce.www.ibm.com +0.0.0.0 common.ziffdavisinternet.com +0.0.0.0 companion.adap.tv +0.0.0.0 computer-offer.com +0.0.0.0 computer-offer.net +0.0.0.0 computers-electronics-rewardpath.com +0.0.0.0 computersncs.com +0.0.0.0 com.shc-rebates.com +0.0.0.0 connect.247media.ads.link4ads.com +0.0.0.0 consumergiftcenter.com +0.0.0.0 consumerincentivenetwork.com +0.0.0.0 consumerinfo.tt.omtrdc.net +0.0.0.0 consumer-org.com +0.0.0.0 contaxe.com +0.0.0.0 content.ad-flow.com +0.0.0.0 content.clipster.ws +0.0.0.0 content.codelnet.com +0.0.0.0 content.promoisland.net +0.0.0.0 contentsearch.de.espotting.com +0.0.0.0 content.yieldmanager.edgesuite.net +0.0.0.0 context3.kanoodle.com +0.0.0.0 context5.kanoodle.com +0.0.0.0 context.adshadow.net +0.0.0.0 contextweb.com +0.0.0.0 conv.adengage.com +0.0.0.0 conversion-pixel.invitemedia.com +0.0.0.0 cookiecontainer.blox.pl +0.0.0.0 cookie.pebblemedia.be +0.0.0.0 cookingtiprewards.com +0.0.0.0 cookonsea.com +0.0.0.0 cool-premiums.com +0.0.0.0 cool-premiums-now.com +0.0.0.0 coolpremiumsnow.com +0.0.0.0 coolsavings.com +0.0.0.0 corba.adtech.de +0.0.0.0 corba.adtech.fr +0.0.0.0 corba.adtech.us +0.0.0.0 core0.node12.top.mail.ru +0.0.0.0 core2.adtlgc.com +0.0.0.0 coreg.flashtrack.net +0.0.0.0 coreglead.co.uk +0.0.0.0 core.insightexpressai.com +0.0.0.0 core.videoegg.com +0.0.0.0 cornflakes.pathfinder.com +0.0.0.0 corusads.dserv.ca +0.0.0.0 cosmeticscentre.uk.com +0.0.0.0 count6.51yes.com +0.0.0.0 count.casino-trade.com +0.0.0.0 cover.m2y.siemens.ch +0.0.0.0 c.ph.msn.com +0.0.0.0 cpmadvisors.com +0.0.0.0 cp.promoisland.net +0.0.0.0 c.prodigy.msn.com +0.0.0.0 c.pt.msn.com +0.0.0.0 cpu.firingsquad.com +0.0.0.0 creatiby1.unicast.com +0.0.0.0 creative.adshuffle.com +0.0.0.0 creative.ak.facebook.com +0.0.0.0 creatives.livejasmin.com +0.0.0.0 creatives.rgadvert.com +0.0.0.0 creatrixads.com +0.0.0.0 crediblegfj.info +0.0.0.0 creditburner.blueadvertise.com +0.0.0.0 creditsoffer.blogspot.com +0.0.0.0 creview.adbureau.net +0.0.0.0 crosspixel.demdex.net +0.0.0.0 crowdgravity.com +0.0.0.0 crowdignite.com +0.0.0.0 c.ru.msn.com +0.0.0.0 crux.songline.com +0.0.0.0 crwdcntrl.net +0.0.0.0 c.se.msn.com +0.0.0.0 cserver.mii.instacontent.net +0.0.0.0 c.sg.msn.com +0.0.0.0 csh.actiondesk.com +0.0.0.0 csm.rotator.hadj7.adjuggler.net +0.0.0.0 cspix.media6degrees.com +0.0.0.0 cs.prd.msys.playstation.net +0.0.0.0 csr.onet.pl +0.0.0.0 ctbdev.net +0.0.0.0 c.th.msn.com +0.0.0.0 c.tr.msn.com +0.0.0.0 cts.channelintelligence.com +0.0.0.0 c.tw.msn.com +0.0.0.0 ctxtad.tribalfusion.com +0.0.0.0 c.uk.msn.com +0.0.0.0 cxoadfarm.dyndns.info +0.0.0.0 cxtad.specificmedia.com +0.0.0.0 cyber-incentives.com +0.0.0.0 cz8.clickzs.com +0.0.0.0 c.za.msn.com +0.0.0.0 cz.bbelements.com +0.0.0.0 d.101m3.com +0.0.0.0 d10.zedo.com +0.0.0.0 d11.zedo.com +0.0.0.0 d12.zedo.com +0.0.0.0 d14.zedo.com +0.0.0.0 d1.openx.org +0.0.0.0 d1ros97qkrwjf5.cloudfront.net +0.0.0.0 d1.zedo.com +0.0.0.0 d2.zedo.com +0.0.0.0 d3.zedo.com +0.0.0.0 d4.zedo.com +0.0.0.0 d5phz18u4wuww.cloudfront.net +0.0.0.0 d5.zedo.com +0.0.0.0 d6.c5.b0.a2.top.mail.ru +0.0.0.0 d6.zedo.com +0.0.0.0 d7.zedo.com +0.0.0.0 d8.zedo.com +0.0.0.0 d9.zedo.com +0.0.0.0 da.2000888.com +0.0.0.0 d.adnetxchange.com +0.0.0.0 d.adserve.com +0.0.0.0 dads.new.digg.com +0.0.0.0 d.ads.readwriteweb.com +0.0.0.0 d.agkn.com +0.0.0.0 daily-saver.com +0.0.0.0 darmowe-liczniki.info +0.0.0.0 dart.chron.com +0.0.0.0 data.flurry.com +0.0.0.0 date.ventivmedia.com +0.0.0.0 datingadvertising.com +0.0.0.0 db4.net-filter.com +0.0.0.0 dbbsrv.com +0.0.0.0 dc.sabela.com.pl +0.0.0.0 dctracking.com +0.0.0.0 de.adserver.yahoo.com +0.0.0.0 del1.phillyburbs.com +0.0.0.0 delb.mspaceads.com +0.0.0.0 delivery.adyea.com +0.0.0.0 delivery.trafficjunky.net +0.0.0.0 delivery.w00tads.com +0.0.0.0 delivery.way2traffic.com +0.0.0.0 demr.mspaceads.com +0.0.0.0 demr.opt.fimserve.com +0.0.0.0 derkeiler.com +0.0.0.0 desb.mspaceads.com +0.0.0.0 descargas2.tuvideogratis.com +0.0.0.0 designbloxlive.com +0.0.0.0 desk.mspaceads.com +0.0.0.0 desk.opt.fimserve.com +0.0.0.0 dev.adforum.com +0.0.0.0 devart.adbureau.net +0.0.0.0 devlp1.linkpulse.com +0.0.0.0 dev.sfbg.com +0.0.0.0 dgm2.com +0.0.0.0 dgmaustralia.com +0.0.0.0 dg.specificclick.net +0.0.0.0 dietoftoday.ca.pn #security risk/fake news# +0.0.0.0 diff3.smartadserver.com +0.0.0.0 dinoadserver1.roka.net +0.0.0.0 dinoadserver2.roka.net +0.0.0.0 directleads.com +0.0.0.0 directpowerrewards.com +0.0.0.0 directrev.cloudapp.net +0.0.0.0 dirtyrhino.com +0.0.0.0 discount-savings-more.com +0.0.0.0 discoverecommerce.tt.omtrdc.net +0.0.0.0 display.gestionpub.com +0.0.0.0 dist.belnk.com +0.0.0.0 divx.adbureau.net +0.0.0.0 djbanners.deadjournal.com +0.0.0.0 djugoogs.com +0.0.0.0 dk.adserver.yahoo.com +0.0.0.0 dl.ncbuy.com +0.0.0.0 dl-plugin.com +0.0.0.0 dlvr.readserver.net +0.0.0.0 dnads.directnic.com +0.0.0.0 dnps.com +0.0.0.0 dnse.linkpulse.com +0.0.0.0 dosugcz.biz +0.0.0.0 dot.wp.pl +0.0.0.0 downloadcdn.com +0.0.0.0 do-wn-lo-ad.com +0.0.0.0 downloads.larivieracasino.com +0.0.0.0 downloads.mytvandmovies.com +0.0.0.0 dqs001.adtech.de +0.0.0.0 dqs001.adtech.fr +0.0.0.0 dqs001.adtech.us +0.0.0.0 dra.amazon-adsystem.com +0.0.0.0 drowle.com +0.0.0.0 ds.contextweb.com +0.0.0.0 ds.onet.pl +0.0.0.0 ds.serving-sys.com +0.0.0.0 dt.linkpulse.com +0.0.0.0 dub.mobileads.msn.com +0.0.0.0 e0.extreme-dm.com +0.0.0.0 e1.addthis.com +0.0.0.0 e2.cdn.qnsr.com +0.0.0.0 e2.emediate.se +0.0.0.0 eads-adserving.com +0.0.0.0 ead.sharethis.com +0.0.0.0 earnmygift.com +0.0.0.0 earnpointsandgifts.com +0.0.0.0 e.as-eu.falkag.net +0.0.0.0 easyadservice.com +0.0.0.0 easyweb.tdcanadatrust.secureserver.host1.customer-identification-process.b88600d8.com +0.0.0.0 eatps.web.aol.com +0.0.0.0 eb.adbureau.net +0.0.0.0 eblastengine.upickem.net +0.0.0.0 ecomadserver.com +0.0.0.0 eddamedia.linkpulse.com +0.0.0.0 edge.bnmla.com +0.0.0.0 edge.quantserve.com +0.0.0.0 edirect.hotkeys.com +0.0.0.0 education-rewardpath.com +0.0.0.0 edu-offer.com +0.0.0.0 electronics-bonuspath.com +0.0.0.0 electronics-offer.net +0.0.0.0 electronicspresent.com +0.0.0.0 electronics-rewardpath.com +0.0.0.0 emailadvantagegroup.com +0.0.0.0 emailproductreview.com +0.0.0.0 emapadserver.com +0.0.0.0 emea-bidder.mathtag.com +0.0.0.0 engage.everyone.net +0.0.0.0 engage.speedera.net +0.0.0.0 engine2.adzerk.net +0.0.0.0 engine.4chan-ads.org +0.0.0.0 engine.adland.ru +0.0.0.0 engine.adzerk.net +0.0.0.0 engine.carbonads.com +0.0.0.0 engine.espace.netavenir.com +0.0.0.0 engine.influads.com +0.0.0.0 engine.rorer.ru +0.0.0.0 enirocode.adtlgc.com +0.0.0.0 enirodk.adtlgc.com +0.0.0.0 enn.advertserve.com +0.0.0.0 entertainment-rewardpath.com +0.0.0.0 entertainment-specials.com +0.0.0.0 es.adserver.yahoo.com +0.0.0.0 escape.insites.eu +0.0.0.0 espn.footprint.net +0.0.0.0 etad.telegraph.co.uk +0.0.0.0 etrk.asus.com +0.0.0.0 etype.adbureau.net +0.0.0.0 eu2.madsone.com +0.0.0.0 euniverseads.com +0.0.0.0 eu-pn4.adserver.yahoo.com +0.0.0.0 europe.adserver.yahoo.com +0.0.0.0 eu.xtms.net +0.0.0.0 eventtracker.videostrip.com +0.0.0.0 exclusivegiftcards.com +0.0.0.0 exits1.webquest.net +0.0.0.0 exits2.webquest.net +0.0.0.0 exponential.com +0.0.0.0 eyewonder.com +0.0.0.0 ezboard.bigbangmedia.com +0.0.0.0 falkag.net +0.0.0.0 family-offer.com +0.0.0.0 farm.plista.com +0.0.0.0 f.as-eu.falkag.net +0.0.0.0 fatcatrewards.com +0.0.0.0 fbcdn-creative-a.akamaihd.net +0.0.0.0 fbfreegifts.com +0.0.0.0 fbi.gov.id402037057-8235504608.d9680.com +0.0.0.0 fcg.casino770.com +0.0.0.0 fc.webmasterpro.de +0.0.0.0 fdimages.fairfax.com.au +0.0.0.0 feedads.googleadservices.com +0.0.0.0 feeds.videosz.com +0.0.0.0 feeds.weselltraffic.com +0.0.0.0 fei.pro-market.net +0.0.0.0 fe.lea.lycos.es +0.0.0.0 fhm.valueclick.net +0.0.0.0 fif49.info +0.0.0.0 files.adbrite.com +0.0.0.0 fin.adbureau.net +0.0.0.0 finance-offer.com +0.0.0.0 finanzmeldungen.com +0.0.0.0 finder.cox.net +0.0.0.0 fixbonus.com +0.0.0.0 floatingads.madisonavenue.com +0.0.0.0 floridat.app.ur.gcion.com +0.0.0.0 flowers-offer.com +0.0.0.0 fls-na.amazon.com +0.0.0.0 flu23.com +0.0.0.0 fmads.osdn.com +0.0.0.0 focusin.ads.targetnet.com +0.0.0.0 folloyu.com +0.0.0.0 food-drink-bonuspath.com +0.0.0.0 food-drink-rewardpath.com +0.0.0.0 foodmixeroffer.com +0.0.0.0 food-offer.com +0.0.0.0 foreignpolicy.advertserve.com +0.0.0.0 fp.uclo.net +0.0.0.0 fp.valueclick.com +0.0.0.0 fr.a2dfp.net +0.0.0.0 fr.adserver.yahoo.com +0.0.0.0 fr.classic.clickintext.net +0.0.0.0 freebiegb.co.uk +0.0.0.0 freecameraonus.com +0.0.0.0 freecameraprovider.com +0.0.0.0 freecamerasource.com +0.0.0.0 freecamerauk.co.uk +0.0.0.0 freecoolgift.com +0.0.0.0 freedesignerhandbagreviews.com +0.0.0.0 freedinnersource.com +0.0.0.0 freedvddept.com +0.0.0.0 freeelectronicscenter.com +0.0.0.0 freeelectronicsdepot.com +0.0.0.0 freeelectronicsonus.com +0.0.0.0 freeelectronicssource.com +0.0.0.0 freeentertainmentsource.com +0.0.0.0 freefoodprovider.com +0.0.0.0 freefoodsource.com +0.0.0.0 freefuelcard.com +0.0.0.0 freefuelcoupon.com +0.0.0.0 freegasonus.com +0.0.0.0 freegasprovider.com +0.0.0.0 free-gift-cards-now.com +0.0.0.0 freegiftcardsource.com +0.0.0.0 freegiftreward.com +0.0.0.0 free-gifts-comp.com +0.0.0.0 free.hotsocialz.com +0.0.0.0 freeipodnanouk.co.uk +0.0.0.0 freeipoduk.com +0.0.0.0 freeipoduk.co.uk +0.0.0.0 freelaptopgift.com +0.0.0.0 freelaptopnation.com +0.0.0.0 free-laptop-reward.com +0.0.0.0 freelaptopreward.com +0.0.0.0 freelaptopwebsites.com +0.0.0.0 freenation.com +0.0.0.0 freeoffers-toys.com +0.0.0.0 freepayasyougotopupuk.co.uk +0.0.0.0 freeplasmanation.com +0.0.0.0 freerestaurantprovider.com +0.0.0.0 freerestaurantsource.com +0.0.0.0 free-rewards.com-s.tv +0.0.0.0 freeshoppingprovider.com +0.0.0.0 freeshoppingsource.com +0.0.0.0 free.thesocialsexnetwork.com +0.0.0.0 freevideodownloadforpc.com +0.0.0.0 frontend-loadbalancer.meteorsolutions.com +0.0.0.0 fwdservice.com +0.0.0.0 fwmrm.net +0.0.0.0 g1.idg.pl +0.0.0.0 g2.gumgum.com +0.0.0.0 g3t4d5.madison.com +0.0.0.0 g4p.grt02.com +0.0.0.0 gadgeteer.pdamart.com +0.0.0.0 gam.adnxs.com +0.0.0.0 gameconsolerewards.com +0.0.0.0 games-toys-bonuspath.com +0.0.0.0 games-toys-free.com +0.0.0.0 games-toys-rewardpath.com +0.0.0.0 gate.hyperpaysys.com +0.0.0.0 gavzad.keenspot.com +0.0.0.0 gazeta.hit.gemius.pl +0.0.0.0 gazetteextra.advertserve.com +0.0.0.0 gbanners.hornymatches.com +0.0.0.0 gcads.osdn.com +0.0.0.0 gcdn.2mdn.net +0.0.0.0 gc.gcl.ru +0.0.0.0 gcir.gannett-tv.com +0.0.0.0 gcirm2.indystar.com +0.0.0.0 gcirm.argusleader.com +0.0.0.0 gcirm.argusleader.gcion.com +0.0.0.0 gcirm.battlecreekenquirer.com +0.0.0.0 gcirm.burlingtonfreepress.com +0.0.0.0 gcirm.centralohio.com +0.0.0.0 gcirm.centralohio.gcion.com +0.0.0.0 gcirm.cincinnati.com +0.0.0.0 gcirm.citizen-times.com +0.0.0.0 gcirm.clarionledger.com +0.0.0.0 gcirm.coloradoan.com +0.0.0.0 gcirm.courier-journal.com +0.0.0.0 gcirm.courierpostonline.com +0.0.0.0 gcirm.customcoupon.com +0.0.0.0 gcirm.dailyrecord.com +0.0.0.0 gcirm.delawareonline.com +0.0.0.0 gcirm.democratandchronicle.com +0.0.0.0 gcirm.desmoinesregister.com +0.0.0.0 gcirm.detnews.com +0.0.0.0 gcirm.dmp.gcion.com +0.0.0.0 gcirm.dmregister.com +0.0.0.0 gcirm.dnj.com +0.0.0.0 gcirm.flatoday.com +0.0.0.0 gcirm.gannettnetwork.com +0.0.0.0 gcirm.gannett-tv.com +0.0.0.0 gcirm.greatfallstribune.com +0.0.0.0 gcirm.greenvilleonline.com +0.0.0.0 gcirm.greenvilleonline.gcion.com +0.0.0.0 gcirm.honoluluadvertiser.gcion.com +0.0.0.0 gcirm.idahostatesman.com +0.0.0.0 gcirm.idehostatesman.com +0.0.0.0 gcirm.indystar.com +0.0.0.0 gcirm.injersey.com +0.0.0.0 gcirm.jacksonsun.com +0.0.0.0 gcirm.laregionalonline.com +0.0.0.0 gcirm.lsj.com +0.0.0.0 gcirm.montgomeryadvertiser.com +0.0.0.0 gcirm.muskogeephoenix.com +0.0.0.0 gcirm.newsleader.com +0.0.0.0 gcirm.news-press.com +0.0.0.0 gcirm.ozarksnow.com +0.0.0.0 gcirm.pensacolanewsjournal.com +0.0.0.0 gcirm.press-citizen.com +0.0.0.0 gcirm.pressconnects.com +0.0.0.0 gcirm.rgj.com +0.0.0.0 gcirm.sctimes.com +0.0.0.0 gcirm.stargazette.com +0.0.0.0 gcirm.statesmanjournal.com +0.0.0.0 gcirm.tallahassee.com +0.0.0.0 gcirm.tennessean.com +0.0.0.0 gcirm.thedailyjournal.com +0.0.0.0 gcirm.thedesertsun.com +0.0.0.0 gcirm.theithacajournal.com +0.0.0.0 gcirm.thejournalnews.com +0.0.0.0 gcirm.theolympian.com +0.0.0.0 gcirm.thespectrum.com +0.0.0.0 gcirm.tucson.com +0.0.0.0 gcirm.wisinfo.com +0.0.0.0 gde.adocean.pl +0.0.0.0 gdeee.hit.gemius.pl +0.0.0.0 gdelt.hit.gemius.pl +0.0.0.0 gdelv.hit.gemius.pl +0.0.0.0 gdyn.cnngo.com +0.0.0.0 gdyn.trutv.com +0.0.0.0 gemius.pl +0.0.0.0 geoads.osdn.com +0.0.0.0 geoloc11.geovisite.com +0.0.0.0 geo.precisionclick.com +0.0.0.0 getacool100.com +0.0.0.0 getacool500.com +0.0.0.0 getacoollaptop.com +0.0.0.0 getacooltv.com +0.0.0.0 getafreeiphone.org +0.0.0.0 getagiftonline.com +0.0.0.0 getmyfreebabystuff.com +0.0.0.0 getmyfreegear.com +0.0.0.0 getmyfreegiftcard.com +0.0.0.0 getmyfreelaptop.com +0.0.0.0 getmyfreelaptophere.com +0.0.0.0 getmyfreeplasma.com +0.0.0.0 getmylaptopfree.com +0.0.0.0 getmyplasmatv.com +0.0.0.0 getspecialgifts.com +0.0.0.0 getyour5kcredits0.blogspot.com +0.0.0.0 getyourfreecomputer.com +0.0.0.0 getyourfreetv.com +0.0.0.0 getyourgiftnow2.blogspot.com +0.0.0.0 getyourgiftnow3.blogspot.com +0.0.0.0 gg.adocean.pl +0.0.0.0 giftcardchallenge.com +0.0.0.0 giftcardsurveys.us.com +0.0.0.0 giftrewardzone.com +0.0.0.0 gifts-flowers-rewardpath.com +0.0.0.0 gimmethatreward.com +0.0.0.0 gingert.net +0.0.0.0 globalwebads.com +0.0.0.0 gmads.net +0.0.0.0 gm.preferences.com +0.0.0.0 go2.hit.gemius.pl +0.0.0.0 go.adee.bbelements.com +0.0.0.0 go.adlt.bbelements.com +0.0.0.0 go.adlv.bbelements.com +0.0.0.0 go.admulti.com +0.0.0.0 go.adnet.bbelements.com +0.0.0.0 go.arbo.bbelements.com +0.0.0.0 go.arbopl.bbelements.com +0.0.0.0 go.arboru.bbelements.com +0.0.0.0 go.bb007.bbelements.com +0.0.0.0 go.evolutionmedia.bbelements.com +0.0.0.0 go-free-gifts.com +0.0.0.0 gofreegifts.com +0.0.0.0 go.ihned.bbelements.com +0.0.0.0 go.intact.bbelements.com +0.0.0.0 go.lfstmedia.com +0.0.0.0 go.lotech.bbelements.com +0.0.0.0 goodsblock.marketgid.com +0.0.0.0 goody-garage.com +0.0.0.0 go.pl.bbelements.com +0.0.0.0 got2goshop.com +0.0.0.0 goto.trafficmultiplier.com +0.0.0.0 gozing.directtrack.com +0.0.0.0 grabbit-rabbit.com +0.0.0.0 graphics.adultfriendfinder.com +0.0.0.0 graphics.pop6.com +0.0.0.0 gratkapl.adocean.pl +0.0.0.0 gravitron.chron.com +0.0.0.0 greasypalm.com +0.0.0.0 grfx.mp3.com +0.0.0.0 groupon.pl +0.0.0.0 grz67.com +0.0.0.0 gs1.idsales.co.uk +0.0.0.0 gserv.cneteu.net +0.0.0.0 gspro.hit.gemius.pl +0.0.0.0 g.thinktarget.com +0.0.0.0 guiaconsumidor.com +0.0.0.0 guide2poker.com +0.0.0.0 guptamedianetwork.com +0.0.0.0 guru.sitescout.netdna-cdn.com +0.0.0.0 gwallet.com +0.0.0.0 gx-in-f109.1e100.net +0.0.0.0 h-afnetwww.adshuffle.com +0.0.0.0 halfords.ukrpts.net +0.0.0.0 happydiscountspecials.com +0.0.0.0 harvest176.adgardener.com +0.0.0.0 harvest284.adgardener.com +0.0.0.0 harvest285.adgardener.com +0.0.0.0 harvest.adgardener.com +0.0.0.0 hathor.eztonez.com +0.0.0.0 haynet.adbureau.net +0.0.0.0 hbads.eboz.com +0.0.0.0 hbadz.eboz.com +0.0.0.0 healthbeautyncs.com +0.0.0.0 health-beauty-rewardpath.com +0.0.0.0 health-beauty-savingblvd.com +0.0.0.0 healthclicks.co.uk +0.0.0.0 hebdotop.com +0.0.0.0 help.adtech.de +0.0.0.0 help.adtech.fr +0.0.0.0 help.adtech.us +0.0.0.0 helpint.mywebsearch.com +0.0.0.0 hightrafficads.com +0.0.0.0 himediads.com +0.0.0.0 hit4.hotlog.ru +0.0.0.0 hk.adserver.yahoo.com +0.0.0.0 hlcc.ca +0.0.0.0 holiday-gift-offers.com +0.0.0.0 holidayproductpromo.com +0.0.0.0 holidayshoppingrewards.com +0.0.0.0 home4bizstart.ru +0.0.0.0 homeelectronicproducts.com +0.0.0.0 home-garden-premiumblvd.com +0.0.0.0 home-garden-rewardempire.com +0.0.0.0 home-garden-rewardpath.com +0.0.0.0 homeimprovementonus.com +0.0.0.0 honolulu.app.ur.gcion.com +0.0.0.0 hooqy.com +0.0.0.0 host207.ewtn.com +0.0.0.0 hostedaje14.thruport.com +0.0.0.0 hosting.adjug.com +0.0.0.0 hot-daily-deal.com +0.0.0.0 hotgiftzone.com +0.0.0.0 hot-product-hangout.com +0.0.0.0 hpad.www.infoseek.co.jp +0.0.0.0 h.ppjol.com +0.0.0.0 htmlads.ru +0.0.0.0 html.centralmediaserver.com +0.0.0.0 htmlwww.youfck.com +0.0.0.0 http300.content.ru4.com +0.0.0.0 httpads.com +0.0.0.0 httpwwwadserver.com +0.0.0.0 hub.com.pl +0.0.0.0 huiwiw.hit.gemius.pl +0.0.0.0 huntingtonbank.tt.omtrdc.net +0.0.0.0 huomdgde.adocean.pl +0.0.0.0 hyperion.adtech.de +0.0.0.0 hyperion.adtech.fr +0.0.0.0 hyperion.adtech.us +0.0.0.0 i1.teaser-goods.ru +0.0.0.0 iacas.adbureau.net +0.0.0.0 iad.anm.co.uk +0.0.0.0 iadc.qwapi.com +#0.0.0.0 iadsdk.apple.com #may interfere with iTunes radio +0.0.0.0 ib.adnxs.com +0.0.0.0 ibis.lgappstv.com +0.0.0.0 i.blogads.com +0.0.0.0 i.casalemedia.com +0.0.0.0 icon.clickthru.net +0.0.0.0 id11938.luxup.ru +0.0.0.0 id5576.al21.luxup.ru +0.0.0.0 idearc.tt.omtrdc.net +0.0.0.0 idpix.media6degrees.com +0.0.0.0 ieee.adbureau.net +0.0.0.0 if.bbanner.it +0.0.0.0 iftarvakitleri.net +0.0.0.0 ih2.gamecopyworld.com +0.0.0.0 i.hotkeys.com +0.0.0.0 i.interia.pl +0.0.0.0 i.laih.com +0.0.0.0 ilinks.industrybrains.com +0.0.0.0 im.adtech.de +0.0.0.0 image2.pubmatic.com +0.0.0.0 imageads.canoe.ca +0.0.0.0 imagec08.247realmedia.com +0.0.0.0 imagec12.247realmedia.com +0.0.0.0 imagec14.247realmedia.com +0.0.0.0 imagecache2.allposters.com +0.0.0.0 imageceu1.247realmedia.com +0.0.0.0 image.click.livedoor.com +0.0.0.0 image.i1img.com +0.0.0.0 image.linkexchange.com +0.0.0.0 images2.laih.com +0.0.0.0 images3.linkwithin.com +0.0.0.0 images.ads.fairfax.com.au +0.0.0.0 images.blogads.com +0.0.0.0 images.bluetime.com +0.0.0.0 images-cdn.azoogleads.com +0.0.0.0 images.clickfinders.com +0.0.0.0 images.conduit-banners.com +0.0.0.0 images.cybereps.com +0.0.0.0 images.directtrack.com +0.0.0.0 images.emapadserver.com +0.0.0.0 imageserv.adtech.de +0.0.0.0 imageserv.adtech.fr +0.0.0.0 imageserv.adtech.us +0.0.0.0 imageserver1.thruport.com +0.0.0.0 images.jambocast.com +0.0.0.0 images.linkwithin.com +0.0.0.0 images.mbuyu.nl +0.0.0.0 images.netcomvad.com +0.0.0.0 images.newsx.cc +0.0.0.0 images.people2people.com +0.0.0.0 images.primaryads.com +0.0.0.0 images.sexlist.com +0.0.0.0 images.steamray.com +0.0.0.0 images.trafficmp.com +0.0.0.0 im.banner.t-online.de +0.0.0.0 i.media.cz +0.0.0.0 img0.ru.redtram.com +0.0.0.0 img1.ru.redtram.com +0.0.0.0 img2.ru.redtram.com +0.0.0.0 img4.cdn.adjuggler.com +0.0.0.0 img-a2.ak.imagevz.net +0.0.0.0 img.blogads.com +0.0.0.0 img-cdn.mediaplex.com +0.0.0.0 img.directtrack.com +0.0.0.0 imgg.dt00.net +0.0.0.0 imgg.marketgid.com +0.0.0.0 img.layer-ads.de +0.0.0.0 img.marketgid.com +0.0.0.0 imgn.dt00.net +0.0.0.0 imgn.dt07.com +0.0.0.0 imgn.marketgid.com +0.0.0.0 imgserv.adbutler.com +0.0.0.0 img.sn00.net +0.0.0.0 img.soulmate.com +0.0.0.0 img.xnxx.com +0.0.0.0 im.of.pl +0.0.0.0 impact.cossette-webpact.com +0.0.0.0 impbe.tradedoubler.com +0.0.0.0 imp.partner2profit.com +0.0.0.0 imppl.tradedoubler.com +0.0.0.0 impressionaffiliate.com +0.0.0.0 impressionaffiliate.mobi +0.0.0.0 impressionlead.com +0.0.0.0 impressionperformance.biz +0.0.0.0 imserv001.adtech.de +0.0.0.0 imserv001.adtech.fr +0.0.0.0 imserv001.adtech.us +0.0.0.0 imserv002.adtech.de +0.0.0.0 imserv002.adtech.fr +0.0.0.0 imserv002.adtech.us +0.0.0.0 imserv003.adtech.de +0.0.0.0 imserv003.adtech.fr +0.0.0.0 imserv003.adtech.us +0.0.0.0 imserv004.adtech.de +0.0.0.0 imserv004.adtech.fr +0.0.0.0 imserv004.adtech.us +0.0.0.0 imserv005.adtech.de +0.0.0.0 imserv005.adtech.fr +0.0.0.0 imserv005.adtech.us +0.0.0.0 imserv006.adtech.de +0.0.0.0 imserv006.adtech.fr +0.0.0.0 imserv006.adtech.us +0.0.0.0 imserv00x.adtech.de +0.0.0.0 imserv00x.adtech.fr +0.0.0.0 imserv00x.adtech.us +0.0.0.0 imssl01.adtech.de +0.0.0.0 imssl01.adtech.fr +0.0.0.0 imssl01.adtech.us +0.0.0.0 im.xo.pl +0.0.0.0 in.adserver.yahoo.com +0.0.0.0 incentivegateway.com +0.0.0.0 incentiverewardcenter.com +0.0.0.0 incentive-scene.com +0.0.0.0 indexhu.adocean.pl +0.0.0.0 infinite-ads.com +0.0.0.0 inklineglobal.com +0.0.0.0 inl.adbureau.net +0.0.0.0 input.insights.gravity.com +0.0.0.0 insightxe.pittsburghlive.com +0.0.0.0 insightxe.vtsgonline.com +0.0.0.0 ins-offer.com +0.0.0.0 installer.zutrack.com +0.0.0.0 insurance-rewardpath.com +0.0.0.0 intela.com +0.0.0.0 intelliads.com +0.0.0.0 internet.billboard.cz +0.0.0.0 intnet-offer.com +0.0.0.0 intrack.pl +0.0.0.0 invitefashion.com +0.0.0.0 ipacc1.adtech.de +0.0.0.0 ipacc1.adtech.fr +0.0.0.0 ipacc1.adtech.us +0.0.0.0 ipad2free4u.com +0.0.0.0 i.pcp001.com +0.0.0.0 ipdata.adtech.de +0.0.0.0 ipdata.adtech.fr +0.0.0.0 ipdata.adtech.us +0.0.0.0 iq001.adtech.de +0.0.0.0 iq001.adtech.fr +0.0.0.0 iq001.adtech.us +0.0.0.0 i.qitrck.com +0.0.0.0 is.casalemedia.com +0.0.0.0 i.securecontactinfo.com +0.0.0.0 isg01.casalemedia.com +0.0.0.0 isg02.casalemedia.com +0.0.0.0 isg03.casalemedia.com +0.0.0.0 isg04.casalemedia.com +0.0.0.0 isg05.casalemedia.com +0.0.0.0 isg06.casalemedia.com +0.0.0.0 isg07.casalemedia.com +0.0.0.0 isg08.casalemedia.com +0.0.0.0 isg09.casalemedia.com +0.0.0.0 i.simpli.fi +0.0.0.0 it.adserver.yahoo.com +0.0.0.0 i.total-media.net +0.0.0.0 itrackerpro.com +0.0.0.0 i.trkjmp.com +0.0.0.0 itsfree123.com +0.0.0.0 itxt.vibrantmedia.com +0.0.0.0 iwantmyfreecash.com +0.0.0.0 iwantmy-freelaptop.com +0.0.0.0 iwantmyfree-laptop.com +0.0.0.0 iwantmyfreelaptop.com +0.0.0.0 iwantmygiftcard.com +0.0.0.0 jambocast.com +0.0.0.0 jb9clfifs6.s.ad6media.fr +0.0.0.0 jcarter.spinbox.net +0.0.0.0 j.clickdensity.com +0.0.0.0 jcrew.tt.omtrdc.net +0.0.0.0 jersey-offer.com +0.0.0.0 jgedads.cjt.net +0.0.0.0 jh.revolvermaps.com +0.0.0.0 jivox.com +0.0.0.0 jl29jd25sm24mc29.com +0.0.0.0 jlinks.industrybrains.com +0.0.0.0 jmn.jangonetwork.com +0.0.0.0 join1.winhundred.com +0.0.0.0 js1.bloggerads.net +0.0.0.0 js77.neodatagroup.com +0.0.0.0 js.adlink.net +0.0.0.0 js.admngr.com +0.0.0.0 js.adscale.de +0.0.0.0 js.adserverpub.com +0.0.0.0 js.adsonar.com +0.0.0.0 jsc.dt07.net +0.0.0.0 js.goods.redtram.com +0.0.0.0 js.himediads.com +0.0.0.0 js.hotkeys.com +0.0.0.0 jsn.dt07.net +0.0.0.0 js.ru.redtram.com +0.0.0.0 js.selectornews.com +0.0.0.0 js.smi2.ru +0.0.0.0 js.tongji.linezing.com +0.0.0.0 js.zevents.com +0.0.0.0 judo.salon.com +0.0.0.0 juggler.inetinteractive.com +0.0.0.0 justwebads.com +0.0.0.0 jxliu.com +0.0.0.0 k5ads.osdn.com +0.0.0.0 kaartenhuis.nl.site-id.nl +0.0.0.0 kansas.valueclick.com +0.0.0.0 katu.adbureau.net +0.0.0.0 kazaa.adserver.co.il +0.0.0.0 kermit.macnn.com +0.0.0.0 kestrel.ospreymedialp.com +0.0.0.0 keys.dmtracker.com +0.0.0.0 keywordblocks.com +0.0.0.0 keywords.adtlgc.com +0.0.0.0 kitaramarketplace.com +0.0.0.0 kitaramedia.com +0.0.0.0 kitaratrk.com +0.0.0.0 kithrup.matchlogic.com +0.0.0.0 kixer.com +0.0.0.0 klikk.linkpulse.com +0.0.0.0 klikmoney.net +0.0.0.0 kliksaya.com +0.0.0.0 klipads.dvlabs.com +0.0.0.0 klipmart.dvlabs.com +0.0.0.0 klipmart.forbes.com +0.0.0.0 kmdl101.com +0.0.0.0 knc.lv +0.0.0.0 knight.economist.com +0.0.0.0 kona2.kontera.com +0.0.0.0 kona3.kontera.com +0.0.0.0 kona4.kontera.com +0.0.0.0 kona5.kontera.com +0.0.0.0 kona6.kontera.com +0.0.0.0 kona7.kontera.com +0.0.0.0 kona8.kontera.com +0.0.0.0 kona.kontera.com +0.0.0.0 kontera.com +0.0.0.0 kreaffiliation.com +0.0.0.0 kropka.onet.pl +0.0.0.0 kuhdi.com +0.0.0.0 l.5min.com +0.0.0.0 ladyclicks.ru +0.0.0.0 lanzar.publicidadweb.com +0.0.0.0 laptopreportcard.com +0.0.0.0 laptoprewards.com +0.0.0.0 laptoprewardsgroup.com +0.0.0.0 laptoprewardszone.com +0.0.0.0 larivieracasino.com +0.0.0.0 lasthr.info +0.0.0.0 lastmeasure.zoy.org +0.0.0.0 launch.adserver.yahoo.com +0.0.0.0 layer-ads.de +0.0.0.0 lb-adserver.ig.com.br +0.0.0.0 ld1.criteo.com +0.0.0.0 ld2.criteo.com +0.0.0.0 ldglob01.adtech.de +0.0.0.0 ldglob01.adtech.fr +0.0.0.0 ldglob01.adtech.us +0.0.0.0 ldglob02.adtech.de +0.0.0.0 ldglob02.adtech.fr +0.0.0.0 ldglob02.adtech.us +0.0.0.0 ldimage01.adtech.de +0.0.0.0 ldimage01.adtech.fr +0.0.0.0 ldimage01.adtech.us +0.0.0.0 ldimage02.adtech.de +0.0.0.0 ldimage02.adtech.fr +0.0.0.0 ldimage02.adtech.us +0.0.0.0 ldserv01.adtech.de +0.0.0.0 ldserv01.adtech.fr +0.0.0.0 ldserv01.adtech.us +0.0.0.0 ldserv02.adtech.de +0.0.0.0 ldserv02.adtech.fr +0.0.0.0 ldserv02.adtech.us +0.0.0.0 le1er.net +0.0.0.0 leadback.advertising.com +0.0.0.0 leader.linkexchange.com +0.0.0.0 lead.program3.com +0.0.0.0 leadsynaptic.go2jump.org +0.0.0.0 learning-offer.com +0.0.0.0 legal-rewardpath.com +0.0.0.0 leisure-offer.com +0.0.0.0 lg.brandreachsys.com +0.0.0.0 liberty.gedads.com +0.0.0.0 link2me.ru +0.0.0.0 link4ads.com +0.0.0.0 linktracker.angelfire.com +0.0.0.0 linuxpark.adtech.de +0.0.0.0 linuxpark.adtech.fr +0.0.0.0 linuxpark.adtech.us +0.0.0.0 liquidad.narrowcastmedia.com +0.0.0.0 live-cams-1.livejasmin.com +0.0.0.0 livingnet.adtech.de +0.0.0.0 ll.atdmt.com +0.0.0.0 l.linkpulse.com +0.0.0.0 lnads.osdn.com +0.0.0.0 load.exelator.com +0.0.0.0 load.focalex.com +0.0.0.0 loading321.com +0.0.0.0 loadm.exelator.com +0.0.0.0 local.promoisland.net +0.0.0.0 logc252.xiti.com +0.0.0.0 log.feedjit.com +0.0.0.0 login.linkpulse.com +0.0.0.0 log.olark.com +0.0.0.0 looksmartcollect.247realmedia.com +0.0.0.0 louisvil.app.ur.gcion.com +0.0.0.0 louisvil.ur.gcion.com +0.0.0.0 lp1.linkpulse.com +0.0.0.0 lp4.linkpulse.com +0.0.0.0 lpcloudsvr405.com +0.0.0.0 lstats.qip.ru +0.0.0.0 lt.andomedia.com +0.0.0.0 lt.angelfire.com +0.0.0.0 lucky-day-uk.com +0.0.0.0 luxup.ru +0.0.0.0 lw1.gamecopyworld.com +0.0.0.0 lw2.gamecopyworld.com +0.0.0.0 lycos.247realmedia.com +0.0.0.0 l.yieldmanager.net +0.0.0.0 m1.emea.2mdn.net.edgesuite.net +0.0.0.0 m2.sexgarantie.nl +0.0.0.0 m3.2mdn.net +0.0.0.0 macaddictads.snv.futurenet.com +0.0.0.0 macads.net +0.0.0.0 mackeeperapp1.zeobit.com +0.0.0.0 mad2.brandreachsys.com +0.0.0.0 m.adbridge.de +0.0.0.0 mads.aol.com +0.0.0.0 mads.cnet.com +0.0.0.0 mail.radar.imgsmail.ru +0.0.0.0 manage001.adtech.de +0.0.0.0 manage001.adtech.fr +0.0.0.0 manage001.adtech.us +0.0.0.0 manager.rovion.com +0.0.0.0 manuel.theonion.com +0.0.0.0 marketgid.com +0.0.0.0 marketing.888.com +0.0.0.0 marketing-rewardpath.com +0.0.0.0 marriottinternationa.tt.omtrdc.net +0.0.0.0 mastertracks.be +0.0.0.0 matomy.adk2.co +0.0.0.0 matrix.mediavantage.de +0.0.0.0 maxadserver.corusradionetwork.com +0.0.0.0 maxads.ruralpress.com +0.0.0.0 maxbounty.com +0.0.0.0 maximumpcads.imaginemedia.com +0.0.0.0 maxmedia.sgaonline.com +0.0.0.0 maxserving.com +0.0.0.0 mb01.com +0.0.0.0 mbox2.offermatica.com +0.0.0.0 mbox9.offermatica.com +0.0.0.0 mds.centrport.net +0.0.0.0 media2021.videostrip.com +0.0.0.0 media2.adshuffle.com +0.0.0.0 media2.legacy.com +0.0.0.0 media2.travelzoo.com +0.0.0.0 media4021.videostrip.com #http://media4021.videostrip.com/dev8/0/000/449/0000449408.mp4 +0.0.0.0 media5021.videostrip.com #http://media5021.videostrip.com/dev14/0/000/363/0000363146.mp4 +0.0.0.0 media6021.videostrip.com +0.0.0.0 media6.sitebrand.com +0.0.0.0 media.888.com +0.0.0.0 media.adcentriconline.com +0.0.0.0 media.adrcdn.com +0.0.0.0 media.adrevolver.com +0.0.0.0 media.adrime.com +0.0.0.0 media.adshadow.net +0.0.0.0 media.b.lead.program3.com +0.0.0.0 media.bonnint.net +0.0.0.0 mediacharger.com +0.0.0.0 media.contextweb.com +0.0.0.0 media.elb-kind.de +0.0.0.0 media.espace-plus.net +0.0.0.0 media.fairlink.ru +0.0.0.0 mediafr.247realmedia.com +0.0.0.0 media.funpic.de +0.0.0.0 medialand.relax.ru +0.0.0.0 media.markethealth.com +0.0.0.0 media.naked.com +0.0.0.0 media.nk-net.pl +0.0.0.0 media.ontarionorth.com +0.0.0.0 media.popuptraffic.com +0.0.0.0 mediapst.adbureau.net +0.0.0.0 mediapst-images.adbureau.net +0.0.0.0 mediative.ca +0.0.0.0 mediative.com +0.0.0.0 media.trafficfactory.biz +0.0.0.0 media.trafficjunky.net +0.0.0.0 mediauk.247realmedia.com +0.0.0.0 media.ventivmedia.com +0.0.0.0 media.viwii.net +0.0.0.0 medical-offer.com +0.0.0.0 medical-rewardpath.com +0.0.0.0 medleyads.com +0.0.0.0 medrx.sensis.com.au +0.0.0.0 megapanel.gem.pl +0.0.0.0 mercury.bravenet.com +0.0.0.0 messagent.duvalguillaume.com +0.0.0.0 messagia.adcentric.proximi-t.com +0.0.0.0 meter-svc.nytimes.com +0.0.0.0 metrics.natmags.co.uk +0.0.0.0 metrics.sfr.fr +0.0.0.0 metrics.target.com +0.0.0.0 m.fr.a2dfp.net +0.0.0.0 m.friendlyduck.com +0.0.0.0 mf.sitescout.com +0.0.0.0 mg.dt00.net +0.0.0.0 mgid.com +0.0.0.0 mhlnk.com +0.0.0.0 mi.adinterax.com +0.0.0.0 microsof.wemfbox.ch +0.0.0.0 mightymagoo.com +0.0.0.0 mii-image.adjuggler.com +0.0.0.0 mini.videostrip.com +0.0.0.0 mirror.pointroll.com +0.0.0.0 mjxads.internet.com +0.0.0.0 mjx.ads.nwsource.com +0.0.0.0 mklik.gazeta.pl +0.0.0.0 mktg-offer.com +0.0.0.0 mlntracker.com +0.0.0.0 mm.admob.com +0.0.0.0 mm.chitika.net +0.0.0.0 mob.adwhirl.com +0.0.0.0 mobileads.msn.com +0.0.0.0 mobile.juicyads.com +0.0.0.0 mobularity.com +0.0.0.0 mochibot.com +0.0.0.0 mojofarm.mediaplex.com +0.0.0.0 moneyraid.com +0.0.0.0 monstersandcritics.advertserve.com +0.0.0.0 morefreecamsecrets.com +0.0.0.0 morevisits.info +0.0.0.0 motd.pinion.gg +0.0.0.0 movieads.imgs.sapo.pt +0.0.0.0 mp3playersource.com +0.0.0.0 mp.tscapeplay.com +0.0.0.0 msn.allyes.com +0.0.0.0 msnbe-hp.metriweb.be +0.0.0.0 msn-cdn.effectivemeasure.net +0.0.0.0 msn.oewabox.at +0.0.0.0 msn.tns-cs.net +0.0.0.0 msn.uvwbox.de +0.0.0.0 msn.wrating.com +0.0.0.0 mt58.mtree.com +0.0.0.0 m.tribalfusion.com +0.0.0.0 mu-in-f167.1e100.net +0.0.0.0 multi.xnxx.com +0.0.0.0 mvonline.com +0.0.0.0 mx.adserver.yahoo.com +0.0.0.0 myao.adocean.pl +0.0.0.0 my.blueadvertise.com +0.0.0.0 mycashback.co.uk +0.0.0.0 mycelloffer.com +0.0.0.0 mychoicerewards.com +0.0.0.0 myexclusiverewards.com +0.0.0.0 myfreedinner.com +0.0.0.0 myfreegifts.co.uk +0.0.0.0 myfreemp3player.com +0.0.0.0 mygiftcardcenter.com +0.0.0.0 mygiftresource.com +0.0.0.0 mygreatrewards.com +0.0.0.0 myoffertracking.com +0.0.0.0 my-reward-channel.com +0.0.0.0 my-rewardsvault.com +0.0.0.0 myseostats.com +0.0.0.0 myusersonline.com +0.0.0.0 myyearbookdigital.checkm8.com +0.0.0.0 n4g.us.intellitxt.com +0.0.0.0 n4p.ru.redtram.com +0.0.0.0 nationalissuepanel.com +0.0.0.0 nationalpost.adperfect.com +0.0.0.0 nationalsurveypanel.com +0.0.0.0 nbads.com +0.0.0.0 nbc.adbureau.net +0.0.0.0 nbimg.dt00.net +0.0.0.0 nb.netbreak.com.au +0.0.0.0 nc.ru.redtram.com +0.0.0.0 nctracking.com +0.0.0.0 nd1.gamecopyworld.com +0.0.0.0 nearbyad.com +0.0.0.0 needadvertising.com +0.0.0.0 netads.hotwired.com +0.0.0.0 netadsrv.iworld.com +0.0.0.0 netads.sohu.com +0.0.0.0 netcomm.spinbox.net +0.0.0.0 netpalnow.com +0.0.0.0 netshelter.adtrix.com +0.0.0.0 netspiderads2.indiatimes.com +0.0.0.0 netsponsors.com +0.0.0.0 networkads.net +0.0.0.0 network-ca.247realmedia.com +0.0.0.0 network.realmedia.com +0.0.0.0 network.realtechnetwork.net +0.0.0.0 newads.cmpnet.com +0.0.0.0 newadserver.interfree.it +0.0.0.0 new-ads.eurogamer.net +0.0.0.0 newbs.hutz.co.il +0.0.0.0 news6health.com +0.0.0.0 newsblock.marketgid.com +0.0.0.0 new.smartcontext.pl +0.0.0.0 newssourceoftoday.com #security risk/fake news# +0.0.0.0 newt1.adultadworld.com +0.0.0.0 newt1.adultworld.com +0.0.0.0 ng3.ads.warnerbros.com +0.0.0.0 ngads.smartage.com +0.0.0.0 nitrous.exitfuel.com +0.0.0.0 nitrous.internetfuel.com +0.0.0.0 nivendas.net +0.0.0.0 nkcache.brandreachsys.com +0.0.0.0 nl.adserver.yahoo.com +0.0.0.0 no.adserver.yahoo.com +0.0.0.0 nospartenaires.com +0.0.0.0 nothing-but-value.com +0.0.0.0 novafinanza.com +0.0.0.0 novem.onet.pl +0.0.0.0 nrads.1host.co.il +0.0.0.0 nrkno.linkpulse.com +0.0.0.0 ns1.lalibco.com +0.0.0.0 ns1.primeinteractive.net +0.0.0.0 ns2.hitbox.com +0.0.0.0 ns2.lalibco.com +0.0.0.0 ns2.primeinteractive.net +0.0.0.0 nsads4.us.publicus.com +0.0.0.0 nsads.hotwired.com +0.0.0.0 nsads.us.publicus.com +0.0.0.0 nspmotion.com +0.0.0.0 ns-vip1.hitbox.com +0.0.0.0 ns-vip2.hitbox.com +0.0.0.0 ns-vip3.hitbox.com +0.0.0.0 ntbanner.digitalriver.com +0.0.0.0 nx-adv0005.247realmedia.com +0.0.0.0 nxs.kidcolez.cn +0.0.0.0 nxtscrn.adbureau.net +0.0.0.0 nysubwayoffer.com +0.0.0.0 nytadvertising.nytimes.com +0.0.0.0 o0.winfuture.de +0.0.0.0 o1.qnsr.com +0.0.0.0 o2.eyereturn.com +0.0.0.0 oads.cracked.com +0.0.0.0 oamsrhads.us.publicus.com +0.0.0.0 oas-1.rmuk.co.uk +0.0.0.0 oasads.whitepages.com +0.0.0.0 oasc02023.247realmedia.com +0.0.0.0 oasc02.247realmedia.com +0.0.0.0 oasc03.247realmedia.com +0.0.0.0 oasc04.247.realmedia.com +0.0.0.0 oasc05050.247realmedia.com +0.0.0.0 oasc05.247realmedia.com +0.0.0.0 oasc16.247realmedia.com +0.0.0.0 oascenral.phoenixnewtimes.com +0.0.0.0 oascentral.videodome.com +0.0.0.0 oas.dn.se +0.0.0.0 oas-eu.247realmedia.com +0.0.0.0 oas.heise.de +0.0.0.0 oasis2.advfn.com +0.0.0.0 oasis.411affiliates.ca +0.0.0.0 oasis.nysun.com +0.0.0.0 oasis.promon.cz +0.0.0.0 oasis.realbeer.com +0.0.0.0 oasis.zmh.zope.com +0.0.0.0 oasis.zmh.zope.net +0.0.0.0 oasn03.247realmedia.com +0.0.0.0 oassis.zmh.zope.com +0.0.0.0 objects.abcvisiteurs.com +0.0.0.0 objects.designbloxlive.com +0.0.0.0 obozua.adocean.pl +0.0.0.0 observer.advertserve.com +0.0.0.0 obs.nnm2.ru +0.0.0.0 offers.impower.com +0.0.0.0 offerx.co.uk +0.0.0.0 oinadserve.com +0.0.0.0 old-darkroast.adknowledge.com +0.0.0.0 ometrics.warnerbros.com +0.0.0.0 onclickads.net +0.0.0.0 online1.webcams.com +0.0.0.0 onlineads.magicvalley.com +0.0.0.0 onlinebestoffers.net +0.0.0.0 onocollect.247realmedia.com +0.0.0.0 open.4info.net +0.0.0.0 openadext.tf1.fr +0.0.0.0 openad.infobel.com +0.0.0.0 openads.dimcab.com +0.0.0.0 openads.friendfinder.com +0.0.0.0 openads.nightlifemagazine.ca +0.0.0.0 openads.smithmag.net +0.0.0.0 openads.zeads.com +0.0.0.0 openad.travelnow.com +0.0.0.0 opentable.tt.omtrdc.net +0.0.0.0 openx2.fotoflexer.com +0.0.0.0 openx.adfactor.nl +0.0.0.0 openx.coolconcepts.nl +0.0.0.0 openx.shinyads.com +0.0.0.0 openxxx.viragemedia.com +0.0.0.0 optimized-by.rubiconproject.com +0.0.0.0 optimized.by.vitalads.net +0.0.0.0 optimize.indieclick.com +0.0.0.0 optimzedby.rmxads.com +0.0.0.0 orange.weborama.fr +0.0.0.0 ordie.adbureau.net +0.0.0.0 origin.chron.com +0.0.0.0 out.popads.net +0.0.0.0 overflow.adsoftware.com +0.0.0.0 overlay.ringtonematcher.com +0.0.0.0 overstock.tt.omtrdc.net +0.0.0.0 ox-d.hbr.org +0.0.0.0 ox-d.hulkshare.com +0.0.0.0 ox-d.hypeads.org +0.0.0.0 ox-d.zenoviagroup.com +0.0.0.0 ox.eurogamer.net +0.0.0.0 ox-i.zenoviagroup.com +0.0.0.0 ozonemedia.adbureau.net +0.0.0.0 oz.valueclick.com +0.0.0.0 oz.valueclick.ne.jp +0.0.0.0 p0rnuha.com +0.0.0.0 p1.adhitzads.com +0.0.0.0 pagead1.googlesyndication.com +0.0.0.0 pagead2.googlesyndication.com +0.0.0.0 pagead3.googlesyndication.com +0.0.0.0 pagead.googlesyndication.com +0.0.0.0 pages.etology.com +0.0.0.0 paime.com +0.0.0.0 panel.adtify.pl +0.0.0.0 paperg.com +0.0.0.0 partner01.oingo.com +0.0.0.0 partner02.oingo.com +0.0.0.0 partner03.oingo.com +0.0.0.0 partner.ah-ha.com +0.0.0.0 partner.ceneo.pl +0.0.0.0 partner.join.com.ua +0.0.0.0 partner.magna.ru +0.0.0.0 partner.pobieraczek.pl +0.0.0.0 partners.sprintrade.com +0.0.0.0 partners.webmasterplan.com +0.0.0.0 partner.wapacz.pl +0.0.0.0 partner.wapster.pl +0.0.0.0 pathforpoints.com +0.0.0.0 paulsnetwork.com +0.0.0.0 pbid.pro-market.net +0.0.0.0 pb.tynt.com +0.0.0.0 pcads.ru +0.0.0.0 pei-ads.playboy.com +0.0.0.0 people-choice-sites.com +0.0.0.0 personalcare-offer.com +0.0.0.0 personalcashbailout.com +0.0.0.0 pg2.solution.weborama.fr +0.0.0.0 ph-ad01.focalink.com +0.0.0.0 ph-ad02.focalink.com +0.0.0.0 ph-ad03.focalink.com +0.0.0.0 ph-ad04.focalink.com +0.0.0.0 ph-ad05.focalink.com +0.0.0.0 ph-ad06.focalink.com +0.0.0.0 ph-ad07.focalink.com +0.0.0.0 ph-ad08.focalink.com +0.0.0.0 ph-ad09.focalink.com +0.0.0.0 ph-ad10.focalink.com +0.0.0.0 ph-ad11.focalink.com +0.0.0.0 ph-ad12.focalink.com +0.0.0.0 ph-ad13.focalink.com +0.0.0.0 ph-ad14.focalink.com +0.0.0.0 ph-ad15.focalink.com +0.0.0.0 ph-ad16.focalink.com +0.0.0.0 ph-ad17.focalink.com +0.0.0.0 ph-ad18.focalink.com +0.0.0.0 ph-ad19.focalink.com +0.0.0.0 ph-ad20.focalink.com +0.0.0.0 ph-ad21.focalink.com +0.0.0.0 ph-cdn.effectivemeasure.net +0.0.0.0 phoenixads.co.in +0.0.0.0 photobucket.adnxs.com +0.0.0.0 photos0.pop6.com +0.0.0.0 photos1.pop6.com +0.0.0.0 photos2.pop6.com +0.0.0.0 photos3.pop6.com +0.0.0.0 photos4.pop6.com +0.0.0.0 photos5.pop6.com +0.0.0.0 photos6.pop6.com +0.0.0.0 photos7.pop6.com +0.0.0.0 photos8.pop6.com +0.0.0.0 photos.daily-deals.analoganalytics.com +0.0.0.0 photos.pop6.com +0.0.0.0 phpads.astalavista.us +0.0.0.0 phpads.cnpapers.com +0.0.0.0 phpads.flipcorp.com +0.0.0.0 phpads.foundrymusic.com +0.0.0.0 phpads.i-merge.net +0.0.0.0 phpads.macbidouille.com +0.0.0.0 phpadsnew.gamefolk.de +0.0.0.0 phpadsnew.wn.com +0.0.0.0 php.fark.com +0.0.0.0 pick-savings.com +0.0.0.0 p.ic.tynt.com +0.0.0.0 pink.habralab.ru +0.0.0.0 pix01.revsci.net +0.0.0.0 pix521.adtech.de +0.0.0.0 pix521.adtech.fr +0.0.0.0 pix521.adtech.us +0.0.0.0 pix522.adtech.de +0.0.0.0 pix522.adtech.fr +0.0.0.0 pix522.adtech.us +0.0.0.0 pixel.everesttech.net +0.0.0.0 pixel.mathtag.com +0.0.0.0 pixel.quantserve.com +0.0.0.0 pixel.sitescout.com +0.0.0.0 plasmatv4free.com +0.0.0.0 plasmatvreward.com +0.0.0.0 playlink.pl +0.0.0.0 playtime.tubemogul.com +0.0.0.0 pl.bbelements.com +0.0.0.0 pmstrk.mercadolivre.com.br +0.0.0.0 pntm.adbureau.net +0.0.0.0 pntm-images.adbureau.net +0.0.0.0 pol.bbelements.com +0.0.0.0 politicalopinionsurvey.com +0.0.0.0 pool.pebblemedia.adhese.com +0.0.0.0 popadscdn.net +0.0.0.0 popclick.net +0.0.0.0 poponclick.com +0.0.0.0 popunder.adsrevenue.net +0.0.0.0 popunder.paypopup.com +0.0.0.0 popupclick.ru +0.0.0.0 popupdomination.com +0.0.0.0 popup.matchmaker.com +0.0.0.0 popups.ad-logics.com +0.0.0.0 popups.infostart.com +0.0.0.0 postmasterdirect.com +0.0.0.0 post.rmbn.ru +0.0.0.0 pp.free.fr +0.0.0.0 p.profistats.net +0.0.0.0 p.publico.es +0.0.0.0 premium.ascensionweb.com +0.0.0.0 premiumholidayoffers.com +0.0.0.0 premiumproductsonline.com +0.0.0.0 premium-reward-club.com +0.0.0.0 prexyone.appspot.com +0.0.0.0 primetime.ad.primetime.net +0.0.0.0 privitize.com +0.0.0.0 prizes.co.uk +0.0.0.0 productopinionpanel.com +0.0.0.0 productresearchpanel.com +0.0.0.0 producttestpanel.com +0.0.0.0 profile.uproxx.com +0.0.0.0 promo.awempire.com +0.0.0.0 promo.easy-dating.org +0.0.0.0 promos.fling.com +0.0.0.0 promote-bz.net +0.0.0.0 promotion.partnercash.com +0.0.0.0 proximityads.flipcorp.com +0.0.0.0 proxy.blogads.com +0.0.0.0 ptrads.mp3.com +0.0.0.0 pubdirecte.com +0.0.0.0 pubimgs.sapo.pt +0.0.0.0 publiads.com +0.0.0.0 publicidades.redtotalonline.com +0.0.0.0 publicis.adcentriconline.com +0.0.0.0 publish.bonzaii.no +0.0.0.0 publishers.adscholar.com +0.0.0.0 publishers.bidtraffic.com +0.0.0.0 publishers.brokertraffic.com +0.0.0.0 publishing.kalooga.com +0.0.0.0 pub.sapo.pt +0.0.0.0 pubshop.img.uol.com.br +0.0.0.0 purgecolon.net +0.0.0.0 px10.net +0.0.0.0 q.azcentral.com +0.0.0.0 q.b.h.cltomedia.info +0.0.0.0 qip.magna.ru +0.0.0.0 qitrck.com +0.0.0.0 quickbrowsersearch.com +0.0.0.0 r1-ads.ace.advertising.com +0.0.0.0 r.ace.advertising.com +0.0.0.0 radaronline.advertserve.com +0.0.0.0 r.admob.com +0.0.0.0 rad.msn.com +0.0.0.0 rads.stackoverflow.com +0.0.0.0 ravel-rewardpath.com +0.0.0.0 rb.burstway.com +0.0.0.0 rb.newsru.com +0.0.0.0 rbqip.pochta.ru +0.0.0.0 rc.asci.freenet.de +0.0.0.0 rc.bt.ilsemedia.nl +0.0.0.0 rccl.bridgetrack.com +0.0.0.0 rcdna.gwallet.com +0.0.0.0 r.chitika.net +0.0.0.0 rc.hotkeys.com +0.0.0.0 rcm-images.amazon.com +0.0.0.0 rcm-it.amazon.it +0.0.0.0 rc.rlcdn.com +0.0.0.0 rc.wl.webads.nl +0.0.0.0 realads.realmedia.com +0.0.0.0 realgfsbucks.com +0.0.0.0 realmedia-a800.d4p.net # Scientific American +0.0.0.0 realmedia.advance.net +0.0.0.0 recreation-leisure-rewardpath.com +0.0.0.0 red01.as-eu.falkag.net +0.0.0.0 red01.as-us.falkag.net +0.0.0.0 red02.as-eu.falkag.net +0.0.0.0 red02.as-us.falkag.net +0.0.0.0 red03.as-eu.falkag.net +0.0.0.0 red03.as-us.falkag.net +0.0.0.0 red04.as-eu.falkag.net +0.0.0.0 red04.as-us.falkag.net +0.0.0.0 red.as-eu.falkag.net +0.0.0.0 red.as-us.falkag.net +0.0.0.0 redherring.ngadcenter.net +0.0.0.0 redirect.click2net.com +0.0.0.0 redirect.hotkeys.com +0.0.0.0 reduxads.valuead.com +0.0.0.0 reg.coolsavings.com +0.0.0.0 regflow.com +0.0.0.0 regie.espace-plus.net +0.0.0.0 regio.adlink.de +0.0.0.0 reklama.onet.pl +0.0.0.0 reklamy.sfd.pl +0.0.0.0 re.kontera.com +0.0.0.0 rek.www.wp.pl +0.0.0.0 relestar.com +0.0.0.0 remotead.cnet.com +0.0.0.0 report02.adtech.de +0.0.0.0 report02.adtech.fr +0.0.0.0 report02.adtech.us +0.0.0.0 reporter001.adtech.de +0.0.0.0 reporter001.adtech.fr +0.0.0.0 reporter001.adtech.us +0.0.0.0 reporter.adtech.de +0.0.0.0 reporter.adtech.fr +0.0.0.0 reporter.adtech.us +0.0.0.0 reportimage.adtech.de +0.0.0.0 reportimage.adtech.fr +0.0.0.0 reportimage.adtech.us +0.0.0.0 resolvingserver.com +0.0.0.0 resources.infolinks.com +0.0.0.0 restaurantcom.tt.omtrdc.net +0.0.0.0 reverso.refr.adgtw.orangeads.fr +0.0.0.0 revsci.net +0.0.0.0 rewardblvd.com +0.0.0.0 rewardhotspot.com +0.0.0.0 rewardsflow.com +0.0.0.0 rhads.sv.publicus.com +0.0.0.0 rh.revolvermaps.com +0.0.0.0 richmedia.yimg.com +0.0.0.0 ridepush.com +0.0.0.0 ringtonepartner.com +0.0.0.0 rmbn.ru +0.0.0.0 rmedia.boston.com +0.0.0.0 rmm1u.checkm8.com +0.0.0.0 rms.admeta.com +0.0.0.0 ro.bbelements.com +0.0.0.0 romepartners.com +0.0.0.0 roosevelt.gjbig.com +0.0.0.0 rosettastone.tt.omtrdc.net +0.0.0.0 rotabanner100.utro.ru +0.0.0.0 rotabanner468.utro.ru +0.0.0.0 rotate.infowars.com +0.0.0.0 rotator.adjuggler.com +0.0.0.0 rotator.juggler.inetinteractive.com +0.0.0.0 rotobanner468.utro.ru +0.0.0.0 rovion.com +0.0.0.0 rpc.trafficfactory.biz +0.0.0.0 rp.hit.gemius.pl +0.0.0.0 r.reklama.biz +0.0.0.0 rscounter10.com +0.0.0.0 rsense-ad.realclick.co.kr +0.0.0.0 rss.buysellads.com +0.0.0.0 rt2.infolinks.com +0.0.0.0 rt3.infolinks.com +0.0.0.0 rtb.pclick.yahoo.com +0.0.0.0 rtb.tubemogul.com +0.0.0.0 rtr.innovid.com +0.0.0.0 rts.sparkstudios.com +0.0.0.0 r.turn.com +0.0.0.0 ru.bbelements.com +0.0.0.0 ru.redtram.com +0.0.0.0 russ-shalavy.ru +0.0.0.0 rv.adcpx.v1.de.eusem.adaos-ads.net +0.0.0.0 rya.rockyou.com +0.0.0.0 s0b.bluestreak.com +0.0.0.0 s1.buysellads.com +0.0.0.0 s1.cz.adocean.pl +0.0.0.0 s1.gratkapl.adocean.pl +0.0.0.0 s2.buysellads.com +0.0.0.0 s3.buysellads.com +0.0.0.0 s5.addthis.com +0.0.0.0 s7.addthis.com +0.0.0.0 s.admulti.com +0.0.0.0 sad.sharethis.com +0.0.0.0 safe.hyperpaysys.com +0.0.0.0 safenyplanet.in +0.0.0.0 salesforcecom.tt.omtrdc.net +0.0.0.0 s.amazon-adsystem.com +0.0.0.0 samsung3.solution.weborama.fr +0.0.0.0 s.as-us.falkag.net +0.0.0.0 sat-city-ads.com +0.0.0.0 s.atemda.com +0.0.0.0 saturn.tiser.com.au +0.0.0.0 save-plan.com +0.0.0.0 savings-specials.com +0.0.0.0 savings-time.com +0.0.0.0 s.boom.ro +0.0.0.0 schoorsteen.geenstijl.nl +0.0.0.0 schumacher.adtech.de +0.0.0.0 schumacher.adtech.fr +0.0.0.0 schumacher.adtech.us +0.0.0.0 schwab.tt.omtrdc.net +0.0.0.0 s.clicktale.net +0.0.0.0 scoremygift.com +0.0.0.0 screen-mates.com +0.0.0.0 script.banstex.com +0.0.0.0 script.crsspxl.com +0.0.0.0 scripts.verticalacuity.com +0.0.0.0 scr.kliksaya.com +0.0.0.0 s.di.com.pl +0.0.0.0 se.adserver.yahoo.com +0.0.0.0 search.addthis.com +0.0.0.0 search.freeonline.com +0.0.0.0 search.keywordblocks.com +0.0.0.0 search.netseer.com +0.0.0.0 searchportal.information.com +0.0.0.0 searchwe.com +0.0.0.0 seasonalsamplerspecials.com +0.0.0.0 sec.hit.gemius.pl +0.0.0.0 secimage.adtech.de +0.0.0.0 secimage.adtech.fr +0.0.0.0 secimage.adtech.us +0.0.0.0 secserv.adtech.de +0.0.0.0 secserv.adtech.fr +0.0.0.0 secserv.adtech.us +0.0.0.0 secure.ace-tag.advertising.com +0.0.0.0 secure.addthis.com +0.0.0.0 secureads.ft.com +0.0.0.0 secure.bidvertiserr.com +0.0.0.0 securecontactinfo.com +0.0.0.0 secure.gaug.es +0.0.0.0 secure.img-cdn.mediaplex.com +0.0.0.0 securerunner.com +0.0.0.0 secure.webconnect.net +0.0.0.0 seduction-zone.com +0.0.0.0 sel.as-eu.falkag.net +0.0.0.0 sel.as-us.falkag.net +0.0.0.0 select001.adtech.de +0.0.0.0 select001.adtech.fr +0.0.0.0 select001.adtech.us +0.0.0.0 select002.adtech.de +0.0.0.0 select002.adtech.fr +0.0.0.0 select002.adtech.us +0.0.0.0 select003.adtech.de +0.0.0.0 select003.adtech.fr +0.0.0.0 select003.adtech.us +0.0.0.0 select004.adtech.de +0.0.0.0 select004.adtech.fr +0.0.0.0 select004.adtech.us +0.0.0.0 sergarius.popunder.ru +0.0.0.0 serv2.ad-rotator.com +0.0.0.0 serv.ad-rotator.com +0.0.0.0 servads.aip.org +0.0.0.0 serv.adspeed.com +0.0.0.0 servedbyadbutler.com +0.0.0.0 servedby.adcombination.com +0.0.0.0 servedby.advertising.com +0.0.0.0 servedby.flashtalking.com +0.0.0.0 servedby.netshelter.net +0.0.0.0 servedby.precisionclick.com +0.0.0.0 serve.freegaypix.com +0.0.0.0 serve.popads.net +0.0.0.0 serve.prestigecasino.com +0.0.0.0 server01.popupmoney.com +0.0.0.0 server2.as5000.com +0.0.0.0 server2.mediajmp.com +0.0.0.0 server3.yieldmanaged.com +0.0.0.0 server.as5000.com +0.0.0.0 server.bittads.com +0.0.0.0 server.cpmstar.com +0.0.0.0 server.popads.net +0.0.0.0 server-ssl.yieldmanaged.com +0.0.0.0 service001.adtech.de +0.0.0.0 service001.adtech.fr +0.0.0.0 service001.adtech.us +0.0.0.0 service002.adtech.de +0.0.0.0 service002.adtech.fr +0.0.0.0 service002.adtech.us +0.0.0.0 service003.adtech.de +0.0.0.0 service003.adtech.fr +0.0.0.0 service003.adtech.us +0.0.0.0 service004.adtech.fr +0.0.0.0 service004.adtech.us +0.0.0.0 service00x.adtech.de +0.0.0.0 service00x.adtech.fr +0.0.0.0 service00x.adtech.us +0.0.0.0 service.adtech.de +0.0.0.0 service.adtech.fr +0.0.0.0 service.adtech.us +0.0.0.0 services1.adtech.de +0.0.0.0 services1.adtech.fr +0.0.0.0 services1.adtech.us +0.0.0.0 services.adtech.de +0.0.0.0 services.adtech.fr +0.0.0.0 services.adtech.us +0.0.0.0 serving.plexop.net +0.0.0.0 sexpartnerx.com +0.0.0.0 sexsponsors.com +0.0.0.0 sexzavod.com +0.0.0.0 sfads.osdn.com +0.0.0.0 s.flite.com +0.0.0.0 sg.adserver.yahoo.com +0.0.0.0 sgs001.adtech.de +0.0.0.0 sgs001.adtech.fr +0.0.0.0 sgs001.adtech.us +0.0.0.0 sh4sure-images.adbureau.net +0.0.0.0 shareasale.com +0.0.0.0 sharebar.addthiscdn.com +0.0.0.0 share-server.com +0.0.0.0 shc-rebates.com +0.0.0.0 shinystat.shiny.it +0.0.0.0 shopperpromotions.com +0.0.0.0 shopping-offer.com +0.0.0.0 shoppingsiterewards.com +0.0.0.0 shops-malls-rewardpath.com +0.0.0.0 shoptosaveenergy.com +0.0.0.0 showads1000.pubmatic.com +0.0.0.0 showadsak.pubmatic.com +0.0.0.0 sifomedia.citypaketet.se +0.0.0.0 signup.advance.net +0.0.0.0 si.hit.gemius.pl +0.0.0.0 simg.zedo.com +0.0.0.0 simpleads.net +0.0.0.0 simpli.fi +0.0.0.0 s.innovid.com +0.0.0.0 sixapart.adbureau.net +0.0.0.0 sizzle-savings.com +0.0.0.0 skgde.adocean.pl +0.0.0.0 skill.skilljam.com +0.0.0.0 slider.plugrush.com +0.0.0.0 smartadserver +0.0.0.0 smartadserver.com +0.0.0.0 smart.besonders.ru +0.0.0.0 smartclip.com +0.0.0.0 smartclip.net +0.0.0.0 smartcontext.pl +0.0.0.0 smartinit.webads.nl +0.0.0.0 smart-scripts.com +0.0.0.0 smartshare.lgtvsdp.com +0.0.0.0 s.media-imdb.com +0.0.0.0 s.megaclick.com +0.0.0.0 smile.modchipstore.com +0.0.0.0 smm.sitescout.com +0.0.0.0 s.moatads.com +0.0.0.0 smokersopinionpoll.com +0.0.0.0 smsmovies.net +0.0.0.0 snaps.vidiemi.com +0.0.0.0 sn.baventures.com +0.0.0.0 snip.answers.com +0.0.0.0 snipjs.answcdn.com +0.0.0.0 sochr.com +0.0.0.0 social.bidsystem.com +0.0.0.0 softlinkers.popunder.ru +0.0.0.0 sokrates.adtech.de +0.0.0.0 sokrates.adtech.fr +0.0.0.0 sokrates.adtech.us +0.0.0.0 sol.adbureau.net +0.0.0.0 sol-images.adbureau.net +0.0.0.0 solitairetime.com +0.0.0.0 solution.weborama.fr +0.0.0.0 somethingawful.crwdcntrl.net +0.0.0.0 sonycomputerentertai.tt.omtrdc.net +0.0.0.0 soongu.info +0.0.0.0 spanids.dictionary.com +0.0.0.0 spanids.thesaurus.com +0.0.0.0 spc.cekfmeoejdbfcfichgbfcgjf.vast2as3.glammedia-pubnet.northamerica.telemetryverification.net +0.0.0.0 spe.atdmt.com +0.0.0.0 specialgiftrewards.com +0.0.0.0 specialoffers.aol.com +0.0.0.0 specialonlinegifts.com +0.0.0.0 specials-rewardpath.com +0.0.0.0 speedboink.com +0.0.0.0 speedclicks.ero-advertising.com +0.0.0.0 speed.pointroll.com # Microsoft +0.0.0.0 spinbox.com +0.0.0.0 spinbox.consumerreview.com +0.0.0.0 spinbox.freedom.com +0.0.0.0 spinbox.macworld.com +0.0.0.0 spinbox.techtracker.com +0.0.0.0 spin.spinbox.net +0.0.0.0 sponsor1.com +0.0.0.0 sponsors.behance.com +0.0.0.0 sponsors.ezgreen.com +0.0.0.0 sponsorships.net +0.0.0.0 sports-bonuspath.com +0.0.0.0 sports-fitness-rewardpath.com +0.0.0.0 sports-offer.com +0.0.0.0 sports-offer.net +0.0.0.0 sports-premiumblvd.com +0.0.0.0 spotxchange.com +0.0.0.0 s.ppjol.net +0.0.0.0 sq2trk2.com +0.0.0.0 srs.targetpoint.com +0.0.0.0 srv.juiceadv.com +0.0.0.0 ssads.osdn.com +0.0.0.0 s.skimresources.com +0.0.0.0 sso.canada.com +0.0.0.0 staging.snip.answers.com +0.0.0.0 stampen.adtlgc.com +0.0.0.0 stampen.linkpulse.com +0.0.0.0 stampscom.tt.omtrdc.net +0.0.0.0 stanzapub.advertserve.com +0.0.0.0 star-advertising.com +0.0.0.0 stat.blogads.com +0.0.0.0 stat.dealtime.com +0.0.0.0 stat.ebuzzing.com +0.0.0.0 static1.influads.com +0.0.0.0 static.2mdn.net +0.0.0.0 static.admaximize.com +0.0.0.0 staticads.btopenworld.com +0.0.0.0 static.adsonar.com +0.0.0.0 static.adtaily.pl +0.0.0.0 static.adzerk.net +0.0.0.0 static.aff-landing-tmp.foxtab.com +0.0.0.0 staticb.mydirtyhobby.com +0.0.0.0 static.carbonads.com +0.0.0.0 static.clicktorrent.info +0.0.0.0 static.creatives.livejasmin.com +0.0.0.0 static.doubleclick.net +0.0.0.0 static.everyone.net +0.0.0.0 static.exoclick.com +0.0.0.0 static.fastpic.ru +0.0.0.0 static.firehunt.com +0.0.0.0 static.fmpub.net +0.0.0.0 static.freenet.de +0.0.0.0 static.groupy.co.nz +0.0.0.0 static.hitfarm.com +0.0.0.0 static.ifa.camads.net +0.0.0.0 static.l3.cdn.adbucks.com +0.0.0.0 static.l3.cdn.adsucks.com +0.0.0.0 static.plista.com +0.0.0.0 static.plugrush.com +0.0.0.0 static.pulse360.com +0.0.0.0 static.scanscout.com +0.0.0.0 static.vpptechnologies.com +0.0.0.0 static.way2traffic.com +0.0.0.0 statistik-gallup.dk +0.0.0.0 stats2.dooyoo.com +0.0.0.0 stats.askmoses.com +0.0.0.0 stats.buzzparadise.com +0.0.0.0 stats.jtvnw.net +0.0.0.0 stats.shopify.com +0.0.0.0 status.addthis.com +0.0.0.0 st.blogads.com +0.0.0.0 s.tcimg.com +0.0.0.0 st.marketgid.com +0.0.0.0 stocker.bonnint.net +0.0.0.0 storage.softure.com +0.0.0.0 storage.trafic.ro +0.0.0.0 streamate.com +0.0.0.0 stts.rbc.ru +0.0.0.0 st.valueclick.com +0.0.0.0 su.addthis.com +0.0.0.0 subtracts.userplane.com +0.0.0.0 sudokuwhiz.com +0.0.0.0 sunmaker.com +0.0.0.0 superbrewards.com +0.0.0.0 support.sweepstakes.com +0.0.0.0 supremeadsonline.com +0.0.0.0 suresafe1.adsovo.com +0.0.0.0 surplus-suppliers.com +0.0.0.0 surveycentral.directinsure.info +0.0.0.0 surveymonkeycom.tt.omtrdc.net +0.0.0.0 surveypass.com +0.0.0.0 susi.adtech.fr +0.0.0.0 susi.adtech.us +0.0.0.0 svd2.adtlgc.com +0.0.0.0 svd.adtlgc.com +0.0.0.0 sview.avenuea.com +0.0.0.0 sweetsforfree.com +0.0.0.0 symbiosting.com +0.0.0.0 synad2.nuffnang.com.cn +0.0.0.0 synad.nuffnang.com.sg +0.0.0.0 syncaccess.net +0.0.0.0 sync.mathtag.com +0.0.0.0 syndicated.mondominishows.com +0.0.0.0 syndication.exoclick.com +0.0.0.0 syndication.traffichaus.com +0.0.0.0 syn.verticalacuity.com +0.0.0.0 sysadmin.map24.com +0.0.0.0 t1.adserver.com +0.0.0.0 t4.liverail.com +0.0.0.0 t-ads.adap.tv +0.0.0.0 tag1.webabacus.com +0.0.0.0 tag.admeld.com +0.0.0.0 tag.contextweb.com +0.0.0.0 tag.regieci.com +0.0.0.0 tags.bluekai.com +0.0.0.0 tags.hypeads.org +0.0.0.0 tag.webcompteur.com +0.0.0.0 tag.yieldoptimizer.com +0.0.0.0 taloussanomat.linkpulse.com +0.0.0.0 tap2-cdn.rubiconproject.com +0.0.0.0 tbtrack.zutrack.com +0.0.0.0 tcadops.ca +0.0.0.0 tcimg.com +0.0.0.0 t.cpmadvisors.com +0.0.0.0 tdameritrade.tt.omtrdc.net +0.0.0.0 tdc.advertorials.dk +0.0.0.0 tdkads.ads.dk +0.0.0.0 techreview.adbureau.net +0.0.0.0 techreview-images.adbureau.net +0.0.0.0 teeser.ru +0.0.0.0 te.kontera.com +0.0.0.0 tel.geenstijl.nl +0.0.0.0 textads.madisonavenue.com +0.0.0.0 textad.traficdublu.ro +0.0.0.0 text-link-ads.com +0.0.0.0 text-link-ads.ientry.com +0.0.0.0 text-link-ads-inventory.com +0.0.0.0 textsrv.com +0.0.0.0 tf.nexac.com +0.0.0.0 tgpmanager.com +0.0.0.0 the-binary-trader.biz +0.0.0.0 the-path-gateway.com +0.0.0.0 thepiratetrader.com +0.0.0.0 the-smart-stop.com +0.0.0.0 theuploadbusiness.com +0.0.0.0 theuseful.com +0.0.0.0 theuseful.net +0.0.0.0 thinknyc.eu-adcenter.net +0.0.0.0 thinktarget.com +0.0.0.0 thinlaptoprewards.com +0.0.0.0 this.content.served.by.adshuffle.com +0.0.0.0 thoughtfully-free.com +0.0.0.0 thruport.com +0.0.0.0 tmp3.nexac.com +0.0.0.0 tmsads.tribune.com +0.0.0.0 tmx.technoratimedia.com +0.0.0.0 tn.adserve.com +0.0.0.0 toads.osdn.com +0.0.0.0 tons-to-see.com +0.0.0.0 toolbar.adperium.com +0.0.0.0 top100-images.rambler.ru +0.0.0.0 top1site.3host.com +0.0.0.0 top5.mail.ru +0.0.0.0 topbrandrewards.com +0.0.0.0 topconsumergifts.com +0.0.0.0 topdemaroc.com +0.0.0.0 topica.advertserve.com +0.0.0.0 top.list.ru +0.0.0.0 toplist.throughput.de +0.0.0.0 topmarketcenter.com +0.0.0.0 touche.adcentric.proximi-t.com +0.0.0.0 tower.adexpedia.com +0.0.0.0 toy-offer.com +0.0.0.0 toy-offer.net +0.0.0.0 tpads.ovguide.com +0.0.0.0 tpc.googlesyndication.com +0.0.0.0 tps30.doubleverify.com +0.0.0.0 tps31.doubleverify.com +0.0.0.0 track.adbooth.net +0.0.0.0 trackadvertising.net +0.0.0.0 track-apmebf.cj.akadns.net +0.0.0.0 track.bigbrandpromotions.com +0.0.0.0 track.e7r.com.br +0.0.0.0 trackers.1st-affiliation.fr +0.0.0.0 tracking.craktraffic.com +0.0.0.0 tracking.edvisors.com +0.0.0.0 tracking.eurowebaffiliates.com +0.0.0.0 tracking.joker.com +0.0.0.0 tracking.keywordmax.com +0.0.0.0 tracking.veoxa.com +0.0.0.0 track.omgpl.com +0.0.0.0 track.the-members-section.com +0.0.0.0 track.vscash.com +0.0.0.0 tradearabia.advertserve.com +0.0.0.0 tradefx.advertserve.com +0.0.0.0 trafficbee.com +0.0.0.0 trafficrevenue.net +0.0.0.0 traffictraders.com +0.0.0.0 traffprofit.com +0.0.0.0 trafmag.com +0.0.0.0 trafsearchonline.com +0.0.0.0 traktum.com +0.0.0.0 travel-leisure-bonuspath.com +0.0.0.0 travel-leisure-premiumblvd.com +0.0.0.0 traveller-offer.com +0.0.0.0 traveller-offer.net +0.0.0.0 travelncs.com +0.0.0.0 trekmedia.net +0.0.0.0 trendnews.com +0.0.0.0 trk.alskeip.com +0.0.0.0 trk.etrigue.com +0.0.0.0 trk.yadomedia.com +0.0.0.0 trustsitesite.com +0.0.0.0 trvlnet.adbureau.net +0.0.0.0 trvlnet-images.adbureau.net +0.0.0.0 tr.wl.webads.nl +0.0.0.0 tsms-ad.tsms.com +0.0.0.0 tste.ivillage.com +0.0.0.0 tste.mcclatchyinteractive.com +0.0.0.0 tste.startribune.com +0.0.0.0 ttarget.adbureau.net +0.0.0.0 ttuk.offers4u.mobi +0.0.0.0 turnerapac.d1.sc.omtrdc.net +0.0.0.0 tv2no.linkpulse.com +0.0.0.0 tvshowsnow.tvmax.hop.clickbank.net +0.0.0.0 tw.adserver.yahoo.com +0.0.0.0 twnads.weather.ca # Canadian Weather Network +0.0.0.0 uac.advertising.com +0.0.0.0 u-ads.adap.tv +0.0.0.0 uav.tidaltv.com +0.0.0.0 uc.csc.adserver.yahoo.com +0.0.0.0 uedata.amazon.com +0.0.0.0 uelbdc74fn.s.ad6media.fr +0.0.0.0 uf2.svrni.ca +0.0.0.0 ugo.eu-adcenter.net +0.0.0.0 ui.ppjol.com +0.0.0.0 uk.adserver.yahoo.com +0.0.0.0 uleadstrk.com +0.0.0.0 ultimatefashiongifts.com +0.0.0.0 ultrabestportal.com +0.0.0.0 um.simpli.fi +0.0.0.0 undertonenetworks.com +0.0.0.0 uole.ad.uol.com.br +0.0.0.0 u.openx.net +0.0.0.0 upload.adtech.de +0.0.0.0 upload.adtech.fr +0.0.0.0 upload.adtech.us +0.0.0.0 uproar.com +0.0.0.0 uproar.fortunecity.com +0.0.0.0 upsellit.com +0.0.0.0 us.adserver.yahoo.com +0.0.0.0 usads.vibrantmedia.com +0.0.0.0 usatoday.app.ur.gcion.com +0.0.0.0 usatravel-specials.com +0.0.0.0 usatravel-specials.net +0.0.0.0 us-choicevalue.com +0.0.0.0 usemax.de +0.0.0.0 usr.marketgid.com +0.0.0.0 us-topsites.com +0.0.0.0 ut.addthis.com +0.0.0.0 utarget.ru +0.0.0.0 utils.media-general.com +0.0.0.0 utils.mediageneral.com +0.0.0.0 vad.adbasket.net +0.0.0.0 vads.adbrite.com +0.0.0.0 van.ads.link4ads.com +0.0.0.0 vast.bp3845260.btrll.com +0.0.0.0 vast.bp3846806.btrll.com +0.0.0.0 vast.bp3846885.btrll.com +0.0.0.0 vast.tubemogul.com +0.0.0.0 vclick.adbrite.com +0.0.0.0 venus.goclick.com +0.0.0.0 ve.tscapeplay.com +0.0.0.0 v.fwmrm.net +0.0.0.0 vibrantmedia.com +0.0.0.0 videocop.com +0.0.0.0 videoegg.adbureau.net +0.0.0.0 video-game-rewards-central.com +0.0.0.0 videogamerewardscentral.com +0.0.0.0 videos.fleshlight.com +0.0.0.0 videoslots.888.com +0.0.0.0 videos.video-loader.com +0.0.0.0 view.atdmt.com #This may interfere with downloading from Microsoft, MSDN and TechNet websites. +0.0.0.0 view.avenuea.com +0.0.0.0 view.binlayer.com +0.0.0.0 view.iballs.a1.avenuea.com +0.0.0.0 view.jamba.de +0.0.0.0 view.netrams.com +0.0.0.0 views.m4n.nl +0.0.0.0 viglink.com +0.0.0.0 viglink.pgpartner.com +0.0.0.0 villagevoicecollect.247realmedia.com +0.0.0.0 vip1.tw.adserver.yahoo.com +0.0.0.0 vipfastmoney.com +0.0.0.0 vk.18sexporn.ru +0.0.0.0 vmcsatellite.com +0.0.0.0 vmix.adbureau.net +0.0.0.0 vms.boldchat.com +0.0.0.0 vnu.eu-adcenter.net +0.0.0.0 vodafoneit.solution.weborama.fr +0.0.0.0 vp.tscapeplay.com +0.0.0.0 vu.veoxa.com +0.0.0.0 vzarabotke.ru +0.0.0.0 w100.am15.net +0.0.0.0 w10.am15.net +0.0.0.0 w10.centralmediaserver.com +0.0.0.0 w11.am15.net +0.0.0.0 w11.centralmediaserver.com +0.0.0.0 w12.am15.net +0.0.0.0 w13.am15.net +0.0.0.0 w14.am15.net +0.0.0.0 w15.am15.net +0.0.0.0 w16.am15.net +0.0.0.0 w17.am15.net +0.0.0.0 w18.am15.net +0.0.0.0 w19.am15.net +0.0.0.0 w1.am15.net +0.0.0.0 w1.webcompteur.com +0.0.0.0 w20.am15.net +0.0.0.0 w21.am15.net +0.0.0.0 w22.am15.net +0.0.0.0 w23.am15.net +0.0.0.0 w24.am15.net +0.0.0.0 w25.am15.net +0.0.0.0 w26.am15.net +0.0.0.0 w27.am15.net +0.0.0.0 w28.am15.net +0.0.0.0 w29.am15.net +0.0.0.0 w2.am15.net +0.0.0.0 w30.am15.net +0.0.0.0 w31.am15.net +0.0.0.0 w32.am15.net +0.0.0.0 w33.am15.net +0.0.0.0 w34.am15.net +0.0.0.0 w35.am15.net +0.0.0.0 w36.am15.net +0.0.0.0 w37.am15.net +0.0.0.0 w38.am15.net +0.0.0.0 w39.am15.net +0.0.0.0 w3.am15.net +0.0.0.0 w40.am15.net +0.0.0.0 w41.am15.net +0.0.0.0 w42.am15.net +0.0.0.0 w43.am15.net +0.0.0.0 w44.am15.net +0.0.0.0 w45.am15.net +0.0.0.0 w46.am15.net +0.0.0.0 w47.am15.net +0.0.0.0 w48.am15.net +0.0.0.0 w49.am15.net +0.0.0.0 w4.am15.net +0.0.0.0 w50.am15.net +0.0.0.0 w51.am15.net +0.0.0.0 w52.am15.net +0.0.0.0 w53.am15.net +0.0.0.0 w54.am15.net +0.0.0.0 w55.am15.net +0.0.0.0 w56.am15.net +0.0.0.0 w57.am15.net +0.0.0.0 w58.am15.net +0.0.0.0 w59.am15.net +0.0.0.0 w5.am15.net +0.0.0.0 w60.am15.net +0.0.0.0 w61.am15.net +0.0.0.0 w62.am15.net +0.0.0.0 w63.am15.net +0.0.0.0 w64.am15.net +0.0.0.0 w65.am15.net +0.0.0.0 w66.am15.net +0.0.0.0 w67.am15.net +0.0.0.0 w68.am15.net +0.0.0.0 w69.am15.net +0.0.0.0 w6.am15.net +0.0.0.0 w70.am15.net +0.0.0.0 w71.am15.net +0.0.0.0 w72.am15.net +0.0.0.0 w73.am15.net +0.0.0.0 w74.am15.net +0.0.0.0 w75.am15.net +0.0.0.0 w76.am15.net +0.0.0.0 w77.am15.net +0.0.0.0 w78.am15.net +0.0.0.0 w79.am15.net +0.0.0.0 w7.am15.net +0.0.0.0 w80.am15.net +0.0.0.0 w81.am15.net +0.0.0.0 w82.am15.net +0.0.0.0 w83.am15.net +0.0.0.0 w84.am15.net +0.0.0.0 w85.am15.net +0.0.0.0 w86.am15.net +0.0.0.0 w87.am15.net +0.0.0.0 w88.am15.net +0.0.0.0 w89.am15.net +0.0.0.0 w8.am15.net +0.0.0.0 w90.am15.net +0.0.0.0 w91.am15.net +0.0.0.0 w92.am15.net +0.0.0.0 w93.am15.net +0.0.0.0 w94.am15.net +0.0.0.0 w95.am15.net +0.0.0.0 w96.am15.net +0.0.0.0 w97.am15.net +0.0.0.0 w98.am15.net +0.0.0.0 w99.am15.net +0.0.0.0 w9.am15.net +0.0.0.0 wahoha.com +0.0.0.0 warp.crystalad.com +0.0.0.0 wdm29.com +0.0.0.0 web1b.netreflector.com +0.0.0.0 web.adblade.com +0.0.0.0 webads.bizservers.com +0.0.0.0 webads.nl +0.0.0.0 webcompteur.com +0.0.0.0 webhosting-ads.home.pl +0.0.0.0 webmdcom.tt.omtrdc.net +0.0.0.0 web.nyc.ads.juno.co +0.0.0.0 webservices-rewardpath.com +0.0.0.0 websurvey.spa-mr.com +0.0.0.0 wegetpaid.net +0.0.0.0 w.ic.tynt.com +0.0.0.0 widget3.linkwithin.com +0.0.0.0 widget5.linkwithin.com +0.0.0.0 widget.crowdignite.com +0.0.0.0 widget.plugrush.com +0.0.0.0 widgets.outbrain.com +0.0.0.0 widgets.tcimg.com +0.0.0.0 wigetmedia.com +0.0.0.0 wikiforosh.ir +0.0.0.0 williamhill.es +0.0.0.0 wmedia.rotator.hadj7.adjuggler.net +0.0.0.0 wordplaywhiz.com +0.0.0.0 work-offer.com +0.0.0.0 worry-free-savings.com +0.0.0.0 wppluginspro.com +0.0.0.0 ws.addthis.com +0.0.0.0 wtp101.com +0.0.0.0 ww251.smartadserver.com +0.0.0.0 wwbtads.com +0.0.0.0 www10.ad.tomshardware.com +0.0.0.0 www10.glam.com +0.0.0.0 www10.indiads.com +0.0.0.0 www10.paypopup.com +0.0.0.0 www11.ad.tomshardware.com +0.0.0.0 www123.glam.com +0.0.0.0 www.123specialgifts.com +0.0.0.0 www12.ad.tomshardware.com +0.0.0.0 www12.glam.com +0.0.0.0 www13.ad.tomshardware.com +0.0.0.0 www13.glam.com +0.0.0.0 www14.ad.tomshardware.com +0.0.0.0 www15.ad.tomshardware.com +0.0.0.0 www17.glam.com +0.0.0.0 www18.glam.com +0.0.0.0 www1.adireland.com +0.0.0.0 www1.ad.tomshardware.com +0.0.0.0 www1.bannerspace.com +0.0.0.0 www1.belboon.de +0.0.0.0 www1.clicktorrent.info +0.0.0.0 www1.mpnrs.com +0.0.0.0 www1.popinads.com +0.0.0.0 www1.safenyplanet.in +0.0.0.0 www210.paypopup.com +0.0.0.0 www211.paypopup.com +0.0.0.0 www212.paypopup.com +0.0.0.0 www213.paypopup.com +0.0.0.0 www.247realmedia.com +0.0.0.0 www24a.glam.com +0.0.0.0 www24.glam.com +0.0.0.0 www25a.glam.com +0.0.0.0 www25.glam.com +0.0.0.0 www2.adireland.com +0.0.0.0 www2.adserverpub.com +0.0.0.0 www2.ad.tomshardware.com +0.0.0.0 www.2-art-coliseum.com +0.0.0.0 www2.bannerspace.com +0.0.0.0 www2.glam.com +0.0.0.0 www30a1.glam.com +0.0.0.0 www30a1-orig.glam.com +0.0.0.0 www30a2-orig.glam.com +0.0.0.0 www30a3.glam.com +0.0.0.0 www30a3-orig.glam.com +0.0.0.0 www30a7.glam.com +0.0.0.0 www30.glam.com +0.0.0.0 www30l2.glam.com +0.0.0.0 www30t1-orig.glam.com +0.0.0.0 www.321cba.com +0.0.0.0 www35f.glam.com +0.0.0.0 www35jm.glam.com +0.0.0.0 www35t.glam.com +0.0.0.0 www.360ads.com +0.0.0.0 www3.addthis.com +0.0.0.0 www3.adireland.com +0.0.0.0 www3.ad.tomshardware.com +0.0.0.0 www3.bannerspace.com +0.0.0.0 www3.game-advertising-online.com +0.0.0.0 www.3qqq.net +0.0.0.0 www.3turtles.com +0.0.0.0 www.404errorpage.com +0.0.0.0 www4.ad.tomshardware.com +0.0.0.0 www4.bannerspace.com +0.0.0.0 www4.glam.com +0.0.0.0 www4.smartadserver.com +0.0.0.0 www5.ad.tomshardware.com +0.0.0.0 www5.bannerspace.com +0.0.0.0 www.5thavenue.com +0.0.0.0 www6.ad.tomshardware.com +0.0.0.0 www6.bannerspace.com +0.0.0.0 www74.valueclick.com +0.0.0.0 www.7500.com +0.0.0.0 www7.ad.tomshardware.com +0.0.0.0 www7.bannerspace.com +0.0.0.0 www.7bpeople.com +0.0.0.0 www.7cnbcnews.com +0.0.0.0 www.805m.com +0.0.0.0 www81.valueclick.com +0.0.0.0 www.888casino.com +0.0.0.0 www.888.com +0.0.0.0 www.888poker.com +0.0.0.0 www8.ad.tomshardware.com +0.0.0.0 www8.bannerspace.com +0.0.0.0 www.961.com +0.0.0.0 www9.ad.tomshardware.com +0.0.0.0 www9.paypopup.com +0.0.0.0 www.abrogatesdv.info +0.0.0.0 www.actiondesk.com +0.0.0.0 www.action.ientry.net +0.0.0.0 www.adbanner.gr +0.0.0.0 www.adbrite.com +0.0.0.0 www.adcanadian.com +0.0.0.0 www.adcash.com +0.0.0.0 www.addthiscdn.com +0.0.0.0 www.adengage.com +0.0.0.0 www.adfunkyserver.com +0.0.0.0 www.adfusion.com +0.0.0.0 www.adimages.beeb.com +0.0.0.0 www.adipics.com +0.0.0.0 www.adireland.com +0.0.0.0 www.adjmps.com +0.0.0.0 www.adjug.com +0.0.0.0 www.adloader.com +0.0.0.0 www.adlogix.com +0.0.0.0 www.admex.com +0.0.0.0 www.adnet.biz +0.0.0.0 www.adnet.com +0.0.0.0 www.adnet.de +0.0.0.0 www.adobee.com +0.0.0.0 www.adocean.pl +0.0.0.0 www.adotube.com +0.0.0.0 www.adpepper.dk +0.0.0.0 www.adpowerzone.com +0.0.0.0 www.adquest3d.com +0.0.0.0 www.adreporting.com +0.0.0.0 www.ads2srv.com +0.0.0.0 www.adsentnetwork.com +0.0.0.0 www.adserver.co.il +0.0.0.0 www.adserver.com +0.0.0.0 www.adserver.com.my +0.0.0.0 www.adserver.com.pl +0.0.0.0 www.adserver-espnet.sportszone.net +0.0.0.0 www.adserver.janes.net +0.0.0.0 www.adserver.janes.org +0.0.0.0 www.adserver.jolt.co.uk +0.0.0.0 www.adserver.net +0.0.0.0 www.adserver.ugo.nl +0.0.0.0 www.adservtech.com +0.0.0.0 www.adsinimages.com +0.0.0.0 www.ads.joetec.net +0.0.0.0 www.adsoftware.com +0.0.0.0 www.ad-souk.com +0.0.0.0 www.adspics.com +0.0.0.0 www.ads.revenue.net +0.0.0.0 www.adstogo.com +0.0.0.0 www.adstreams.org +0.0.0.0 www.adtaily.pl +0.0.0.0 www.adtechus.com +0.0.0.0 www.ad.tgdaily.com +0.0.0.0 www.adtlgc.com +0.0.0.0 www.ad.tomshardware.com +0.0.0.0 www.adtrader.com +0.0.0.0 www.adtrix.com +0.0.0.0 www.ad.twitchguru.com +0.0.0.0 www.ad-up.com +0.0.0.0 www.advaliant.com +0.0.0.0 www.advertising-department.com +0.0.0.0 www.advertlets.com +0.0.0.0 www.advertpro.com +0.0.0.0 www.adverts.dcthomson.co.uk +0.0.0.0 www.advertyz.com +0.0.0.0 www.ad-words.ru +0.0.0.0 www.afcyhf.com +0.0.0.0 www.affiliateclick.com +0.0.0.0 www.affiliate-fr.com +0.0.0.0 www.affiliation-france.com +0.0.0.0 www.afform.co.uk +0.0.0.0 www.affpartners.com +0.0.0.0 www.afterdownload.com +0.0.0.0 www.agkn.com +0.0.0.0 www.alexxe.com +0.0.0.0 www.allosponsor.com +0.0.0.0 www.annuaire-autosurf.com +0.0.0.0 www.apparelncs.com +0.0.0.0 www.apparel-offer.com +0.0.0.0 www.applelounge.com +0.0.0.0 www.appnexus.com +0.0.0.0 www.art-music-rewardpath.com +0.0.0.0 www.art-offer.com +0.0.0.0 www.art-offer.net +0.0.0.0 www.art-photo-music-premiumblvd.com +0.0.0.0 www.art-photo-music-rewardempire.com +0.0.0.0 www.art-photo-music-savingblvd.com +0.0.0.0 www.auctionshare.net +0.0.0.0 www.aureate.com +0.0.0.0 www.autohipnose.com +0.0.0.0 www.automotive-offer.com +0.0.0.0 www.automotive-rewardpath.com +0.0.0.0 www.avcounter10.com +0.0.0.0 www.avsads.com +0.0.0.0 www.a.websponsors.com +0.0.0.0 www.awesomevipoffers.com +0.0.0.0 www.awin1.com +0.0.0.0 www.awltovhc.com #qksrv +0.0.0.0 www.bananacashback.com +0.0.0.0 www.banner4all.dk +0.0.0.0 www.bannerads.de +0.0.0.0 www.bannerbackup.com +0.0.0.0 www.bannerconnect.net +0.0.0.0 www.banners.paramountzone.com +0.0.0.0 www.bannersurvey.biz +0.0.0.0 www.banstex.com +0.0.0.0 www.bargainbeautybuys.com +0.0.0.0 www.bbelements.com +0.0.0.0 www.bestshopperrewards.com +0.0.0.0 www.bet365.com +0.0.0.0 www.bidtraffic.com +0.0.0.0 www.bidvertiser.com +0.0.0.0 www.bigbrandpromotions.com +0.0.0.0 www.bigbrandrewards.com +0.0.0.0 www.biggestgiftrewards.com +0.0.0.0 www.binarysystem4u.com +0.0.0.0 www.biz-offer.com +0.0.0.0 www.bizopprewards.com +0.0.0.0 www.blasphemysfhs.info +0.0.0.0 www.blatant8jh.info +0.0.0.0 www.bluediamondoffers.com +0.0.0.0 www.bnnr.nl +0.0.0.0 www.bonzi.com +0.0.0.0 www.bookclub-offer.com +0.0.0.0 www.books-media-edu-premiumblvd.com +0.0.0.0 www.books-media-edu-rewardempire.com +0.0.0.0 www.books-media-rewardpath.com +0.0.0.0 www.boonsolutions.com +0.0.0.0 www.bostonsubwayoffer.com +0.0.0.0 www.brandrewardcentral.com +0.0.0.0 www.brandsurveypanel.com +0.0.0.0 www.brokertraffic.com +0.0.0.0 www.budsinc.com +0.0.0.0 www.bugsbanner.it +0.0.0.0 www.bulkclicks.com +0.0.0.0 www.bulletads.com +0.0.0.0 www.burstnet.com +0.0.0.0 www.business-rewardpath.com +0.0.0.0 www.bus-offer.com +0.0.0.0 www.buttcandy.com +0.0.0.0 www.buwobarun.cn +0.0.0.0 www.buycheapadvertising.com +0.0.0.0 www.buyhitscheap.com +0.0.0.0 www.capath.com +0.0.0.0 www.careers-rewardpath.com +0.0.0.0 www.car-truck-boat-bonuspath.com +0.0.0.0 www.car-truck-boat-premiumblvd.com +0.0.0.0 www.cashback.co.uk +0.0.0.0 www.cashbackwow.co.uk +0.0.0.0 www.cashcount.com +0.0.0.0 www.casino770.com +0.0.0.0 www.catalinkcashback.com +0.0.0.0 www.cell-phone-giveaways.com +0.0.0.0 www.cellphoneincentives.com +0.0.0.0 www.chainsawoffer.com +0.0.0.0 www.chartbeat.com +0.0.0.0 www.choicedealz.com +0.0.0.0 www.choicesurveypanel.com +0.0.0.0 www.christianbusinessadvertising.com +0.0.0.0 www.ciqugasox.cn +0.0.0.0 www.claimfreerewards.com +0.0.0.0 www.clashmediausa.com +0.0.0.0 www.click10.com +0.0.0.0 www.click4click.com +0.0.0.0 www.clickbank.com +0.0.0.0 www.clickdensity.com +0.0.0.0 www.click-find-save.com +0.0.0.0 www.click-see-save.com +0.0.0.0 www.clicksor.com +0.0.0.0 www.clicksotrk.com +0.0.0.0 www.clicktale.com +0.0.0.0 www.clicktale.net +0.0.0.0 www.clickthruserver.com +0.0.0.0 www.clickthrutraffic.com +0.0.0.0 www.clicktilluwin.com +0.0.0.0 www.clicktorrent.info +0.0.0.0 www.clickxchange.com +0.0.0.0 www.closeoutproductsreview.com +0.0.0.0 www.cm1359.com +0.0.0.0 www.come-see-it-all.com +0.0.0.0 www.commerce-offer.com +0.0.0.0 www.commerce-rewardpath.com +0.0.0.0 www.computer-offer.com +0.0.0.0 www.computer-offer.net +0.0.0.0 www.computers-electronics-rewardpath.com +0.0.0.0 www.computersncs.com +0.0.0.0 www.consumergiftcenter.com +0.0.0.0 www.consumerincentivenetwork.com +0.0.0.0 www.consumer-org.com +0.0.0.0 www.contaxe.com +0.0.0.0 www.contextuads.com +0.0.0.0 www.contextweb.com +0.0.0.0 www.cookingtiprewards.com +0.0.0.0 www.coolconcepts.nl +0.0.0.0 www.cool-premiums.com +0.0.0.0 www.cool-premiums-now.com +0.0.0.0 www.coolpremiumsnow.com +0.0.0.0 www.coolsavings.com +0.0.0.0 www.coreglead.co.uk +0.0.0.0 www.cosmeticscentre.uk.com +0.0.0.0 www.cpabank.com +0.0.0.0 www.cpmadvisors.com +0.0.0.0 www.crazypopups.com +0.0.0.0 www.crazywinnings.com +0.0.0.0 www.crediblegfj.info +0.0.0.0 www.crispads.com +0.0.0.0 www.crowdgravity.com +0.0.0.0 www.crowdignite.com +0.0.0.0 www.ctbdev.net +0.0.0.0 www.cyber-incentives.com +0.0.0.0 www.d03x2011.com +0.0.0.0 www.da-ads.com +0.0.0.0 www.daily-saver.com +0.0.0.0 www.datatech.es +0.0.0.0 www.datingadvertising.com +0.0.0.0 www.dctracking.com +0.0.0.0 www.depravedwhores.com +0.0.0.0 www.designbloxlive.com +0.0.0.0 www.dgmaustralia.com +0.0.0.0 www.dietoftoday.ca.pn +0.0.0.0 www.digimedia.com +0.0.0.0 www.directnetadvertising.net +0.0.0.0 www.directpowerrewards.com +0.0.0.0 www.dirtyrhino.com +0.0.0.0 www.discount-savings-more.com +0.0.0.0 www.djugoogs.com +0.0.0.0 www.dl-plugin.com +0.0.0.0 www.drowle.com +0.0.0.0 www.dutchsales.org +0.0.0.0 www.earnmygift.com +0.0.0.0 www.earnpointsandgifts.com +0.0.0.0 www.easyadservice.com +0.0.0.0 www.e-bannerx.com +0.0.0.0 www.ebaybanner.com +0.0.0.0 www.education-rewardpath.com +0.0.0.0 www.edu-offer.com +0.0.0.0 www.electronics-bonuspath.com +0.0.0.0 www.electronics-offer.net +0.0.0.0 www.electronicspresent.com +0.0.0.0 www.electronics-rewardpath.com +0.0.0.0 www.emailadvantagegroup.com +0.0.0.0 www.emailproductreview.com +0.0.0.0 www.emarketmakers.com +0.0.0.0 www.entertainment-rewardpath.com +0.0.0.0 www.entertainment-specials.com +0.0.0.0 www.eshopads2.com +0.0.0.0 www.euros4click.de +0.0.0.0 www.exclusivegiftcards.com +0.0.0.0 www.eyeblaster-bs.com +0.0.0.0 www.eyewonder.com #: Interactive Digital Advertising, Rich Media Ads, Flash Ads, Online Advertising +0.0.0.0 www.falkag.de +0.0.0.0 www.family-offer.com +0.0.0.0 www.fast-adv.it +0.0.0.0 www.fatcatrewards.com +0.0.0.0 www.feedjit.com +0.0.0.0 www.feedstermedia.com +0.0.0.0 www.fif49.info +0.0.0.0 www.finance-offer.com +0.0.0.0 www.finder.cox.net +0.0.0.0 www.fineclicks.com +0.0.0.0 www.flagcounter.com +0.0.0.0 www.flowers-offer.com +0.0.0.0 www.flu23.com +0.0.0.0 www.focalex.com +0.0.0.0 www.folloyu.com +0.0.0.0 www.food-drink-bonuspath.com +0.0.0.0 www.food-drink-rewardpath.com +0.0.0.0 www.foodmixeroffer.com +0.0.0.0 www.food-offer.com +0.0.0.0 www.fpctraffic2.com +0.0.0.0 www.freeadguru.com +0.0.0.0 www.freebiegb.co.uk +0.0.0.0 www.freecameraonus.com +0.0.0.0 www.freecameraprovider.com +0.0.0.0 www.freecamerasource.com +0.0.0.0 www.freecamerauk.co.uk +0.0.0.0 www.freecamsecrets.com +0.0.0.0 www.freecoolgift.com +0.0.0.0 www.freedesignerhandbagreviews.com +0.0.0.0 www.freedinnersource.com +0.0.0.0 www.freedvddept.com +0.0.0.0 www.freeelectronicscenter.com +0.0.0.0 www.freeelectronicsdepot.com +0.0.0.0 www.freeelectronicsonus.com +0.0.0.0 www.freeelectronicssource.com +0.0.0.0 www.freeentertainmentsource.com +0.0.0.0 www.freefoodprovider.com +0.0.0.0 www.freefoodsource.com +0.0.0.0 www.freefuelcard.com +0.0.0.0 www.freefuelcoupon.com +0.0.0.0 www.freegasonus.com +0.0.0.0 www.freegasprovider.com +0.0.0.0 www.free-gift-cards-now.com +0.0.0.0 www.freegiftcardsource.com +0.0.0.0 www.freegiftreward.com +0.0.0.0 www.free-gifts-comp.com +0.0.0.0 www.freeipodnanouk.co.uk +0.0.0.0 www.freeipoduk.com +0.0.0.0 www.freeipoduk.co.uk +0.0.0.0 www.freelaptopgift.com +0.0.0.0 www.freelaptopnation.com +0.0.0.0 www.free-laptop-reward.com +0.0.0.0 www.freelaptopreward.com +0.0.0.0 www.freelaptopwebsites.com +0.0.0.0 www.freenation.com +0.0.0.0 www.freeoffers-toys.com +0.0.0.0 www.freepayasyougotopupuk.co.uk +0.0.0.0 www.freeplasmanation.com +0.0.0.0 www.freerestaurantprovider.com +0.0.0.0 www.freerestaurantsource.com +0.0.0.0 www.freeshoppingprovider.com +0.0.0.0 www.freeshoppingsource.com +0.0.0.0 www.friendlyduck.com +0.0.0.0 www.frontpagecash.com +0.0.0.0 www.ftjcfx.com #commission junction +0.0.0.0 www.fusionbanners.com +0.0.0.0 www.gameconsolerewards.com +0.0.0.0 www.games-toys-bonuspath.com +0.0.0.0 www.games-toys-free.com +0.0.0.0 www.games-toys-rewardpath.com +0.0.0.0 www.gatoradvertisinginformationnetwork.com +0.0.0.0 www.getacool100.com +0.0.0.0 www.getacool500.com +0.0.0.0 www.getacoollaptop.com +0.0.0.0 www.getacooltv.com +0.0.0.0 www.getagiftonline.com +0.0.0.0 www.getloan.com +0.0.0.0 www.getmyfreebabystuff.com +0.0.0.0 www.getmyfreegear.com +0.0.0.0 www.getmyfreegiftcard.com +0.0.0.0 www.getmyfreelaptop.com +0.0.0.0 www.getmyfreelaptophere.com +0.0.0.0 www.getmyfreeplasma.com +0.0.0.0 www.getmylaptopfree.com +0.0.0.0 www.getmyplasmatv.com +0.0.0.0 www.getspecialgifts.com +0.0.0.0 www.getyourfreecomputer.com +0.0.0.0 www.getyourfreetv.com +0.0.0.0 www.giftcardchallenge.com +0.0.0.0 www.giftcardsurveys.us.com +0.0.0.0 www.giftrewardzone.com +0.0.0.0 www.gifts-flowers-rewardpath.com +0.0.0.0 www.gimmethatreward.com +0.0.0.0 www.gmads.net +0.0.0.0 www.go-free-gifts.com +0.0.0.0 www.gofreegifts.com +0.0.0.0 www.goody-garage.com +0.0.0.0 www.gopopup.com +0.0.0.0 www.grabbit-rabbit.com +0.0.0.0 www.greasypalm.com +0.0.0.0 www.grz67.com +0.0.0.0 www.guesstheview.com +0.0.0.0 www.guptamedianetwork.com +0.0.0.0 www.happydiscountspecials.com +0.0.0.0 www.healthbeautyncs.com +0.0.0.0 www.health-beauty-rewardpath.com +0.0.0.0 www.health-beauty-savingblvd.com +0.0.0.0 www.healthclicks.co.uk +0.0.0.0 www.hebdotop.com +0.0.0.0 www.hightrafficads.com +0.0.0.0 www.holiday-gift-offers.com +0.0.0.0 www.holidayproductpromo.com +0.0.0.0 www.holidayshoppingrewards.com +0.0.0.0 www.home4bizstart.ru +0.0.0.0 www.homeelectronicproducts.com +0.0.0.0 www.home-garden-premiumblvd.com +0.0.0.0 www.home-garden-rewardempire.com +0.0.0.0 www.home-garden-rewardpath.com +0.0.0.0 www.hooqy.com +0.0.0.0 www.hot-daily-deal.com +0.0.0.0 www.hotgiftzone.com +0.0.0.0 www.hotkeys.com +0.0.0.0 www.hot-product-hangout.com +0.0.0.0 www.idealcasino.net +0.0.0.0 www.idirect.com +0.0.0.0 www.iicdn.com +0.0.0.0 www.ijacko.net +0.0.0.0 www.ilovecheating.com +0.0.0.0 www.impressionaffiliate.com +0.0.0.0 www.impressionaffiliate.mobi +0.0.0.0 www.impressionlead.com +0.0.0.0 www.impressionperformance.biz +0.0.0.0 www.incentivegateway.com +0.0.0.0 www.incentiverewardcenter.com +0.0.0.0 www.incentive-scene.com +0.0.0.0 www.inckamedia.com +0.0.0.0 www.indiads.com +0.0.0.0 www.infinite-ads.com # www.shareactor.com +0.0.0.0 www.ins-offer.com +0.0.0.0 www.insurance-rewardpath.com +0.0.0.0 www.intela.com +0.0.0.0 www.interstitialzone.com +0.0.0.0 www.intnet-offer.com +0.0.0.0 www.invitefashion.com +0.0.0.0 www.is1.clixgalore.com +0.0.0.0 www.itrackerpro.com +0.0.0.0 www.itsfree123.com +0.0.0.0 www.iwantmyfreecash.com +0.0.0.0 www.iwantmy-freelaptop.com +0.0.0.0 www.iwantmyfree-laptop.com +0.0.0.0 www.iwantmyfreelaptop.com +0.0.0.0 www.iwantmygiftcard.com +0.0.0.0 www.jersey-offer.com +0.0.0.0 www.jetseeker.com +0.0.0.0 www.jivox.com +0.0.0.0 www.jl29jd25sm24mc29.com +0.0.0.0 www.joinfree.ro +0.0.0.0 www.jxliu.com +0.0.0.0 www.keybinary.com +0.0.0.0 www.keywordblocks.com +0.0.0.0 www.kitaramarketplace.com +0.0.0.0 www.kitaramedia.com +0.0.0.0 www.kitaratrk.com +0.0.0.0 www.kixer.com +0.0.0.0 www.kliksaya.com +0.0.0.0 www.kmdl101.com +0.0.0.0 www.kontera.com +0.0.0.0 www.konversation.com +0.0.0.0 www.kreaffiliation.com +0.0.0.0 www.kuhdi.com +0.0.0.0 www.ladyclicks.ru +0.0.0.0 www.laptopreportcard.com +0.0.0.0 www.laptoprewards.com +0.0.0.0 www.laptoprewardsgroup.com +0.0.0.0 www.laptoprewardszone.com +0.0.0.0 www.larivieracasino.com +0.0.0.0 www.lasthr.info +0.0.0.0 www.lduhtrp.net #commission junction +0.0.0.0 www.le1er.net +0.0.0.0 www.leadgreed.com +0.0.0.0 www.learning-offer.com +0.0.0.0 www.legal-rewardpath.com +0.0.0.0 www.leisure-offer.com +0.0.0.0 www.linkhut.com +0.0.0.0 www.linkpulse.com +0.0.0.0 www.linkwithin.com +0.0.0.0 www.liveinternet.ru +0.0.0.0 www.lottoforever.com +0.0.0.0 www.lpcloudsvr302.com +0.0.0.0 www.lucky-day-uk.com +0.0.0.0 www.macombdisplayads.com +0.0.0.0 www.marketing-rewardpath.com +0.0.0.0 www.mastertracks.be +0.0.0.0 www.maxbounty.com +0.0.0.0 www.mb01.com +0.0.0.0 www.media2.travelzoo.com +0.0.0.0 www.media-motor.com +0.0.0.0 www.medical-offer.com +0.0.0.0 www.medical-rewardpath.com +0.0.0.0 www.merchantapp.com +0.0.0.0 www.merlin.co.il +0.0.0.0 www.mgid.com +0.0.0.0 www.mightymagoo.com +0.0.0.0 www.mktg-offer.com +0.0.0.0 www.mlntracker.com +0.0.0.0 www.mochibot.com +0.0.0.0 www.morefreecamsecrets.com +0.0.0.0 www.morevisits.info +0.0.0.0 www.mp3playersource.com +0.0.0.0 www.mpression.net +0.0.0.0 www.myadsl.co.za +0.0.0.0 www.myaffiliateprogram.com +0.0.0.0 www.myairbridge.com +0.0.0.0 www.mycashback.co.uk +0.0.0.0 www.mycelloffer.com +0.0.0.0 www.mychoicerewards.com +0.0.0.0 www.myexclusiverewards.com +0.0.0.0 www.myfreedinner.com +0.0.0.0 www.myfreegifts.co.uk +0.0.0.0 www.myfreemp3player.com +0.0.0.0 www.mygiftcardcenter.com +0.0.0.0 www.mygreatrewards.com +0.0.0.0 www.myoffertracking.com +0.0.0.0 www.my-reward-channel.com +0.0.0.0 www.my-rewardsvault.com +0.0.0.0 www.myseostats.com +0.0.0.0 www.my-stats.com +0.0.0.0 www.myuitm.com +0.0.0.0 www.myusersonline.com +0.0.0.0 www.na47.com +0.0.0.0 www.nationalissuepanel.com +0.0.0.0 www.nationalsurveypanel.com +0.0.0.0 www.nctracking.com +0.0.0.0 www.nearbyad.com +0.0.0.0 www.needadvertising.com +0.0.0.0 www.neptuneads.com +0.0.0.0 www.netpalnow.com +0.0.0.0 www.netpaloffers.net +0.0.0.0 www.news6health.com +0.0.0.0 www.newssourceoftoday.com +0.0.0.0 www.nospartenaires.com +0.0.0.0 www.nothing-but-value.com +0.0.0.0 www.nysubwayoffer.com +0.0.0.0 www.offerx.co.uk +0.0.0.0 www.oinadserve.com +0.0.0.0 www.onlinebestoffers.net +0.0.0.0 www.ontheweb.com +0.0.0.0 www.opendownload.de +0.0.0.0 www.openload.de +0.0.0.0 www.optiad.net +0.0.0.0 www.paperg.com +0.0.0.0 www.parsads.com +0.0.0.0 www.pathforpoints.com +0.0.0.0 www.paypopup.com +0.0.0.0 www.people-choice-sites.com +0.0.0.0 www.personalcare-offer.com +0.0.0.0 www.personalcashbailout.com +0.0.0.0 www.phoenixads.co.in +0.0.0.0 www.pick-savings.com +0.0.0.0 www.plasmatv4free.com +0.0.0.0 www.plasmatvreward.com +0.0.0.0 www.politicalopinionsurvey.com +0.0.0.0 www.poponclick.com +0.0.0.0 www.popupad.net +0.0.0.0 www.popupdomination.com +0.0.0.0 www.popuptraffic.com +0.0.0.0 www.postmasterbannernet.com +0.0.0.0 www.postmasterdirect.com +0.0.0.0 www.postnewsads.com +0.0.0.0 www.premiumholidayoffers.com +0.0.0.0 www.premiumproductsonline.com +0.0.0.0 www.premium-reward-club.com +0.0.0.0 www.prizes.co.uk +0.0.0.0 www.probabilidades.net +0.0.0.0 www.productopinionpanel.com +0.0.0.0 www.productresearchpanel.com +0.0.0.0 www.producttestpanel.com +0.0.0.0 www.psclicks.com +0.0.0.0 www.pubdirecte.com +0.0.0.0 www.qitrck.com +0.0.0.0 www.quickbrowsersearch.com +0.0.0.0 www.radiate.com +0.0.0.0 www.rankyou.com +0.0.0.0 www.ravel-rewardpath.com +0.0.0.0 www.recreation-leisure-rewardpath.com +0.0.0.0 www.regflow.com +0.0.0.0 www.registrarads.com +0.0.0.0 www.resolvingserver.com +0.0.0.0 www.rewardblvd.com +0.0.0.0 www.rewardhotspot.com +0.0.0.0 www.rewardsflow.com +0.0.0.0 www.ringtonepartner.com +0.0.0.0 www.romepartners.com +0.0.0.0 www.roulettebotplus.com +0.0.0.0 www.rovion.com +0.0.0.0 www.rscounter10.com +0.0.0.0 www.rtcode.com +0.0.0.0 www.rwpads.net +0.0.0.0 www.sa44.net +0.0.0.0 www.salesonline.ie +0.0.0.0 www.save-plan.com +0.0.0.0 www.savings-specials.com +0.0.0.0 www.savings-time.com +0.0.0.0 www.scoremygift.com +0.0.0.0 www.screen-mates.com +0.0.0.0 www.searchwe.com +0.0.0.0 www.seasonalsamplerspecials.com +0.0.0.0 www.securecontactinfo.com +0.0.0.0 www.securerunner.com +0.0.0.0 www.servedby.advertising.com +0.0.0.0 www.sexpartnerx.com +0.0.0.0 www.sexsponsors.com +0.0.0.0 www.shareasale.com +0.0.0.0 www.share-server.com +0.0.0.0 www.shc-rebates.com +0.0.0.0 www.shopperpromotions.com +0.0.0.0 www.shoppingjobshere.com +0.0.0.0 www.shopping-offer.com +0.0.0.0 www.shoppingsiterewards.com +0.0.0.0 www.shops-malls-rewardpath.com +0.0.0.0 www.shoptosaveenergy.com +0.0.0.0 www.simpli.fi +0.0.0.0 www.sizzle-savings.com +0.0.0.0 www.smartadserver.com +0.0.0.0 www.smart-scripts.com +0.0.0.0 www.smarttargetting.com +0.0.0.0 www.smokersopinionpoll.com +0.0.0.0 www.smspop.com +0.0.0.0 www.sochr.com +0.0.0.0 www.sociallypublish.com +0.0.0.0 www.soongu.info +0.0.0.0 www.specialgiftrewards.com +0.0.0.0 www.specialonlinegifts.com +0.0.0.0 www.specials-rewardpath.com +0.0.0.0 www.speedboink.com +0.0.0.0 www.speedyclick.com +0.0.0.0 www.spinbox.com +0.0.0.0 www.sponsorads.de +0.0.0.0 www.sponsoradulto.com +0.0.0.0 www.sports-bonuspath.com +0.0.0.0 www.sports-fitness-rewardpath.com +0.0.0.0 www.sports-offer.com +0.0.0.0 www.sports-offer.net +0.0.0.0 www.sports-premiumblvd.com +0.0.0.0 www.sq2trk2.com +0.0.0.0 www.star-advertising.com +0.0.0.0 www.subsitesadserver.co.uk +0.0.0.0 www.sudokuwhiz.com +0.0.0.0 www.superbrewards.com +0.0.0.0 www.supremeadsonline.com +0.0.0.0 www.surplus-suppliers.com +0.0.0.0 www.sweetsforfree.com +0.0.0.0 www.symbiosting.com +0.0.0.0 www.syncaccess.net +0.0.0.0 www.system-live-media.cz +0.0.0.0 www.tcimg.com +0.0.0.0 www.textbanners.net +0.0.0.0 www.text-link-ads.com +0.0.0.0 www.textsrv.com +0.0.0.0 www.tgpmanager.com +0.0.0.0 www.thatrendsystem.com +0.0.0.0 www.the-binary-options-guide.com +0.0.0.0 www.the-binary-theorem.com +0.0.0.0 www.the-path-gateway.com +0.0.0.0 www.the-smart-stop.com +0.0.0.0 www.thetraderinpajamas.com +0.0.0.0 www.theuseful.com +0.0.0.0 www.theuseful.net +0.0.0.0 www.thinktarget.com +0.0.0.0 www.thinlaptoprewards.com +0.0.0.0 www.thoughtfully-free.com +0.0.0.0 www.thruport.com +0.0.0.0 www.tons-to-see.com +0.0.0.0 www.top20free.com +0.0.0.0 www.topbrandrewards.com +0.0.0.0 www.topconsumergifts.com +0.0.0.0 www.topdemaroc.com +0.0.0.0 www.toy-offer.com +0.0.0.0 www.toy-offer.net +0.0.0.0 www.tqlkg.com #commission junction +0.0.0.0 www.trackadvertising.net +0.0.0.0 www.tracklead.net +0.0.0.0 www.trafficrevenue.net +0.0.0.0 www.traffictrader.net +0.0.0.0 www.traffictraders.com +0.0.0.0 www.trafsearchonline.com +0.0.0.0 www.traktum.com +0.0.0.0 www.traveladvertising.com +0.0.0.0 www.travel-leisure-bonuspath.com +0.0.0.0 www.travel-leisure-premiumblvd.com +0.0.0.0 www.traveller-offer.com +0.0.0.0 www.traveller-offer.net +0.0.0.0 www.travelncs.com +0.0.0.0 www.treeloot.com +0.0.0.0 www.trendnews.com +0.0.0.0 www.trendsonline.biz +0.0.0.0 www.trendsonline.me +0.0.0.0 www.trendsonline.mobi +0.0.0.0 www.trndsys.mobi +0.0.0.0 www.tutop.com +0.0.0.0 www.tuttosessogratis.org +0.0.0.0 www.ukbanners.com +0.0.0.0 www.uleadstrk.com +0.0.0.0 www.ultimatefashiongifts.com +0.0.0.0 www.uproar.com +0.0.0.0 www.upsellit.com +0.0.0.0 www.usatravel-specials.com +0.0.0.0 www.usatravel-specials.net +0.0.0.0 www.us-choicevalue.com +0.0.0.0 www.usemax.de +0.0.0.0 www.us-topsites.com +0.0.0.0 www.utarget.co.uk +0.0.0.0 www.valueclick.com +0.0.0.0 www.via22.net +0.0.0.0 www.vibrantmedia.com +0.0.0.0 www.video-game-rewards-central.com +0.0.0.0 www.videogamerewardscentral.com +0.0.0.0 www.view4cash.de +0.0.0.0 www.virtumundo.com +0.0.0.0 www.vmcsatellite.com +0.0.0.0 www.wdm29.com +0.0.0.0 www.webcashvideos.com +0.0.0.0 www.webcompteur.com +0.0.0.0 www.webservices-rewardpath.com +0.0.0.0 www.websponsors.com +0.0.0.0 www.wegetpaid.net +0.0.0.0 www.whatuwhatuwhatuwant.com +0.0.0.0 www.widgetbucks.com +0.0.0.0 www.wigetmedia.com +0.0.0.0 www.williamhill.es +0.0.0.0 www.windaily.com +0.0.0.0 www.winnerschoiceservices.com +0.0.0.0 www.wordplaywhiz.com +0.0.0.0 www.work-offer.com +0.0.0.0 www.worry-free-savings.com +0.0.0.0 www.wppluginspro.com +0.0.0.0 www.wtp101.com +0.0.0.0 www.xbn.ru # exclusive banner network (Russian) +0.0.0.0 www.yceml.net +0.0.0.0 www.yibaruxet.cn +0.0.0.0 www.yieldmanager.net +0.0.0.0 www.youfck.com +0.0.0.0 www.yourdvdplayer.com +0.0.0.0 www.yourfreegascard.com +0.0.0.0 www.yourgascards.com +0.0.0.0 www.yourgiftrewards.com +0.0.0.0 www.your-gift-zone.com +0.0.0.0 www.yourgiftzone.com +0.0.0.0 www.yourhandytips.com +0.0.0.0 www.yourhotgiftzone.com +0.0.0.0 www.youripad4free.com +0.0.0.0 www.yourrewardzone.com +0.0.0.0 www.yoursmartrewards.com +0.0.0.0 www.zemgo.com +0.0.0.0 www.zevents.com +0.0.0.0 x86adserve006.adtech.de +0.0.0.0 xads.zedo.com +0.0.0.0 x.azjmp.com +0.0.0.0 x.iasrv.com +0.0.0.0 x.interia.pl +0.0.0.0 xlonhcld.xlontech.net +0.0.0.0 xml.adtech.de +0.0.0.0 xml.adtech.fr +0.0.0.0 xml.adtech.us +0.0.0.0 xml.click9.com +0.0.0.0 x.mochiads.com +0.0.0.0 xpantivirus.com +0.0.0.0 xpcs.ads.yahoo.com +0.0.0.0 xstatic.nk-net.pl +0.0.0.0 yadro.ru +0.0.0.0 y.cdn.adblade.com +0.0.0.0 yieldmanagement.adbooth.net +0.0.0.0 yieldmanager.net +0.0.0.0 ym.adnxs.com +0.0.0.0 yodleeinc.tt.omtrdc.net +0.0.0.0 youfck.com +0.0.0.0 yourdvdplayer.com +0.0.0.0 yourfreegascard.com +0.0.0.0 your-free-iphone.com +0.0.0.0 yourgascards.com +0.0.0.0 yourgiftrewards.com +0.0.0.0 your-gift-zone.com +0.0.0.0 yourgiftzone.com +0.0.0.0 yourhandytips.com +0.0.0.0 yourhotgiftzone.com +0.0.0.0 youripad4free.com +0.0.0.0 yourrewardzone.com +0.0.0.0 yoursmartrewards.com +0.0.0.0 ypn-js.overture.com +0.0.0.0 ysiu.freenation.com +0.0.0.0 ytaahg.vo.llnwd.net +0.0.0.0 yumenetworks.com +0.0.0.0 yx-in-f108.1e100.net +0.0.0.0 z1.adserver.com +0.0.0.0 zads.zedo.com +0.0.0.0 z.blogads.com +0.0.0.0 z.ceotrk.com +0.0.0.0 zdads.e-media.com +0.0.0.0 zeevex-online.com +0.0.0.0 zemgo.com +0.0.0.0 zevents.com +0.0.0.0 zuzzer5.com +# + +# + +# yahoo banner ads +0.0.0.0 eur.a1.yimg.com +0.0.0.0 in.yimg.com +0.0.0.0 sg.yimg.com +0.0.0.0 uk.i1.yimg.com +0.0.0.0 us.a1.yimg.com +0.0.0.0 us.b1.yimg.com +0.0.0.0 us.c1.yimg.com +0.0.0.0 us.d1.yimg.com +0.0.0.0 us.e1.yimg.com +0.0.0.0 us.f1.yimg.com +0.0.0.0 us.g1.yimg.com +0.0.0.0 us.h1.yimg.com +#0.0.0.0 us.i1.yimg.com #Uncomment this to block yahoo images +0.0.0.0 us.j1.yimg.com +0.0.0.0 us.k1.yimg.com +0.0.0.0 us.l1.yimg.com +0.0.0.0 us.m1.yimg.com +0.0.0.0 us.n1.yimg.com +0.0.0.0 us.o1.yimg.com +0.0.0.0 us.p1.yimg.com +0.0.0.0 us.q1.yimg.com +0.0.0.0 us.r1.yimg.com +0.0.0.0 us.s1.yimg.com +0.0.0.0 us.t1.yimg.com +0.0.0.0 us.u1.yimg.com +0.0.0.0 us.v1.yimg.com +0.0.0.0 us.w1.yimg.com +0.0.0.0 us.x1.yimg.com +0.0.0.0 us.y1.yimg.com +0.0.0.0 us.z1.yimg.com +# + +# + +# hitbox.com web bugs +0.0.0.0 1cgi.hitbox.com +0.0.0.0 2cgi.hitbox.com +0.0.0.0 adminec1.hitbox.com +0.0.0.0 ads.hitbox.com +0.0.0.0 ag1.hitbox.com +0.0.0.0 ahbn1.hitbox.com +0.0.0.0 ahbn2.hitbox.com +0.0.0.0 ahbn3.hitbox.com +0.0.0.0 ahbn4.hitbox.com +0.0.0.0 aibg.hitbox.com +0.0.0.0 aibl.hitbox.com +0.0.0.0 aics.hitbox.com +0.0.0.0 ai.hitbox.com +0.0.0.0 aiui.hitbox.com +0.0.0.0 bigip1.hitbox.com +0.0.0.0 bigip2.hitbox.com +0.0.0.0 blowfish.hitbox.com +0.0.0.0 cdb.hitbox.com +0.0.0.0 cgi.hitbox.com +0.0.0.0 counter2.hitbox.com +0.0.0.0 counter.hitbox.com +0.0.0.0 dev101.hitbox.com +0.0.0.0 dev102.hitbox.com +0.0.0.0 dev103.hitbox.com +0.0.0.0 dev.hitbox.com +0.0.0.0 download.hitbox.com +0.0.0.0 ec1.hitbox.com +0.0.0.0 ehg-247internet.hitbox.com +0.0.0.0 ehg-accuweather.hitbox.com +0.0.0.0 ehg-acdsystems.hitbox.com +0.0.0.0 ehg-adeptscience.hitbox.com +0.0.0.0 ehg-affinitynet.hitbox.com +0.0.0.0 ehg-aha.hitbox.com +0.0.0.0 ehg-amerix.hitbox.com +0.0.0.0 ehg-apcc.hitbox.com +0.0.0.0 ehg-associatenewmedia.hitbox.com +0.0.0.0 ehg-ati.hitbox.com +0.0.0.0 ehg-attenza.hitbox.com +0.0.0.0 ehg-autodesk.hitbox.com +0.0.0.0 ehg-baa.hitbox.com +0.0.0.0 ehg-backweb.hitbox.com +0.0.0.0 ehg-bestbuy.hitbox.com +0.0.0.0 ehg-bizjournals.hitbox.com +0.0.0.0 ehg-bmwna.hitbox.com +0.0.0.0 ehg-boschsiemens.hitbox.com +0.0.0.0 ehg-bskyb.hitbox.com +0.0.0.0 ehg-cafepress.hitbox.com +0.0.0.0 ehg-careerbuilder.hitbox.com +0.0.0.0 ehg-cbc.hitbox.com +0.0.0.0 ehg-cbs.hitbox.com +0.0.0.0 ehg-cbsradio.hitbox.com +0.0.0.0 ehg-cedarpoint.hitbox.com +0.0.0.0 ehg-clearchannel.hitbox.com +0.0.0.0 ehg-closetmaid.hitbox.com +0.0.0.0 ehg-commjun.hitbox.com +0.0.0.0 ehg.commjun.hitbox.com +0.0.0.0 ehg-communityconnect.hitbox.com +0.0.0.0 ehg-communityconnet.hitbox.com +0.0.0.0 ehg-comscore.hitbox.com +0.0.0.0 ehg-corusentertainment.hitbox.com +0.0.0.0 ehg-coverityinc.hitbox.com +0.0.0.0 ehg-crain.hitbox.com +0.0.0.0 ehg-ctv.hitbox.com +0.0.0.0 ehg-cygnusbm.hitbox.com +0.0.0.0 ehg-datamonitor.hitbox.com +0.0.0.0 ehg-digg.hitbox.com +0.0.0.0 ehg-dig.hitbox.com +0.0.0.0 ehg-eckounlimited.hitbox.com +0.0.0.0 ehg-esa.hitbox.com +0.0.0.0 ehg-espn.hitbox.com +0.0.0.0 ehg-fifa.hitbox.com +0.0.0.0 ehg-findlaw.hitbox.com +0.0.0.0 ehg-foundation.hitbox.com +0.0.0.0 ehg-foxsports.hitbox.com +0.0.0.0 ehg-futurepub.hitbox.com +0.0.0.0 ehg-gamedaily.hitbox.com +0.0.0.0 ehg-gamespot.hitbox.com +0.0.0.0 ehg-gatehousemedia.hitbox.com +0.0.0.0 ehg-gatehoussmedia.hitbox.com +0.0.0.0 ehg-glam.hitbox.com +0.0.0.0 ehg-groceryworks.hitbox.com +0.0.0.0 ehg-groupernetworks.hitbox.com +0.0.0.0 ehg-guardian.hitbox.com +0.0.0.0 ehg-hasbro.hitbox.com +0.0.0.0 ehg-hellodirect.hitbox.com +0.0.0.0 ehg-himedia.hitbox.com +0.0.0.0 ehg.hitbox.com +0.0.0.0 ehg-hitent.hitbox.com +0.0.0.0 ehg-hollywood.hitbox.com +0.0.0.0 ehg-idgentertainment.hitbox.com +0.0.0.0 ehg-idg.hitbox.com +0.0.0.0 ehg-ifilm.hitbox.com +0.0.0.0 ehg-ignitemedia.hitbox.com +0.0.0.0 ehg-intel.hitbox.com +0.0.0.0 ehg-ittoolbox.hitbox.com +0.0.0.0 ehg-itworldcanada.hitbox.com +0.0.0.0 ehg-kingstontechnology.hitbox.com +0.0.0.0 ehg-knightridder.hitbox.com +0.0.0.0 ehg-learningco.hitbox.com +0.0.0.0 ehg-legonewyorkinc.hitbox.com +0.0.0.0 ehg-liveperson.hitbox.com +0.0.0.0 ehg-macpublishingllc.hitbox.com +0.0.0.0 ehg-macromedia.hitbox.com +0.0.0.0 ehg-magicalia.hitbox.com +0.0.0.0 ehg-maplesoft.hitbox.com +0.0.0.0 ehg-mgnlimited.hitbox.com +0.0.0.0 ehg-mindshare.hitbox.com +0.0.0.0 ehg.mindshare.hitbox.com +0.0.0.0 ehg-mtv.hitbox.com +0.0.0.0 ehg-mybc.hitbox.com +0.0.0.0 ehg-newarkinone.hitbox.com.hitbox.com +0.0.0.0 ehg-newegg.hitbox.com +0.0.0.0 ehg-newscientist.hitbox.com +0.0.0.0 ehg-newsinternational.hitbox.com +0.0.0.0 ehg-nokiafin.hitbox.com +0.0.0.0 ehg-novell.hitbox.com +0.0.0.0 ehg-nvidia.hitbox.com +0.0.0.0 ehg-oreilley.hitbox.com +0.0.0.0 ehg-oreilly.hitbox.com +0.0.0.0 ehg-pacifictheatres.hitbox.com +0.0.0.0 ehg-pennwell.hitbox.com +0.0.0.0 ehg-peoplesoft.hitbox.com +0.0.0.0 ehg-philipsvheusen.hitbox.com +0.0.0.0 ehg-pizzahut.hitbox.com +0.0.0.0 ehg-playboy.hitbox.com +0.0.0.0 ehg-presentigsolutions.hitbox.com +0.0.0.0 ehg-qualcomm.hitbox.com +0.0.0.0 ehg-quantumcorp.hitbox.com +0.0.0.0 ehg-randomhouse.hitbox.com +0.0.0.0 ehg-redherring.hitbox.com +0.0.0.0 ehg-register.hitbox.com +0.0.0.0 ehg-researchinmotion.hitbox.com +0.0.0.0 ehg-rfa.hitbox.com +0.0.0.0 ehg-rodale.hitbox.com +0.0.0.0 ehg-salesforce.hitbox.com +0.0.0.0 ehg-salonmedia.hitbox.com +0.0.0.0 ehg-samsungusa.hitbox.com +0.0.0.0 ehg-seca.hitbox.com +0.0.0.0 ehg-shoppersdrugmart.hitbox.com +0.0.0.0 ehg-sonybssc.hitbox.com +0.0.0.0 ehg-sonycomputer.hitbox.com +0.0.0.0 ehg-sonyelec.hitbox.com +0.0.0.0 ehg-sonymusic.hitbox.com +0.0.0.0 ehg-sonyny.hitbox.com +0.0.0.0 ehg-space.hitbox.com +0.0.0.0 ehg-sportsline.hitbox.com +0.0.0.0 ehg-streamload.hitbox.com +0.0.0.0 ehg-superpages.hitbox.com +0.0.0.0 ehg-techtarget.hitbox.com +0.0.0.0 ehg-tfl.hitbox.com +0.0.0.0 ehg-thefirstchurchchrist.hitbox.com +0.0.0.0 ehg-tigerdirect2.hitbox.com +0.0.0.0 ehg-tigerdirect.hitbox.com +0.0.0.0 ehg-topps.hitbox.com +0.0.0.0 ehg-tribute.hitbox.com +0.0.0.0 ehg-tumbleweed.hitbox.com +0.0.0.0 ehg-ubisoft.hitbox.com +0.0.0.0 ehg-uniontrib.hitbox.com +0.0.0.0 ehg-usnewsworldreport.hitbox.com +0.0.0.0 ehg-verizoncommunications.hitbox.com +0.0.0.0 ehg-viacom.hitbox.com +0.0.0.0 ehg-vmware.hitbox.com +0.0.0.0 ehg-vonage.hitbox.com +0.0.0.0 ehg-wachovia.hitbox.com +0.0.0.0 ehg-wacomtechnology.hitbox.com +0.0.0.0 ehg-warner-brothers.hitbox.com +0.0.0.0 ehg-wizardsofthecoast.hitbox.com.hitbox.com +0.0.0.0 ehg-womanswallstreet.hitbox.com +0.0.0.0 ehg-wss.hitbox.com +0.0.0.0 ehg-xxolympicwintergames.hitbox.com +0.0.0.0 ehg-yellowpages.hitbox.com +0.0.0.0 ehg-youtube.hitbox.com +0.0.0.0 ejs.hitbox.com +0.0.0.0 enterprise-admin.hitbox.com +0.0.0.0 enterprise.hitbox.com +0.0.0.0 esg.hitbox.com +0.0.0.0 evwr.hitbox.com +0.0.0.0 get.hitbox.com +0.0.0.0 hg10.hitbox.com +0.0.0.0 hg11.hitbox.com +0.0.0.0 hg12.hitbox.com +0.0.0.0 hg13.hitbox.com +0.0.0.0 hg14.hitbox.com +0.0.0.0 hg15.hitbox.com +0.0.0.0 hg16.hitbox.com +0.0.0.0 hg17.hitbox.com +0.0.0.0 hg1.hitbox.com +0.0.0.0 hg2.hitbox.com +0.0.0.0 hg3.hitbox.com +0.0.0.0 hg4.hitbox.com +0.0.0.0 hg5.hitbox.com +0.0.0.0 hg6a.hitbox.com +0.0.0.0 hg6.hitbox.com +0.0.0.0 hg7.hitbox.com +0.0.0.0 hg8.hitbox.com +0.0.0.0 hg9.hitbox.com +0.0.0.0 hitboxbenchmarker.com +0.0.0.0 hitboxcentral.com +0.0.0.0 hitbox.com +0.0.0.0 hitboxenterprise.com +0.0.0.0 hitboxwireless.com +0.0.0.0 host6.hitbox.com +0.0.0.0 ias2.hitbox.com +0.0.0.0 ias.hitbox.com +0.0.0.0 ibg.hitbox.com +0.0.0.0 ics.hitbox.com +0.0.0.0 idb.hitbox.com +0.0.0.0 js1.hitbox.com +0.0.0.0 lb.hitbox.com +0.0.0.0 lesbian-erotica.hitbox.com +0.0.0.0 lookup2.hitbox.com +0.0.0.0 lookup.hitbox.com +0.0.0.0 mrtg.hitbox.com +0.0.0.0 myhitbox.com +0.0.0.0 na.hitbox.com +0.0.0.0 narwhal.hitbox.com +0.0.0.0 nei.hitbox.com +0.0.0.0 nocboard.hitbox.com +0.0.0.0 noc.hitbox.com +0.0.0.0 noc-request.hitbox.com +0.0.0.0 ns1.hitbox.com +0.0.0.0 oas.hitbox.com +0.0.0.0 phg.hitbox.com +0.0.0.0 pure.hitbox.com +0.0.0.0 rainbowclub.hitbox.com +0.0.0.0 rd1.hitbox.com +0.0.0.0 reseller.hitbox.com +0.0.0.0 resources.hitbox.com +0.0.0.0 sitesearch.hitbox.com +0.0.0.0 specialtyclub.hitbox.com +0.0.0.0 ss.hitbox.com +0.0.0.0 stage101.hitbox.com +0.0.0.0 stage102.hitbox.com +0.0.0.0 stage103.hitbox.com +0.0.0.0 stage104.hitbox.com +0.0.0.0 stage105.hitbox.com +0.0.0.0 stage.hitbox.com +0.0.0.0 stats2.hitbox.com +0.0.0.0 stats3.hitbox.com +0.0.0.0 stats.hitbox.com +0.0.0.0 switch10.hitbox.com +0.0.0.0 switch11.hitbox.com +0.0.0.0 switch1.hitbox.com +0.0.0.0 switch5.hitbox.com +0.0.0.0 switch6.hitbox.com +0.0.0.0 switch8.hitbox.com +0.0.0.0 switch9.hitbox.com +0.0.0.0 switch.hitbox.com +0.0.0.0 tetra.hitbox.com +0.0.0.0 tools2.hitbox.com +0.0.0.0 toolsa.hitbox.com +0.0.0.0 tools.hitbox.com +0.0.0.0 ts1.hitbox.com +0.0.0.0 ts2.hitbox.com +0.0.0.0 vwr1.hitbox.com +0.0.0.0 vwr2.hitbox.com +0.0.0.0 vwr3.hitbox.com +0.0.0.0 w100.hitbox.com +0.0.0.0 w101.hitbox.com +0.0.0.0 w102.hitbox.com +0.0.0.0 w103.hitbox.com +0.0.0.0 w104.hitbox.com +0.0.0.0 w105.hitbox.com +0.0.0.0 w106.hitbox.com +0.0.0.0 w107.hitbox.com +0.0.0.0 w108.hitbox.com +0.0.0.0 w109.hitbox.com +0.0.0.0 w10.hitbox.com +0.0.0.0 w110.hitbox.com +0.0.0.0 w111.hitbox.com +0.0.0.0 w112.hitbox.com +0.0.0.0 w113.hitbox.com +0.0.0.0 w114.hitbox.com +0.0.0.0 w115.hitbox.com +0.0.0.0 w116.hitbox.com +0.0.0.0 w117.hitbox.com +0.0.0.0 w118.hitbox.com +0.0.0.0 w119.hitbox.com +0.0.0.0 w11.hitbox.com +0.0.0.0 w120.hitbox.com +0.0.0.0 w121.hitbox.com +0.0.0.0 w122.hitbox.com +0.0.0.0 w123.hitbox.com +0.0.0.0 w124.hitbox.com +0.0.0.0 w126.hitbox.com +0.0.0.0 w128.hitbox.com +0.0.0.0 w129.hitbox.com +0.0.0.0 w12.hitbox.com +0.0.0.0 w130.hitbox.com +0.0.0.0 w131.hitbox.com +0.0.0.0 w132.hitbox.com +0.0.0.0 w133.hitbox.com +0.0.0.0 w135.hitbox.com +0.0.0.0 w136.hitbox.com +0.0.0.0 w137.hitbox.com +0.0.0.0 w138.hitbox.com +0.0.0.0 w139.hitbox.com +0.0.0.0 w13.hitbox.com +0.0.0.0 w140.hitbox.com +0.0.0.0 w141.hitbox.com +0.0.0.0 w144.hitbox.com +0.0.0.0 w147.hitbox.com +0.0.0.0 w14.hitbox.com +0.0.0.0 w153.hitbox.com +0.0.0.0 w154.hitbox.com +0.0.0.0 w155.hitbox.com +0.0.0.0 w157.hitbox.com +0.0.0.0 w159.hitbox.com +0.0.0.0 w15.hitbox.com +0.0.0.0 w161.hitbox.com +0.0.0.0 w162.hitbox.com +0.0.0.0 w167.hitbox.com +0.0.0.0 w168.hitbox.com +0.0.0.0 w16.hitbox.com +0.0.0.0 w170.hitbox.com +0.0.0.0 w175.hitbox.com +0.0.0.0 w177.hitbox.com +0.0.0.0 w179.hitbox.com +0.0.0.0 w17.hitbox.com +0.0.0.0 w18.hitbox.com +0.0.0.0 w19.hitbox.com +0.0.0.0 w1.hitbox.com +0.0.0.0 w20.hitbox.com +0.0.0.0 w21.hitbox.com +0.0.0.0 w22.hitbox.com +0.0.0.0 w23.hitbox.com +0.0.0.0 w24.hitbox.com +0.0.0.0 w25.hitbox.com +0.0.0.0 w26.hitbox.com +0.0.0.0 w27.hitbox.com +0.0.0.0 w28.hitbox.com +0.0.0.0 w29.hitbox.com +0.0.0.0 w2.hitbox.com +0.0.0.0 w30.hitbox.com +0.0.0.0 w31.hitbox.com +0.0.0.0 w32.hitbox.com +0.0.0.0 w33.hitbox.com +0.0.0.0 w34.hitbox.com +0.0.0.0 w35.hitbox.com +0.0.0.0 w36.hitbox.com +0.0.0.0 w3.hitbox.com +0.0.0.0 w4.hitbox.com +0.0.0.0 w5.hitbox.com +0.0.0.0 w6.hitbox.com +0.0.0.0 w7.hitbox.com +0.0.0.0 w8.hitbox.com +0.0.0.0 w9.hitbox.com +0.0.0.0 webload101.hitbox.com +0.0.0.0 wss-gw-1.hitbox.com +0.0.0.0 wss-gw-3.hitbox.com +0.0.0.0 wvwr1.hitbox.com +0.0.0.0 ww1.hitbox.com +0.0.0.0 ww2.hitbox.com +0.0.0.0 ww3.hitbox.com +0.0.0.0 wwa.hitbox.com +0.0.0.0 wwb.hitbox.com +0.0.0.0 wwc.hitbox.com +0.0.0.0 wwd.hitbox.com +0.0.0.0 www.ehg-rr.hitbox.com +0.0.0.0 www.hitbox.com +0.0.0.0 www.hitboxwireless.com +0.0.0.0 y2k.hitbox.com +0.0.0.0 yang.hitbox.com +0.0.0.0 ying.hitbox.com +# + +# + +# www.extreme-dm.com tracking +0.0.0.0 extreme-dm.com +0.0.0.0 reports.extreme-dm.com +0.0.0.0 t0.extreme-dm.com +0.0.0.0 t1.extreme-dm.com +0.0.0.0 t.extreme-dm.com +0.0.0.0 u0.extreme-dm.com +0.0.0.0 u1.extreme-dm.com +0.0.0.0 u.extreme-dm.com +0.0.0.0 v0.extreme-dm.com +0.0.0.0 v1.extreme-dm.com +0.0.0.0 v.extreme-dm.com +0.0.0.0 w0.extreme-dm.com +0.0.0.0 w1.extreme-dm.com +0.0.0.0 w2.extreme-dm.com +0.0.0.0 w3.extreme-dm.com +0.0.0.0 w4.extreme-dm.com +0.0.0.0 w5.extreme-dm.com +0.0.0.0 w6.extreme-dm.com +0.0.0.0 w7.extreme-dm.com +0.0.0.0 w8.extreme-dm.com +0.0.0.0 w9.extreme-dm.com +0.0.0.0 w.extreme-dm.com +0.0.0.0 www.extreme-dm.com +0.0.0.0 x3.extreme-dm.com +0.0.0.0 y0.extreme-dm.com +0.0.0.0 y1.extreme-dm.com +0.0.0.0 y.extreme-dm.com +0.0.0.0 z0.extreme-dm.com +0.0.0.0 z1.extreme-dm.com +0.0.0.0 z.extreme-dm.com +# + +# + +# realmedia.com's Open Ad Stream +0.0.0.0 ap.oasfile.aftenposten.no +0.0.0.0 imagenen1.247realmedia.com +0.0.0.0 oacentral.cepro.com +0.0.0.0 oas.adx.nu +0.0.0.0 oas.aurasports.com +0.0.0.0 oas.benchmark.fr +0.0.0.0 oasc03012.247realmedia.com +0.0.0.0 oasc03049.247realmedia.com +0.0.0.0 oasc06006.247realmedia.com +0.0.0.0 oasc08008.247realmedia.com +0.0.0.0 oasc09.247realmedia.com +0.0.0.0 oascentral.123greetings.com +0.0.0.0 oascentral.abclocal.go.com +0.0.0.0 oascentral.adage.com +0.0.0.0 oascentral.adageglobal.com +0.0.0.0 oascentral.aircanada.com +0.0.0.0 oascentral.alanicnewsnet.ca +0.0.0.0 oascentral.alanticnewsnet.ca +0.0.0.0 oascentral.americanheritage.com +0.0.0.0 oascentral.artistdirect.com +0.0.0.0 oascentral.artistirect.com +0.0.0.0 oascentral.askmen.com +0.0.0.0 oascentral.aviationnow.com +0.0.0.0 oascentral.blackenterprises.com +0.0.0.0 oascentral.blogher.org +0.0.0.0 oascentral.bostonherald.com +0.0.0.0 oascentral.bostonphoenix.com +0.0.0.0 oascentral.businessinsider.com +0.0.0.0 oascentral.businessweek.com +0.0.0.0 oascentral.businessweeks.com +0.0.0.0 oascentral.buy.com +0.0.0.0 oascentral.canadaeast.com +0.0.0.0 oascentral.canadianliving.com +0.0.0.0 oascentral.charleston.net +0.0.0.0 oascentral.chicagobusiness.com +0.0.0.0 oascentral.chron.com +0.0.0.0 oascentral.citypages.com +0.0.0.0 oascentral.clearchannel.com +0.0.0.0 oascentral.comcast.net +0.0.0.0 oascentral.comics.com +0.0.0.0 oascentral.construction.com +0.0.0.0 oascentral.consumerreports.org +0.0.0.0 oascentral.covers.com +0.0.0.0 oascentral.crainsdetroit.com +0.0.0.0 oascentral.crimelibrary.com +0.0.0.0 oascentral.cybereps.com +0.0.0.0 oascentral.dailybreeze.com +0.0.0.0 oascentral.dailyherald.com +0.0.0.0 oascentral.dilbert.com +0.0.0.0 oascentral.discovery.com +0.0.0.0 oascentral.drphil.com +0.0.0.0 oascentral.eastbayexpress.com +0.0.0.0 oas-central.east.realmedia.com +0.0.0.0 oascentral.encyclopedia.com +0.0.0.0 oascentral.fashionmagazine.com +0.0.0.0 oascentral.fayettevillenc.com +0.0.0.0 oascentral.feedroom.com +0.0.0.0 oascentral.forsythnews.com +0.0.0.0 oascentral.fortunecity.com +0.0.0.0 oascentral.foxnews.com +0.0.0.0 oascentral.freedom.com +0.0.0.0 oascentral.g4techtv.com +0.0.0.0 oascentral.ggl.com +0.0.0.0 oascentral.gigex.com +0.0.0.0 oascentral.globalpost.com +0.0.0.0 oascentral.hamptonroads.com +0.0.0.0 oascentral.hamptoroads.com +0.0.0.0 oascentral.hamtoroads.com +0.0.0.0 oascentral.herenb.com +0.0.0.0 oascentral.hollywood.com +0.0.0.0 oascentral.houstonpress.com +0.0.0.0 oascentral.inq7.net +0.0.0.0 oascentral.investors.com +0.0.0.0 oascentral.investorwords.com +0.0.0.0 oascentral.itbusiness.ca +0.0.0.0 oascentral.killsometime.com +0.0.0.0 oascentral.laptopmag.com +0.0.0.0 oascentral.law.com +0.0.0.0 oascentral.laweekly.com +0.0.0.0 oascentral.looksmart.com +0.0.0.0 oascentral.lycos.com +0.0.0.0 oascentral.mailtribune.com +0.0.0.0 oascentral.mayoclinic.com +0.0.0.0 oascentral.medbroadcast.com +0.0.0.0 oascentral.metro.us +0.0.0.0 oascentral.minnpost.com +0.0.0.0 oascentral.mochila.com +0.0.0.0 oascentral.motherjones.com +0.0.0.0 oascentral.nerve.com +0.0.0.0 oascentral.newsmax.com +0.0.0.0 oascentral.nowtoronto.com +0.0.0.0 oascentralnx.comcast.net +0.0.0.0 oascentral.onwisconsin.com +0.0.0.0 oascentral.phoenixnewtimes.com +0.0.0.0 oascentral.phoenixvillenews.com +0.0.0.0 oascentral.pitch.com +0.0.0.0 oascentral.poconorecord.com +0.0.0.0 oascentral.politico.com +0.0.0.0 oascentral.post-gazette.com +0.0.0.0 oascentral.pottsmerc.com +0.0.0.0 oascentral.princetonreview.com +0.0.0.0 oascentral.publicradio.org +0.0.0.0 oascentral.radaronline.com +0.0.0.0 oascentral.rcrnews.com +0.0.0.0 oas-central.realmedia.com +0.0.0.0 oascentral.redherring.com +0.0.0.0 oascentral.redorbit.com +0.0.0.0 oascentral.redstate.com +0.0.0.0 oascentral.reference.com +0.0.0.0 oascentral.regalinterative.com +0.0.0.0 oascentral.register.com +0.0.0.0 oascentral.registerguard.com +0.0.0.0 oascentral.registguard.com +0.0.0.0 oascentral.riverfronttimes.com +0.0.0.0 oascentral.salon.com +0.0.0.0 oascentral.santacruzsentinel.com +0.0.0.0 oascentral.sciam.com +0.0.0.0 oascentral.scientificamerican.com +0.0.0.0 oascentral.seacoastonline.com +0.0.0.0 oascentral.seattleweekly.com +0.0.0.0 oascentral.sfgate.com +0.0.0.0 oascentral.sfweekly.com +0.0.0.0 oascentral.sina.com +0.0.0.0 oascentral.sina.com.hk +0.0.0.0 oascentral.sparknotes.com +0.0.0.0 oascentral.sptimes.com +0.0.0.0 oascentral.starbulletin.com +0.0.0.0 oascentral.suntimes.com +0.0.0.0 oascentral.surfline.com +0.0.0.0 oascentral.thechronicleherald.ca +0.0.0.0 oascentral.thehockeynews.com +0.0.0.0 oascentral.thenation.com +0.0.0.0 oascentral.theonionavclub.com +0.0.0.0 oascentral.theonion.com +0.0.0.0 oascentral.thephoenix.com +0.0.0.0 oascentral.thesmokinggun.com +0.0.0.0 oascentral.thespark.com +0.0.0.0 oascentral.tmcnet.com +0.0.0.0 oascentral.tnr.com +0.0.0.0 oascentral.tourismvancouver.com +0.0.0.0 oascentral.townhall.com +0.0.0.0 oascentral.tribe.net +0.0.0.0 oascentral.trutv.com +0.0.0.0 oascentral.upi.com +0.0.0.0 oascentral.urbanspoon.com +0.0.0.0 oascentral.villagevoice.com +0.0.0.0 oascentral.virtualtourist.com +0.0.0.0 oascentral.warcry.com +0.0.0.0 oascentral.washtimes.com +0.0.0.0 oascentral.wciv.com +0.0.0.0 oascentral.westword.com +0.0.0.0 oascentral.where.ca +0.0.0.0 oascentral.wjla.com +0.0.0.0 oascentral.wkrn.com +0.0.0.0 oascentral.wwe.com +0.0.0.0 oascentral.yellowpages.com +0.0.0.0 oascentral.ywlloewpages.ca +0.0.0.0 oascentral.zwire.com +0.0.0.0 oascentreal.adcritic.com +0.0.0.0 oascetral.laweekly.com +0.0.0.0 oas.dispatch.com +0.0.0.0 oas.foxnews.com +0.0.0.0 oas.greensboro.com +0.0.0.0 oas.guardian.co.uk +0.0.0.0 oas.ibnlive.com +0.0.0.0 oas.lee.net +0.0.0.0 oas.nrjlink.fr +0.0.0.0 oas.nzz.ch +0.0.0.0 oas.portland.com +0.0.0.0 oas.publicitas.ch +0.0.0.0 oasroanoke.com +0.0.0.0 oas.salon.com +0.0.0.0 oas.sciencemag.org +0.0.0.0 oas.signonsandiego.com +0.0.0.0 oas.startribune.com +0.0.0.0 oas.toronto.com +0.0.0.0 oas.uniontrib.com +0.0.0.0 oas.villagevoice.com +0.0.0.0 oas.vtsgonline.com +# + +# + +# fastclick banner ads +0.0.0.0 media1.fastclick.net +0.0.0.0 media2.fastclick.net +0.0.0.0 media3.fastclick.net +0.0.0.0 media4.fastclick.net +0.0.0.0 media5.fastclick.net +0.0.0.0 media6.fastclick.net +0.0.0.0 media7.fastclick.net +0.0.0.0 media8.fastclick.net +0.0.0.0 media9.fastclick.net +0.0.0.0 media10.fastclick.net +0.0.0.0 media11.fastclick.net +0.0.0.0 media12.fastclick.net +0.0.0.0 media13.fastclick.net +0.0.0.0 media14.fastclick.net +0.0.0.0 media15.fastclick.net +0.0.0.0 media16.fastclick.net +0.0.0.0 media17.fastclick.net +0.0.0.0 media18.fastclick.net +0.0.0.0 media19.fastclick.net +0.0.0.0 media20.fastclick.net +0.0.0.0 media21.fastclick.net +0.0.0.0 media22.fastclick.net +0.0.0.0 media23.fastclick.net +0.0.0.0 media24.fastclick.net +0.0.0.0 media25.fastclick.net +0.0.0.0 media26.fastclick.net +0.0.0.0 media27.fastclick.net +0.0.0.0 media28.fastclick.net +0.0.0.0 media29.fastclick.net +0.0.0.0 media30.fastclick.net +0.0.0.0 media31.fastclick.net +0.0.0.0 media32.fastclick.net +0.0.0.0 media33.fastclick.net +0.0.0.0 media34.fastclick.net +0.0.0.0 media35.fastclick.net +0.0.0.0 media36.fastclick.net +0.0.0.0 media37.fastclick.net +0.0.0.0 media38.fastclick.net +0.0.0.0 media39.fastclick.net +0.0.0.0 media40.fastclick.net +0.0.0.0 media41.fastclick.net +0.0.0.0 media42.fastclick.net +0.0.0.0 media43.fastclick.net +0.0.0.0 media44.fastclick.net +0.0.0.0 media45.fastclick.net +0.0.0.0 media46.fastclick.net +0.0.0.0 media47.fastclick.net +0.0.0.0 media48.fastclick.net +0.0.0.0 media49.fastclick.net +0.0.0.0 media50.fastclick.net +0.0.0.0 media51.fastclick.net +0.0.0.0 media52.fastclick.net +0.0.0.0 media53.fastclick.net +0.0.0.0 media54.fastclick.net +0.0.0.0 media55.fastclick.net +0.0.0.0 media56.fastclick.net +0.0.0.0 media57.fastclick.net +0.0.0.0 media58.fastclick.net +0.0.0.0 media59.fastclick.net +0.0.0.0 media60.fastclick.net +0.0.0.0 media61.fastclick.net +0.0.0.0 media62.fastclick.net +0.0.0.0 media63.fastclick.net +0.0.0.0 media64.fastclick.net +0.0.0.0 media65.fastclick.net +0.0.0.0 media66.fastclick.net +0.0.0.0 media67.fastclick.net +0.0.0.0 media68.fastclick.net +0.0.0.0 media69.fastclick.net +0.0.0.0 media70.fastclick.net +0.0.0.0 media71.fastclick.net +0.0.0.0 media72.fastclick.net +0.0.0.0 media73.fastclick.net +0.0.0.0 media74.fastclick.net +0.0.0.0 media75.fastclick.net +0.0.0.0 media76.fastclick.net +0.0.0.0 media77.fastclick.net +0.0.0.0 media78.fastclick.net +0.0.0.0 media79.fastclick.net +0.0.0.0 media80.fastclick.net +0.0.0.0 media81.fastclick.net +0.0.0.0 media82.fastclick.net +0.0.0.0 media83.fastclick.net +0.0.0.0 media84.fastclick.net +0.0.0.0 media85.fastclick.net +0.0.0.0 media86.fastclick.net +0.0.0.0 media87.fastclick.net +0.0.0.0 media88.fastclick.net +0.0.0.0 media89.fastclick.net +0.0.0.0 media90.fastclick.net +0.0.0.0 media91.fastclick.net +0.0.0.0 media92.fastclick.net +0.0.0.0 media93.fastclick.net +0.0.0.0 media94.fastclick.net +0.0.0.0 media95.fastclick.net +0.0.0.0 media96.fastclick.net +0.0.0.0 media97.fastclick.net +0.0.0.0 media98.fastclick.net +0.0.0.0 media99.fastclick.net +0.0.0.0 fastclick.net +# + +# + +# belo interactive ads +0.0.0.0 te.about.com +0.0.0.0 te.adlandpro.com +0.0.0.0 te.advance.net +0.0.0.0 te.ap.org +0.0.0.0 te.astrology.com +0.0.0.0 te.audiencematch.net +0.0.0.0 te.belointeractive.com +0.0.0.0 te.boston.com +0.0.0.0 te.businessweek.com +0.0.0.0 te.chicagotribune.com +0.0.0.0 te.chron.com +0.0.0.0 te.cleveland.net +0.0.0.0 te.ctnow.com +0.0.0.0 te.dailycamera.com +0.0.0.0 te.dailypress.com +0.0.0.0 te.dentonrc.com +0.0.0.0 te.greenwichtime.com +0.0.0.0 te.idg.com +0.0.0.0 te.infoworld.com +0.0.0.0 te.ivillage.com +0.0.0.0 te.journalnow.com +0.0.0.0 te.latimes.com +0.0.0.0 te.mcall.com +0.0.0.0 te.mgnetwork.com +0.0.0.0 te.mysanantonio.com +0.0.0.0 te.newsday.com +0.0.0.0 te.nytdigital.com +0.0.0.0 te.orlandosentinel.com +0.0.0.0 te.scripps.com +0.0.0.0 te.scrippsnetworksprivacy.com +0.0.0.0 te.scrippsnewspapersprivacy.com +0.0.0.0 te.sfgate.com +0.0.0.0 te.signonsandiego.com +0.0.0.0 te.stamfordadvocate.com +0.0.0.0 te.sun-sentinel.com +0.0.0.0 te.sunspot.net +0.0.0.0 te.suntimes.com +0.0.0.0 te.tbo.com +0.0.0.0 te.thestar.ca +0.0.0.0 te.thestar.com +0.0.0.0 te.trb.com +0.0.0.0 te.versiontracker.com +0.0.0.0 te.wsls.com +# + +# + +# popup traps -- sites that bounce you around or won't let you leave +0.0.0.0 24hwebsex.com +0.0.0.0 adultfriendfinder.com +0.0.0.0 all-tgp.org +0.0.0.0 fioe.info +0.0.0.0 incestland.com +0.0.0.0 lesview.com +0.0.0.0 searchforit.com +0.0.0.0 www.asiansforu.com +0.0.0.0 www.bangbuddy.com +0.0.0.0 www.datanotary.com +0.0.0.0 www.entercasino.com +0.0.0.0 www.incestdot.com +0.0.0.0 www.incestgold.com +0.0.0.0 www.justhookup.com +0.0.0.0 www.mangayhentai.com +0.0.0.0 www.myluvcrush.ca +0.0.0.0 www.ourfuckbook.com +0.0.0.0 www.realincestvideos.com +0.0.0.0 www.searchforit.com +0.0.0.0 www.searchv.com +0.0.0.0 www.secretosx.com +0.0.0.0 www.seductiveamateurs.com +0.0.0.0 www.smsmovies.net +0.0.0.0 www.wowjs.1www.cn +0.0.0.0 www.xxxnations.com +0.0.0.0 www.xxxnightly.com +0.0.0.0 www.xxxtoolbar.com +0.0.0.0 www.yourfuckbook.com +# + +# + +# malicious e-card -- these sites send out mass quantities of spam + # and some distribute adware and spyware +0.0.0.0 123greetings.com # contains one link to distributor of adware or spyware +0.0.0.0 2000greetings.com +0.0.0.0 celebwelove.com +0.0.0.0 ecard4all.com +0.0.0.0 eforu.com +0.0.0.0 freewebcards.com +0.0.0.0 fukkad.com +0.0.0.0 fun-e-cards.com +0.0.0.0 funnyreign.com # heavy spam (Site Advisor received 1075 e-mails/week) +0.0.0.0 funsilly.com +0.0.0.0 myfuncards.com +0.0.0.0 www.cool-downloads.com +0.0.0.0 www.cool-downloads.net +0.0.0.0 www.friend-card.com +0.0.0.0 www.friend-cards.com +0.0.0.0 www.friend-cards.net +0.0.0.0 www.friend-greeting.com +0.0.0.0 www.friend-greetings.com +0.0.0.0 www.friendgreetings.com +0.0.0.0 www.friend-greetings.net +0.0.0.0 www.friendgreetings.net +0.0.0.0 www.laugh-mail.com +0.0.0.0 www.laugh-mail.net +# + +# + +# European network of tracking sites +0.0.0.0 0ivwbox.de +0.0.0.0 1ivwbox.de +0.0.0.0 1und1.ivwbox.de +0.0.0.0 2ivwbox.de +0.0.0.0 3ivwbox.de +0.0.0.0 4ivwbox.de +0.0.0.0 5ivwbox.de +0.0.0.0 6ivwbox.de +0.0.0.0 7ivwbox.de +0.0.0.0 8ivwbox.de +0.0.0.0 8vwbox.de +0.0.0.0 9ivwbox.de +0.0.0.0 9vwbox.de +0.0.0.0 aivwbox.de +0.0.0.0 avwbox.de +0.0.0.0 bild.ivwbox.de +0.0.0.0 bivwbox.de +0.0.0.0 civwbox.de +0.0.0.0 divwbox.de +0.0.0.0 eevwbox.de +0.0.0.0 eivwbox.de +0.0.0.0 evwbox.de +0.0.0.0 faz.ivwbox.de +0.0.0.0 fivwbox.de +0.0.0.0 givwbox.de +0.0.0.0 hivwbox.de +0.0.0.0 i8vwbox.de +0.0.0.0 i9vwbox.de +0.0.0.0 iavwbox.de +0.0.0.0 ibvwbox.de +0.0.0.0 ibwbox.de +0.0.0.0 icvwbox.de +0.0.0.0 icwbox.de +0.0.0.0 ievwbox.de +0.0.0.0 ifvwbox.de +0.0.0.0 ifwbox.de +0.0.0.0 igvwbox.de +0.0.0.0 igwbox.de +0.0.0.0 iivwbox.de +0.0.0.0 ijvwbox.de +0.0.0.0 ikvwbox.de +0.0.0.0 iovwbox.de +0.0.0.0 iuvwbox.de +0.0.0.0 iv2box.de +0.0.0.0 iv2wbox.de +0.0.0.0 iv3box.de +0.0.0.0 iv3wbox.de +0.0.0.0 ivabox.de +0.0.0.0 ivawbox.de +0.0.0.0 ivbox.de +0.0.0.0 ivbwbox.de +0.0.0.0 ivbwox.de +0.0.0.0 ivcwbox.de +0.0.0.0 ivebox.de +0.0.0.0 ivewbox.de +0.0.0.0 ivfwbox.de +0.0.0.0 ivgwbox.de +0.0.0.0 ivqbox.de +0.0.0.0 ivqwbox.de +0.0.0.0 ivsbox.de +0.0.0.0 ivswbox.de +0.0.0.0 ivvbox.de +0.0.0.0 ivvwbox.de +0.0.0.0 ivw2box.de +0.0.0.0 ivw3box.de +0.0.0.0 ivwabox.de +0.0.0.0 ivwb0ox.de +0.0.0.0 ivwb0x.de +0.0.0.0 ivwb9ox.de +0.0.0.0 ivwb9x.de +0.0.0.0 ivwbaox.de +0.0.0.0 ivwbax.de +0.0.0.0 ivwbbox.de +0.0.0.0 ivwbeox.de +0.0.0.0 ivwbex.de +0.0.0.0 ivwbgox.de +0.0.0.0 ivwbhox.de +0.0.0.0 ivwbiox.de +0.0.0.0 ivwbix.de +0.0.0.0 ivwbkox.de +0.0.0.0 ivwbkx.de +0.0.0.0 ivwblox.de +0.0.0.0 ivwblx.de +0.0.0.0 ivwbnox.de +0.0.0.0 ivwbo0x.de +0.0.0.0 ivwbo9x.de +0.0.0.0 ivwboax.de +0.0.0.0 ivwboc.de +0.0.0.0 ivwbock.de +0.0.0.0 ivwbocx.de +0.0.0.0 ivwbod.de +0.0.0.0 ivwbo.de +0.0.0.0 ivwbodx.de +0.0.0.0 ivwboex.de +0.0.0.0 ivwboix.de +0.0.0.0 ivwboks.de +0.0.0.0 ivwbokx.de +0.0.0.0 ivwbolx.de +0.0.0.0 ivwboox.de +0.0.0.0 ivwbopx.de +0.0.0.0 ivwbos.de +0.0.0.0 ivwbosx.de +0.0.0.0 ivwboux.de +0.0.0.0 ivwbox0.de +0.0.0.0 ivwbox1.de +0.0.0.0 ivwbox2.de +0.0.0.0 ivwbox3.de +0.0.0.0 ivwbox4.de +0.0.0.0 ivwbox5.de +0.0.0.0 ivwbox6.de +0.0.0.0 ivwbox7.de +0.0.0.0 ivwbox8.de +0.0.0.0 ivwbox9.de +0.0.0.0 ivwboxa.de +0.0.0.0 ivwboxb.de +0.0.0.0 ivwboxc.de +0.0.0.0 ivwboxd.de +0.0.0.0 ivwbox.de +0.0.0.0 ivwboxe.de +0.0.0.0 ivwboxes.de +0.0.0.0 ivwboxf.de +0.0.0.0 ivwboxg.de +0.0.0.0 ivwboxh.de +0.0.0.0 ivwboxi.de +0.0.0.0 ivwboxj.de +0.0.0.0 ivwboxk.de +0.0.0.0 ivwboxl.de +0.0.0.0 ivwboxm.de +0.0.0.0 ivwboxn.de +0.0.0.0 ivwboxo.de +0.0.0.0 ivwboxp.de +0.0.0.0 ivwboxq.de +0.0.0.0 ivwboxr.de +0.0.0.0 ivwboxs.de +0.0.0.0 ivwboxt.de +0.0.0.0 ivwboxu.de +0.0.0.0 ivwboxv.de +0.0.0.0 ivwboxw.de +0.0.0.0 ivwboxx.de +0.0.0.0 ivwboxy.de +0.0.0.0 ivwboxz.de +0.0.0.0 ivwboyx.de +0.0.0.0 ivwboz.de +0.0.0.0 ivwbozx.de +0.0.0.0 ivwbpox.de +0.0.0.0 ivwbpx.de +0.0.0.0 ivwbuox.de +0.0.0.0 ivwbux.de +0.0.0.0 ivwbvox.de +0.0.0.0 ivwbx.de +0.0.0.0 ivwbxo.de +0.0.0.0 ivwbyox.de +0.0.0.0 ivwbyx.de +0.0.0.0 ivwebox.de +0.0.0.0 ivwgbox.de +0.0.0.0 ivwgox.de +0.0.0.0 ivwhbox.de +0.0.0.0 ivwhox.de +0.0.0.0 ivwnbox.de +0.0.0.0 ivwnox.de +0.0.0.0 ivwobx.de +0.0.0.0 ivwox.de +0.0.0.0 ivwpbox.de +0.0.0.0 ivwpox.de +0.0.0.0 ivwqbox.de +0.0.0.0 ivwsbox.de +0.0.0.0 ivwvbox.de +0.0.0.0 ivwvox.de +0.0.0.0 ivwwbox.de +0.0.0.0 iwbox.de +0.0.0.0 iwvbox.de +0.0.0.0 iwvwbox.de +0.0.0.0 iwwbox.de +0.0.0.0 iyvwbox.de +0.0.0.0 jivwbox.de +0.0.0.0 jvwbox.de +0.0.0.0 kicker.ivwbox.de +0.0.0.0 kivwbox.de +0.0.0.0 kvwbox.de +0.0.0.0 livwbox.de +0.0.0.0 mivwbox.de +0.0.0.0 netzmarkt.ivwbox.de +0.0.0.0 nivwbox.de +0.0.0.0 ntv.ivwbox.de +0.0.0.0 oivwbox.de +0.0.0.0 onvis.ivwbox.de +0.0.0.0 ovwbox.de +0.0.0.0 pivwbox.de +0.0.0.0 qivwbox.de +0.0.0.0 rivwbox.de +0.0.0.0 sivwbox.de +0.0.0.0 spiegel.ivwbox.de +0.0.0.0 tivwbox.de +0.0.0.0 uivwbox.de +0.0.0.0 uvwbox.de +0.0.0.0 vivwbox.de +0.0.0.0 viwbox.de +0.0.0.0 vwbox.de +0.0.0.0 wivwbox.de +0.0.0.0 wwivwbox.de +0.0.0.0 www.0ivwbox.de +0.0.0.0 www.1ivwbox.de +0.0.0.0 www.2ivwbox.de +0.0.0.0 www.3ivwbox.de +0.0.0.0 www.4ivwbox.de +0.0.0.0 www.5ivwbox.de +0.0.0.0 www.6ivwbox.de +0.0.0.0 www.7ivwbox.de +0.0.0.0 www.8ivwbox.de +0.0.0.0 www.8vwbox.de +0.0.0.0 www.9ivwbox.de +0.0.0.0 www.9vwbox.de +0.0.0.0 www.aivwbox.de +0.0.0.0 www.avwbox.de +0.0.0.0 www.bivwbox.de +0.0.0.0 www.civwbox.de +0.0.0.0 www.divwbox.de +0.0.0.0 www.eevwbox.de +0.0.0.0 www.eivwbox.de +0.0.0.0 www.evwbox.de +0.0.0.0 www.fivwbox.de +0.0.0.0 www.givwbox.de +0.0.0.0 www.hivwbox.de +0.0.0.0 www.i8vwbox.de +0.0.0.0 www.i9vwbox.de +0.0.0.0 www.iavwbox.de +0.0.0.0 www.ibvwbox.de +0.0.0.0 www.ibwbox.de +0.0.0.0 www.icvwbox.de +0.0.0.0 www.icwbox.de +0.0.0.0 www.ievwbox.de +0.0.0.0 www.ifvwbox.de +0.0.0.0 www.ifwbox.de +0.0.0.0 www.igvwbox.de +0.0.0.0 www.igwbox.de +0.0.0.0 www.iivwbox.de +0.0.0.0 www.ijvwbox.de +0.0.0.0 www.ikvwbox.de +0.0.0.0 www.iovwbox.de +0.0.0.0 www.iuvwbox.de +0.0.0.0 www.iv2box.de +0.0.0.0 www.iv2wbox.de +0.0.0.0 www.iv3box.de +0.0.0.0 www.iv3wbox.de +0.0.0.0 www.ivabox.de +0.0.0.0 www.ivawbox.de +0.0.0.0 www.ivbox.de +0.0.0.0 www.ivbwbox.de +0.0.0.0 www.ivbwox.de +0.0.0.0 www.ivcwbox.de +0.0.0.0 www.ivebox.de +0.0.0.0 www.ivewbox.de +0.0.0.0 www.ivfwbox.de +0.0.0.0 www.ivgwbox.de +0.0.0.0 www.ivqbox.de +0.0.0.0 www.ivqwbox.de +0.0.0.0 www.ivsbox.de +0.0.0.0 www.ivswbox.de +0.0.0.0 www.ivvbox.de +0.0.0.0 www.ivvwbox.de +0.0.0.0 www.ivw2box.de +0.0.0.0 www.ivw3box.de +0.0.0.0 www.ivwabox.de +0.0.0.0 www.ivwb0ox.de +0.0.0.0 www.ivwb0x.de +0.0.0.0 www.ivwb9ox.de +0.0.0.0 www.ivwb9x.de +0.0.0.0 www.ivwbaox.de +0.0.0.0 www.ivwbax.de +0.0.0.0 www.ivwbbox.de +0.0.0.0 www.ivwbeox.de +0.0.0.0 www.ivwbex.de +0.0.0.0 www.ivwbgox.de +0.0.0.0 www.ivwbhox.de +0.0.0.0 www.ivwbiox.de +0.0.0.0 www.ivwbix.de +0.0.0.0 www.ivwbkox.de +0.0.0.0 www.ivwbkx.de +0.0.0.0 www.ivwblox.de +0.0.0.0 www.ivwblx.de +0.0.0.0 www.ivwbnox.de +0.0.0.0 www.ivwbo0x.de +0.0.0.0 www.ivwbo9x.de +0.0.0.0 www.ivwboax.de +0.0.0.0 www.ivwboc.de +0.0.0.0 www.ivwbock.de +0.0.0.0 www.ivwbocx.de +0.0.0.0 www.ivwbod.de +0.0.0.0 www.ivwbo.de +0.0.0.0 www.ivwbodx.de +0.0.0.0 www.ivwboex.de +0.0.0.0 www.ivwboix.de +0.0.0.0 www.ivwboks.de +0.0.0.0 www.ivwbokx.de +0.0.0.0 www.ivwbolx.de +0.0.0.0 www.ivwboox.de +0.0.0.0 www.ivwbopx.de +0.0.0.0 www.ivwbos.de +0.0.0.0 www.ivwbosx.de +0.0.0.0 www.ivwboux.de +0.0.0.0 www.ivwbox0.de +0.0.0.0 www.ivwbox1.de +0.0.0.0 www.ivwbox2.de +0.0.0.0 www.ivwbox3.de +0.0.0.0 www.ivwbox4.de +0.0.0.0 www.ivwbox5.de +0.0.0.0 www.ivwbox6.de +0.0.0.0 www.ivwbox7.de +0.0.0.0 www.ivwbox8.de +0.0.0.0 www.ivwbox9.de +0.0.0.0 www.ivwboxa.de +0.0.0.0 www.ivwboxb.de +0.0.0.0 www.ivwboxc.de +0.0.0.0 www.ivwboxd.de +0.0.0.0 www.ivwbox.de +0.0.0.0 wwwivwbox.de +0.0.0.0 www.ivwboxe.de +0.0.0.0 www.ivwboxes.de +0.0.0.0 www.ivwboxf.de +0.0.0.0 www.ivwboxg.de +0.0.0.0 www.ivwboxh.de +0.0.0.0 www.ivwboxi.de +0.0.0.0 www.ivwboxj.de +0.0.0.0 www.ivwboxk.de +0.0.0.0 www.ivwboxl.de +0.0.0.0 www.ivwboxm.de +0.0.0.0 www.ivwboxn.de +0.0.0.0 www.ivwboxo.de +0.0.0.0 www.ivwboxp.de +0.0.0.0 www.ivwboxq.de +0.0.0.0 www.ivwboxr.de +0.0.0.0 www.ivwboxs.de +0.0.0.0 www.ivwboxt.de +0.0.0.0 www.ivwboxu.de +0.0.0.0 www.ivwboxv.de +0.0.0.0 www.ivwboxw.de +0.0.0.0 www.ivwboxx.de +0.0.0.0 www.ivwboxy.de +0.0.0.0 www.ivwboxz.de +0.0.0.0 www.ivwboyx.de +0.0.0.0 www.ivwboz.de +0.0.0.0 www.ivwbozx.de +0.0.0.0 www.ivwbpox.de +0.0.0.0 www.ivwbpx.de +0.0.0.0 www.ivwbuox.de +0.0.0.0 www.ivwbux.de +0.0.0.0 www.ivwbvox.de +0.0.0.0 www.ivwbx.de +0.0.0.0 www.ivwbxo.de +0.0.0.0 www.ivwbyox.de +0.0.0.0 www.ivwbyx.de +0.0.0.0 www.ivwebox.de +0.0.0.0 www.ivwgbox.de +0.0.0.0 www.ivwgox.de +0.0.0.0 www.ivwhbox.de +0.0.0.0 www.ivwhox.de +0.0.0.0 www.ivwnbox.de +0.0.0.0 www.ivwnox.de +0.0.0.0 www.ivwobx.de +0.0.0.0 www.ivwox.de +0.0.0.0 www.ivwpbox.de +0.0.0.0 www.ivwpox.de +0.0.0.0 www.ivwqbox.de +0.0.0.0 www.ivwsbox.de +0.0.0.0 www.ivwvbox.de +0.0.0.0 www.ivwvox.de +0.0.0.0 www.ivwwbox.de +0.0.0.0 www.iwbox.de +0.0.0.0 www.iwvbox.de +0.0.0.0 www.iwvwbox.de +0.0.0.0 www.iwwbox.de +0.0.0.0 www.iyvwbox.de +0.0.0.0 www.jivwbox.de +0.0.0.0 www.jvwbox.de +0.0.0.0 www.kivwbox.de +0.0.0.0 www.kvwbox.de +0.0.0.0 www.livwbox.de +0.0.0.0 www.mivwbox.de +0.0.0.0 www.nivwbox.de +0.0.0.0 www.oivwbox.de +0.0.0.0 www.ovwbox.de +0.0.0.0 www.pivwbox.de +0.0.0.0 www.qivwbox.de +0.0.0.0 www.rivwbox.de +0.0.0.0 www.sivwbox.de +0.0.0.0 www.tivwbox.de +0.0.0.0 www.uivwbox.de +0.0.0.0 www.uvwbox.de +0.0.0.0 www.vivwbox.de +0.0.0.0 www.viwbox.de +0.0.0.0 www.vwbox.de +0.0.0.0 www.wivwbox.de +0.0.0.0 www.wwivwbox.de +0.0.0.0 www.wwwivwbox.de +0.0.0.0 www.xivwbox.de +0.0.0.0 www.yevwbox.de +0.0.0.0 www.yivwbox.de +0.0.0.0 www.yvwbox.de +0.0.0.0 www.zivwbox.de +0.0.0.0 xivwbox.de +0.0.0.0 yevwbox.de +0.0.0.0 yivwbox.de +0.0.0.0 yvwbox.de +0.0.0.0 zivwbox.de +# + +# + +# message board and wiki spam -- these sites are linked in + # message board spam and are unlikely to be real sites +0.0.0.0 10pg.scl5fyd.info +0.0.0.0 21jewelry.com +0.0.0.0 24x7.soliday.org +0.0.0.0 2site.com +0.0.0.0 33b.b33r.net +0.0.0.0 48.2mydns.net +0.0.0.0 4allfree.com +0.0.0.0 55.2myip.com +0.0.0.0 6165.rapidforum.com +0.0.0.0 6pg.ryf3hgf.info +0.0.0.0 7x7.ruwe.net +0.0.0.0 7x.cc +0.0.0.0 911.x24hr.com +0.0.0.0 ab.5.p2l.info +0.0.0.0 aboutharrypotter.fasthost.tv +0.0.0.0 aciphex.about-tabs.com +0.0.0.0 actonel.about-tabs.com +0.0.0.0 actos.about-tabs.com +0.0.0.0 acyclovir.1.p2l.info +0.0.0.0 adderall.ourtablets.com +0.0.0.0 adderallxr.freespaces.com +0.0.0.0 adipex.1.p2l.info +0.0.0.0 adipex.24sws.ws +0.0.0.0 adipex.3.p2l.info +0.0.0.0 adipex.4.p2l.info +0.0.0.0 adipex.hut1.ru +0.0.0.0 adipex.ourtablets.com +0.0.0.0 adipexp.3xforum.ro +0.0.0.0 adipex.shengen.ru +0.0.0.0 adipex.t-amo.net +0.0.0.0 adsearch.www1.biz +0.0.0.0 adult.shengen.ru +0.0.0.0 aguileranude.1stOK.com +0.0.0.0 ahh-teens.com +0.0.0.0 aid-golf-golfdust-training.tabrays.com +0.0.0.0 airline-ticket.gloses.net +0.0.0.0 air-plane-ticket.beesearch.info +0.0.0.0 ak.5.p2l.info +0.0.0.0 al.5.p2l.info +0.0.0.0 alcohol-treatment.gloses.net +0.0.0.0 allegra.1.p2l.info +0.0.0.0 allergy.1.p2l.info +0.0.0.0 all-sex.shengen.ru +0.0.0.0 alprazolamonline.findmenow.info +0.0.0.0 alprazolam.ourtablets.com +0.0.0.0 alyssamilano.1stOK.com +0.0.0.0 alyssamilano.ca.tt +0.0.0.0 alyssamilano.home.sapo.pt +0.0.0.0 amateur-mature-sex.adaltabaza.net +0.0.0.0 ambien.1.p2l.info +0.0.0.0 ambien.3.p2l.info +0.0.0.0 ambien.4.p2l.info +0.0.0.0 ambien.ourtablets.com +0.0.0.0 amoxicillin.ourtablets.com +0.0.0.0 angelinajolie.1stOK.com +0.0.0.0 angelinajolie.ca.tt +0.0.0.0 anklets.shengen.ru +0.0.0.0 annanicolesannanicolesmith.ca.tt +0.0.0.0 annanicolesmith.1stOK.com +0.0.0.0 antidepressants.1.p2l.info +0.0.0.0 anxiety.1.p2l.info +0.0.0.0 aol.spb.su +0.0.0.0 ar.5.p2l.info +0.0.0.0 arcade.ya.com +0.0.0.0 armanix.white.prohosting.com +0.0.0.0 arthritis.atspace.com +0.0.0.0 as.5.p2l.info +0.0.0.0 aspirin.about-tabs.com +0.0.0.0 ativan.ourtablets.com +0.0.0.0 austria-car-rental.findworm.net +0.0.0.0 auto.allewagen.de +0.0.0.0 az.5.p2l.info +0.0.0.0 azz.badazz.org +0.0.0.0 balabass.peerserver.com +0.0.0.0 balab.portx.net +0.0.0.0 bbs.ws +0.0.0.0 bc.5.p2l.info +0.0.0.0 beauty.finaltips.com +0.0.0.0 berkleynude.ca.tt +0.0.0.0 bestlolaray.com +0.0.0.0 bet-online.petrovka.info +0.0.0.0 betting-online.petrovka.info +0.0.0.0 bextra.ourtablets.com +0.0.0.0 bextra-store.shengen.ru +0.0.0.0 bingo-online.petrovka.info +0.0.0.0 birth-control.1.p2l.info +0.0.0.0 bontril.1.p2l.info +0.0.0.0 bontril.ourtablets.com +0.0.0.0 britneyspears.1stOK.com +0.0.0.0 britneyspears.ca.tt +0.0.0.0 br.rawcomm.net +0.0.0.0 bupropion-hcl.1.p2l.info +0.0.0.0 buspar.1.p2l.info +0.0.0.0 buspirone.1.p2l.info +0.0.0.0 butalbital-apap.1.p2l.info +0.0.0.0 buy-adipex.aca.ru +0.0.0.0 buy-adipex-cheap-adipex-online.com +0.0.0.0 buy-adipex.hut1.ru +0.0.0.0 buy-adipex.i-jogo.net +0.0.0.0 buy-adipex-online.md-online24.de +0.0.0.0 buy-adipex.petrovka.info +0.0.0.0 buy-carisoprodol.polybuild.ru +0.0.0.0 buy-cheap-phentermine.blogspot.com +0.0.0.0 buy-cheap-xanax.all.at +0.0.0.0 buy-cialis-cheap-cialis-online.info +0.0.0.0 buy-cialis.freewebtools.com +0.0.0.0 buycialisonline.7h.com +0.0.0.0 buycialisonline.bigsitecity.com +0.0.0.0 buy-cialis-online.iscool.nl +0.0.0.0 buy-cialis-online.meperdoe.net +0.0.0.0 buy-cialis.splinder.com +0.0.0.0 buy-diazepam.connect.to +0.0.0.0 buyfioricet.findmenow.info +0.0.0.0 buy-fioricet.hut1.ru +0.0.0.0 buyfioricetonline.7h.com +0.0.0.0 buyfioricetonline.bigsitecity.com +0.0.0.0 buyfioricetonline.freeservers.com +0.0.0.0 buy-flower.petrovka.info +0.0.0.0 buy-hydrocodone.aca.ru +0.0.0.0 buyhydrocodone.all.at +0.0.0.0 buy-hydrocodone-cheap-hydrocodone-online.com +0.0.0.0 buy-hydrocodone.este.ru +0.0.0.0 buyhydrocodoneonline.findmenow.info +0.0.0.0 buy-hydrocodone-online.tche.com +0.0.0.0 buy-hydrocodone.petrovka.info +0.0.0.0 buy-hydrocodone.polybuild.ru +0.0.0.0 buy-hydrocodone.quesaudade.net +0.0.0.0 buy-hydrocodone.scromble.com +0.0.0.0 buylevitra.3xforum.ro +0.0.0.0 buy-levitra-cheap-levitra-online.info +0.0.0.0 buylevitraonline.7h.com +0.0.0.0 buylevitraonline.bigsitecity.com +0.0.0.0 buy-lortab-cheap-lortab-online.com +0.0.0.0 buy-lortab.hut1.ru +0.0.0.0 buylortabonline.7h.com +0.0.0.0 buylortabonline.bigsitecity.com +0.0.0.0 buy-lortab-online.iscool.nl +0.0.0.0 buypaxilonline.7h.com +0.0.0.0 buypaxilonline.bigsitecity.com +0.0.0.0 buy-phentermine-cheap-phentermine-online.com +0.0.0.0 buy-phentermine.hautlynx.com +0.0.0.0 buy-phentermine-online.135.it +0.0.0.0 buyphentermineonline.7h.com +0.0.0.0 buyphentermineonline.bigsitecity.com +0.0.0.0 buy-phentermine-online.i-jogo.net +0.0.0.0 buy-phentermine-online.i-ltda.net +0.0.0.0 buy-phentermine.polybuild.ru +0.0.0.0 buy-phentermine.thepizza.net +0.0.0.0 buy-tamiflu.asian-flu-vaccine.com +0.0.0.0 buy-ultram-online.iscool.nl +0.0.0.0 buy-valium-cheap-valium-online.com +0.0.0.0 buy-valium.este.ru +0.0.0.0 buy-valium.hut1.ru +0.0.0.0 buy-valium.polybuild.ru +0.0.0.0 buyvalium.polybuild.ru +0.0.0.0 buy-viagra.aca.ru +0.0.0.0 buy-viagra.go.to +0.0.0.0 buy-viagra.polybuild.ru +0.0.0.0 buyviagra.polybuild.ru +0.0.0.0 buy-vicodin-cheap-vicodin-online.com +0.0.0.0 buy-vicodin.dd.vu +0.0.0.0 buy-vicodin.hut1.ru +0.0.0.0 buy-vicodin.iscool.nl +0.0.0.0 buy-vicodin-online.i-blog.net +0.0.0.0 buy-vicodin-online.seumala.net +0.0.0.0 buy-vicodin-online.supersite.fr +0.0.0.0 buyvicodinonline.veryweird.com +0.0.0.0 buy-xanax.aztecaonline.net +0.0.0.0 buy-xanax-cheap-xanax-online.com +0.0.0.0 buy-xanax.hut1.ru +0.0.0.0 buy-xanax-online.amovoce.net +0.0.0.0 buy-zyban.all.at +0.0.0.0 bx6.blrf.net +0.0.0.0 ca.5.p2l.info +0.0.0.0 camerondiaznude.1stOK.com +0.0.0.0 camerondiaznude.ca.tt +0.0.0.0 car-donation.shengen.ru +0.0.0.0 car-insurance.inshurance-from.com +0.0.0.0 carisoprodol.1.p2l.info +0.0.0.0 carisoprodol.hut1.ru +0.0.0.0 carisoprodol.ourtablets.com +0.0.0.0 carisoprodol.polybuild.ru +0.0.0.0 carisoprodol.shengen.ru +0.0.0.0 car-loan.shengen.ru +0.0.0.0 carmenelectra.1stOK.com +0.0.0.0 cash-advance.now-cash.com +0.0.0.0 casino-gambling-online.searchservice.info +0.0.0.0 casino-online.100gal.net +0.0.0.0 cat.onlinepeople.net +0.0.0.0 cc5f.dnyp.com +0.0.0.0 celebrex.1.p2l.info +0.0.0.0 celexa.1.p2l.info +0.0.0.0 celexa.3.p2l.info +0.0.0.0 celexa.4.p2l.info +0.0.0.0 cephalexin.ourtablets.com +0.0.0.0 charlizetheron.1stOK.com +0.0.0.0 cheap-adipex.hut1.ru +0.0.0.0 cheap-carisoprodol.polybuild.ru +0.0.0.0 cheap-hydrocodone.go.to +0.0.0.0 cheap-hydrocodone.polybuild.ru +0.0.0.0 cheap-phentermine.polybuild.ru +0.0.0.0 cheap-valium.polybuild.ru +0.0.0.0 cheap-viagra.polybuild.ru +0.0.0.0 cheap-web-hosting-here.blogspot.com +0.0.0.0 cheap-xanax-here.blogspot.com +0.0.0.0 cheapxanax.hut1.ru +0.0.0.0 cialis.1.p2l.info +0.0.0.0 cialis.3.p2l.info +0.0.0.0 cialis.4.p2l.info +0.0.0.0 cialis-finder.com +0.0.0.0 cialis-levitra-viagra.com.cn +0.0.0.0 cialis.ourtablets.com +0.0.0.0 cialis-store.shengen.ru +0.0.0.0 co.5.p2l.info +0.0.0.0 co.dcclan.co.uk +0.0.0.0 codeine.ourtablets.com +0.0.0.0 creampie.afdss.info +0.0.0.0 credit-card-application.now-cash.com +0.0.0.0 credit-cards.shengen.ru +0.0.0.0 ct.5.p2l.info +0.0.0.0 cuiland.info +0.0.0.0 cyclobenzaprine.1.p2l.info +0.0.0.0 cyclobenzaprine.ourtablets.com +0.0.0.0 dal.d.la +0.0.0.0 danger-phentermine.allforyourlife.com +0.0.0.0 darvocet.ourtablets.com +0.0.0.0 dc.5.p2l.info +0.0.0.0 de.5.p2l.info +0.0.0.0 debt.shengen.ru +0.0.0.0 def.5.p2l.info +0.0.0.0 demimoorenude.1stOK.com +0.0.0.0 deniserichards.1stOK.com +0.0.0.0 detox-kit.com +0.0.0.0 detox.shengen.ru +0.0.0.0 diazepam.ourtablets.com +0.0.0.0 diazepam.razma.net +0.0.0.0 diazepam.shengen.ru +0.0.0.0 didrex.1.p2l.info +0.0.0.0 diet-pills.hut1.ru +0.0.0.0 digital-cable-descrambler.planet-high-heels.com +0.0.0.0 dir.opank.com +0.0.0.0 dos.velek.com +0.0.0.0 drewbarrymore.ca.tt +0.0.0.0 drugdetox.shengen.ru +0.0.0.0 drug-online.petrovka.info +0.0.0.0 drug-testing.shengen.ru +0.0.0.0 eb.dd.bluelinecomputers.be +0.0.0.0 eb.prout.be +0.0.0.0 ed.at.is13.de +0.0.0.0 ed.at.thamaster.de +0.0.0.0 e-dot.hut1.ru +0.0.0.0 efam4.info +0.0.0.0 effexor-xr.1.p2l.info +0.0.0.0 e-hosting.hut1.ru +0.0.0.0 ei.imbucurator-de-prost.com +0.0.0.0 eminemticket.freespaces.com +0.0.0.0 en.dd.blueline.be +0.0.0.0 enpresse.1.p2l.info +0.0.0.0 en.ultrex.ru +0.0.0.0 epson-printer-ink.beesearch.info +0.0.0.0 erectile.byethost33.com +0.0.0.0 esgic.1.p2l.info +0.0.0.0 fahrrad.bikesshop.de +0.0.0.0 famous-pics.com +0.0.0.0 famvir.1.p2l.info +0.0.0.0 farmius.org +0.0.0.0 fee-hydrocodone.bebto.com +0.0.0.0 female-v.1.p2l.info +0.0.0.0 femaleviagra.findmenow.info +0.0.0.0 fg.softguy.com +0.0.0.0 findmenow.info +0.0.0.0 fioricet.1.p2l.info +0.0.0.0 fioricet.3.p2l.info +0.0.0.0 fioricet.4.p2l.info +0.0.0.0 fioricet-online.blogspot.com +0.0.0.0 firstfinda.info +0.0.0.0 fl.5.p2l.info +0.0.0.0 flexeril.1.p2l.info +0.0.0.0 flextra.1.p2l.info +0.0.0.0 flonase.1.p2l.info +0.0.0.0 flonase.3.p2l.info +0.0.0.0 flonase.4.p2l.info +0.0.0.0 florineff.ql.st +0.0.0.0 flower-online.petrovka.info +0.0.0.0 fluoxetine.1.p2l.info +0.0.0.0 fo4n.com +0.0.0.0 forex-broker.hut1.ru +0.0.0.0 forex-chart.hut1.ru +0.0.0.0 forex-market.hut1.ru +0.0.0.0 forex-news.hut1.ru +0.0.0.0 forex-online.hut1.ru +0.0.0.0 forex-signal.hut1.ru +0.0.0.0 forex-trade.hut1.ru +0.0.0.0 forex-trading-benefits.blogspot.com +0.0.0.0 forextrading.hut1.ru +0.0.0.0 freechat.llil.de +0.0.0.0 free.hostdepartment.com +0.0.0.0 free-money.host.sk +0.0.0.0 free-viagra.polybuild.ru +0.0.0.0 free-virus-scan.100gal.net +0.0.0.0 ga.5.p2l.info +0.0.0.0 game-online-video.petrovka.info +0.0.0.0 gaming-online.petrovka.info +0.0.0.0 gastrointestinal.1.p2l.info +0.0.0.0 gen-hydrocodone.polybuild.ru +0.0.0.0 getcarisoprodol.polybuild.ru +0.0.0.0 gocarisoprodol.polybuild.ru +0.0.0.0 gsm-mobile-phone.beesearch.info +0.0.0.0 gu.5.p2l.info +0.0.0.0 guerria-skateboard-tommy.tabrays.com +0.0.0.0 gwynethpaltrow.ca.tt +0.0.0.0 h1.ripway.com +0.0.0.0 hair-dos.resourcesarchive.com +0.0.0.0 halleberrynude.ca.tt +0.0.0.0 heathergraham.ca.tt +0.0.0.0 herpes.1.p2l.info +0.0.0.0 herpes.3.p2l.info +0.0.0.0 herpes.4.p2l.info +0.0.0.0 hf.themafia.info +0.0.0.0 hi.5.p2l.info +0.0.0.0 hi.pacehillel.org +0.0.0.0 holobumo.info +0.0.0.0 homehre.bravehost.com +0.0.0.0 homehre.ifrance.com +0.0.0.0 homehre.tripod.com +0.0.0.0 hoodia.kogaryu.com +0.0.0.0 hotel-las-vegas.gloses.net +0.0.0.0 hydrocodone-buy-online.blogspot.com +0.0.0.0 hydrocodone.irondel.swisshost.by +0.0.0.0 hydrocodone.on.to +0.0.0.0 hydrocodone.shengen.ru +0.0.0.0 hydrocodone.t-amo.net +0.0.0.0 hydrocodone.visa-usa.ru +0.0.0.0 hydro.polybuild.ru +0.0.0.0 ia.5.p2l.info +0.0.0.0 ia.warnet-thunder.net +0.0.0.0 ibm-notebook-battery.wp-club.net +0.0.0.0 id.5.p2l.info +0.0.0.0 il.5.p2l.info +0.0.0.0 imitrex.1.p2l.info +0.0.0.0 imitrex.3.p2l.info +0.0.0.0 imitrex.4.p2l.info +0.0.0.0 in.5.p2l.info +0.0.0.0 ionamin.1.p2l.info +0.0.0.0 ionamin.t35.com +0.0.0.0 irondel.swisshost.by +0.0.0.0 japanese-girl-xxx.com +0.0.0.0 java-games.bestxs.de +0.0.0.0 jg.hack-inter.net +0.0.0.0 job-online.petrovka.info +0.0.0.0 jobs-online.petrovka.info +0.0.0.0 kitchen-island.mensk.us +0.0.0.0 konstantin.freespaces.com +0.0.0.0 ks.5.p2l.info +0.0.0.0 ky.5.p2l.info +0.0.0.0 la.5.p2l.info +0.0.0.0 lamictal.about-tabs.com +0.0.0.0 lamisil.about-tabs.com +0.0.0.0 levitra.1.p2l.info +0.0.0.0 levitra.3.p2l.info +0.0.0.0 levitra.4.p2l.info +0.0.0.0 lexapro.1.p2l.info +0.0.0.0 lexapro.3.p2l.info +0.0.0.0 lexapro.4.p2l.info +0.0.0.0 loan.aol.msk.su +0.0.0.0 loan.maybachexelero.org +0.0.0.0 loestrin.1.p2l.info +0.0.0.0 lo.ljkeefeco.com +0.0.0.0 lol.to +0.0.0.0 lortab-cod.hut1.ru +0.0.0.0 lortab.hut1.ru +0.0.0.0 ma.5.p2l.info +0.0.0.0 mailforfreedom.com +0.0.0.0 make-money.shengen.ru +0.0.0.0 maps-antivert58.eksuziv.net +0.0.0.0 maps-spyware251-300.eksuziv.net +0.0.0.0 marketing.beesearch.info +0.0.0.0 mb.5.p2l.info +0.0.0.0 mba-online.petrovka.info +0.0.0.0 md.5.p2l.info +0.0.0.0 me.5.p2l.info +0.0.0.0 medical.carway.net +0.0.0.0 mens.1.p2l.info +0.0.0.0 meridia.1.p2l.info +0.0.0.0 meridia.3.p2l.info +0.0.0.0 meridia.4.p2l.info +0.0.0.0 meridiameridia.3xforum.ro +0.0.0.0 mesotherapy.jino-net.ru +0.0.0.0 mi.5.p2l.info +0.0.0.0 micardiss.ql.st +0.0.0.0 microsoft-sql-server.wp-club.net +0.0.0.0 mn.5.p2l.info +0.0.0.0 mo.5.p2l.info +0.0.0.0 moc.silk.com +0.0.0.0 mortgage-memphis.hotmail.ru +0.0.0.0 mortgage-rates.now-cash.com +0.0.0.0 mp.5.p2l.info +0.0.0.0 mrjeweller.us +0.0.0.0 ms.5.p2l.info +0.0.0.0 mt.5.p2l.info +0.0.0.0 multimedia-projector.katrina.ru +0.0.0.0 muscle-relaxers.1.p2l.info +0.0.0.0 music102.awardspace.com +0.0.0.0 mydaddy.b0x.com +0.0.0.0 myphentermine.polybuild.ru +0.0.0.0 nasacort.1.p2l.info +0.0.0.0 nasonex.1.p2l.info +0.0.0.0 nb.5.p2l.info +0.0.0.0 nc.5.p2l.info +0.0.0.0 nd.5.p2l.info +0.0.0.0 ne.5.p2l.info +0.0.0.0 nellyticket.beast-space.com +0.0.0.0 nelsongod.ca +0.0.0.0 nexium.1.p2l.info +0.0.0.0 nextel-ringtone.komi.su +0.0.0.0 nextel-ringtone.spb.su +0.0.0.0 nf.5.p2l.info +0.0.0.0 nh.5.p2l.info +0.0.0.0 nj.5.p2l.info +0.0.0.0 nm.5.p2l.info +0.0.0.0 nordette.1.p2l.info +0.0.0.0 nordette.3.p2l.info +0.0.0.0 nordette.4.p2l.info +0.0.0.0 norton-antivirus-trial.searchservice.info +0.0.0.0 notebook-memory.searchservice.info +0.0.0.0 ns.5.p2l.info +0.0.0.0 nv.5.p2l.info +0.0.0.0 ny.5.p2l.info +0.0.0.0 o8.aus.cc +0.0.0.0 ofni.al0ne.info +0.0.0.0 oh.5.p2l.info +0.0.0.0 ok.5.p2l.info +0.0.0.0 on.5.p2l.info +0.0.0.0 online-auto-insurance.petrovka.info +0.0.0.0 online-bingo.petrovka.info +0.0.0.0 online-broker.petrovka.info +0.0.0.0 online-cash.petrovka.info +0.0.0.0 online-casino.shengen.ru +0.0.0.0 online-casino.webpark.pl +0.0.0.0 online-cigarettes.hitslog.net +0.0.0.0 online-college.petrovka.info +0.0.0.0 online-degree.petrovka.info +0.0.0.0 online-florist.petrovka.info +0.0.0.0 online-forex.hut1.ru +0.0.0.0 online-forex-trading-systems.blogspot.com +0.0.0.0 online-gaming.petrovka.info +0.0.0.0 online-job.petrovka.info +0.0.0.0 online-loan.petrovka.info +0.0.0.0 online-mortgage.petrovka.info +0.0.0.0 online-personal.petrovka.info +0.0.0.0 online-personals.petrovka.info +0.0.0.0 online-pharmacy-online.blogspot.com +0.0.0.0 online-pharmacy.petrovka.info +0.0.0.0 online-phentermine.petrovka.info +0.0.0.0 online-poker-gambling.petrovka.info +0.0.0.0 online-poker-game.petrovka.info +0.0.0.0 online-poker.shengen.ru +0.0.0.0 online-prescription.petrovka.info +0.0.0.0 online-school.petrovka.info +0.0.0.0 online-schools.petrovka.info +0.0.0.0 online-single.petrovka.info +0.0.0.0 online-tarot-reading.beesearch.info +0.0.0.0 online-travel.petrovka.info +0.0.0.0 online-university.petrovka.info +0.0.0.0 online-viagra.petrovka.info +0.0.0.0 online-xanax.petrovka.info +0.0.0.0 onlypreteens.com +0.0.0.0 only-valium.go.to +0.0.0.0 only-valium.shengen.ru +0.0.0.0 or.5.p2l.info +0.0.0.0 oranla.info +0.0.0.0 orderadipex.findmenow.info +0.0.0.0 order-hydrocodone.polybuild.ru +0.0.0.0 order-phentermine.polybuild.ru +0.0.0.0 order-valium.polybuild.ru +0.0.0.0 ortho-tri-cyclen.1.p2l.info +0.0.0.0 pa.5.p2l.info +0.0.0.0 pacific-poker.e-online-poker-4u.net +0.0.0.0 pain-relief.1.p2l.info +0.0.0.0 paintball-gun.tripod.com +0.0.0.0 patio-furniture.dreamhoster.com +0.0.0.0 paxil.1.p2l.info +0.0.0.0 pay-day-loans.beesearch.info +0.0.0.0 payday-loans.now-cash.com +0.0.0.0 pctuzing.php5.cz +0.0.0.0 pd1.funnyhost.com +0.0.0.0 pe.5.p2l.info +0.0.0.0 peter-north-cum-shot.blogspot.com +0.0.0.0 pets.finaltips.com +0.0.0.0 pharmacy-canada.forsearch.net +0.0.0.0 pharmacy.hut1.ru +0.0.0.0 pharmacy-news.blogspot.com +0.0.0.0 pharmacy-online.petrovka.info +0.0.0.0 phendimetrazine.1.p2l.info +0.0.0.0 phentermine.1.p2l.info +0.0.0.0 phentermine.3.p2l.info +0.0.0.0 phentermine.4.p2l.info +0.0.0.0 phentermine.aussie7.com +0.0.0.0 phentermine-buy-online.hitslog.net +0.0.0.0 phentermine-buy.petrovka.info +0.0.0.0 phentermine-online.iscool.nl +0.0.0.0 phentermine-online.petrovka.info +0.0.0.0 phentermine.petrovka.info +0.0.0.0 phentermine.polybuild.ru +0.0.0.0 phentermine.shengen.ru +0.0.0.0 phentermine.t-amo.net +0.0.0.0 phentermine.webpark.pl +0.0.0.0 phone-calling-card.exnet.su +0.0.0.0 plavix.shengen.ru +0.0.0.0 play-poker-free.forsearch.net +0.0.0.0 poker-games.e-online-poker-4u.net +0.0.0.0 pop.egi.biz +0.0.0.0 pr.5.p2l.info +0.0.0.0 prescription-drugs.easy-find.net +0.0.0.0 prescription-drugs.shengen.ru +0.0.0.0 preteenland.com +0.0.0.0 preteensite.com +0.0.0.0 prevacid.1.p2l.info +0.0.0.0 prevent-asian-flu.com +0.0.0.0 prilosec.1.p2l.info +0.0.0.0 propecia.1.p2l.info +0.0.0.0 protonix.shengen.ru +0.0.0.0 psorias.atspace.com +0.0.0.0 purchase.hut1.ru +0.0.0.0 qc.5.p2l.info +0.0.0.0 qz.informs.com +0.0.0.0 refinance.shengen.ru +0.0.0.0 relenza.asian-flu-vaccine.com +0.0.0.0 renova.1.p2l.info +0.0.0.0 replacement-windows.gloses.net +0.0.0.0 re.rutan.org +0.0.0.0 resanium.com +0.0.0.0 retin-a.1.p2l.info +0.0.0.0 ri.5.p2l.info +0.0.0.0 rise-media.ru +0.0.0.0 root.dns.bz +0.0.0.0 roulette-online.petrovka.info +0.0.0.0 router.googlecom.biz +0.0.0.0 s32.bilsay.com +0.0.0.0 samsclub33.pochta.ru +0.0.0.0 sc10.net +0.0.0.0 sc.5.p2l.info +0.0.0.0 sd.5.p2l.info +0.0.0.0 search4you.50webs.com +0.0.0.0 search-phentermine.hpage.net +0.0.0.0 searchpill.boom.ru +0.0.0.0 seasonale.1.p2l.info +0.0.0.0 shop.kauffes.de +0.0.0.0 single-online.petrovka.info +0.0.0.0 sk.5.p2l.info +0.0.0.0 skelaxin.1.p2l.info +0.0.0.0 skelaxin.3.p2l.info +0.0.0.0 skelaxin.4.p2l.info +0.0.0.0 skin-care.1.p2l.info +0.0.0.0 skocz.pl +0.0.0.0 sleep-aids.1.p2l.info +0.0.0.0 sleeper-sofa.dreamhoster.com +0.0.0.0 slf5cyd.info +0.0.0.0 sobolev.net.ru +0.0.0.0 soma.1.p2l.info +0.0.0.0 soma.3xforum.ro +0.0.0.0 soma-store.visa-usa.ru +0.0.0.0 sonata.1.p2l.info +0.0.0.0 sport-betting-online.hitslog.net +0.0.0.0 spyware-removers.shengen.ru +0.0.0.0 spyware-scan.100gal.net +0.0.0.0 spyware.usafreespace.com +0.0.0.0 sq7.co.uk +0.0.0.0 sql-server-driver.beesearch.info +0.0.0.0 starlix.ql.st +0.0.0.0 stop-smoking.1.p2l.info +0.0.0.0 supplements.1.p2l.info +0.0.0.0 sx.nazari.org +0.0.0.0 sx.z0rz.com +0.0.0.0 ta.at.ic5mp.net +0.0.0.0 ta.at.user-mode-linux.net +0.0.0.0 tamiflu-in-canada.asian-flu-vaccine.com +0.0.0.0 tamiflu-no-prescription.asian-flu-vaccine.com +0.0.0.0 tamiflu-purchase.asian-flu-vaccine.com +0.0.0.0 tamiflu-without-prescription.asian-flu-vaccine.com +0.0.0.0 tenuate.1.p2l.info +0.0.0.0 texas-hold-em.e-online-poker-4u.net +0.0.0.0 texas-holdem.shengen.ru +0.0.0.0 ticket20.tripod.com +0.0.0.0 tizanidine.1.p2l.info +0.0.0.0 tn.5.p2l.info +0.0.0.0 topmeds10.com +0.0.0.0 top.pcanywhere.net +0.0.0.0 toyota.cyberealhosting.com +0.0.0.0 tramadol.1.p2l.info +0.0.0.0 tramadol2006.3xforum.ro +0.0.0.0 tramadol.3.p2l.info +0.0.0.0 tramadol.4.p2l.info +0.0.0.0 travel-insurance-quotes.beesearch.info +0.0.0.0 triphasil.1.p2l.info +0.0.0.0 triphasil.3.p2l.info +0.0.0.0 triphasil.4.p2l.info +0.0.0.0 tx.5.p2l.info +0.0.0.0 uf2aasn.111adfueo.us +0.0.0.0 ultracet.1.p2l.info +0.0.0.0 ultram.1.p2l.info +0.0.0.0 united-airline-fare.100pantyhose.com +0.0.0.0 university-online.petrovka.info +0.0.0.0 urlcut.net +0.0.0.0 urshort.net +0.0.0.0 us.kopuz.com +0.0.0.0 ut.5.p2l.info +0.0.0.0 utairway.com +0.0.0.0 va.5.p2l.info +0.0.0.0 vacation.toppick.info +0.0.0.0 valium.este.ru +0.0.0.0 valium.hut1.ru +0.0.0.0 valium.ourtablets.com +0.0.0.0 valium.polybuild.ru +0.0.0.0 valiumvalium.3xforum.ro +0.0.0.0 valtrex.1.p2l.info +0.0.0.0 valtrex.3.p2l.info +0.0.0.0 valtrex.4.p2l.info +0.0.0.0 valtrex.7h.com +0.0.0.0 vaniqa.1.p2l.info +0.0.0.0 vi.5.p2l.info +0.0.0.0 viagra.1.p2l.info +0.0.0.0 viagra.3.p2l.info +0.0.0.0 viagra.4.p2l.info +0.0.0.0 viagra-online.petrovka.info +0.0.0.0 viagra-pill.blogspot.com +0.0.0.0 viagra.polybuild.ru +0.0.0.0 viagra-soft-tabs.1.p2l.info +0.0.0.0 viagra-store.shengen.ru +0.0.0.0 viagraviagra.3xforum.ro +0.0.0.0 vicodin-online.petrovka.info +0.0.0.0 vicodin-store.shengen.ru +0.0.0.0 vicodin.t-amo.net +0.0.0.0 viewtools.com +0.0.0.0 vioxx.1.p2l.info +0.0.0.0 vitalitymax.1.p2l.info +0.0.0.0 vt.5.p2l.info +0.0.0.0 vxv.phre.net +0.0.0.0 w0.drag0n.org +0.0.0.0 wa.5.p2l.info +0.0.0.0 water-bed.8p.org.uk +0.0.0.0 web-hosting.hitslog.net +0.0.0.0 webhosting.hut1.ru +0.0.0.0 weborg.hut1.ru +0.0.0.0 weight-loss.1.p2l.info +0.0.0.0 weight-loss.3.p2l.info +0.0.0.0 weight-loss.4.p2l.info +0.0.0.0 weight-loss.hut1.ru +0.0.0.0 wellbutrin.1.p2l.info +0.0.0.0 wellbutrin.3.p2l.info +0.0.0.0 wellbutrin.4.p2l.info +0.0.0.0 wellnessmonitor.bravehost.com +0.0.0.0 wi.5.p2l.info +0.0.0.0 world-trade-center.hawaiicity.com +0.0.0.0 wp-club.net +0.0.0.0 ws01.do.nu +0.0.0.0 ws02.do.nu +0.0.0.0 ws03.do.nu +0.0.0.0 ws03.home.sapo.pt +0.0.0.0 ws04.do.nu +0.0.0.0 ws04.home.sapo.pt +0.0.0.0 ws05.home.sapo.pt +0.0.0.0 ws06.home.sapo.pt +0.0.0.0 wv.5.p2l.info +0.0.0.0 www.31d.net +0.0.0.0 www3.ddns.ms +0.0.0.0 www4.at.debianbase.de +0.0.0.0 www4.epac.to +0.0.0.0 www5.3-a.net +0.0.0.0 www69.bestdeals.at +0.0.0.0 www69.byinter.net +0.0.0.0 www69.dynu.com +0.0.0.0 www69.findhere.org +0.0.0.0 www69.fw.nu +0.0.0.0 www69.ugly.as +0.0.0.0 www6.ezua.com +0.0.0.0 www6.ns1.name +0.0.0.0 www7.ygto.com +0.0.0.0 www8.ns01.us +0.0.0.0 www99.bounceme.net +0.0.0.0 www99.fdns.net +0.0.0.0 www99.zapto.org +0.0.0.0 www9.compblue.com +0.0.0.0 www9.servequake.com +0.0.0.0 www9.trickip.org +0.0.0.0 www.adspoll.com +0.0.0.0 www.adult-top-list.com +0.0.0.0 www.aektschen.de +0.0.0.0 www.aeqs.com +0.0.0.0 www.alladultdirectories.com +0.0.0.0 www.alladultdirectory.net +0.0.0.0 www.arbeitssuche-web.de +0.0.0.0 www.bestrxpills.com +0.0.0.0 www.bigsister.cxa.de +0.0.0.0 www.bigsister-puff.cxa.de +0.0.0.0 www.bitlocker.net +0.0.0.0 www.cheap-laptops-notebook-computers.info +0.0.0.0 www.cheap-online-stamp.cast.cc +0.0.0.0 www.codez-knacken.de +0.0.0.0 www.computerxchange.com +0.0.0.0 www.credit-dreams.com +0.0.0.0 www.edle-stuecke.de +0.0.0.0 www.exe-file.de +0.0.0.0 www.exttrem.de +0.0.0.0 www.fetisch-pornos.cxa.de +0.0.0.0 www.ficken-ficken-ficken.cxa.de +0.0.0.0 www.ficken-xxx.cxa.de +0.0.0.0 www.financial-advice-books.com +0.0.0.0 www.finanzmarkt2004.de +0.0.0.0 www.furnitureulimited.com +0.0.0.0 www.gewinnspiele-slotmachine.de +0.0.0.0 www.hardware4freaks.de +0.0.0.0 www.healthyaltprods.com +0.0.0.0 www.heimlich-gefilmt.cxa.de +0.0.0.0 www.huberts-kochseite.de +0.0.0.0 www.huren-verzeichnis.is4all.de +0.0.0.0 www.kaaza-legal.de +0.0.0.0 www.kajahdfssa.net +0.0.0.0 www.keyofhealth.com +0.0.0.0 www.kitchentablegang.org +0.0.0.0 www.km69.de +0.0.0.0 www.koch-backrezepte.de +0.0.0.0 www.kvr-systems.de +0.0.0.0 www.lesben-pornos.cxa.de +0.0.0.0 www.links-private-krankenversicherung.de +0.0.0.0 www.littledevildoubt.com +0.0.0.0 www.mailforfreedom.com +0.0.0.0 www.masterspace.biz +0.0.0.0 www.medical-research-books.com +0.0.0.0 www.microsoft2010.com +0.0.0.0 www.nelsongod.ca +0.0.0.0 www.nextstudent.com +0.0.0.0 www.ntdesk.de +0.0.0.0 www.nutten-verzeichnis.cxa.de +0.0.0.0 www.obesitycheck.com +0.0.0.0 www.pawnauctions.net +0.0.0.0 www.pills-home.com +0.0.0.0 www.poker4spain.com +0.0.0.0 www.poker-new.com +0.0.0.0 www.poker-unique.com +0.0.0.0 www.porno-lesben.cxa.de +0.0.0.0 www.prevent-asian-flu.com +0.0.0.0 www.randppro-cuts.com +0.0.0.0 www.romanticmaui.net +0.0.0.0 www.salldo.de +0.0.0.0 www.samsclub33.pochta.ru +0.0.0.0 www.schwarz-weisses.de +0.0.0.0 www.schwule-boys-nackt.cxa.de +0.0.0.0 www.shopping-artikel.de +0.0.0.0 www.showcaserealestate.net +0.0.0.0 www.skattabrain.com +0.0.0.0 www.softcha.com +0.0.0.0 www.striemline.de +0.0.0.0 www.talentbroker.net +0.0.0.0 www.the-discount-store.com +0.0.0.0 www.topmeds10.com +0.0.0.0 www.uniqueinternettexasholdempoker.com +0.0.0.0 www.viagra-home.com +0.0.0.0 www.vthought.com +0.0.0.0 www.vtoyshop.com +0.0.0.0 www.vulcannonibird.de +0.0.0.0 www.webabrufe.de +0.0.0.0 www.wilddreams.info +0.0.0.0 www.willcommen.de +0.0.0.0 www.xcr-286.com +0.0.0.0 wy.5.p2l.info +0.0.0.0 x25.2mydns.com +0.0.0.0 x25.plorp.com +0.0.0.0 x4.lov3.net +0.0.0.0 x6x.a.la +0.0.0.0 x888x.myserver.org +0.0.0.0 x8x.dyndns.dk +0.0.0.0 x8x.trickip.net +0.0.0.0 xanax-online.dot.de +0.0.0.0 xanax-online.run.to +0.0.0.0 xanax-online.sms2.us +0.0.0.0 xanax.ourtablets.com +0.0.0.0 xanax-store.shengen.ru +0.0.0.0 xanax.t-amo.net +0.0.0.0 xanaxxanax.3xforum.ro +0.0.0.0 x-box.t35.com +0.0.0.0 xcr-286.com +0.0.0.0 xenical.1.p2l.info +0.0.0.0 xenical.3.p2l.info +0.0.0.0 xenical.4.p2l.info +0.0.0.0 x-hydrocodone.info +0.0.0.0 xoomer.alice.it +0.0.0.0 x-phentermine.info +0.0.0.0 xr.h4ck.la +0.0.0.0 yasmin.1.p2l.info +0.0.0.0 yasmin.3.p2l.info +0.0.0.0 yasmin.4.p2l.info +0.0.0.0 yt.5.p2l.info +0.0.0.0 zanaflex.1.p2l.info +0.0.0.0 zebutal.1.p2l.info +0.0.0.0 zocor.about-tabs.com +0.0.0.0 zoloft.1.p2l.info +0.0.0.0 zoloft.3.p2l.info +0.0.0.0 zoloft.4.p2l.info +0.0.0.0 zoloft.about-tabs.com +0.0.0.0 zyban.1.p2l.info +0.0.0.0 zyban.about-tabs.com +0.0.0.0 zyban-store.shengen.ru +0.0.0.0 zyprexa.about-tabs.com +0.0.0.0 zyrtec.1.p2l.info +0.0.0.0 zyrtec.3.p2l.info +0.0.0.0 zyrtec.4.p2l.info +# + +# + +# Phorm contextual advertising sites +0.0.0.0 a.oix.com +0.0.0.0 a.oix.net +0.0.0.0 a.openinternetexchange.com +0.0.0.0 a.phormlabs.com +0.0.0.0 a.webwise.com +0.0.0.0 a.webwise.net +0.0.0.0 b.oix.net +0.0.0.0 br.phorm.com +0.0.0.0 bt.phorm.com +0.0.0.0 bt.webwise.com +0.0.0.0 b.webwise.net +0.0.0.0 c.webwise.com +0.0.0.0 c.webwise.net +0.0.0.0 d.oix.com +0.0.0.0 d.phormlabs.com +0.0.0.0 ig.fp.oix.net +0.0.0.0 invite.gezinti.com +0.0.0.0 kentsucks.youcanoptout.com +0.0.0.0 kr.phorm.com +0.0.0.0 mail.youcanoptout.com +0.0.0.0 mail.youcanoptout.net +0.0.0.0 mail.youcanoptout.org +0.0.0.0 monitor.phorm.com +0.0.0.0 mx01.openinternetexchange.com +0.0.0.0 mx01.openinternetexchange.net +0.0.0.0 mx01.webwise.com +0.0.0.0 mx03.phorm.com +0.0.0.0 navegador.oi.com.br +0.0.0.0 navegador.telefonica.com.br +0.0.0.0 ns1.oix.com +0.0.0.0 ns1.openinternetexchange.com +0.0.0.0 ns1.phorm.com +0.0.0.0 ns2.oix.com +0.0.0.0 ns2.openinternetexchange.com +0.0.0.0 ns2.phorm.com +0.0.0.0 ns2.youcanoptout.com +0.0.0.0 ns3.openinternetexchange.com +0.0.0.0 oi.webnavegador.com.br +0.0.0.0 oixcrv-lab.net +0.0.0.0 oixcrv.net +0.0.0.0 oixcrv-stage.net +0.0.0.0 oix.phorm.com +0.0.0.0 oixpre.net +0.0.0.0 oixpre-stage.net +0.0.0.0 oixssp-lab.net +0.0.0.0 oixssp.net +0.0.0.0 oix-stage.net +0.0.0.0 openinternetexchange.com +0.0.0.0 openinternetexchange.net +0.0.0.0 phorm.kr +0.0.0.0 phormlabs.com +0.0.0.0 prm-ext.phorm.com +0.0.0.0 romdiscover.com +0.0.0.0 rtc.romdiscover.com +0.0.0.0 stats.oix.com +0.0.0.0 stopphoulplay.com +0.0.0.0 stopphoulplay.net +0.0.0.0 telefonica.webnavegador.com.br +0.0.0.0 webnavegador.com.br +0.0.0.0 webwise.com +0.0.0.0 webwise.net +0.0.0.0 w.oix.net +0.0.0.0 www.gezinti.com +0.0.0.0 www.gozatar.com +0.0.0.0 www.oix.com +0.0.0.0 www.openinternetexchange.com +0.0.0.0 www.phormlabs.com +0.0.0.0 www.stopphoulplay.com +0.0.0.0 www.youcanoptout.com +0.0.0.0 www.youcanoptout.net +0.0.0.0 www.youcanoptout.org +0.0.0.0 xxyyzz.youcanoptout.com +0.0.0.0 youcanoptout.com +0.0.0.0 youcanoptout.net +0.0.0.0 youcanoptout.org +# diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/https_svn_python_org_root.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/https_svn_python_org_root.pem new file mode 100644 index 0000000000000000000000000000000000000000..e7dfc82947e30af0637575869fba5eef4c683b7d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/https_svn_python_org_root.pem @@ -0,0 +1,41 @@ +-----BEGIN CERTIFICATE----- +MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290 +IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB +IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA +Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO +BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi +MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ +ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ +8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6 +zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y +fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7 +w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc +G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k +epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q +laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ +QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU +fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826 +YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w +ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY +gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe +MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0 +IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy +dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw +czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0 +dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl +aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC +AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg +b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB +ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc +nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg +18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c +gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl +Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY +sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T +SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF +CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum +GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk +zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW +omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/keycert.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/keycert.pem new file mode 100644 index 0000000000000000000000000000000000000000..2f46fcf1c6251aabb9d39c6b20d7b8975708ee8b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/keycert.pem @@ -0,0 +1,32 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L +opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH +fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB +AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU +D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA +IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM +oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0 +ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/ +loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j +oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA +z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq +ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV +q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU= +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD +VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x +IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT +U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1 +NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl +bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m +dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj +aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh +m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8 +M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn +fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC +AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb +08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx +CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/ +iHkC6gGdBJhogs4= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/known_failures.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/known_failures.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf63962e06e3ddb50ed3a8c764e3a2ccdadfb10 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/known_failures.py @@ -0,0 +1,546 @@ +# This is a list of known failures (=bugs). +# The tests listed there must fail (or testrunner.py will report error) unless they are prefixed with FLAKY +# in which cases the result of them is simply ignored +from __future__ import print_function + +import sys +import struct + +from gevent.testing import sysinfo + +class Condition(object): + __slots__ = () + + def __and__(self, other): + return AndCondition(self, other) + + def __or__(self, other): + return OrCondition(self, other) + + def __bool__(self): + raise NotImplementedError + + +class AbstractBinaryCondition(Condition): # pylint:disable=abstract-method + __slots__ = ( + 'lhs', + 'rhs', + ) + OP = None + def __init__(self, lhs, rhs): + self.lhs = lhs + self.rhs = rhs + + def __repr__(self): + return "(%r %s %r)" % ( + self.lhs, + self.OP, + self.rhs + ) + +class OrCondition(AbstractBinaryCondition): + __slots__ = () + OP = '|' + def __bool__(self): + return bool(self.lhs) or bool(self.rhs) + +class AndCondition(AbstractBinaryCondition): + __slots__ = () + OP = '&' + def __bool__(self): + return bool(self.lhs) and bool(self.rhs) + +class ConstantCondition(Condition): + __slots__ = ( + 'value', + '__name__', + ) + + def __init__(self, value, name=None): + self.value = bool(value) + self.__name__ = name or str(value) + + def __bool__(self): + return self.value + + def __repr__(self): + return self.__name__ + +ALWAYS = ConstantCondition(True) +NEVER = ConstantCondition(False) + +class _AttrCondition(ConstantCondition): + __slots__ = ( + ) + + def __init__(self, name): + ConstantCondition.__init__(self, getattr(sysinfo, name), name) + +PYPY = _AttrCondition('PYPY') +PYPY3 = _AttrCondition('PYPY3') +PY3 = _AttrCondition('PY3') +PY2 = _AttrCondition('PY2') +OSX = _AttrCondition('OSX') +LIBUV = _AttrCondition('LIBUV') +WIN = _AttrCondition('WIN') +APPVEYOR = _AttrCondition('RUNNING_ON_APPVEYOR') +TRAVIS = _AttrCondition('RUNNING_ON_TRAVIS') +CI = _AttrCondition('RUNNING_ON_CI') +LEAKTEST = _AttrCondition('RUN_LEAKCHECKS') +COVERAGE = _AttrCondition('RUN_COVERAGE') +RESOLVER_NOT_SYSTEM = _AttrCondition('RESOLVER_NOT_SYSTEM') +BIT_64 = ConstantCondition(struct.calcsize('P') * 8 == 64, 'BIT_64') +PY380_EXACTLY = ConstantCondition(sys.version_info[:3] == (3, 8, 0), 'PY380_EXACTLY') +PY312B3_EXACTLY = ConstantCondition(sys.version_info == (3, 12, 0, 'beta', 3)) +PY312B4_EXACTLY = ConstantCondition(sys.version_info == (3, 12, 0, 'beta', 4)) + +class _Definition(object): + __slots__ = ( + '__name__', + # When does the class of this condition apply? + 'when', + # When should this test be run alone, if it's run? + 'run_alone', + # Should this test be ignored during coverage measurement? + 'ignore_coverage', + # {name: (Condition, value)} + 'options', + ) + + def __init__(self, when, run_alone, ignore_coverage, options): + assert isinstance(when, Condition) + assert isinstance(run_alone, Condition) + assert isinstance(ignore_coverage, Condition) + self.when = when + self.__name__ = None # pylint:disable=non-str-assignment-to-dunder-name + self.run_alone = run_alone + self.ignore_coverage = ignore_coverage + if options: + for v in options.values(): + assert isinstance(v, tuple) and len(v) == 2 + assert isinstance(v[0], Condition) + self.options = options + + def __set_name__(self, owner, name): + self.__name__ = name + + def __repr__(self): + return '<%s for %s when=%r=%s run_alone=%r=%s>' % ( + type(self).__name__, + self.__name__, + self.when, bool(self.when), + self.run_alone, bool(self.run_alone) + ) + +class _Action(_Definition): + __slots__ = ( + 'reason', + ) + def __init__(self, reason='', when=ALWAYS, run_alone=NEVER, ignore_coverage=NEVER, + options=None): + _Definition.__init__(self, when, run_alone, ignore_coverage, options) + self.reason = reason + +class RunAlone(_Action): + __slots__ = () + + def __init__(self, reason='', when=ALWAYS, ignore_coverage=NEVER): + _Action.__init__(self, reason, run_alone=when, ignore_coverage=ignore_coverage) + +class Failing(_Action): + __slots__ = () + +class Flaky(Failing): + __slots__ = () + +class Ignored(_Action): + __slots__ = () + +class Multi(object): + def __init__(self): + self._conds = [] + + def flaky(self, reason='', when=True, ignore_coverage=NEVER, run_alone=NEVER): + self._conds.append( + Flaky( + reason, when=when, + ignore_coverage=ignore_coverage, + run_alone=run_alone, + ) + ) + return self + + def ignored(self, reason='', when=True): + self._conds.append(Ignored(reason, when=when)) + return self + + def __set_name__(self, owner, name): + for c in self._conds: + c.__set_name__(owner, name) + + +class DefinitionsMeta(type): + # a metaclass on Python 3 that makes sure we only set attributes once. pylint doesn't + # warn about that. + @classmethod + def __prepare__(mcs, name, bases): # pylint:disable=unused-argument,bad-dunder-name + return SetOnceMapping() + + +class SetOnceMapping(dict): + + def __setitem__(self, name, value): + if name in self: + raise AttributeError(name) + dict.__setitem__(self, name, value) + +som = SetOnceMapping() +som[1] = 1 +try: + som[1] = 2 +except AttributeError: + del som +else: + raise AssertionError("SetOnceMapping is broken") + +DefinitionsBase = DefinitionsMeta('DefinitionsBase', (object,), {}) + +class Definitions(DefinitionsBase): + + test__util = RunAlone( + """ + If we have extra greenlets hanging around due to changes in GC, we won't + match the expected output. + + So far, this is only seen on one version, in CI environment. + """, + when=(CI & (PY312B3_EXACTLY | PY312B4_EXACTLY)) + ) + + test__issue6 = Flaky( + """test__issue6 (see comments in test file) is really flaky on both Travis and Appveyor; + on Travis we could just run the test again (but that gets old fast), but on appveyor + we don't have that option without a new commit---and sometimes we really need a build + to succeed in order to get a release wheel""" + ) + + test__core_fork = Ignored( + """fork watchers don't get called on windows + because fork is not a concept windows has. + See this file for a detailed explanation.""", + when=WIN + ) + + test__greenletset = Flaky( + when=WIN, + ignore_coverage=PYPY + ) + + test__example_udp_client = test__example_udp_server = Flaky( + """ + These both run on port 9000 and can step on each other...seems + like the appveyor containers aren't fully port safe? Or it + takes longer for the processes to shut down? Or we run them in + a different order in the process pool than we do other places? + + On PyPy on Travis, this fails to get the correct results, + sometimes. I can't reproduce locally + """, + when=APPVEYOR | (PYPY & TRAVIS) + ) + + # This one sometimes randomly closes connections, but no indication + # of a server crash, only a client side close. + test__server_pywsgi = Flaky(when=APPVEYOR) + + test_threading = Multi().ignored( + """ + This one seems to just stop right after patching is done. It + passes on a local win 10 vm, and the main test_threading_2.py + does as well. Based on the printouts we added, it appears to + not even finish importing: + https://ci.appveyor.com/project/denik/gevent/build/1.0.1277/job/tpvhesij5gldjxqw#L1190 + Ignored because it takes two minutes to time out. + """, + when=APPVEYOR & LIBUV & PYPY + ).flaky( + """ + test_set_and_clear in Py3 relies on 5 threads all starting and + coming to an Event wait point while a sixth thread sleeps for a half + second. The sixth thread then does something and checks that + the 5 threads were all at the wait point. But the timing is sometimes + too tight for appveyor. This happens even if Event isn't + monkey-patched + """, + when=APPVEYOR & PY3 + ) + + test_ftplib = Flaky( + r""" + could be a problem of appveyor - not sure + ====================================================================== + ERROR: test_af (__main__.TestIPv6Environment) + ---------------------------------------------------------------------- + File "C:\Python27-x64\lib\ftplib.py", line 135, in connect + self.sock = socket.create_connection((self.host, self.port), self.timeout) + File "c:\projects\gevent\gevent\socket.py", line 73, in create_connection + raise err + error: [Errno 10049] [Error 10049] The requested address is not valid in its context. + XXX: On Jan 3 2016 this suddenly started passing on Py27/64; no idea why, the python version + was 2.7.11 before and after. + """, + when=APPVEYOR & BIT_64 + ) + + + test__backdoor = Flaky(when=LEAKTEST | PYPY) + test__socket_errors = Flaky(when=LEAKTEST) + test_signal = Multi().flaky( + "On Travis, this very frequently fails due to timing", + when=TRAVIS & LEAKTEST, + # Partial workaround for the _testcapi issue on PyPy, + # but also because signal delivery can sometimes be slow, and this + # spawn processes of its own + run_alone=APPVEYOR, + ).ignored( + """ + This fails to run a single test. It looks like just importing the module + can hang. All I see is the output from patch_all() + """, + when=APPVEYOR & PYPY3 + ) + + test__monkey_sigchld_2 = Ignored( + """ + This hangs for no apparent reason when run by the testrunner, + even wher maked standalone when run standalone from the + command line, it's fine. Issue in pypy2 6.0? + """, + when=PYPY & LIBUV + ) + + test_ssl = Ignored( + """ + PyPy 7.0 and 7.1 on Travis with Ubunto Xenial 16.04 can't + allocate SSL Context objects, either in Python 2.7 or 3.6. + There must be some library incompatibility. No point even + running them. XXX: Remember to turn this back on. + + On Windows, with PyPy3.7 7.3.7, there seem to be all kind of certificate + errors. + """, + when=(PYPY & TRAVIS) | (PYPY3 & WIN) + ) + + test_httpservers = Ignored( + """ + All the CGI tests hang. There appear to be subprocess problems. + """, + when=PYPY3 & WIN + ) + + + + test__pywsgi = Ignored( + """ + XXX: Re-enable this when we can investigate more. This has + started crashing with a SystemError. I cannot reproduce with + the same version on macOS and I cannot reproduce with the same + version in a Linux vm. Commenting out individual tests just + moves the crash around. + https://bitbucket.org/pypy/pypy/issues/2769/systemerror-unexpected-internal-exception + + On Appveyor 3.8.0, for some reason this takes *way* too long, about 100s, which + often goes just over the default timeout of 100s. This makes no sense. + But it also takes nearly that long in 3.7. 3.6 and earlier are much faster. + + It also takes just over 100s on PyPy 3.7. + """, + when=(PYPY & TRAVIS & LIBUV) | PY380_EXACTLY, + # https://bitbucket.org/pypy/pypy/issues/2769/systemerror-unexpected-internal-exception + run_alone=(CI & LEAKTEST & PY3) | (PYPY & LIBUV), + # This often takes much longer on PyPy on CI. + options={'timeout': (CI & PYPY, 180)}, + ) + + test_subprocess = Multi().flaky( + "Unknown, can't reproduce locally; times out one test", + when=PYPY & PY3 & TRAVIS, + ignore_coverage=ALWAYS, + ).ignored( + "Tests don't even start before the process times out.", + when=PYPY3 & WIN + ) + + test__threadpool = Ignored( + """ + XXX: Re-enable these when we have more time to investigate. + + This test, which normally takes ~60s, sometimes + hangs forever after running several tests. I cannot reproduce, + it seems highly load dependent. Observed with both libev and libuv. + """, + when=TRAVIS & (PYPY | OSX), + # This often takes much longer on PyPy on CI. + options={'timeout': (CI & PYPY, 180)}, + ) + + test__threading_2 = Ignored( + """ + This test, which normally takes 4-5s, sometimes + hangs forever after running two tests. I cannot reproduce, + it seems highly load dependent. Observed with both libev and libuv. + """, + when=TRAVIS & (PYPY | OSX), + # This often takes much longer on PyPy on CI. + options={'timeout': (CI & PYPY, 180)}, + ) + + test__issue230 = Ignored( + """ + This rarely hangs for unknown reasons. I cannot reproduce + locally. + """, + when=TRAVIS & OSX + ) + + test_selectors = Flaky( + """ + Timing issues on appveyor. + """, + when=PY3 & APPVEYOR, + ignore_coverage=ALWAYS, + ) + + test__example_portforwarder = Flaky( + """ + This one sometimes times out, often after output "The process + with PID XXX could not be terminated. Reason: There is no + running instance of the task.", + """, + when=APPVEYOR | COVERAGE + ) + + test__issue302monkey = test__threading_vs_settrace = Flaky( + """ + The gevent concurrency plugin tends to slow things + down and get us past our default timeout value. These + tests in particular are sensitive to it. So in fact we just turn them + off. + """, + when=COVERAGE, + ignore_coverage=ALWAYS, + ) + + test__hub_join_timeout = Ignored( + r""" + This sometimes times out. It appears to happen when the + times take too long and a test raises a FlakyTestTimeout error, + aka a unittest.SkipTest error. This probably indicates that we're + not cleaning something up correctly: + + .....ss + GEVENTTEST_USE_RESOURCES=-network C:\Python38-x64\python.exe -u \ + -mgevent.tests.test__hub_join_timeout [code TIMEOUT] [took 100.4s] + """, + when=APPVEYOR + ) + + test__example_wsgiserver = test__example_webproxy = RunAlone( + """ + These share the same port, which means they can conflict + between concurrent test runs too + XXX: Fix this by dynamically picking a port. + """, + ) + + test__pool = RunAlone( + """ + On a heavily loaded box, these can all take upwards of 200s. + """, + when=(CI & LEAKTEST) | (PYPY3 & APPVEYOR) + ) + + test_socket = RunAlone( + "Sometimes has unexpected timeouts", + when=CI & PYPY & PY3, + ignore_coverage=ALWAYS, # times out + ) + + test__refcount = Ignored( + "Sometimes fails to connect for no reason", + when=(CI & OSX) | (CI & PYPY) | APPVEYOR, + ignore_coverage=PYPY + ) + + test__doctests = Ignored( + "Sometimes times out during/after gevent._config.Config", + when=CI & OSX + ) + + + +# tests that can't be run when coverage is enabled +# TODO: Now that we have this declarative, we could eliminate this list, +# just add them to the main IGNORED_TESTS list. +IGNORE_COVERAGE = [ +] + +# A mapping from test file basename to a dictionary of +# options that will be applied on top of the DEFAULT_RUN_OPTIONS. +TEST_FILE_OPTIONS = { + +} + +FAILING_TESTS = [] +IGNORED_TESTS = [] +# tests that don't do well when run on busy box +# or that are mutually exclusive +RUN_ALONE = [ + +] + +def populate(): # pylint:disable=too-many-branches + # TODO: Maybe move to the metaclass. + # TODO: This could be better. + for k, v in Definitions.__dict__.items(): + if isinstance(v, Multi): + actions = v._conds + else: + actions = (v,) + test_name = k + '.py' + del k, v + + for action in actions: + if not isinstance(action, _Action): + continue + + if action.run_alone: + RUN_ALONE.append(test_name) + if action.ignore_coverage: + IGNORE_COVERAGE.append(test_name) + if action.options: + for opt_name, (condition, value) in action.options.items(): + # TODO: Verify that this doesn't match more than once. + if condition: + TEST_FILE_OPTIONS.setdefault(test_name, {})[opt_name] = value + if action.when: + if isinstance(action, Ignored): + IGNORED_TESTS.append(test_name) + elif isinstance(action, Flaky): + FAILING_TESTS.append('FLAKY ' + test_name) + elif isinstance(action, Failing): + FAILING_TESTS.append(test_name) + + FAILING_TESTS.sort() + IGNORED_TESTS.sort() + RUN_ALONE.sort() + +populate() + +if __name__ == '__main__': + print('known_failures:\n', FAILING_TESTS) + print('ignored tests:\n', IGNORED_TESTS) + print('run alone:\n', RUN_ALONE) + print('options:\n', TEST_FILE_OPTIONS) + print("ignore during coverage:\n", IGNORE_COVERAGE) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/lock_tests.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/lock_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..1033df7803ce18c9c83eefa54056be395cd96e72 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/lock_tests.py @@ -0,0 +1,764 @@ +""" +Various tests for synchronization primitives. +""" +# pylint:disable=no-member,abstract-method +import sys +import time +try: + from thread import start_new_thread, get_ident +except ImportError: + from _thread import start_new_thread, get_ident +import threading +import unittest + +from gevent.testing import support +from gevent.testing.testcase import TimeAssertMixin + +def _wait(): + # A crude wait/yield function not relying on synchronization primitives. + time.sleep(0.01) + +class Bunch(object): + """ + A bunch of threads. + """ + def __init__(self, f, n, wait_before_exit=False): + """ + Construct a bunch of `n` threads running the same function `f`. + If `wait_before_exit` is True, the threads won't terminate until + do_finish() is called. + """ + self.f = f + self.n = n + self.started = [] + self.finished = [] + self._can_exit = not wait_before_exit + def task(): + tid = get_ident() + self.started.append(tid) + try: + f() + finally: + self.finished.append(tid) + while not self._can_exit: + _wait() + for _ in range(n): + start_new_thread(task, ()) + + def wait_for_started(self): + while len(self.started) < self.n: + _wait() + + def wait_for_finished(self): + while len(self.finished) < self.n: + _wait() + + def do_finish(self): + self._can_exit = True + + +class BaseTestCase(TimeAssertMixin, unittest.TestCase): + def setUp(self): + self._threads = support.threading_setup() + + def tearDown(self): + support.threading_cleanup(*self._threads) + support.reap_children() + + +class BaseLockTests(BaseTestCase): + """ + Tests for both recursive and non-recursive locks. + """ + + def locktype(self): + raise NotImplementedError() + + def test_constructor(self): + lock = self.locktype() + del lock + + def test_acquire_destroy(self): + lock = self.locktype() + lock.acquire() + del lock + + def test_acquire_release(self): + lock = self.locktype() + lock.acquire() + lock.release() + del lock + + def test_try_acquire(self): + lock = self.locktype() + self.assertTrue(lock.acquire(False)) + lock.release() + + def test_try_acquire_contended(self): + lock = self.locktype() + lock.acquire() + result = [] + def f(): + result.append(lock.acquire(False)) + Bunch(f, 1).wait_for_finished() + self.assertFalse(result[0]) + lock.release() + + def test_acquire_contended(self): + lock = self.locktype() + lock.acquire() + N = 5 + def f(): + lock.acquire() + lock.release() + + b = Bunch(f, N) + b.wait_for_started() + _wait() + self.assertEqual(len(b.finished), 0) + lock.release() + b.wait_for_finished() + self.assertEqual(len(b.finished), N) + + def test_with(self): + lock = self.locktype() + def f(): + lock.acquire() + lock.release() + def _with(err=None): + with lock: + if err is not None: + raise err # pylint:disable=raising-bad-type + _with() + # Check the lock is unacquired + Bunch(f, 1).wait_for_finished() + self.assertRaises(TypeError, _with, TypeError) + # Check the lock is unacquired + Bunch(f, 1).wait_for_finished() + + def test_thread_leak(self): + # The lock shouldn't leak a Thread instance when used from a foreign + # (non-threading) thread. + lock = self.locktype() + def f(): + lock.acquire() + lock.release() + n = len(threading.enumerate()) + # We run many threads in the hope that existing threads ids won't + # be recycled. + Bunch(f, 15).wait_for_finished() + self.assertEqual(n, len(threading.enumerate())) + + +class LockTests(BaseLockTests): # pylint:disable=abstract-method + """ + Tests for non-recursive, weak locks + (which can be acquired and released from different threads). + """ + def test_reacquire(self): + # Lock needs to be released before re-acquiring. + lock = self.locktype() + phase = [] + def f(): + lock.acquire() + phase.append(None) + lock.acquire() + phase.append(None) + start_new_thread(f, ()) + while not phase: + _wait() + _wait() + self.assertEqual(len(phase), 1) + lock.release() + while len(phase) == 1: + _wait() + self.assertEqual(len(phase), 2) + + def test_different_thread(self): + # Lock can be released from a different thread. + lock = self.locktype() + lock.acquire() + def f(): + lock.release() + b = Bunch(f, 1) + b.wait_for_finished() + lock.acquire() + lock.release() + + +class RLockTests(BaseLockTests): + """ + Tests for recursive locks. + """ + def test_reacquire(self): + lock = self.locktype() + lock.acquire() + lock.acquire() + lock.release() + lock.acquire() + lock.release() + lock.release() + + def test_release_unacquired(self): + # Cannot release an unacquired lock + lock = self.locktype() + self.assertRaises(RuntimeError, lock.release) + lock.acquire() + lock.acquire() + lock.release() + lock.acquire() + lock.release() + lock.release() + self.assertRaises(RuntimeError, lock.release) + + def test_different_thread(self): + # Cannot release from a different thread + lock = self.locktype() + def f(): + lock.acquire() + b = Bunch(f, 1, True) + try: + self.assertRaises(RuntimeError, lock.release) + finally: + b.do_finish() + + def test__is_owned(self): + lock = self.locktype() + self.assertFalse(lock._is_owned()) + lock.acquire() + self.assertTrue(lock._is_owned()) + lock.acquire() + self.assertTrue(lock._is_owned()) + result = [] + def f(): + result.append(lock._is_owned()) + Bunch(f, 1).wait_for_finished() + self.assertFalse(result[0]) + lock.release() + self.assertTrue(lock._is_owned()) + lock.release() + self.assertFalse(lock._is_owned()) + + +class EventTests(BaseTestCase): + """ + Tests for Event objects. + """ + + def eventtype(self): + raise NotImplementedError() + + def test_is_set(self): + evt = self.eventtype() + self.assertFalse(evt.is_set()) + evt.set() + self.assertTrue(evt.is_set()) + evt.set() + self.assertTrue(evt.is_set()) + evt.clear() + self.assertFalse(evt.is_set()) + evt.clear() + self.assertFalse(evt.is_set()) + + def _check_notify(self, evt): + # All threads get notified + N = 5 + results1 = [] + results2 = [] + def f(): + evt.wait() + results1.append(evt.is_set()) + evt.wait() + results2.append(evt.is_set()) + b = Bunch(f, N) + b.wait_for_started() + _wait() + self.assertEqual(len(results1), 0) + evt.set() + b.wait_for_finished() + self.assertEqual(results1, [True] * N) + self.assertEqual(results2, [True] * N) + + def test_notify(self): + evt = self.eventtype() + self._check_notify(evt) + # Another time, after an explicit clear() + evt.set() + evt.clear() + self._check_notify(evt) + + def test_timeout(self): + evt = self.eventtype() + results1 = [] + results2 = [] + N = 5 + def f(): + evt.wait(0.0) + results1.append(evt.is_set()) + t1 = time.time() + evt.wait(0.2) + r = evt.is_set() + t2 = time.time() + results2.append((r, t2 - t1)) + Bunch(f, N).wait_for_finished() + self.assertEqual(results1, [False] * N) + for r, dt in results2: + self.assertFalse(r) + self.assertTimeWithinRange(dt, 0.18, 10) + # The event is set + results1 = [] + results2 = [] + evt.set() + Bunch(f, N).wait_for_finished() + self.assertEqual(results1, [True] * N) + for r, dt in results2: + self.assertTrue(r) + + +class ConditionTests(BaseTestCase): + """ + Tests for condition variables. + """ + + def condtype(self, *args): + raise NotImplementedError() + + def test_acquire(self): + cond = self.condtype() + # Be default we have an RLock: the condition can be acquired multiple + # times. + # pylint:disable=consider-using-with + cond.acquire() + cond.acquire() + cond.release() + cond.release() + lock = threading.Lock() + cond = self.condtype(lock) + cond.acquire() + self.assertFalse(lock.acquire(False)) + cond.release() + self.assertTrue(lock.acquire(False)) + self.assertFalse(cond.acquire(False)) + lock.release() + with cond: + self.assertFalse(lock.acquire(False)) + + def test_unacquired_wait(self): + cond = self.condtype() + self.assertRaises(RuntimeError, cond.wait) + + def test_unacquired_notify(self): + cond = self.condtype() + self.assertRaises(RuntimeError, cond.notify) + + def _check_notify(self, cond): + N = 5 + results1 = [] + results2 = [] + phase_num = 0 + def f(): + cond.acquire() + cond.wait() + cond.release() + results1.append(phase_num) + cond.acquire() + cond.wait() + cond.release() + results2.append(phase_num) + b = Bunch(f, N) + b.wait_for_started() + _wait() + self.assertEqual(results1, []) + # Notify 3 threads at first + cond.acquire() + cond.notify(3) + _wait() + phase_num = 1 + cond.release() + while len(results1) < 3: + _wait() + self.assertEqual(results1, [1] * 3) + self.assertEqual(results2, []) + # Notify 5 threads: they might be in their first or second wait + cond.acquire() + cond.notify(5) + _wait() + phase_num = 2 + cond.release() + while len(results1) + len(results2) < 8: + _wait() + self.assertEqual(results1, [1] * 3 + [2] * 2) + self.assertEqual(results2, [2] * 3) + # Notify all threads: they are all in their second wait + cond.acquire() + cond.notify_all() + _wait() + phase_num = 3 + cond.release() + while len(results2) < 5: + _wait() + self.assertEqual(results1, [1] * 3 + [2] * 2) + self.assertEqual(results2, [2] * 3 + [3] * 2) + b.wait_for_finished() + + def test_notify(self): + cond = self.condtype() + self._check_notify(cond) + # A second time, to check internal state is still ok. + self._check_notify(cond) + + def test_timeout(self): + cond = self.condtype() + results = [] + N = 5 + def f(): + cond.acquire() + t1 = time.time() + cond.wait(0.2) + t2 = time.time() + cond.release() + results.append(t2 - t1) + Bunch(f, N).wait_for_finished() + self.assertEqual(len(results), 5) + for dt in results: + # XXX: libuv sometimes produces 0.19958 + self.assertTimeWithinRange(dt, 0.19, 2.0) + + +class BaseSemaphoreTests(BaseTestCase): + """ + Common tests for {bounded, unbounded} semaphore objects. + """ + + def semtype(self, *args): + raise NotImplementedError() + + def test_constructor(self): + self.assertRaises(ValueError, self.semtype, value=-1) + # Py3 doesn't have sys.maxint + self.assertRaises((ValueError, OverflowError), self.semtype, + value=-getattr(sys, 'maxint', getattr(sys, 'maxsize', None))) + + def test_acquire(self): + sem = self.semtype(1) + sem.acquire() + sem.release() + sem = self.semtype(2) + sem.acquire() + sem.acquire() + sem.release() + sem.release() + + def test_acquire_destroy(self): + sem = self.semtype() + sem.acquire() + del sem + + def test_acquire_contended(self): + sem = self.semtype(7) + sem.acquire() + #N = 10 + results1 = [] + results2 = [] + phase_num = 0 + def f(): + sem.acquire() + results1.append(phase_num) + sem.acquire() + results2.append(phase_num) + b = Bunch(f, 10) + b.wait_for_started() + while len(results1) + len(results2) < 6: + _wait() + self.assertEqual(results1 + results2, [0] * 6) + phase_num = 1 + for _ in range(7): + sem.release() + while len(results1) + len(results2) < 13: + _wait() + self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7) + phase_num = 2 + for _ in range(6): + sem.release() + while len(results1) + len(results2) < 19: + _wait() + self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7 + [2] * 6) + # The semaphore is still locked + self.assertFalse(sem.acquire(False)) + # Final release, to let the last thread finish + sem.release() + b.wait_for_finished() + + def test_try_acquire(self): + sem = self.semtype(2) + self.assertTrue(sem.acquire(False)) + self.assertTrue(sem.acquire(False)) + self.assertFalse(sem.acquire(False)) + sem.release() + self.assertTrue(sem.acquire(False)) + + def test_try_acquire_contended(self): + sem = self.semtype(4) + sem.acquire() + results = [] + def f(): + results.append(sem.acquire(False)) + results.append(sem.acquire(False)) + Bunch(f, 5).wait_for_finished() + # There can be a thread switch between acquiring the semaphore and + # appending the result, therefore results will not necessarily be + # ordered. + self.assertEqual(sorted(results), [False] * 7 + [True] * 3) + + def test_default_value(self): + # The default initial value is 1. + sem = self.semtype() + sem.acquire() + def f(): + sem.acquire() + sem.release() + b = Bunch(f, 1) + b.wait_for_started() + _wait() + self.assertFalse(b.finished) + sem.release() + b.wait_for_finished() + + def test_with(self): + sem = self.semtype(2) + def _with(err=None): + with sem: + self.assertTrue(sem.acquire(False)) + sem.release() + with sem: + self.assertFalse(sem.acquire(False)) + if err: + raise err # pylint:disable=raising-bad-type + _with() + self.assertTrue(sem.acquire(False)) + sem.release() + self.assertRaises(TypeError, _with, TypeError) + self.assertTrue(sem.acquire(False)) + sem.release() + +class SemaphoreTests(BaseSemaphoreTests): + """ + Tests for unbounded semaphores. + """ + + def test_release_unacquired(self): + # Unbounded releases are allowed and increment the semaphore's value + sem = self.semtype(1) + sem.release() + sem.acquire() + sem.acquire() + sem.release() + + +class BoundedSemaphoreTests(BaseSemaphoreTests): + """ + Tests for bounded semaphores. + """ + + def test_release_unacquired(self): + # Cannot go past the initial value + sem = self.semtype() + self.assertRaises(ValueError, sem.release) + sem.acquire() + sem.release() + self.assertRaises(ValueError, sem.release) + +class BarrierTests(BaseTestCase): + """ + Tests for Barrier objects. + """ + N = 5 + defaultTimeout = 2.0 + + def setUp(self): + self.barrier = self.barriertype(self.N, timeout=self.defaultTimeout) + def tearDown(self): + self.barrier.abort() + + def run_threads(self, f): + b = Bunch(f, self.N-1) + f() + b.wait_for_finished() + + def multipass(self, results, n): + m = self.barrier.parties + self.assertEqual(m, self.N) + for i in range(n): + results[0].append(True) + self.assertEqual(len(results[1]), i * m) + self.barrier.wait() + results[1].append(True) + self.assertEqual(len(results[0]), (i + 1) * m) + self.barrier.wait() + self.assertEqual(self.barrier.n_waiting, 0) + self.assertFalse(self.barrier.broken) + + def test_barrier(self, passes=1): + """ + Test that a barrier is passed in lockstep + """ + results = [[], []] + def f(): + self.multipass(results, passes) + self.run_threads(f) + + def test_barrier_10(self): + """ + Test that a barrier works for 10 consecutive runs + """ + return self.test_barrier(10) + + def test_wait_return(self): + """ + test the return value from barrier.wait + """ + results = [] + def f(): + r = self.barrier.wait() + results.append(r) + + self.run_threads(f) + self.assertEqual(sum(results), sum(range(self.N))) + + def test_action(self): + """ + Test the 'action' callback + """ + results = [] + def action(): + results.append(True) + barrier = self.barriertype(self.N, action) + def f(): + barrier.wait() + self.assertEqual(len(results), 1) + + self.run_threads(f) + + def test_abort(self): + """ + Test that an abort will put the barrier in a broken state + """ + results1 = [] + results2 = [] + def f(): + try: + i = self.barrier.wait() + if i == self.N//2: + raise RuntimeError + self.barrier.wait() + results1.append(True) + except threading.BrokenBarrierError: + results2.append(True) + except RuntimeError: + self.barrier.abort() + + self.run_threads(f) + self.assertEqual(len(results1), 0) + self.assertEqual(len(results2), self.N-1) + self.assertTrue(self.barrier.broken) + + def test_reset(self): + """ + Test that a 'reset' on a barrier frees the waiting threads + """ + results1 = [] + results2 = [] + results3 = [] + def f(): + i = self.barrier.wait() + if i == self.N//2: + # Wait until the other threads are all in the barrier. + while self.barrier.n_waiting < self.N-1: + time.sleep(0.001) + self.barrier.reset() + else: + try: + self.barrier.wait() + results1.append(True) + except threading.BrokenBarrierError: + results2.append(True) + # Now, pass the barrier again + self.barrier.wait() + results3.append(True) + + self.run_threads(f) + self.assertEqual(len(results1), 0) + self.assertEqual(len(results2), self.N-1) + self.assertEqual(len(results3), self.N) + + + def test_abort_and_reset(self): + """ + Test that a barrier can be reset after being broken. + """ + results1 = [] + results2 = [] + results3 = [] + barrier2 = self.barriertype(self.N) + def f(): + try: + i = self.barrier.wait() + if i == self.N//2: + raise RuntimeError + self.barrier.wait() + results1.append(True) + except threading.BrokenBarrierError: + results2.append(True) + except RuntimeError: + self.barrier.abort() + + # Synchronize and reset the barrier. Must synchronize first so + # that everyone has left it when we reset, and after so that no + # one enters it before the reset. + if barrier2.wait() == self.N//2: + self.barrier.reset() + barrier2.wait() + self.barrier.wait() + results3.append(True) + + self.run_threads(f) + self.assertEqual(len(results1), 0) + self.assertEqual(len(results2), self.N-1) + self.assertEqual(len(results3), self.N) + + def test_timeout(self): + """ + Test wait(timeout) + """ + def f(): + i = self.barrier.wait() + if i == self.N // 2: + # One thread is late! + time.sleep(1.0) + # Default timeout is 2.0, so this is shorter. + self.assertRaises(threading.BrokenBarrierError, + self.barrier.wait, 0.5) + self.run_threads(f) + + def test_default_timeout(self): + """ + Test the barrier's default timeout + """ + # create a barrier with a low default timeout + barrier = self.barriertype(self.N, timeout=0.3) + def f(): + i = barrier.wait() + if i == self.N // 2: + # One thread is later than the default timeout of 0.3s. + time.sleep(1.0) + self.assertRaises(threading.BrokenBarrierError, barrier.wait) + self.run_threads(f) + + def test_single_thread(self): + b = self.barriertype(1) + b.wait() + b.wait() + + +if __name__ == '__main__': + print("This module contains no tests; it is used by other test cases like test_threading_2") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34431cf33b6e4940a258d72d340e8ae1d33c411c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +""" +Make a package. + +This file has no other functionality. Individual modules in this package +are used for testing, often being run with 'python -m ...' in individual +test cases (functions). + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__main__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..edfd6f0da95fc96ebc0ac1a96bd716bc1b0b83f2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/__main__.py @@ -0,0 +1,9 @@ +from __future__ import print_function +# This file makes this directory into a runnable package. +# it exists to test 'python -m gevent.monkey monkey_package' +# Note that the __file__ may differ slightly; starting with +# Python 3.9, directly running it gets an abspath, but +# using ``runpy`` doesn't. +import os.path +print(os.path.abspath(__file__)) +print(__name__) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_no_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_no_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..38bb195b2361c04eb9c9185fd7dbd9b06f221f3c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_no_monkey.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +""" +Test for issue #1526: +- dnspython is imported first; +- no monkey-patching is done. +""" +from __future__ import print_function +from __future__ import absolute_import + +import dns # pylint:disable=import-error +assert dns +import gevent.socket as socket # pylint:disable=consider-using-from-import +socket.getfqdn() # create the resolver + +from gevent.resolver.dnspython import dns as gdns +import dns.rdtypes # pylint:disable=import-error + +assert dns is not gdns, (dns, gdns) +assert dns.rdtypes is not gdns.rdtypes +import sys +print(sorted(sys.modules)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_with_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_with_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..e3fbfe33d1cb259ad9707ff1fff0ff2389c28d9a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue1526_with_monkey.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +""" +Test for issue #1526: +- dnspython is imported first; +- monkey-patching happens early +""" +from __future__ import print_function, absolute_import + +from gevent import monkey +monkey.patch_all() +# pylint:disable=import-error +import dns +assert dns + +import socket +import sys + +socket.getfqdn() + +import gevent.resolver.dnspython +from gevent.resolver.dnspython import dns as gdns +from dns import rdtypes # NOT import dns.rdtypes + +assert gevent.resolver.dnspython.dns is gdns +assert gdns is not dns, (gdns, dns, "id dns", id(dns)) +assert gdns.rdtypes is not rdtypes, (gdns.rdtypes, rdtypes) +assert hasattr(dns, 'rdtypes') +print(sorted(sys.modules)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue302monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue302monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..104e9431c0f70ce8a0e59490bd3c89814a502570 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/issue302monkey.py @@ -0,0 +1,26 @@ +from __future__ import print_function +import socket +import sys +import os.path +if sys.argv[1] == 'patched': + print('gevent' in repr(socket.socket)) +else: + assert sys.argv[1] == 'stdlib' + print('gevent' not in repr(socket.socket)) +print(os.path.abspath(__file__)) + + + +if sys.argv[1] == 'patched': + # __package__ is handled differently, for some reason, and + # runpy doesn't let us override it. When we call it, it + # becomes ''. This appears to be against the documentation for + # runpy, which says specifically "If the supplied path + # directly references a script file (whether as source or as + # precompiled byte code), then __file__ will be set to the + # supplied path, and __spec__, __cached__, __loader__ and + # __package__ will all be set to None." + print(__package__ == '') # pylint:disable=compare-to-empty-string +else: + # but the interpreter sets it to None + print(__package__ is None) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/script.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/script.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3f616a0cee26f9e23ae3d2c8b177aa56de4e6f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/script.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +""" +Test script file, to be used directly as a file. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +# We need some global imports +from textwrap import dedent + +def use_import(): + return dedent(" text") + +if __name__ == '__main__': + import os.path + print(os.path.abspath(__file__)) + print(__name__) + print(use_import()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_monkey_patches.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_monkey_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee922b7f9e329b6e40de419af70c408e7d739ce --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_monkey_patches.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +""" +This file runs ``gevent.monkey.patch_all()``. + +It is intended to be used by ``python -m gevent.monkey `` +to prove that monkey-patching twice doesn't have unfortunate sife effects (such as +breaking the threadpool). +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +from gevent import monkey +from gevent import get_hub + +monkey.patch_all(thread=False, sys=True) + +def thread_is_greenlet(): + from gevent.thread import get_ident as gr_ident + std_thread_mod = 'thread' if bytes is str else '_thread' + thr_ident = monkey.get_original(std_thread_mod, 'get_ident') + return thr_ident() == gr_ident() + + +is_greenlet = get_hub().threadpool.apply(thread_is_greenlet) +print(is_greenlet) +print(len(sys._current_frames())) +sys.stdout.flush() +sys.stderr.flush() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_no_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_no_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..bcbccbb89ac2836aa7aa40194d4f6d1645d13856 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/monkey_package/threadpool_no_monkey.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +""" +This file *does not* run ``gevent.monkey.patch_all()``. + +It is intended to be used by ``python -m gevent.monkey `` +to prove that the threadpool and getting the original value of things +works. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +from gevent import monkey +from gevent import get_hub + +from gevent.thread import get_ident as gr_ident + +std_thread_mod = 'thread' if bytes is str else '_thread' +thr_ident = monkey.get_original(std_thread_mod, 'get_ident') + +print(thr_ident is gr_ident) + +def thread_is_greenlet(): + return thr_ident() == gr_ident() + + +is_greenlet = get_hub().threadpool.apply(thread_is_greenlet) +print(is_greenlet) +print(len(sys._current_frames())) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/nullcert.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/nullcert.pem new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.crt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.crt new file mode 100644 index 0000000000000000000000000000000000000000..78f036f930f7167d9cdc3fcdb876c4a3a74385fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.crt @@ -0,0 +1,29 @@ +-----BEGIN CERTIFICATE----- +MIIFCzCCAvOgAwIBAgIUePnEKFfhxpt3oypt6nTicAGTFJowDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIxMDcwODExMzQzNVoYDzIxMjEw +NjE0MTEzNDM1WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQChqfmG6uOG95Jb7uRi6yxohJ8GOR3gi39yX6JB+Xdu +kvqxy2/vsjH1+CF1i8jKZZO0hJLGT+/GmKIc1c0XUEjVoQvCNQHIaDTXiUXOGXfk +QNKR0vtJH5ZOZn/tvYAKPniYPmHuF3TpAB6HouLpyIC55SXdK7pTEbmU7J1aBjug +n3O56cu6FzjU1j/0QVUVGloxApLvv57bmINaX9ygKsh/ug0lhV1RwYLJ9UX57m95 +FIlcofa98tCuoKi++G+sWsjopDXVmsiTbjZfs72kcDUTRYKNZbRFRRETORdOVRHx +lAIPEn4QFYn/3wVSNFvfeY0j8RI5YcPLU66Batun6HU+YAs6z8Qc8S1EMElJdoyV +eLCqLA07btICzKq2I16TZAOWVng2P7NOtibAeCzDAxAxJ3Oby+BVikKcu8WmJLxG +vRvaPljdD76xjPB5NK6O0J62C3uU3EWhPODX9H5l/WF+aNRqSccgs0Umddj33N+b +/mTJnHn1GpanThrv1UfOFGKfxjemwESz66d1iqD7iXvTxt7yZeU7LIMRgDqhVe6z +oBpJEeWl9YYyfGPwgIOhwzNVZ5WkzQARs7si3j3Wkmyca7hEN8qq8DkLWNf1PTcI +wo/239wKRbyW3Z+U4IGRrVMdeSoC2JpRAx/eEXTjuUePQlHCvwW9iiY7jTjDfbIv +pwIDAQABo1MwUTAdBgNVHQ4EFgQUTUfShFbaXGMwrWEAkm05sXFH/x4wHwYDVR0j +BBgwFoAUTUfShFbaXGMwrWEAkm05sXFH/x4wDwYDVR0TAQH/BAUwAwEB/zANBgkq +hkiG9w0BAQsFAAOCAgEAe65ORDx0NDxTo1q6EY221KS3vEezUNBdZNaeOQsQeUAY +lEO5iZ+2QLIVlWC5UtvISK96FU2CX0ucgAGfHS2ZB7o8i95fbjG2qrWC+VUH4V/6 +jse9jlfGlYGkPuU5onNIDGcZ7gay3n0prCDiguAmCzV419GnGDWgSSgyVNCp/0tx +b7pR5cVr0kZ5bTZjiysEEprkG2ofAlXzj09VGtTfM8gQvCz9Puj7pGzw2iaIEQVk +hSGjoRWlI5x6+o16JOTHXzv9cYRUfDX6tjw3nQJIeMipuUkR8pkHUFjG3EeJEtO3 +X/GO0G8rwUPaZiskGPiMZj7XqoVclnYL7JtntwUHR/dU5A/EhDfhgEfTXTqT78Oe +cKri+VJE+G/hYxbP0FNYaDtqIwJcX1tsy4HOpKVBncc+K/PvXElVsyQET/+uwH7p +Wm5ymndnuLoiQrWIA4nJC6rVwR4GPijuN0NCKcVdE+8jlOCBs3VBJTWKuu0J80RP +71iZy03AoK1YY4+nHglmE9HetAgSsbGh2fWC7DUS/4JzLSzOBeb+nn74zfmIfMU+ +qUArFXvVGAtjmZZ/63cWzXDMZsp1BZ+O5dx6Gi2QtjgGYhh6DhW7ocQYXDkAeN/O +K1Yzwq/G4AEQA0k0/1I+F0Rdlo41+7tOp+LMCOoZXqUzhM0ZQ2sf3QclubxLX9U= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.key b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.key new file mode 100644 index 0000000000000000000000000000000000000000..754ad8df099646ab44016d92638fd20622684cc8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/server.key @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQChqfmG6uOG95Jb +7uRi6yxohJ8GOR3gi39yX6JB+Xdukvqxy2/vsjH1+CF1i8jKZZO0hJLGT+/GmKIc +1c0XUEjVoQvCNQHIaDTXiUXOGXfkQNKR0vtJH5ZOZn/tvYAKPniYPmHuF3TpAB6H +ouLpyIC55SXdK7pTEbmU7J1aBjugn3O56cu6FzjU1j/0QVUVGloxApLvv57bmINa +X9ygKsh/ug0lhV1RwYLJ9UX57m95FIlcofa98tCuoKi++G+sWsjopDXVmsiTbjZf +s72kcDUTRYKNZbRFRRETORdOVRHxlAIPEn4QFYn/3wVSNFvfeY0j8RI5YcPLU66B +atun6HU+YAs6z8Qc8S1EMElJdoyVeLCqLA07btICzKq2I16TZAOWVng2P7NOtibA +eCzDAxAxJ3Oby+BVikKcu8WmJLxGvRvaPljdD76xjPB5NK6O0J62C3uU3EWhPODX +9H5l/WF+aNRqSccgs0Umddj33N+b/mTJnHn1GpanThrv1UfOFGKfxjemwESz66d1 +iqD7iXvTxt7yZeU7LIMRgDqhVe6zoBpJEeWl9YYyfGPwgIOhwzNVZ5WkzQARs7si +3j3Wkmyca7hEN8qq8DkLWNf1PTcIwo/239wKRbyW3Z+U4IGRrVMdeSoC2JpRAx/e +EXTjuUePQlHCvwW9iiY7jTjDfbIvpwIDAQABAoICAC3CJMTRe3FaZezro210T2+O +Ck0CobhLA9nlw9GUwP9lTtxATwCzmXybrSzOUhknwzUXSUwkmCPIVCqBQbnVmagO +G3vu8QA+rqZLTpzVjJ/o0TFBXKsH681pKdCrELDVmeDN135C2W6SABI4Qq4VeIol +mCAQHn8gxzyl9Kvkk8AVIfZ/fJDBve5Qbm2+iEye1uSEa/68aEST2Kod9B7JvVKZ +4Nq78vwPH+v2JsZlfNvyuiakGWkOb47eHqVfQIyybaebwzkgxKEmUvGnuIfw0rUP +ubI4FVx9/iVIxZYAckHEuQh3HYOD9TmdcK4h79dDWnXP6G6hg3/rwbsT+fR+0aBQ +9rkKnA4uToGikYmplixAQ/jDBwMs3VQqenO+YBIsC4HEZ0fJUbs+l4LEnuUJxYcR +UlAvnVQXa1WGne3Yzb2xONWeiocKfhcdJ2JuQo00UR74+2Qonxn/WpimvlLCBDgI +uKxHCSWOgv5yPpU2kwTPIjORXcy/y2G9K2bnsQCzznPRDyNkZmavQxxG6greFcrO +/0yhRPuBgxKBRvXPO+F5fybKFlU9IPLFehV60jLUybBejab/lMJyxdkh9UMu2Xqy +FVsRGazJt6T6AGp6TFEEcFUQw7qXNhVo9S7zGGaJFJdYc+Vx8QJRoCe8EAYVH7Mp +b/eYGhHaKg6iG7QCjPPxAoIBAQDN54wtuDqpAA+4PmqhiEhQKhabNqAoVmAWUxnJ +Db4Zzvkkc3Fo/Yg0HnQVaT0KmkcxY7397lTdtiwNkWPgJ0f6+g7L4K7PA7xh/q84 +IoXFGvYWwVdiVXLR1l06jorpA20clnba6CsbezwcllTq4bWvNnrAcM8l1YrAlRnV +qqqbPL78Rnba4C8q+VFy8r0d9OGnbvFcV7VWJjhr0a3aZbHQ67jPinNiUWvBVFFx +yGrqPMjkeHyiTLMhqQpaSHH67S88rj0g9RKexBaSUrl18QO7xnQHHSCcFWMQOiSN +shNvFri48dnU+Ms6ZLc3MBHbTK6uzP8xJCVnmsz/MWPGkQZFAoIBAQDI/vj/3/y/ +EpIawyHN7PQAMoto4AQF6sVasrgGd1tRsJnGKrCugH9gILvyke3L7qg0JTV3bDJY +e8+vH1vC3NV7PsOlCFjMtRWG0lRbCh/b7Qe3pCvPu4mbFhJgMT/mz+vbl5zvcdgX +kvne+St/267NKnY5gHBDhqitBwkZwNlTWJ0zVmTecKXn/KwjS9lX1qU3HiT3UFkd +5Y5Nt5lj1IOK/6NCXkxVkgOc4Zjcxx138Cg03VJhIiHTusRq6z9iTSTDubhkaSbi +2nadptFBiQtkVhAJ5G53U7pl/pIhhiJy901bu/v/wrIMJ2l6hiZIcLrbg6VGXxjV +5dB7LDEtKoL7AoIBAQC8+ffA+mX0N9c1nSuWh5L+6DIJUHBbtTLJKonu6gsAeuJU +3xNGbfK1CwI1qHnaolAW91knlrcTKaBy726ACu1YXmp4GgW2f9JFCk/csGqfxaf4 +qIg/+va/ugOku7CoPXnGFB6PuSffOBKqlhrn3DI41kKBHsgwDDYlnHKylMmyYmVS ++oUZS0pfIaXsXvbNaLQ2TG9+9gy7Pabo5e+vE0jI25+p84MEyH+iV3XMfUoLI7Cp +aB/TgZuimBelVvotd8Sz56K4/dSSHJwuvXfz1Dk9/Nz+rnAAcOyTtxlXZwnJGkx9 +iZMIkTNMq6UwJJEu+ckVK5ZHjso5tWzSBo1xcCcVAoIBAQCPL0x1A7zK5VDd7cqE +J1w/U8KKiKN1D6VeElkUiiysyjERwdGxzmpvMYKSsDCGCdMbqrInDBXlgPYXnDBD +ZgxSywiW5ZZU5l+advWPEWxWwMmxoitvxfqmV5fpnMwYAmDUQ3KSBTjaumJ03G6H +nBkvoSMtnXjcMe6xrIRoK0Dmpgb+znn3GKqn1BFQ57TCZW+3DytoX33M1X6FkNie +DINVHv3Pxtt8ThNyzCeYh+RPT+9kkZIhDi6o5bENNd8miSw6nnBkX6BLFTRQ5MjH +dfh+luzAD1I+gZAVHsA9T4/09IXQZt+DeNBb5iu3FB/rlRsYS/UOZ6qKnjfhtz6l +HVbHAoIBAFjNY/UPJDxQ/uG+rMU0nrmSBRGdgBvQkcefjWX/LIZV3MjNilUQ+B2a +lXz5AHGmHRnnwQsBVfN8rf4qQLln8l34Kgm7+cIFavgfg2oqVbNyNgezSlUmRq0J +Ttf3xYJtRgRUx8F+BcgJXMqlNGTMQJY8wawM/ATkwkbmSwGOKe04sBeIkwEycMId +BupvfN5lxDrKqJVPSl1t5Rh4us95CNh22/c5Tq5rsynl02ZB4swlcsVTdv8FSGmM +QVf/MkWXGN/x4lHJhKyklHMGv15GGvys1nlPTstMfUYs55ioWRW46TXQ8vOyzzpg +67xzBKYFEde+hgYk7X1Xeqj8A6bsqro= +-----END PRIVATE KEY----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/sha256.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/sha256.pem new file mode 100644 index 0000000000000000000000000000000000000000..01878e9678aa13a1d88454c9380aa520e8db5ef6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/sha256.pem @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFxzCCA6+gAwIBAgIJALnlnf5uzTkIMA0GCSqGSIb3DQEBCwUAMEsxCzAJBgNV +BAYTAkRFMRcwFQYDVQQKEw5zY2hva29rZWtzLm9yZzEjMCEGCSqGSIb3DQEJARYU +aGFubm9Ac2Nob2tva2Vrcy5vcmcwHhcNMTAwMTI3MDAyMTI1WhcNMjAwMTI1MDAy +MTI1WjBLMQswCQYDVQQGEwJERTEXMBUGA1UEChMOc2Nob2tva2Vrcy5vcmcxIzAh +BgkqhkiG9w0BCQEWFGhhbm5vQHNjaG9rb2tla3Mub3JnMIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEApJ4ODPwEooMW35dQPlBqdvcfkEvjhcsA7jmJfFqN +e/1T34zT44X9+KnMBSG2InacbD7eyFgjfaENFsZ87YkEBDIFZ/SHotLJZORQ8PUj +YoxPG4mjKN+yL2WthNcYbRyJreTbbDroNMuw6tkTSxeSXyYFQrKMCUfErVbZa/d5 +RvfFVk+Au9dVUFhed/Stn5cv+a0ffvpyA7ygihm1kMFICbvPeI0846tmC2Ph7rM5 +pYQyNBDOVpULODTk5Wu6jiiJJygvJWCZ1FdpsdBs5aKWHWdRhX++quGuflTTjH5d +qaIka4op9H7XksYphTDXmV+qHnva5jbPogwutDQcVsGBQcJaLmQqhsQK13bf4khE +iWJvfBLfHn8OOpY25ZwwuigJIwifNCxQeeT1FrLmyuYNhz2phPpzx065kqSUSR+A +Iw8DPE6e65UqMDKqZnID3dQeiQaFrHEV+Ibo0U/tD0YSBw5p33TMh0Es33IBWMac +m7x4hIFWdhl8W522u6qOrTswY3s8vB7blNWqMc9n7oWH8ybFf7EgKeDVtEN9AyBE +0WotXIEZWI+WvDbU1ACJXau9sQhYP/eerg7Zwr3iGUy4IQ5oUJibnjtcE+z8zmDN +pE6YcMCLJyLjXiQ3iHG9mNXzw7wPnslTbEEEukrfSlHGgW8Dm+VrNyW0JUM1bntx +vbMCAwEAAaOBrTCBqjAdBgNVHQ4EFgQUCedv7pDTuXtCxm4HTw9hUtrTvsowewYD +VR0jBHQwcoAUCedv7pDTuXtCxm4HTw9hUtrTvsqhT6RNMEsxCzAJBgNVBAYTAkRF +MRcwFQYDVQQKEw5zY2hva29rZWtzLm9yZzEjMCEGCSqGSIb3DQEJARYUaGFubm9A +c2Nob2tva2Vrcy5vcmeCCQC55Z3+bs05CDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3 +DQEBCwUAA4ICAQBHKAxA7WA/MEFjet03K8ouzEOr6Jrk2fZOuRhoDZ+9gr4FtaJB +P3Hh5D00kuSOvDnwsvCohxeNd1KTMAwVmVoH+NZkHERn3UXniUENlp18koI1ehlr +CZbXbzzE9Te9BelliSFA63q0cq0yJN1x9GyabU34XkAouCAmOqfSpKNZWZHGBHPF +bbYnZrHEMcsye6vKeTOcg1GqUHGrQM2WK0QaOwnCQv2RblI9VN+SeRoUJ44qTXdW +TwIYStsIPesacNcAQTStnHgKqIPx4zCwdx5xo8zONbXJfocqwyFqiAofvb9dN1nW +g1noVBcXB+oRBZW5CjFw87U88itq39i9+BWl835DWLBW2pVmx1QTLGv0RNgs/xVx +mWnjH4nNHvrjn6pRmqHZTk/SS0Hkl2qtDsynVxIl8EiMTfWSU3DBTuD2J/RSzuOE +eKtAbaoXkXE31jCl4FEZLITIZd8UkXacb9rN304tAK92L76JOAV+xOZxFRipmvx4 ++A9qQXgLhtP4VaDajb44V/kCKPSA0Vm3apehke9Wl8dDtagfos1e6MxSu3EVLXRF +SP2U777V77pdMSd0f/7cerKn5FjrxW1v1FaP1oIGniMk4qQNTgA/jvvhjybsPlVA +jsfnhWGbh1voJa0RQcMiRMsxpw2P1KNOEu37W2eq/vFghVztZJQUmb5iNw== +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__GreenletExit.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__GreenletExit.py new file mode 100644 index 0000000000000000000000000000000000000000..acad1bb17fa6f133306eb8b097e4517ad938a0ec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__GreenletExit.py @@ -0,0 +1,4 @@ +from gevent import GreenletExit + +assert issubclass(GreenletExit, BaseException) +assert not issubclass(GreenletExit, Exception) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___config.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___config.py new file mode 100644 index 0000000000000000000000000000000000000000..a512bbeae57e5fddeeddbae4d7461d00a965c784 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___config.py @@ -0,0 +1,159 @@ +# Copyright 2018 gevent contributors. See LICENSE for details. + +import os +import unittest +import sys + +from gevent import _config + +class TestResolver(unittest.TestCase): + + old_resolver = None + + def setUp(self): + if 'GEVENT_RESOLVER' in os.environ: + self.old_resolver = os.environ['GEVENT_RESOLVER'] + del os.environ['GEVENT_RESOLVER'] + + def tearDown(self): + if self.old_resolver: + os.environ['GEVENT_RESOLVER'] = self.old_resolver + + def test_key(self): + self.assertEqual(_config.Resolver.environment_key, 'GEVENT_RESOLVER') + + def test_default(self): + from gevent.resolver.thread import Resolver + + conf = _config.Resolver() + self.assertEqual(conf.get(), Resolver) + + def test_env(self): + from gevent.resolver.blocking import Resolver + + os.environ['GEVENT_RESOLVER'] = 'foo,bar,block,dnspython' + + conf = _config.Resolver() + self.assertEqual(conf.get(), Resolver) + + os.environ['GEVENT_RESOLVER'] = 'dnspython' + + # The existing value is unchanged + self.assertEqual(conf.get(), Resolver) + + # A new object reflects it + try: + from gevent.resolver.dnspython import Resolver as DResolver + except ImportError: # pragma: no cover + # dnspython is optional; skip it. + import warnings + warnings.warn('dnspython not installed') + else: + conf = _config.Resolver() + + self.assertEqual(conf.get(), DResolver) + + def test_set_str_long(self): + from gevent.resolver.blocking import Resolver + conf = _config.Resolver() + conf.set('gevent.resolver.blocking.Resolver') + + self.assertEqual(conf.get(), Resolver) + + def test_set_str_short(self): + from gevent.resolver.blocking import Resolver + conf = _config.Resolver() + conf.set('block') + + self.assertEqual(conf.get(), Resolver) + + def test_set_class(self): + from gevent.resolver.blocking import Resolver + conf = _config.Resolver() + conf.set(Resolver) + + self.assertEqual(conf.get(), Resolver) + + + def test_set_through_config(self): + from gevent.resolver.thread import Resolver as Default + from gevent.resolver.blocking import Resolver + + conf = _config.Config() + self.assertEqual(conf.resolver, Default) + + conf.resolver = 'block' + self.assertEqual(conf.resolver, Resolver) + +class TestFunctions(unittest.TestCase): + + def test_validate_bool(self): + self.assertTrue(_config.validate_bool('on')) + self.assertTrue(_config.validate_bool('1')) + self.assertFalse(_config.validate_bool('off')) + self.assertFalse(_config.validate_bool('0')) + self.assertFalse(_config.validate_bool('')) + + with self.assertRaises(ValueError): + _config.validate_bool(' hmm ') + + def test_validate_invalid(self): + with self.assertRaises(ValueError): + _config.validate_invalid(self) + +class TestConfig(unittest.TestCase): + + def test__dir__(self): + self.assertEqual(sorted(_config.config.settings), + sorted(dir(_config.config))) + + def test_getattr(self): + # Bypass the property that might be set here + self.assertIsNotNone(_config.config.__getattr__('resolver')) + + def test__getattr__invalid(self): + with self.assertRaises(AttributeError): + getattr(_config.config, 'no_such_setting') + + def test_set_invalid(self): + with self.assertRaises(AttributeError): + _config.config.set('no such setting', True) + +class TestImportableSetting(unittest.TestCase): + + def test_empty_list(self): + i = _config.ImportableSetting() + with self.assertRaisesRegex(ImportError, + "Cannot import from empty list"): + i._import_one_of([]) + + def test_path_not_supported(self): + import warnings + i = _config.ImportableSetting() + path = list(sys.path) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with self.assertRaisesRegex(ImportError, + "Cannot import 'foo/bar/gevent.no_such_module'"): + i._import_one('foo/bar/gevent.no_such_module') + + # We restored the path + self.assertEqual(path, sys.path) + + # We did not issue a warning + self.assertEqual(len(w), 0) + + def test_non_string(self): + i = _config.ImportableSetting() + self.assertIs(i._import_one(self), self) + + def test_get_options(self): + i = _config.ImportableSetting() + self.assertEqual({}, i.get_options()) + + i.shortname_map = {'foo': 'bad/path'} + options = i.get_options() + self.assertIn('foo', options) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___ident.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___ident.py new file mode 100644 index 0000000000000000000000000000000000000000..34d76d1aa99add518e5e3abd7fa17640780157d0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___ident.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# copyright 2018 gevent contributors. See LICENSE for details. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import gc + + +import gevent.testing as greentest +from gevent._ident import IdentRegistry +from gevent._compat import PYPY + +class Target(object): + pass + +class TestIdent(greentest.TestCase): + + def setUp(self): + self.reg = IdentRegistry() + + def tearDown(self): + self.reg = None + + def test_basic(self): + target = Target() + self.assertEqual(0, self.reg.get_ident(target)) + self.assertEqual(1, len(self.reg)) + + self.assertEqual(0, self.reg.get_ident(target)) + self.assertEqual(1, len(self.reg)) + + target2 = Target() + self.assertEqual(1, self.reg.get_ident(target2)) + self.assertEqual(2, len(self.reg)) + + self.assertEqual(1, self.reg.get_ident(target2)) + self.assertEqual(2, len(self.reg)) + + self.assertEqual(0, self.reg.get_ident(target)) + + # When an object dies, we can re-use + # its id. Under PyPy we need to collect garbage first. + del target + if PYPY: + for _ in range(3): + gc.collect() + + self.assertEqual(1, len(self.reg)) + + target3 = Target() + self.assertEqual(1, self.reg.get_ident(target2)) + self.assertEqual(0, self.reg.get_ident(target3)) + self.assertEqual(2, len(self.reg)) + + @greentest.skipOnPyPy("This would need to GC very frequently") + def test_circle(self): + keep_count = 3 + keepalive = [None] * keep_count + + for i in range(1000): + target = Target() + # Drop an old one. + keepalive[i % keep_count] = target + self.assertLessEqual(self.reg.get_ident(target), keep_count) + + +@greentest.skipOnPurePython("Needs C extension") +class TestCExt(greentest.TestCase): + + def test_c_extension(self): + self.assertEqual(IdentRegistry.__module__, + 'gevent._gevent_c_ident') + + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monitor.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..71aba103b8938f4c6e0ebd1f473f5837146114e7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monitor.py @@ -0,0 +1,386 @@ +# Copyright 2018 gevent contributors. See LICENSE for details. + +import gc +import unittest + + +from greenlet import gettrace +from greenlet import settrace + +from gevent.monkey import get_original +from gevent._compat import thread_mod_name +from gevent._compat import NativeStrIO + +from gevent.testing import verify +from gevent.testing.skipping import skipWithoutPSUtil + +from gevent import _monitor as monitor +from gevent import config as GEVENT_CONFIG + +get_ident = get_original(thread_mod_name, 'get_ident') + +class MockHub(object): + _threadpool = None + _resolver = None + + def __init__(self): + self.thread_ident = get_ident() + self.exception_stream = NativeStrIO() + self.dead = False + + def __bool__(self): + return not self.dead + + __nonzero__ = __bool__ + + def handle_error(self, *args): # pylint:disable=unused-argument + raise # pylint:disable=misplaced-bare-raise + + @property + def loop(self): + return self + + def reinit(self): + "mock loop.reinit" + +class _AbstractTestPeriodicMonitoringThread(object): + # Makes sure we don't actually spin up a new monitoring thread. + + # pylint:disable=no-member + + def setUp(self): + super(_AbstractTestPeriodicMonitoringThread, self).setUp() + self._orig_start_new_thread = monitor.start_new_thread + self._orig_thread_sleep = monitor.thread_sleep + monitor.thread_sleep = lambda _s: gc.collect() # For PyPy + self.tid = 0xDEADBEEF + def start_new_thread(_f, _a): + r = self.tid + self.tid += 1 + return r + + monitor.start_new_thread = start_new_thread + self.hub = MockHub() + self.pmt = monitor.PeriodicMonitoringThread(self.hub) + self.hub.periodic_monitoring_thread = self.pmt + self.pmt_default_funcs = self.pmt.monitoring_functions()[:] + self.len_pmt_default_funcs = len(self.pmt_default_funcs) + + def tearDown(self): + monitor.start_new_thread = self._orig_start_new_thread + monitor.thread_sleep = self._orig_thread_sleep + prev = self.pmt._greenlet_tracer.previous_trace_function + self.pmt.kill() + assert gettrace() is prev, (gettrace(), prev) + settrace(None) + super(_AbstractTestPeriodicMonitoringThread, self).tearDown() + + +class TestPeriodicMonitoringThread(_AbstractTestPeriodicMonitoringThread, + unittest.TestCase): + + def test_constructor(self): + self.assertEqual(0xDEADBEEF, self.pmt.monitor_thread_ident) + self.assertEqual(gettrace(), self.pmt._greenlet_tracer) + + @skipWithoutPSUtil("Verifies the process") + def test_get_process(self): + proc = self.pmt._get_process() + self.assertIsNotNone(proc) + # Same object is returned each time. + self.assertIs(proc, self.pmt._get_process()) + + def test_hub_wref(self): + self.assertIs(self.hub, self.pmt.hub) + del self.hub + + gc.collect() + self.assertIsNone(self.pmt.hub) + + # And it killed itself. + self.assertFalse(self.pmt.should_run) + self.assertIsNone(gettrace()) + + + def test_add_monitoring_function(self): + + self.assertRaises(ValueError, self.pmt.add_monitoring_function, None, 1) + self.assertRaises(ValueError, self.pmt.add_monitoring_function, lambda: None, -1) + + def f(): + "Does nothing" + + # Add + self.pmt.add_monitoring_function(f, 1) + self.assertEqual(self.len_pmt_default_funcs + 1, len(self.pmt.monitoring_functions())) + self.assertEqual(1, self.pmt.monitoring_functions()[1].period) + + # Update + self.pmt.add_monitoring_function(f, 2) + self.assertEqual(self.len_pmt_default_funcs + 1, len(self.pmt.monitoring_functions())) + self.assertEqual(2, self.pmt.monitoring_functions()[1].period) + + # Remove + self.pmt.add_monitoring_function(f, None) + self.assertEqual(self.len_pmt_default_funcs, len(self.pmt.monitoring_functions())) + + def test_calculate_sleep_time(self): + self.assertEqual( + self.pmt.monitoring_functions()[0].period, + self.pmt.calculate_sleep_time()) + + # Pretend that GEVENT_CONFIG.max_blocking_time was set to 0, + # to disable this monitor. + self.pmt._calculated_sleep_time = 0 + self.assertEqual( + self.pmt.inactive_sleep_time, + self.pmt.calculate_sleep_time() + ) + + # Getting the list of monitoring functions will also + # do this, if it looks like it has changed + self.pmt.monitoring_functions()[0].period = -1 + self.pmt._calculated_sleep_time = 0 + self.pmt.monitoring_functions() + self.assertEqual( + self.pmt.monitoring_functions()[0].period, + self.pmt.calculate_sleep_time()) + self.assertEqual( + self.pmt.monitoring_functions()[0].period, + self.pmt._calculated_sleep_time) + + def test_call_destroyed_hub(self): + # Add a function that destroys the hub so we break out (eventually) + # This clears the wref, which eventually calls kill() + def f(_hub): + _hub = None + self.hub = None + gc.collect() + + self.pmt.add_monitoring_function(f, 0.1) + self.pmt() + self.assertFalse(self.pmt.should_run) + + def test_call_dead_hub(self): + # Add a function that makes the hub go false (e.g., it quit) + # This causes the function to kill itself. + def f(hub): + hub.dead = True + self.pmt.add_monitoring_function(f, 0.1) + self.pmt() + self.assertFalse(self.pmt.should_run) + + def test_call_SystemExit(self): + # breaks the loop + def f(_hub): + raise SystemExit() + + self.pmt.add_monitoring_function(f, 0.1) + self.pmt() + + def test_call_other_error(self): + class MyException(Exception): + pass + + def f(_hub): + raise MyException() + + self.pmt.add_monitoring_function(f, 0.1) + with self.assertRaises(MyException): + self.pmt() + + def test_hub_reinit(self): + import os + from gevent.hub import reinit + self.pmt.pid = -1 + old_tid = self.pmt.monitor_thread_ident + + reinit(self.hub) + + self.assertEqual(os.getpid(), self.pmt.pid) + self.assertEqual(old_tid + 1, self.pmt.monitor_thread_ident) + + + +class TestPeriodicMonitorBlocking(_AbstractTestPeriodicMonitoringThread, + unittest.TestCase): + + def test_previous_trace(self): + self.pmt.kill() + self.assertIsNone(gettrace()) + + called = [] + def f(*args): + called.append(args) + + settrace(f) + + self.pmt = monitor.PeriodicMonitoringThread(self.hub) + self.assertEqual(gettrace(), self.pmt._greenlet_tracer) + self.assertIs(self.pmt._greenlet_tracer.previous_trace_function, f) + + self.pmt._greenlet_tracer('event', ('args',)) + + self.assertEqual([('event', ('args',))], called) + + def test__greenlet_tracer(self): + self.assertEqual(0, self.pmt._greenlet_tracer.greenlet_switch_counter) + # Unknown event still counts as a switch (should it?) + self.pmt._greenlet_tracer('unknown', None) + self.assertEqual(1, self.pmt._greenlet_tracer.greenlet_switch_counter) + self.assertIsNone(self.pmt._greenlet_tracer.active_greenlet) + + origin = object() + target = object() + + self.pmt._greenlet_tracer('switch', (origin, target)) + self.assertEqual(2, self.pmt._greenlet_tracer.greenlet_switch_counter) + self.assertIs(target, self.pmt._greenlet_tracer.active_greenlet) + + # Unknown event removes active greenlet + self.pmt._greenlet_tracer('unknown', ()) + self.assertEqual(3, self.pmt._greenlet_tracer.greenlet_switch_counter) + self.assertIsNone(self.pmt._greenlet_tracer.active_greenlet) + + def test_monitor_blocking(self): + # Initially there's no active greenlet and no switches, + # so nothing is considered blocked + from gevent.events import subscribers + from gevent.events import IEventLoopBlocked + events = [] + subscribers.append(events.append) + + self.assertFalse(self.pmt.monitor_blocking(self.hub)) + + # Give it an active greenlet + origin = object() + target = object() + self.pmt._greenlet_tracer('switch', (origin, target)) + + # We've switched, so we're not blocked + self.assertFalse(self.pmt.monitor_blocking(self.hub)) + self.assertFalse(events) + + # Again without switching is a problem. + self.assertTrue(self.pmt.monitor_blocking(self.hub)) + self.assertTrue(events) + verify.verifyObject(IEventLoopBlocked, events[0]) + del events[:] + + # But we can order it not to be a problem + self.pmt.ignore_current_greenlet_blocking() + self.assertFalse(self.pmt.monitor_blocking(self.hub)) + self.assertFalse(events) + + # And back again + self.pmt.monitor_current_greenlet_blocking() + self.assertTrue(self.pmt.monitor_blocking(self.hub)) + + # A bad thread_ident in the hub doesn't mess things up + self.hub.thread_ident = -1 + self.assertTrue(self.pmt.monitor_blocking(self.hub)) + + +class MockProcess(object): + + def __init__(self, rss): + self.rss = rss + + def memory_full_info(self): + return self + + +@skipWithoutPSUtil("Accessess memory info") +class TestPeriodicMonitorMemory(_AbstractTestPeriodicMonitoringThread, + unittest.TestCase): + + rss = 0 + + def setUp(self): + _AbstractTestPeriodicMonitoringThread.setUp(self) + self._old_max = GEVENT_CONFIG.max_memory_usage + GEVENT_CONFIG.max_memory_usage = None + + self.pmt._get_process = lambda: MockProcess(self.rss) + + def tearDown(self): + GEVENT_CONFIG.max_memory_usage = self._old_max + _AbstractTestPeriodicMonitoringThread.tearDown(self) + + def test_can_monitor_and_install(self): + # We run tests with psutil installed, and we have access to our + # process. + self.assertTrue(self.pmt.can_monitor_memory_usage()) + # No warning, adds a function + + self.pmt.install_monitor_memory_usage() + self.assertEqual(self.len_pmt_default_funcs + 1, len(self.pmt.monitoring_functions())) + + def test_cannot_monitor_and_install(self): + import warnings + self.pmt._get_process = lambda: None + self.assertFalse(self.pmt.can_monitor_memory_usage()) + + # This emits a warning, visible by default + with warnings.catch_warnings(record=True) as ws: + self.pmt.install_monitor_memory_usage() + + self.assertEqual(1, len(ws)) + self.assertIs(monitor.MonitorWarning, ws[0].category) + + def test_monitor_no_allowed(self): + self.assertEqual(-1, self.pmt.monitor_memory_usage(None)) + + def test_monitor_greater(self): + from gevent import events + + self.rss = 2 + GEVENT_CONFIG.max_memory_usage = 1 + + # Initial event + event = self.pmt.monitor_memory_usage(None) + self.assertIsInstance(event, events.MemoryUsageThresholdExceeded) + self.assertEqual(2, event.mem_usage) + self.assertEqual(1, event.max_allowed) # pylint:disable=no-member + self.assertIsInstance(event.memory_info, MockProcess) # pylint:disable=no-member + + # No growth, no event + event = self.pmt.monitor_memory_usage(None) + self.assertIsNone(event) + + # Growth, event + self.rss = 3 + event = self.pmt.monitor_memory_usage(None) + self.assertIsInstance(event, events.MemoryUsageThresholdExceeded) + self.assertEqual(3, event.mem_usage) + + # Shrinking below gets us back + self.rss = 1 + event = self.pmt.monitor_memory_usage(None) + self.assertIsInstance(event, events.MemoryUsageUnderThreshold) + self.assertEqual(1, event.mem_usage) + + # coverage + repr(event) + + # No change, no event + event = self.pmt.monitor_memory_usage(None) + self.assertIsNone(event) + + # Growth, event + self.rss = 3 + event = self.pmt.monitor_memory_usage(None) + self.assertIsInstance(event, events.MemoryUsageThresholdExceeded) + self.assertEqual(3, event.mem_usage) + + + def test_monitor_initial_below(self): + self.rss = 1 + GEVENT_CONFIG.max_memory_usage = 10 + + + event = self.pmt.monitor_memory_usage(None) + self.assertIsNone(event) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monkey_patching.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monkey_patching.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fcb165872e5ec1aabd0a2560a812c8f357cd34 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test___monkey_patching.py @@ -0,0 +1,102 @@ +import sys +import os +import glob + +import atexit +# subprocess: include in subprocess tests + +from gevent.testing import util +from gevent.testing import sysinfo +from gevent.testing.support import is_resource_enabled + +TIMEOUT = 120 + +# XXX: Generalize this so other packages can use it. + + +def get_absolute_pythonpath(): + paths = [os.path.abspath(p) for p in os.environ.get('PYTHONPATH', '').split(os.pathsep)] + return os.pathsep.join(paths) + + +def TESTRUNNER(tests=None): + if not is_resource_enabled('gevent_monkey'): + util.log('WARNING: Testing monkey-patched stdlib has been disabled', + color="suboptimal-behaviour") + return + + try: + test_dir, version_test_dir = util.find_stdlib_tests() + except util.NoSetupPyFound as e: + util.log("WARNING: No setup.py and src/greentest found: %r", e, + color="suboptimal-behaviour") + return + + if not os.path.exists(test_dir): + util.log('WARNING: No test directory found at %s', test_dir, + color="suboptimal-behaviour") + return + + # pylint:disable=unspecified-encoding + with open(os.path.join(test_dir, 'version')) as f: + preferred_version = f.read().strip() + + running_version = sysinfo.get_python_version() + if preferred_version != running_version: + util.log('WARNING: The tests in %s/ are from version %s and your Python is %s', + test_dir, preferred_version, running_version, + color="suboptimal-behaviour") + + version_tests = glob.glob('%s/test_*.py' % version_test_dir) + version_tests = sorted(version_tests) + if not tests: + tests = glob.glob('%s/test_*.py' % test_dir) + tests = sorted(tests) + + PYTHONPATH = (os.getcwd() + os.pathsep + get_absolute_pythonpath()).rstrip(':') + + tests = sorted(set(os.path.basename(x) for x in tests)) + version_tests = sorted(set(os.path.basename(x) for x in version_tests)) + + util.log("Discovered %d tests in %s", len(tests), test_dir) + util.log("Discovered %d version-specific tests in %s", len(version_tests), version_test_dir) + + options = { + 'cwd': test_dir, + 'timeout': TIMEOUT, + 'setenv': { + 'PYTHONPATH': PYTHONPATH, + # debug produces resource tracking warnings for the + # CFFI backends. On Python 2, many of the stdlib tests + # rely on refcounting to close sockets so they produce + # lots of noise. Python 3 is not completely immune; + # test_ftplib.py tends to produce warnings---and the Python 3 + # test framework turns those into test failures! + 'GEVENT_DEBUG': 'error', + } + } + + if tests and not sys.platform.startswith("win"): + atexit.register(os.system, 'rm -f */@test*') + + basic_args = [sys.executable, '-u', '-W', 'ignore', '-m', 'gevent.testing.monkey_test'] + for filename in tests: + if filename in version_tests: + util.log("Overriding %s from %s with file from %s", filename, test_dir, version_test_dir) + continue + yield basic_args + [filename], options.copy() + + options['cwd'] = version_test_dir + for filename in version_tests: + yield basic_args + [filename], options.copy() + + +def main(): + from gevent.testing import testrunner + discovered_tests = TESTRUNNER(sys.argv[1:]) + discovered_tests = list(discovered_tests) + return testrunner.Runner(discovered_tests, quiet=None)() + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__all__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__all__.py new file mode 100644 index 0000000000000000000000000000000000000000..c73ae7b8d23daef710d092f66b20599b0ce2f01e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__all__.py @@ -0,0 +1,327 @@ +# Check __all__, __implements__, __extensions__, __imports__ of the modules + +from __future__ import print_function +from __future__ import absolute_import + + +import functools +import sys +import unittest +import types +import importlib +import warnings + +from gevent.testing import six +from gevent.testing import modules +from gevent.testing.sysinfo import PLATFORM_SPECIFIC_SUFFIXES +from gevent.testing.util import debug + +from gevent._patcher import MAPPING + +class ANY(object): + def __contains__(self, item): + return True + +ANY = ANY() + +NOT_IMPLEMENTED = { + 'socket': ['CAPI'], + 'thread': ['allocate', 'exit_thread', 'interrupt_main', 'start_new'], + 'select': ANY, + 'os': ANY, + 'threading': ANY, + '__builtin__' if six.PY2 else 'builtins': ANY, + 'signal': ANY, +} + +COULD_BE_MISSING = { + 'socket': ['create_connection', 'RAND_add', 'RAND_egd', 'RAND_status'], + 'subprocess': ['_posixsubprocess'], +} + +# Things without an __all__ should generally be internal implementation +# helpers +NO_ALL = { + 'gevent.threading', + 'gevent._compat', + 'gevent._corecffi', + 'gevent._ffi', + 'gevent._fileobjectcommon', + 'gevent._fileobjectposix', + 'gevent._patcher', + 'gevent._socketcommon', + 'gevent._tblib', + 'gevent._util', + 'gevent.resolver._addresses', + 'gevent.resolver._hostsfile', + # gevent.monkey is handled specially. +} + +ALLOW_IMPLEMENTS = [ + 'gevent._queue', + # 'gevent.resolver.dnspython', + # 'gevent.resolver_thread', + # 'gevent.resolver.blocking', + # 'gevent.resolver_ares', + # 'gevent.server', + # 'gevent._resolver.hostfile', + # 'gevent.util', + # 'gevent.threadpool', + # 'gevent.timeout', +] + +# A list of modules that may contain things that aren't actually, technically, +# extensions, but that need to be in __extensions__ anyway due to the way, +# for example, monkey patching, needs to work. +EXTRA_EXTENSIONS = [] +if sys.platform.startswith('win'): + EXTRA_EXTENSIONS.append('gevent.signal') + + + +_MISSING = '' + +def skip_if_no_stdlib_counterpart(f): + @functools.wraps(f) + def m(self): + if not self.stdlib_module: + self.skipTest("Need stdlib counterpart to %s" % self.modname) + f(self) + + return m + +class AbstractTestMixin(object): + modname = None + stdlib_has_all = False + stdlib_all = None + stdlib_name = None + stdlib_module = None + + @classmethod + def setUpClass(cls): + modname = cls.modname + if modname.endswith(PLATFORM_SPECIFIC_SUFFIXES): + raise unittest.SkipTest("Module %s is platform specific" % modname) + + + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + try: + cls.module = importlib.import_module(modname) + except ImportError: + if modname in modules.OPTIONAL_MODULES: + msg = "Unable to import %s" % modname + raise unittest.SkipTest(msg) + raise + + cls.__implements__ = getattr(cls.module, '__implements__', None) + cls.__imports__ = getattr(cls.module, '__imports__', []) + cls.__extensions__ = getattr(cls.module, '__extensions__', []) + + cls.stdlib_name = MAPPING.get(modname) + + if cls.stdlib_name is not None: + try: + cls.stdlib_module = __import__(cls.stdlib_name) + except ImportError: + pass + else: + cls.stdlib_has_all = True + cls.stdlib_all = getattr(cls.stdlib_module, '__all__', None) + if cls.stdlib_all is None: + cls.stdlib_has_all = False + cls.stdlib_all = [ + name + for name in dir(cls.stdlib_module) + if not name.startswith('_') + and not isinstance(getattr(cls.stdlib_module, name), types.ModuleType) + ] + + def skipIfNoAll(self): + if not hasattr(self.module, '__all__'): + self.assertTrue( + self.modname in NO_ALL or self.modname.startswith('gevent.monkey.'), + "Module has no all" + ) + + self.skipTest("%s Needs __all__" % self.modname) + + def test_all(self): + # Check that __all__ is present in the gevent module, + # and only includes things that actually exist and can be + # imported from it. + self.skipIfNoAll() + names = {} + six.exec_("from %s import *" % self.modname, names) + names.pop('__builtins__', None) + self.maxDiff = None + + # It should match both as a set + self.assertEqual(set(names), set(self.module.__all__)) + # and it should not contain duplicates. + self.assertEqual(sorted(names), sorted(self.module.__all__)) + + def test_all_formula(self): + self.skipIfNoAll() + # Check __all__ = __implements__ + __extensions__ + __imported__ + # This is disabled because it was previously being skipped entirely + # back when we had to call things manually. In that time, it drifted + # out of sync. It should be enabled again and problems corrected. + all_calculated = ( + tuple(self.__implements__ or ()) + + tuple(self.__imports__ or ()) + + tuple(self.__extensions__ or ()) + ) + try: + self.assertEqual(sorted(all_calculated), + sorted(self.module.__all__)) + except AssertionError: + self.skipTest("Module %s fails the all formula; fix it" % self.modname) + except TypeError: + # TypeError: '<' not supported between instances of 'type' and 'str' + raise AssertionError( + "Unable to sort %r from all %s in %s" % ( + all_calculated, self.module.__all__, self.module + ) + ) + + def test_implements_presence_justified(self): + # Check that __implements__ is present only if the module is modeled + # after a module from stdlib (like gevent.socket). + + if self.modname in ALLOW_IMPLEMENTS: + return + if self.__implements__ is not None and self.stdlib_module is None: + raise AssertionError( + '%s (%r) has __implements__ (%s) but no stdlib counterpart module exists (%s)' + % (self.modname, self.module, self.__implements__, self.stdlib_name)) + + @skip_if_no_stdlib_counterpart + def test_implements_subset_of_stdlib_all(self): + # Check that __implements__ + __imports__ is a subset of the + # corresponding standard module __all__ or dir() + for name in tuple(self.__implements__ or ()) + tuple(self.__imports__): + if name in self.stdlib_all: + continue + if name in COULD_BE_MISSING.get(self.stdlib_name, ()): + continue + if name in dir(self.stdlib_module): # like thread._local which is not in thread.__all__ + continue + raise AssertionError('%r is not found in %r.__all__ nor in dir(%r)' % (name, self.stdlib_module, self.stdlib_module)) + + @skip_if_no_stdlib_counterpart + def test_implements_actually_implements(self): + # Check that the module actually implements the entries from + # __implements__ + + for name in self.__implements__ or (): + item = getattr(self.module, name) + try: + stdlib_item = getattr(self.stdlib_module, name) + self.assertIsNot(item, stdlib_item) + except AttributeError: + if name not in COULD_BE_MISSING.get(self.stdlib_name, []): + raise + + @skip_if_no_stdlib_counterpart + def test_imports_actually_imports(self): + # Check that the module actually imports the entries from + # __imports__ + for name in self.__imports__: + item = getattr(self.module, name) + stdlib_item = getattr(self.stdlib_module, name) + self.assertIs(item, stdlib_item) + + @skip_if_no_stdlib_counterpart + def test_extensions_actually_extend(self): + # Check that the module actually defines new entries in + # __extensions__ + + if self.modname in EXTRA_EXTENSIONS: + return + for name in self.__extensions__: + try: + if hasattr(self.stdlib_module, name): + raise AssertionError("'%r' is not an extension, it is found in %r" % ( + name, self.stdlib_module + )) + except TypeError as ex: + # TypeError: attribute name must be string, not 'type' + raise AssertionError( + "Got TypeError (%r) getting %r (of %s) from %s/%s" % ( + ex, name, self.__extensions__, self.stdlib_module, self.modname + ) + ) + + @skip_if_no_stdlib_counterpart + def test_completeness(self): # pylint:disable=too-many-branches + # Check that __all__ (or dir()) of the corresponsing stdlib is + # a subset of __all__ of this module + + missed = [] + for name in self.stdlib_all: + if name not in getattr(self.module, '__all__', []): + missed.append(name) + + # handle stuff like ssl.socket and ssl.socket_error which have no reason to be in gevent.ssl.__all__ + if not self.stdlib_has_all: + for name in missed[:]: + if hasattr(self.module, name): + missed.remove(name) + + # remove known misses + not_implemented = NOT_IMPLEMENTED.get(self.stdlib_name) + if not_implemented is not None: + result = [] + for name in missed: + if name in not_implemented: + # We often don't want __all__ to be set because we wind up + # documenting things that we just copy in from the stdlib. + # But if we implement it, don't print a warning + if getattr(self.module, name, _MISSING) is _MISSING: + debug('IncompleteImplWarning: %s.%s' % (self.modname, name)) + else: + result.append(name) + missed = result + + if missed: + if self.stdlib_has_all: + msg = '''The following items + in %r.__all__ +are missing from %r: + %r''' % (self.stdlib_module, self.module, missed) + else: + msg = '''The following items + in dir(%r) +are missing from %r: + %r''' % (self.stdlib_module, self.module, missed) + raise AssertionError(msg) + + +def _create_tests(): + for _, modname in modules.walk_modules(include_so=False, recursive=True, + check_optional=False): + if modname.endswith(PLATFORM_SPECIFIC_SUFFIXES): + continue + if modname.endswith('__main__'): + # gevent.monkey.__main__ especially is a problem. + # These aren't meant to be imported anyway. + continue + + orig_modname = modname + modname_no_period = orig_modname.replace('.', '_') + + cls = type( + 'Test_' + modname_no_period, + (AbstractTestMixin, unittest.TestCase), + { + '__module__': __name__, + 'modname': orig_modname + } + ) + globals()[cls.__name__] = cls + +_create_tests() + +if __name__ == "__main__": + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api.py new file mode 100644 index 0000000000000000000000000000000000000000..697a3e07a64cab720a0099981d5230df2bdb727d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api.py @@ -0,0 +1,132 @@ +# Copyright (c) 2008 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import gevent.testing as greentest +import gevent +from gevent import util, socket + +DELAY = 0.1 + + +class Test(greentest.TestCase): + + @greentest.skipOnAppVeyor("Timing causes the state to often be [start,finished]") + def test_killing_dormant(self): + state = [] + + def test(): + try: + state.append('start') + gevent.sleep(DELAY * 3.0) + except: # pylint:disable=bare-except + state.append('except') + # catching GreenletExit + + state.append('finished') + + g = gevent.spawn(test) + gevent.sleep(DELAY / 2) + assert state == ['start'], state + g.kill() + # will not get there, unless switching is explicitly scheduled by kill + self.assertEqual(state, ['start', 'except', 'finished']) + + def test_nested_with_timeout(self): + def func(): + return gevent.with_timeout(0.2, gevent.sleep, 2, timeout_value=1) + self.assertRaises(gevent.Timeout, gevent.with_timeout, 0.1, func) + + def test_sleep_invalid_switch(self): + p = gevent.spawn(util.wrap_errors(AssertionError, gevent.sleep), 2) + gevent.sleep(0) # wait for p to start, because actual order of switching is reversed + switcher = gevent.spawn(p.switch, None) + result = p.get() + assert isinstance(result, AssertionError), result + assert 'Invalid switch' in str(result), repr(str(result)) + switcher.kill() + + if hasattr(socket, 'socketpair'): + + def _test_wait_read_invalid_switch(self, sleep): + sock1, sock2 = socket.socketpair() + try: + p = gevent.spawn(util.wrap_errors(AssertionError, + socket.wait_read), # pylint:disable=no-member + sock1.fileno()) + gevent.get_hub().loop.run_callback(switch_None, p) + if sleep is not None: + gevent.sleep(sleep) + result = p.get() + assert isinstance(result, AssertionError), result + assert 'Invalid switch' in str(result), repr(str(result)) + finally: + sock1.close() + sock2.close() + + def test_invalid_switch_None(self): + self._test_wait_read_invalid_switch(None) + + def test_invalid_switch_0(self): + self._test_wait_read_invalid_switch(0) + + def test_invalid_switch_1(self): + self._test_wait_read_invalid_switch(0.001) + + # we don't test wait_write the same way, because socket is always ready to write + + +def switch_None(g): + g.switch(None) + + +class TestTimers(greentest.TestCase): + + def test_timer_fired(self): + lst = [1] + + def func(): + gevent.spawn_later(0.01, lst.pop) + gevent.sleep(0.02) + + gevent.spawn(func) + # Func has not run yet + self.assertEqual(lst, [1]) + # Run callbacks but don't yield. + gevent.sleep() + + # Let timers fire. Func should be done. + gevent.sleep(0.1) + self.assertEqual(lst, []) + + + def test_spawn_is_not_cancelled(self): + lst = [1] + + def func(): + gevent.spawn(lst.pop) + # exiting immediately, but self.lst.pop must be called + gevent.spawn(func) + gevent.sleep(0.1) + self.assertEqual(lst, []) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api_timeout.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..c208399e704dcdf0ed7298fbd2b86196eb3c9480 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__api_timeout.py @@ -0,0 +1,210 @@ +# Copyright (c) 2008 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import sys +import gevent.testing as greentest +import weakref +import time +import gc + +from gevent import sleep +from gevent import Timeout +from gevent import get_hub + + +from gevent.testing.timing import SMALL_TICK as DELAY +from gevent.testing import flaky + + +class Error(Exception): + pass + + +class _UpdateNowProxy(object): + + update_now_calls = 0 + + def __init__(self, loop): + self.loop = loop + + def __getattr__(self, name): + return getattr(self.loop, name) + + def update_now(self): + self.update_now_calls += 1 + self.loop.update_now() + +class _UpdateNowWithTimerProxy(_UpdateNowProxy): + + def timer(self, *_args, **_kwargs): + return _Timer(self) + +class _Timer(object): + + pending = False + active = False + + def __init__(self, loop): + self.loop = loop + + def start(self, *_args, **kwargs): + if kwargs.get("update"): + self.loop.update_now() + self.pending = self.active = True + + def stop(self): + self.active = self.pending = False + + def close(self): + "Does nothing" + + +class Test(greentest.TestCase): + + def test_timeout_calls_update_now(self): + hub = get_hub() + loop = hub.loop + proxy = _UpdateNowWithTimerProxy(loop) + hub.loop = proxy + + try: + with Timeout(DELAY * 2) as t: + self.assertTrue(t.pending) + finally: + hub.loop = loop + + self.assertEqual(1, proxy.update_now_calls) + + def test_sleep_calls_update_now(self): + hub = get_hub() + loop = hub.loop + proxy = _UpdateNowProxy(loop) + hub.loop = proxy + try: + sleep(0.01) + finally: + hub.loop = loop + + self.assertEqual(1, proxy.update_now_calls) + + + @greentest.skipOnAppVeyor("Timing is flaky, especially under Py 3.4/64-bit") + @greentest.skipOnPyPy3OnCI("Timing is flaky, especially under Py 3.4/64-bit") + @greentest.reraises_flaky_timeout((Timeout, AssertionError)) + def test_api(self): + # Nothing happens if with-block finishes before the timeout expires + t = Timeout(DELAY * 2) + self.assertFalse(t.pending, t) + with t: + self.assertTrue(t.pending, t) + sleep(DELAY) + # check if timer was actually cancelled + self.assertFalse(t.pending, t) + sleep(DELAY * 2) + + # An exception will be raised if it's not + with self.assertRaises(Timeout) as exc: + with Timeout(DELAY) as t: + sleep(DELAY * 10) + + self.assertIs(exc.exception, t) + + # You can customize the exception raised: + with self.assertRaises(IOError): + with Timeout(DELAY, IOError("Operation takes way too long")): + sleep(DELAY * 10) + + # Providing classes instead of values should be possible too: + with self.assertRaises(ValueError): + with Timeout(DELAY, ValueError): + sleep(DELAY * 10) + + + try: + 1 / 0 + except ZeroDivisionError: + with self.assertRaises(ZeroDivisionError): + with Timeout(DELAY, sys.exc_info()[0]): + sleep(DELAY * 10) + raise AssertionError('should not get there') + raise AssertionError('should not get there') + else: + raise AssertionError('should not get there') + + # It's possible to cancel the timer inside the block: + with Timeout(DELAY) as timer: + timer.cancel() + sleep(DELAY * 2) + + # To silent the exception before exiting the block, pass False as second parameter. + XDELAY = 0.1 + start = time.time() + with Timeout(XDELAY, False): + sleep(XDELAY * 2) + delta = time.time() - start + self.assertTimeWithinRange(delta, 0, XDELAY * 2) + + # passing None as seconds disables the timer + with Timeout(None): + sleep(DELAY) + sleep(DELAY) + + def test_ref(self): + err = Error() + err_ref = weakref.ref(err) + with Timeout(DELAY * 2, err): + sleep(DELAY) + del err + gc.collect() + self.assertFalse(err_ref(), err_ref) + + @flaky.reraises_flaky_race_condition() + def test_nested_timeout(self): + with Timeout(DELAY, False): + with Timeout(DELAY * 10, False): + sleep(DELAY * 3 * 20) + raise AssertionError('should not get there') + + with Timeout(DELAY) as t1: + with Timeout(DELAY * 20) as t2: + with self.assertRaises(Timeout) as exc: + sleep(DELAY * 30) + self.assertIs(exc.exception, t1) + + self.assertFalse(t1.pending, t1) + self.assertTrue(t2.pending, t2) + + self.assertFalse(t2.pending) + + with Timeout(DELAY * 20) as t1: + with Timeout(DELAY) as t2: + with self.assertRaises(Timeout) as exc: + sleep(DELAY * 30) + self.assertIs(exc.exception, t2) + + self.assertTrue(t1.pending, t1) + self.assertFalse(t2.pending, t2) + + self.assertFalse(t1.pending) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_host_result.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_host_result.py new file mode 100644 index 0000000000000000000000000000000000000000..c65a9db4ed39e2430adfa830063ecc5c24d5bd0b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_host_result.py @@ -0,0 +1,32 @@ +from __future__ import print_function + +import pickle +import gevent.testing as greentest +try: + from gevent.resolver.cares import ares_host_result +except ImportError: # pragma: no cover + ares_host_result = None + + +@greentest.skipIf(ares_host_result is None, + "Must be able to import ares") +class TestPickle(greentest.TestCase): + # Issue 104: ares.ares_host_result unpickleable + + def _test(self, protocol): + r = ares_host_result('family', ('arg1', 'arg2', )) + dumped = pickle.dumps(r, protocol) + loaded = pickle.loads(dumped) + self.assertEqual(r, loaded) + # pylint:disable=no-member + self.assertEqual(r.family, loaded.family) + + +for i in range(0, pickle.HIGHEST_PROTOCOL): + def make_test(j): + return lambda self: self._test(j) + setattr(TestPickle, 'test' + str(i), make_test(i)) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_timeout.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..cb88ff2e074975e0a5a3daf5fddaf93177cc27a6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ares_timeout.py @@ -0,0 +1,44 @@ +from __future__ import print_function + +import unittest + +import gevent +try: + from gevent.resolver.ares import Resolver +except ImportError as ex: + Resolver = None +from gevent import socket + +import gevent.testing as greentest +from gevent.testing.sockets import udp_listener + +@unittest.skipIf( + Resolver is None, + "Needs ares resolver" +) +class TestTimeout(greentest.TestCase): + + __timeout__ = 30 + + def test(self): + listener = self._close_on_teardown(udp_listener()) + address = listener.getsockname() + + + def reader(): + while True: + listener.recvfrom(10000) + + greader = gevent.spawn(reader) + self._close_on_teardown(greader.kill) + + r = Resolver(servers=[address[0]], timeout=0.001, tries=1, + udp_port=address[-1]) + self._close_on_teardown(r) + + with self.assertRaisesRegex(socket.herror, "ARES_ETIMEOUT"): + r.gethostbyname('www.google.com') + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__backdoor.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__backdoor.py new file mode 100644 index 0000000000000000000000000000000000000000..232e05d95b605cf9bf0ae7f43db3c188219f0e4e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__backdoor.py @@ -0,0 +1,168 @@ +from __future__ import print_function +from __future__ import absolute_import + +import gevent +from gevent import socket +from gevent import backdoor + +import gevent.testing as greentest +from gevent.testing.params import DEFAULT_BIND_ADDR_TUPLE +from gevent.testing.params import DEFAULT_CONNECT + +def read_until(conn, postfix): + read = b'' + assert isinstance(postfix, bytes) + + while not read.endswith(postfix): + result = conn.recv(1) + if not result: + raise AssertionError('Connection ended before %r. Data read:\n%r' % (postfix, read)) + read += result + + return read if isinstance(read, str) else read.decode('utf-8') + +def readline(conn): + with conn.makefile() as f: + return f.readline() + + +class WorkerGreenlet(gevent.Greenlet): + spawning_stack_limit = 2 + +class SocketWithBanner(socket.socket): + __slots__ = ('banner',) + + def __init__(self, *args, **kwargs): + self.banner = None + super(SocketWithBanner, self).__init__(*args, **kwargs) + + def __enter__(self): + return socket.socket.__enter__(self) + + def __exit__(self, t, v, tb): + return socket.socket.__exit__(self, t, v, tb) + + +@greentest.skipOnAppVeyor( + "With the update to libev 4.31 and potentially closing sockets in the background, " + "alternate tests started hanging on appveyor. Something like .E.E.E. " + "See https://ci.appveyor.com/project/denik/gevent/build/job/n9fynkoyt2bvk8b5 " + "It's not clear why, but presumably a socket isn't getting closed and a watcher is tied " + "to the wrong file descriptor. I haven't been able to reproduce. If it were a systemic " + "problem I'd expect to see more failures, so it is probably specific to resource management " + "in this test." +) +class Test(greentest.TestCase): + + __timeout__ = 10 + + def tearDown(self): + gevent.sleep() # let spawned greenlets die + super(Test, self).tearDown() + + def _make_and_start_server(self, *args, **kwargs): + server = backdoor.BackdoorServer(DEFAULT_BIND_ADDR_TUPLE, *args, **kwargs) + server.start() + return server + + def _create_connection(self, server): + conn = SocketWithBanner() + conn.connect((DEFAULT_CONNECT, server.server_port)) # pylint:disable=not-callable + try: + banner = self._wait_for_prompt(conn) + except: + conn.close() + raise + + conn.banner = banner + return conn + + def _wait_for_prompt(self, conn): + return read_until(conn, b'>>> ') + + def _close(self, conn, cmd=b'quit()\r\n)'): + conn.sendall(cmd) + line = readline(conn) + self.assertEqual(line, '') + conn.close() + + @greentest.skipOnMacOnCI( + "Sometimes fails to get the right answers; " + "https://travis-ci.org/github/gevent/gevent/jobs/692184822" + ) + def test_multi(self): + with self._make_and_start_server() as server: + def connect(): + with self._create_connection(server) as conn: + conn.sendall(b'2+2\r\n') + line = readline(conn) + self.assertEqual(line.strip(), '4', repr(line)) + self._close(conn) + + jobs = [WorkerGreenlet.spawn(connect) for _ in range(10)] + try: + done = gevent.joinall(jobs, raise_error=True) + finally: + gevent.joinall(jobs, raise_error=False) + + self.assertEqual(len(done), len(jobs), done) + + def test_quit(self): + with self._make_and_start_server() as server: + with self._create_connection(server) as conn: + self._close(conn) + + def test_sys_exit(self): + with self._make_and_start_server() as server: + with self._create_connection(server) as conn: + self._close(conn, b'import sys; sys.exit(0)\r\n') + + def test_banner(self): + expected_banner = "Welcome stranger!" # native string + with self._make_and_start_server(banner=expected_banner) as server: + with self._create_connection(server) as conn: + banner = conn.banner + self._close(conn) + + self.assertEqual(banner[:len(expected_banner)], expected_banner, banner) + + + def test_builtins(self): + with self._make_and_start_server() as server: + with self._create_connection(server) as conn: + conn.sendall(b'locals()["__builtins__"]\r\n') + response = read_until(conn, b'>>> ') + self._close(conn) + + self.assertLess( + len(response), 300, + msg="locals() unusable: %s..." % response) + + def test_switch_exc(self): + from gevent.queue import Queue, Empty + + def bad(): + q = Queue() + print('switching out, then throwing in') + try: + q.get(block=True, timeout=0.1) + except Empty: + print("Got Empty") + print('switching out') + gevent.sleep(0.1) + print('switched in') + + with self._make_and_start_server(locals={'bad': bad}) as server: + with self._create_connection(server) as conn: + conn.sendall(b'bad()\r\n') + response = self._wait_for_prompt(conn) + self._close(conn) + + response = response.replace('\r\n', '\n') + self.assertEqual( + 'switching out, then throwing in\nGot Empty\nswitching out\nswitched in\n>>> ', + response) + + +if __name__ == '__main__': + greentest.main() # pragma: testrunner-no-combine diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__close_backend_fd.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__close_backend_fd.py new file mode 100644 index 0000000000000000000000000000000000000000..977b27597e53d93ca589f3ad28dd4ea0364e8e65 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__close_backend_fd.py @@ -0,0 +1,114 @@ +from __future__ import print_function +import os +import unittest + +import gevent +from gevent import core +from gevent.hub import Hub + +from gevent.testing import sysinfo + +@unittest.skipUnless( + getattr(core, 'LIBEV_EMBED', False), + "Needs embedded libev. " + "hub.loop.fileno is only defined when " + "we embed libev for some reason. " + "Choosing specific backends is also only supported by libev " + "(not libuv), and besides, libuv has a nasty tendency to " + "abort() the process if its FD gets closed. " +) +class Test(unittest.TestCase): + # NOTE that we extend unittest.TestCase, not greentest.TestCase + # Extending the later causes the wrong hub to get used. + + BACKENDS_THAT_SUCCEED_WHEN_FD_CLOSED = ( + 'kqueue', + 'epoll', + 'linux_aio', + 'linux_iouring', + ) + + BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME = ( + # This fails on the Fedora Rawhide 33 image. It's not clear + # why; needs investigated. + 'linux_iouring', + ) if not sysinfo.libev_supports_linux_iouring() else ( + # Even on systems that ought to support it, according to the + # version number, it often fails to actually work. See the + # manylinux_2_28_x86_64 image as-of 2024-10-03; it seems that + # 6.8.0-1014-azure, as used in the Ubuntu 22.04 Github Actions + # runner works fine, though. So it's not clear what we can do + # other than skip it. It's possible this has to do with + # running the manylinux images in docker? " Docker also + # consequently disabled io_uring from their default seccomp + # profile." + ) + + BACKENDS_TO_SKIP = ( + 'linux_iouring', + ) + + BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME += ( + # This can be compiled on any (?) version of + # linux, but there's a runtime check that you're + # running at least kernel 4.19, so we can fail to create + # the hub. When we updated to libev 4.31 from 4.25, Travis Ci + # was still on kernel 1.15 (Ubuntu 16.04). + 'linux_aio', + ) if not sysinfo.libev_supports_linux_aio() else ( + ) + + def _check_backend(self, backend): + hub = Hub(backend, default=False) + + try: + self.assertEqual(hub.loop.backend, backend) + + gevent.sleep(0.001) + fileno = hub.loop.fileno() + if fileno is None: + return # nothing to close, test implicitly passes. + + os.close(fileno) + + if backend in self.BACKENDS_THAT_SUCCEED_WHEN_FD_CLOSED: + gevent.sleep(0.001) + else: + with self.assertRaisesRegex(SystemError, "(libev)"): + gevent.sleep(0.001) + + hub.destroy() + self.assertIn('destroyed', repr(hub)) + finally: + if hub.loop is not None: + hub.destroy() + + @classmethod + def _make_test(cls, count, backend): # pylint:disable=no-self-argument + if backend in cls.BACKENDS_TO_SKIP: + def test(self): + self.skipTest('Expecting %s to fail' % (backend, )) + elif backend in cls.BACKENDS_THAT_WILL_FAIL_TO_CREATE_AT_RUNTIME: + def test(self): + with self.assertRaisesRegex(SystemError, 'ev_loop_new'): + Hub(backend, default=False) + else: + def test(self): + self._check_backend(backend) + test.__name__ = 'test_' + backend + '_' + str(count) + return test.__name__, test + + @classmethod + def _make_tests(cls): + count = backend = None + + for count in range(2): + for backend in core.supported_backends(): + name, func = cls._make_test(count, backend) + setattr(cls, name, func) + name = func = None + +Test._make_tests() + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__compat.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__compat.py new file mode 100644 index 0000000000000000000000000000000000000000..76795974eefcce6256a43b87ac1c03c03122bd2a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__compat.py @@ -0,0 +1,56 @@ +from __future__ import absolute_import, print_function, division + +import os +import unittest + +class TestFSPath(unittest.TestCase): + + def setUp(self): + self.__path = None + + def __fspath__(self): + if self.__path is not None: + return self.__path + raise AttributeError("Accessing path data") + + def _callFUT(self, arg): + from gevent._compat import _fspath + return _fspath(arg) + + def test_text(self): + s = u'path' + self.assertIs(s, self._callFUT(s)) + + def test_bytes(self): + s = b'path' + self.assertIs(s, self._callFUT(s)) + + def test_None(self): + with self.assertRaises(TypeError): + self._callFUT(None) + + def test_working_path(self): + self.__path = u'text' + self.assertIs(self.__path, self._callFUT(self)) + + self.__path = b'bytes' + self.assertIs(self.__path, self._callFUT(self)) + + def test_failing_path_AttributeError(self): + self.assertIsNone(self.__path) + with self.assertRaises(AttributeError): + self._callFUT(self) + + def test_fspath_non_str(self): + self.__path = object() + with self.assertRaises(TypeError): + self._callFUT(self) + +@unittest.skipUnless(hasattr(os, 'fspath'), "Tests native os.fspath") +class TestNativeFSPath(TestFSPath): + + def _callFUT(self, arg): + return os.fspath(arg) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__contextvars.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__contextvars.py new file mode 100644 index 0000000000000000000000000000000000000000..883e83af13b3460e40b113d5c08bc7b3531540ec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__contextvars.py @@ -0,0 +1,1088 @@ +# gevent: copied from 3.7 to test our monkey-patch. +# Modified to work on all versions of Python. +from gevent import monkey +monkey.patch_all() + +# pylint:disable=superfluous-parens,pointless-statement,not-callable +# pylint:disable=unused-argument,too-many-public-methods,unused-variable +# pylint:disable=too-many-branches,too-many-statements + +import concurrent.futures +try: + import contextvars +except ImportError: + from gevent import contextvars +import functools +# import gc +import random +import time +import unittest +# import weakref + +# try: +# from _testcapi import hamt +# except ImportError: +# hamt = None +hamt = None + +def isolated_context(func): + """Needed to make reftracking test mode work.""" + @functools.wraps(func) + def wrapper(*args, **kwargs): + ctx = contextvars.Context() + return ctx.run(func, *args, **kwargs) + return wrapper + + +class ContextTest(unittest.TestCase): + + if not hasattr(unittest.TestCase, 'assertRaisesRegex'): + assertRaisesRegex = unittest.TestCase.assertRaisesRegexp + + def test_context_var_new_1(self): + with self.assertRaises(TypeError): + contextvars.ContextVar() + + # gevent: Doesn't raise + # with self.assertRaisesRegex(TypeError, 'must be a str'): + # contextvars.ContextVar(1) + + c = contextvars.ContextVar('aaa') + self.assertEqual(c.name, 'aaa') + + with self.assertRaises(AttributeError): + c.name = 'bbb' + + self.assertNotEqual(hash(c), hash('aaa')) + + @isolated_context + def test_context_var_repr_1(self): + c = contextvars.ContextVar('a') + self.assertIn('a', repr(c)) + + c = contextvars.ContextVar('a', default=123) + self.assertIn('123', repr(c)) + + lst = [] + c = contextvars.ContextVar('a', default=lst) + lst.append(c) + self.assertIn('...', repr(c)) + self.assertIn('...', repr(lst)) + + t = c.set(1) + self.assertIn(repr(c), repr(t)) + self.assertNotIn(' used ', repr(t)) + c.reset(t) + self.assertIn(' used ', repr(t)) + + # gevent: Doesn't raise + # def test_context_subclassing_1(self): + # with self.assertRaisesRegex(TypeError, 'not an acceptable base type'): + # class MyContextVar(contextvars.ContextVar): + # # Potentially we might want ContextVars to be subclassable. + # pass + + # with self.assertRaisesRegex(TypeError, 'not an acceptable base type'): + # class MyContext(contextvars.Context): + # pass + + # with self.assertRaisesRegex(TypeError, 'not an acceptable base type'): + # class MyToken(contextvars.Token): + # pass + + def test_context_new_1(self): + with self.assertRaises(TypeError): + contextvars.Context(1) + with self.assertRaises(TypeError): + contextvars.Context(1, a=1) + with self.assertRaises(TypeError): + contextvars.Context(a=1) + contextvars.Context(**{}) + + def test_context_typerrors_1(self): + ctx = contextvars.Context() + + with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'): + ctx[1] + with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'): + 1 in ctx + with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'): + ctx.get(1) + + def test_context_get_context_1(self): + ctx = contextvars.copy_context() + self.assertIsInstance(ctx, contextvars.Context) + + # gevent: This doesn't raise + # def test_context_run_1(self): + # ctx = contextvars.Context() + + # with self.assertRaisesRegex(TypeError, 'missing 1 required'): + # ctx.run() + + def test_context_run_2(self): + ctx = contextvars.Context() + + def func(*args, **kwargs): + kwargs['spam'] = 'foo' + args += ('bar',) + return args, kwargs + + for f in (func, functools.partial(func)): + # partial doesn't support FASTCALL + + self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'})) + self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'})) + + self.assertEqual( + ctx.run(f, a=2), + (('bar',), {'a': 2, 'spam': 'foo'})) + + self.assertEqual( + ctx.run(f, 11, a=2), + ((11, 'bar'), {'a': 2, 'spam': 'foo'})) + + a = {} + self.assertEqual( + ctx.run(f, 11, **a), + ((11, 'bar'), {'spam': 'foo'})) + self.assertEqual(a, {}) + + def test_context_run_3(self): + ctx = contextvars.Context() + + def func(*args, **kwargs): + 1 / 0 + + with self.assertRaises(ZeroDivisionError): + ctx.run(func) + with self.assertRaises(ZeroDivisionError): + ctx.run(func, 1, 2) + with self.assertRaises(ZeroDivisionError): + ctx.run(func, 1, 2, a=123) + + @isolated_context + def test_context_run_4(self): + ctx1 = contextvars.Context() + ctx2 = contextvars.Context() + var = contextvars.ContextVar('var') + + def func2(): + self.assertIsNone(var.get(None)) + + def func1(): + self.assertIsNone(var.get(None)) + var.set('spam') + ctx2.run(func2) + self.assertEqual(var.get(None), 'spam') + + cur = contextvars.copy_context() + self.assertEqual(len(cur), 1) + self.assertEqual(cur[var], 'spam') + return cur + + returned_ctx = ctx1.run(func1) + self.assertEqual(ctx1, returned_ctx) + self.assertEqual(returned_ctx[var], 'spam') + self.assertIn(var, returned_ctx) + + def test_context_run_5(self): + ctx = contextvars.Context() + var = contextvars.ContextVar('var') + + def func(): + self.assertIsNone(var.get(None)) + var.set('spam') + 1 / 0 + + with self.assertRaises(ZeroDivisionError): + ctx.run(func) + + self.assertIsNone(var.get(None)) + + def test_context_run_6(self): + ctx = contextvars.Context() + c = contextvars.ContextVar('a', default=0) + + def fun(): + self.assertEqual(c.get(), 0) + self.assertIsNone(ctx.get(c)) + + c.set(42) + self.assertEqual(c.get(), 42) + self.assertEqual(ctx.get(c), 42) + + ctx.run(fun) + + def test_context_run_7(self): + ctx = contextvars.Context() + + def fun(): + with self.assertRaisesRegex(RuntimeError, 'is already entered'): + ctx.run(fun) + + ctx.run(fun) + + @isolated_context + def test_context_getset_1(self): + c = contextvars.ContextVar('c') + with self.assertRaises(LookupError): + c.get() + + self.assertIsNone(c.get(None)) + + t0 = c.set(42) + self.assertEqual(c.get(), 42) + self.assertEqual(c.get(None), 42) + self.assertIs(t0.old_value, t0.MISSING) + self.assertIs(t0.old_value, contextvars.Token.MISSING) + self.assertIs(t0.var, c) + + t = c.set('spam') + self.assertEqual(c.get(), 'spam') + self.assertEqual(c.get(None), 'spam') + self.assertEqual(t.old_value, 42) + c.reset(t) + + self.assertEqual(c.get(), 42) + self.assertEqual(c.get(None), 42) + + c.set('spam2') + with self.assertRaisesRegex(RuntimeError, 'has already been used'): + c.reset(t) + self.assertEqual(c.get(), 'spam2') + + ctx1 = contextvars.copy_context() + self.assertIn(c, ctx1) + + c.reset(t0) + with self.assertRaisesRegex(RuntimeError, 'has already been used'): + c.reset(t0) + self.assertIsNone(c.get(None)) + + self.assertIn(c, ctx1) + self.assertEqual(ctx1[c], 'spam2') + self.assertEqual(ctx1.get(c, 'aa'), 'spam2') + self.assertEqual(len(ctx1), 1) + self.assertEqual(list(ctx1.items()), [(c, 'spam2')]) + self.assertEqual(list(ctx1.values()), ['spam2']) + self.assertEqual(list(ctx1.keys()), [c]) + self.assertEqual(list(ctx1), [c]) + + ctx2 = contextvars.copy_context() + self.assertNotIn(c, ctx2) + with self.assertRaises(KeyError): + ctx2[c] + self.assertEqual(ctx2.get(c, 'aa'), 'aa') + self.assertEqual(len(ctx2), 0) + self.assertEqual(list(ctx2), []) + + @isolated_context + def test_context_getset_2(self): + v1 = contextvars.ContextVar('v1') + v2 = contextvars.ContextVar('v2') + + t1 = v1.set(42) + with self.assertRaisesRegex(ValueError, 'by a different'): + v2.reset(t1) + + @isolated_context + def test_context_getset_3(self): + c = contextvars.ContextVar('c', default=42) + ctx = contextvars.Context() + + def fun(): + self.assertEqual(c.get(), 42) + with self.assertRaises(KeyError): + ctx[c] + self.assertIsNone(ctx.get(c)) + self.assertEqual(ctx.get(c, 'spam'), 'spam') + self.assertNotIn(c, ctx) + self.assertEqual(list(ctx.keys()), []) + + t = c.set(1) + self.assertEqual(list(ctx.keys()), [c]) + self.assertEqual(ctx[c], 1) + + c.reset(t) + self.assertEqual(list(ctx.keys()), []) + with self.assertRaises(KeyError): + ctx[c] + + ctx.run(fun) + + @isolated_context + def test_context_getset_4(self): + c = contextvars.ContextVar('c', default=42) + ctx = contextvars.Context() + + tok = ctx.run(c.set, 1) + + with self.assertRaisesRegex(ValueError, 'different Context'): + c.reset(tok) + + @isolated_context + def test_context_getset_5(self): + c = contextvars.ContextVar('c', default=42) + c.set([]) + + def fun(): + c.set([]) + c.get().append(42) + self.assertEqual(c.get(), [42]) + + contextvars.copy_context().run(fun) + self.assertEqual(c.get(), []) + + def test_context_copy_1(self): + ctx1 = contextvars.Context() + c = contextvars.ContextVar('c', default=42) + + def ctx1_fun(): + c.set(10) + + ctx2 = ctx1.copy() + self.assertEqual(ctx2[c], 10) + + c.set(20) + self.assertEqual(ctx1[c], 20) + self.assertEqual(ctx2[c], 10) + + ctx2.run(ctx2_fun) + self.assertEqual(ctx1[c], 20) + self.assertEqual(ctx2[c], 30) + + def ctx2_fun(): + self.assertEqual(c.get(), 10) + c.set(30) + self.assertEqual(c.get(), 30) + + ctx1.run(ctx1_fun) + + @isolated_context + def test_context_threads_1(self): + cvar = contextvars.ContextVar('cvar') + + def sub(num): + for i in range(10): + cvar.set(num + i) + time.sleep(random.uniform(0.001, 0.05)) + self.assertEqual(cvar.get(), num + i) + return num + + with concurrent.futures.ThreadPoolExecutor(max_workers=10) as tp: + results = list(tp.map(sub, range(10))) + + self.assertEqual(results, list(range(10))) + + # gevent: clases's can't be subscripted on Python 3.6 + # def test_contextvar_getitem(self): + # clss = contextvars.ContextVar + # self.assertEqual(clss[str], clss) + + +# HAMT Tests + + +# class HashKey: +# _crasher = None + +# def __init__(self, hash, name, error_on_eq_to=None): +# assert hash != -1 +# self.name = name +# self.hash = hash +# self.error_on_eq_to = error_on_eq_to + +# # def __repr__(self): +# # return f'' + +# def __hash__(self): +# if self._crasher is not None and self._crasher.error_on_hash: +# raise HashingError + +# return self.hash + +# def __eq__(self, other): +# if not isinstance(other, HashKey): +# return NotImplemented + +# if self._crasher is not None and self._crasher.error_on_eq: +# raise EqError + +# if self.error_on_eq_to is not None and self.error_on_eq_to is other: +# raise ValueError#(f'cannot compare {self!r} to {other!r}') +# if other.error_on_eq_to is not None and other.error_on_eq_to is self: +# raise ValueError#(f'cannot compare {other!r} to {self!r}') + +# return (self.name, self.hash) == (other.name, other.hash) + + +# class KeyStr(str): +# def __hash__(self): +# if HashKey._crasher is not None and HashKey._crasher.error_on_hash: +# raise HashingError +# return super().__hash__() + +# def __eq__(self, other): +# if HashKey._crasher is not None and HashKey._crasher.error_on_eq: +# raise EqError +# return super().__eq__(other) + + +# class HaskKeyCrasher: +# def __init__(self, error_on_hash=False, error_on_eq=False): +# self.error_on_hash = error_on_hash +# self.error_on_eq = error_on_eq + +# def __enter__(self): +# if HashKey._crasher is not None: +# raise RuntimeError('cannot nest crashers') +# HashKey._crasher = self + +# def __exit__(self, *exc): +# HashKey._crasher = None + + +# class HashingError(Exception): +# pass + + +# class EqError(Exception): +# pass + + +# @unittest.skipIf(hamt is None, '_testcapi lacks "hamt()" function') +# class HamtTest(unittest.TestCase): + +# def test_hashkey_helper_1(self): +# k1 = HashKey(10, 'aaa') +# k2 = HashKey(10, 'bbb') + +# self.assertNotEqual(k1, k2) +# self.assertEqual(hash(k1), hash(k2)) + +# d = dict() +# d[k1] = 'a' +# d[k2] = 'b' + +# self.assertEqual(d[k1], 'a') +# self.assertEqual(d[k2], 'b') + +# def test_hamt_basics_1(self): +# h = hamt() +# h = None # NoQA + +# def test_hamt_basics_2(self): +# h = hamt() +# self.assertEqual(len(h), 0) + +# h2 = h.set('a', 'b') +# self.assertIsNot(h, h2) +# self.assertEqual(len(h), 0) +# self.assertEqual(len(h2), 1) + +# self.assertIsNone(h.get('a')) +# self.assertEqual(h.get('a', 42), 42) + +# self.assertEqual(h2.get('a'), 'b') + +# h3 = h2.set('b', 10) +# self.assertIsNot(h2, h3) +# self.assertEqual(len(h), 0) +# self.assertEqual(len(h2), 1) +# self.assertEqual(len(h3), 2) +# self.assertEqual(h3.get('a'), 'b') +# self.assertEqual(h3.get('b'), 10) + +# self.assertIsNone(h.get('b')) +# self.assertIsNone(h2.get('b')) + +# self.assertIsNone(h.get('a')) +# self.assertEqual(h2.get('a'), 'b') + +# h = h2 = h3 = None + +# def test_hamt_basics_3(self): +# h = hamt() +# o = object() +# h1 = h.set('1', o) +# h2 = h1.set('1', o) +# self.assertIs(h1, h2) + +# def test_hamt_basics_4(self): +# h = hamt() +# h1 = h.set('key', []) +# h2 = h1.set('key', []) +# self.assertIsNot(h1, h2) +# self.assertEqual(len(h1), 1) +# self.assertEqual(len(h2), 1) +# self.assertIsNot(h1.get('key'), h2.get('key')) + +# def test_hamt_collision_1(self): +# k1 = HashKey(10, 'aaa') +# k2 = HashKey(10, 'bbb') +# k3 = HashKey(10, 'ccc') + +# h = hamt() +# h2 = h.set(k1, 'a') +# h3 = h2.set(k2, 'b') + +# self.assertEqual(h.get(k1), None) +# self.assertEqual(h.get(k2), None) + +# self.assertEqual(h2.get(k1), 'a') +# self.assertEqual(h2.get(k2), None) + +# self.assertEqual(h3.get(k1), 'a') +# self.assertEqual(h3.get(k2), 'b') + +# h4 = h3.set(k2, 'cc') +# h5 = h4.set(k3, 'aa') + +# self.assertEqual(h3.get(k1), 'a') +# self.assertEqual(h3.get(k2), 'b') +# self.assertEqual(h4.get(k1), 'a') +# self.assertEqual(h4.get(k2), 'cc') +# self.assertEqual(h4.get(k3), None) +# self.assertEqual(h5.get(k1), 'a') +# self.assertEqual(h5.get(k2), 'cc') +# self.assertEqual(h5.get(k2), 'cc') +# self.assertEqual(h5.get(k3), 'aa') + +# self.assertEqual(len(h), 0) +# self.assertEqual(len(h2), 1) +# self.assertEqual(len(h3), 2) +# self.assertEqual(len(h4), 2) +# self.assertEqual(len(h5), 3) + +# def test_hamt_stress(self): +# COLLECTION_SIZE = 7000 +# TEST_ITERS_EVERY = 647 +# CRASH_HASH_EVERY = 97 +# CRASH_EQ_EVERY = 11 +# RUN_XTIMES = 3 + +# for _ in range(RUN_XTIMES): +# h = hamt() +# d = dict() + +# for i in range(COLLECTION_SIZE): +# key = KeyStr(i) + +# if not (i % CRASH_HASH_EVERY): +# with HaskKeyCrasher(error_on_hash=True): +# with self.assertRaises(HashingError): +# h.set(key, i) + +# h = h.set(key, i) + +# if not (i % CRASH_EQ_EVERY): +# with HaskKeyCrasher(error_on_eq=True): +# with self.assertRaises(EqError): +# h.get(KeyStr(i)) # really trigger __eq__ + +# d[key] = i +# self.assertEqual(len(d), len(h)) + +# if not (i % TEST_ITERS_EVERY): +# self.assertEqual(set(h.items()), set(d.items())) +# self.assertEqual(len(h.items()), len(d.items())) + +# self.assertEqual(len(h), COLLECTION_SIZE) + +# for key in range(COLLECTION_SIZE): +# self.assertEqual(h.get(KeyStr(key), 'not found'), key) + +# keys_to_delete = list(range(COLLECTION_SIZE)) +# random.shuffle(keys_to_delete) +# for iter_i, i in enumerate(keys_to_delete): +# key = KeyStr(i) + +# if not (iter_i % CRASH_HASH_EVERY): +# with HaskKeyCrasher(error_on_hash=True): +# with self.assertRaises(HashingError): +# h.delete(key) + +# if not (iter_i % CRASH_EQ_EVERY): +# with HaskKeyCrasher(error_on_eq=True): +# with self.assertRaises(EqError): +# h.delete(KeyStr(i)) + +# h = h.delete(key) +# self.assertEqual(h.get(key, 'not found'), 'not found') +# del d[key] +# self.assertEqual(len(d), len(h)) + +# if iter_i == COLLECTION_SIZE // 2: +# hm = h +# dm = d.copy() + +# if not (iter_i % TEST_ITERS_EVERY): +# self.assertEqual(set(h.keys()), set(d.keys())) +# self.assertEqual(len(h.keys()), len(d.keys())) + +# self.assertEqual(len(d), 0) +# self.assertEqual(len(h), 0) + +# # ============ + +# for key in dm: +# self.assertEqual(hm.get(str(key)), dm[key]) +# self.assertEqual(len(dm), len(hm)) + +# for i, key in enumerate(keys_to_delete): +# hm = hm.delete(str(key)) +# self.assertEqual(hm.get(str(key), 'not found'), 'not found') +# dm.pop(str(key), None) +# self.assertEqual(len(d), len(h)) + +# if not (i % TEST_ITERS_EVERY): +# self.assertEqual(set(h.values()), set(d.values())) +# self.assertEqual(len(h.values()), len(d.values())) + +# self.assertEqual(len(d), 0) +# self.assertEqual(len(h), 0) +# self.assertEqual(list(h.items()), []) + +# def test_hamt_delete_1(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(102, 'C') +# D = HashKey(103, 'D') +# E = HashKey(104, 'E') +# Z = HashKey(-100, 'Z') + +# Er = HashKey(103, 'Er', error_on_eq_to=D) + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') + +# orig_len = len(h) + +# # BitmapNode(size=10 bitmap=0b111110000 id=0x10eadc618): +# # : 'a' +# # : 'b' +# # : 'c' +# # : 'd' +# # : 'e' + +# h = h.delete(C) +# self.assertEqual(len(h), orig_len - 1) + +# with self.assertRaisesRegex(ValueError, 'cannot compare'): +# h.delete(Er) + +# h = h.delete(D) +# self.assertEqual(len(h), orig_len - 2) + +# h2 = h.delete(Z) +# self.assertIs(h2, h) + +# h = h.delete(A) +# self.assertEqual(len(h), orig_len - 3) + +# self.assertEqual(h.get(A, 42), 42) +# self.assertEqual(h.get(B), 'b') +# self.assertEqual(h.get(E), 'e') + +# def test_hamt_delete_2(self): +# A = HashKey(100, 'A') +# B = HashKey(201001, 'B') +# C = HashKey(101001, 'C') +# D = HashKey(103, 'D') +# E = HashKey(104, 'E') +# Z = HashKey(-100, 'Z') + +# Er = HashKey(201001, 'Er', error_on_eq_to=B) + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') + +# orig_len = len(h) + +# # BitmapNode(size=8 bitmap=0b1110010000): +# # : 'a' +# # : 'd' +# # : 'e' +# # NULL: +# # BitmapNode(size=4 bitmap=0b100000000001000000000): +# # : 'b' +# # : 'c' + +# with self.assertRaisesRegex(ValueError, 'cannot compare'): +# h.delete(Er) + +# h = h.delete(Z) +# self.assertEqual(len(h), orig_len) + +# h = h.delete(C) +# self.assertEqual(len(h), orig_len - 1) + +# h = h.delete(B) +# self.assertEqual(len(h), orig_len - 2) + +# h = h.delete(A) +# self.assertEqual(len(h), orig_len - 3) + +# self.assertEqual(h.get(D), 'd') +# self.assertEqual(h.get(E), 'e') + +# h = h.delete(A) +# h = h.delete(B) +# h = h.delete(D) +# h = h.delete(E) +# self.assertEqual(len(h), 0) + +# def test_hamt_delete_3(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(100100, 'C') +# D = HashKey(100100, 'D') +# E = HashKey(104, 'E') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') + +# orig_len = len(h) + +# # BitmapNode(size=6 bitmap=0b100110000): +# # NULL: +# # BitmapNode(size=4 bitmap=0b1000000000000000000001000): +# # : 'a' +# # NULL: +# # CollisionNode(size=4 id=0x108572410): +# # : 'c' +# # : 'd' +# # : 'b' +# # : 'e' + +# h = h.delete(A) +# self.assertEqual(len(h), orig_len - 1) + +# h = h.delete(E) +# self.assertEqual(len(h), orig_len - 2) + +# self.assertEqual(h.get(C), 'c') +# self.assertEqual(h.get(B), 'b') + +# def test_hamt_delete_4(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(100100, 'C') +# D = HashKey(100100, 'D') +# E = HashKey(100100, 'E') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') + +# orig_len = len(h) + +# # BitmapNode(size=4 bitmap=0b110000): +# # NULL: +# # BitmapNode(size=4 bitmap=0b1000000000000000000001000): +# # : 'a' +# # NULL: +# # CollisionNode(size=6 id=0x10515ef30): +# # : 'c' +# # : 'd' +# # : 'e' +# # : 'b' + +# h = h.delete(D) +# self.assertEqual(len(h), orig_len - 1) + +# h = h.delete(E) +# self.assertEqual(len(h), orig_len - 2) + +# h = h.delete(C) +# self.assertEqual(len(h), orig_len - 3) + +# h = h.delete(A) +# self.assertEqual(len(h), orig_len - 4) + +# h = h.delete(B) +# self.assertEqual(len(h), 0) + +# def test_hamt_delete_5(self): +# h = hamt() + +# keys = [] +# for i in range(17): +# key = HashKey(i, str(i)) +# keys.append(key) +# h = h.set(key, 'val-{i}'.format(i=i)) + +# collision_key16 = HashKey(16, '18') +# h = h.set(collision_key16, 'collision') + +# # ArrayNode(id=0x10f8b9318): +# # 0:: +# # BitmapNode(size=2 count=1 bitmap=0b1): +# # : 'val-0' +# # +# # ... 14 more BitmapNodes ... +# # +# # 15:: +# # BitmapNode(size=2 count=1 bitmap=0b1): +# # : 'val-15' +# # +# # 16:: +# # BitmapNode(size=2 count=1 bitmap=0b1): +# # NULL: +# # CollisionNode(size=4 id=0x10f2f5af8): +# # : 'val-16' +# # : 'collision' + +# self.assertEqual(len(h), 18) + +# h = h.delete(keys[2]) +# self.assertEqual(len(h), 17) + +# h = h.delete(collision_key16) +# self.assertEqual(len(h), 16) +# h = h.delete(keys[16]) +# self.assertEqual(len(h), 15) + +# h = h.delete(keys[1]) +# self.assertEqual(len(h), 14) +# h = h.delete(keys[1]) +# self.assertEqual(len(h), 14) + +# for key in keys: +# h = h.delete(key) +# self.assertEqual(len(h), 0) + +# def test_hamt_items_1(self): +# A = HashKey(100, 'A') +# B = HashKey(201001, 'B') +# C = HashKey(101001, 'C') +# D = HashKey(103, 'D') +# E = HashKey(104, 'E') +# F = HashKey(110, 'F') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') +# h = h.set(F, 'f') + +# it = h.items() +# self.assertEqual( +# set(list(it)), +# {(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')}) + +# def test_hamt_items_2(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(100100, 'C') +# D = HashKey(100100, 'D') +# E = HashKey(100100, 'E') +# F = HashKey(110, 'F') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') +# h = h.set(F, 'f') + +# it = h.items() +# self.assertEqual( +# set(list(it)), +# {(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')}) + +# def test_hamt_keys_1(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(100100, 'C') +# D = HashKey(100100, 'D') +# E = HashKey(100100, 'E') +# F = HashKey(110, 'F') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(B, 'b') +# h = h.set(C, 'c') +# h = h.set(D, 'd') +# h = h.set(E, 'e') +# h = h.set(F, 'f') + +# self.assertEqual(set(list(h.keys())), {A, B, C, D, E, F}) +# self.assertEqual(set(list(h)), {A, B, C, D, E, F}) + +# def test_hamt_items_3(self): +# h = hamt() +# self.assertEqual(len(h.items()), 0) +# self.assertEqual(list(h.items()), []) + +# def test_hamt_eq_1(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') +# C = HashKey(100100, 'C') +# D = HashKey(100100, 'D') +# E = HashKey(120, 'E') + +# h1 = hamt() +# h1 = h1.set(A, 'a') +# h1 = h1.set(B, 'b') +# h1 = h1.set(C, 'c') +# h1 = h1.set(D, 'd') + +# h2 = hamt() +# h2 = h2.set(A, 'a') + +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.set(B, 'b') +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.set(C, 'c') +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.set(D, 'd2') +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.set(D, 'd') +# self.assertTrue(h1 == h2) +# self.assertFalse(h1 != h2) + +# h2 = h2.set(E, 'e') +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.delete(D) +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# h2 = h2.set(E, 'd') +# self.assertFalse(h1 == h2) +# self.assertTrue(h1 != h2) + +# def test_hamt_eq_2(self): +# A = HashKey(100, 'A') +# Er = HashKey(100, 'Er', error_on_eq_to=A) + +# h1 = hamt() +# h1 = h1.set(A, 'a') + +# h2 = hamt() +# h2 = h2.set(Er, 'a') + +# with self.assertRaisesRegex(ValueError, 'cannot compare'): +# h1 == h2 + +# with self.assertRaisesRegex(ValueError, 'cannot compare'): +# h1 != h2 + +# def test_hamt_gc_1(self): +# A = HashKey(100, 'A') + +# h = hamt() +# h = h.set(0, 0) # empty HAMT node is memoized in hamt.c +# ref = weakref.ref(h) + +# a = [] +# a.append(a) +# a.append(h) +# b = [] +# a.append(b) +# b.append(a) +# h = h.set(A, b) + +# del h, a, b + +# gc.collect() +# gc.collect() +# gc.collect() + +# self.assertIsNone(ref()) + +# def test_hamt_gc_2(self): +# A = HashKey(100, 'A') +# B = HashKey(101, 'B') + +# h = hamt() +# h = h.set(A, 'a') +# h = h.set(A, h) + +# ref = weakref.ref(h) +# hi = h.items() +# next(hi) + +# del h, hi + +# gc.collect() +# gc.collect() +# gc.collect() + +# self.assertIsNone(ref()) + +# def test_hamt_in_1(self): +# A = HashKey(100, 'A') +# AA = HashKey(100, 'A') + +# B = HashKey(101, 'B') + +# h = hamt() +# h = h.set(A, 1) + +# self.assertTrue(A in h) +# self.assertFalse(B in h) + +# with self.assertRaises(EqError): +# with HaskKeyCrasher(error_on_eq=True): +# AA in h + +# with self.assertRaises(HashingError): +# with HaskKeyCrasher(error_on_hash=True): +# AA in h + +# def test_hamt_getitem_1(self): +# A = HashKey(100, 'A') +# AA = HashKey(100, 'A') + +# B = HashKey(101, 'B') + +# h = hamt() +# h = h.set(A, 1) + +# self.assertEqual(h[A], 1) +# self.assertEqual(h[AA], 1) + +# with self.assertRaises(KeyError): +# h[B] + +# with self.assertRaises(EqError): +# with HaskKeyCrasher(error_on_eq=True): +# h[AA] + +# with self.assertRaises(HashingError): +# with HaskKeyCrasher(error_on_hash=True): +# h[AA] + + +if __name__ == "__main__": + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core.py new file mode 100644 index 0000000000000000000000000000000000000000..14e6e82492823a68a72942dd4a60ab7e6e690058 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core.py @@ -0,0 +1,164 @@ + +from __future__ import absolute_import, print_function, division + +# Important: This file should have no dependencies that are part of the +# ``test`` extra, because it is sometimes run for quick checks without those +# installed. + +import unittest +import sys +import gevent.testing as greentest + +from gevent._config import Loop + +available_loops = Loop().get_options() +available_loops.pop('libuv', None) + +def not_available(name): + return isinstance(available_loops[name], ImportError) + + +class WatcherTestMixin(object): + kind = None + + def _makeOne(self): + return self.kind(default=False) # pylint:disable=not-callable + + def destroyOne(self, loop): + loop.destroy() + + def setUp(self): + self.loop = self._makeOne() + self.core = sys.modules[self.kind.__module__] + + def tearDown(self): + self.destroyOne(self.loop) + del self.loop + + def test_get_version(self): + version = self.core.get_version() # pylint: disable=no-member + self.assertIsInstance(version, str) + self.assertTrue(version) + header_version = self.core.get_header_version() # pylint: disable=no-member + self.assertIsInstance(header_version, str) + self.assertTrue(header_version) + self.assertEqual(version, header_version) + + def test_events_conversion(self): + self.assertEqual(self.core._events_to_str(self.core.READ | self.core.WRITE), # pylint: disable=no-member + 'READ|WRITE') + + def test_EVENTS(self): + self.assertEqual(str(self.core.EVENTS), # pylint: disable=no-member + 'gevent.core.EVENTS') + self.assertEqual(repr(self.core.EVENTS), # pylint: disable=no-member + 'gevent.core.EVENTS') + + def test_io(self): + if greentest.WIN: + # libev raises IOError, libuv raises ValueError + Error = (IOError, ValueError) + else: + Error = ValueError + + with self.assertRaises(Error): + self.loop.io(-1, 1) + + if hasattr(self.core, 'TIMER'): + # libev + with self.assertRaises(ValueError): + self.loop.io(1, self.core.TIMER) # pylint:disable=no-member + + # Test we can set events and io before it's started + if not greentest.WIN: + # We can't do this with arbitrary FDs on windows; + # see libev_vfd.h + io = self.loop.io(1, self.core.READ) # pylint:disable=no-member + io.fd = 2 + self.assertEqual(io.fd, 2) + io.events = self.core.WRITE # pylint:disable=no-member + if not hasattr(self.core, 'libuv'): + # libev + # pylint:disable=no-member + self.assertEqual(self.core._events_to_str(io.events), 'WRITE|_IOFDSET') + else: + + self.assertEqual(self.core._events_to_str(io.events), # pylint:disable=no-member + 'WRITE') + io.start(lambda: None) + io.close() + + def test_timer_constructor(self): + with self.assertRaises(ValueError): + self.loop.timer(1, -1) + + def test_signal_constructor(self): + with self.assertRaises(ValueError): + self.loop.signal(1000) + + +class LibevTestMixin(WatcherTestMixin): + + def test_flags_conversion(self): + # pylint: disable=no-member + core = self.core + if not greentest.WIN: + self.assertEqual(core.loop(2, default=False).backend_int, 2) + self.assertEqual(core.loop('select', default=False).backend, 'select') + self.assertEqual(core._flags_to_int(None), 0) + self.assertEqual(core._flags_to_int(['kqueue', 'SELECT']), core.BACKEND_KQUEUE | core.BACKEND_SELECT) + self.assertEqual(core._flags_to_list(core.BACKEND_PORT | core.BACKEND_POLL), ['port', 'poll']) + self.assertRaises(ValueError, core.loop, ['port', 'blabla']) + self.assertRaises(TypeError, core.loop, object()) + +@unittest.skipIf(not_available('libev-cext'), "Needs libev-cext") +class TestLibevCext(LibevTestMixin, unittest.TestCase): + kind = available_loops['libev-cext'] + +@unittest.skipIf(not_available('libev-cffi'), "Needs libev-cffi") +class TestLibevCffi(LibevTestMixin, unittest.TestCase): + kind = available_loops['libev-cffi'] + +@unittest.skipIf(not_available('libuv-cffi'), "Needs libuv-cffi") +class TestLibuvCffi(WatcherTestMixin, unittest.TestCase): + kind = available_loops['libuv-cffi'] + + @greentest.skipOnLibev("libuv-specific") + @greentest.skipOnWindows("Destroying the loop somehow fails") + def test_io_multiplex_events(self): + # pylint:disable=no-member + import socket + sock = socket.socket() + fd = sock.fileno() + core = self.core + read = self.loop.io(fd, core.READ) + write = self.loop.io(fd, core.WRITE) + + try: + real_watcher = read._watcher_ref + + read.start(lambda: None) + self.assertEqual(real_watcher.events, core.READ) + + write.start(lambda: None) + self.assertEqual(real_watcher.events, core.READ | core.WRITE) + + write.stop() + self.assertEqual(real_watcher.events, core.READ) + + write.start(lambda: None) + self.assertEqual(real_watcher.events, core.READ | core.WRITE) + + read.stop() + self.assertEqual(real_watcher.events, core.WRITE) + + write.stop() + self.assertEqual(real_watcher.events, 0) + finally: + read.close() + write.close() + sock.close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_async.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_async.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9a435fb414061f5a5f131e584f075fb3cbe8f1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_async.py @@ -0,0 +1,31 @@ +from __future__ import print_function +import gevent +import gevent.core +import time +try: + import thread +except ImportError: + import _thread as thread + +from gevent import testing as greentest + +class Test(greentest.TestCase): + def test(self): + hub = gevent.get_hub() + watcher = hub.loop.async_() + + # BWC for <3.7: This should still be an attribute + assert hasattr(hub.loop, 'async') + + gevent.spawn_later(0.1, thread.start_new_thread, watcher.send, ()) + + start = time.time() + + with gevent.Timeout(1.0): # Large timeout for appveyor + hub.wait(watcher) + + print('Watcher %r reacted after %.6f seconds' % (watcher, time.time() - start - 0.1)) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_callback.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..f5af08831cae53f32f87308ee01f8ae51a776512 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_callback.py @@ -0,0 +1,32 @@ +import gevent +from gevent.hub import get_hub + +from gevent import testing as greentest + +class Test(greentest.TestCase): + + def test(self): + loop = get_hub().loop + called = [] + + def f(): + called.append(1) + + x = loop.run_callback(f) + + assert x, x + gevent.sleep(0) + assert called == [1], called + assert not x, (x, bool(x)) + + x = loop.run_callback(f) + assert x, x + x.stop() + assert not x, x + gevent.sleep(0) + assert called == [1], called + assert not x, x + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_fork.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..db5170322ac9e63c6f530478505c97bc65ba9659 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_fork.py @@ -0,0 +1,84 @@ +from __future__ import print_function +from gevent import monkey +monkey.patch_all() + +import os +import unittest +import multiprocessing + +import gevent + +hub = gevent.get_hub() +pid = os.getpid() +newpid = None + + +def on_fork(): + global newpid + newpid = os.getpid() + +fork_watcher = hub.loop.fork(ref=False) +fork_watcher.start(on_fork) + + +def in_child(q): + # libev only calls fork callbacks at the beginning of + # the loop; we use callbacks extensively so it takes *two* + # calls to sleep (with a timer) to actually get wrapped + # around to the beginning of the loop. + gevent.sleep(0.001) + gevent.sleep(0.001) + q.put(newpid) + + +class Test(unittest.TestCase): + + def test(self): + self.assertEqual(hub.threadpool.size, 0) + # Use a thread to make us multi-threaded + hub.threadpool.apply(lambda: None) + self.assertEqual(hub.threadpool.size, 1) + + # Not all platforms use fork by default, so we want to force it, + # where possible. The test is still useful even if we can't + # fork though. + try: + fork_ctx = multiprocessing.get_context('fork') + except (AttributeError, ValueError): + # ValueError if fork isn't supported. + # AttributeError on Python 2, which doesn't have get_context + fork_ctx = multiprocessing + + # If the Queue is global, q.get() hangs on Windows; must pass as + # an argument. + q = fork_ctx.Queue() + p = fork_ctx.Process(target=in_child, args=(q,)) + p.start() + p.join() + p_val = q.get() + + self.assertIsNone( + newpid, + "The fork watcher ran in the parent for some reason." + ) + self.assertIsNotNone( + p_val, + "The child process returned nothing, meaning the fork watcher didn't run in the child." + ) + self.assertNotEqual(p_val, pid) + assert p_val != pid + +if __name__ == '__main__': + # Must call for Windows to fork properly; the fork can't be in the top-level + multiprocessing.freeze_support() + + # fork watchers weren't firing in multi-threading processes. + # This test is designed to prove that they are. + # However, it fails on Windows: The fork watcher never runs! + # This makes perfect sense: on Windows, our patches to os.fork() + # that call gevent.hub.reinit() don't get used; os.fork doesn't + # exist and multiprocessing.Process uses the windows-specific _subprocess.CreateProcess() + # to create a whole new process that has no relation to the current process; + # that process then calls multiprocessing.forking.main() to do its work. + # Since no state is shared, a fork watcher cannot exist in that process. + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_loop_run.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_loop_run.py new file mode 100644 index 0000000000000000000000000000000000000000..64c4c04b58f99c9aaec84e0499b7a8dc6291c94f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_loop_run.py @@ -0,0 +1,22 @@ +from __future__ import print_function +import sys +from gevent import core +from gevent import signal_handler as signal +loop = core.loop(default=False) + + +signal = signal(2, sys.stderr.write, 'INTERRUPT!') + +print('must exit immediately...') +loop.run() # must exit immediately +print('...and once more...') +loop.run() # repeating does not fail +print('..done') + +print('must exit after 0.5 seconds.') +timer = loop.timer(0.5) +timer.start(lambda: None) +loop.run() +timer.close() +loop.destroy() +del loop diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_stat.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_stat.py new file mode 100644 index 0000000000000000000000000000000000000000..d022d90e5dcfd5fab928098bf82ff6f564435a1d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_stat.py @@ -0,0 +1,118 @@ +from __future__ import print_function + +import os +import tempfile +import time + +import gevent +import gevent.core + +import gevent.testing as greentest +import gevent.testing.flaky + +#pylint: disable=protected-access + + +DELAY = 0.5 + +WIN = greentest.WIN + +LIBUV = greentest.LIBUV + +class TestCoreStat(greentest.TestCase): + + __timeout__ = greentest.LARGE_TIMEOUT + + def setUp(self): + super(TestCoreStat, self).setUp() + fd, path = tempfile.mkstemp(suffix='.gevent_test_core_stat') + os.close(fd) + self.temp_path = path + self.hub = gevent.get_hub() + # If we don't specify an interval, we default to zero. + # libev interprets that as meaning to use its default interval, + # which is about 5 seconds. If we go below it's minimum check + # threshold, it bumps it up to the minimum. + self.watcher = self.hub.loop.stat(self.temp_path, interval=-1) + + def tearDown(self): + self.watcher.close() + if os.path.exists(self.temp_path): + os.unlink(self.temp_path) + super(TestCoreStat, self).tearDown() + + def _write(self): + with open(self.temp_path, 'wb', buffering=0) as f: + f.write(b'x') + + def _check_attr(self, name, none): + # Deals with the complex behaviour of the 'attr' and 'prev' + # attributes on Windows. This codifies it, rather than simply letting + # the test fail, so we know exactly when and what changes it. + try: + x = getattr(self.watcher, name) + except ImportError: + if WIN: + # the 'posix' module is not available + pass + else: + raise + else: + if WIN and not LIBUV: + # The ImportError is only raised for the first time; + # after that, the attribute starts returning None + self.assertIsNone(x, "Only None is supported on Windows") + if none: + self.assertIsNone(x, name) + else: + self.assertIsNotNone(x, name) + + def _wait_on_greenlet(self, func, *greenlet_args): + start = time.time() + + self.hub.loop.update_now() + greenlet = gevent.spawn_later(DELAY, func, *greenlet_args) + with gevent.Timeout(5 + DELAY + 0.5): + self.hub.wait(self.watcher) + now = time.time() + + self.assertGreaterEqual(now, start, "Time must move forward") + + wait_duration = now - start + reaction = wait_duration - DELAY + + if reaction <= 0.0: + # Sigh. This is especially true on PyPy on Windows + raise gevent.testing.flaky.FlakyTestRaceCondition( + "Bad timer resolution (on Windows?), test is useless. Start %s, now %s" % (start, now)) + + self.assertGreaterEqual( + reaction, 0.0, + 'Watcher %s reacted too early: %.3fs' % (self.watcher, reaction)) + + greenlet.join() + + def test_watcher_basics(self): + watcher = self.watcher + filename = self.temp_path + self.assertEqual(watcher.path, filename) + filenames = filename if isinstance(filename, bytes) else filename.encode('ascii') + self.assertEqual(watcher._paths, filenames) + self.assertEqual(watcher.interval, -1) + + def test_write(self): + self._wait_on_greenlet(self._write) + + self._check_attr('attr', False) + self._check_attr('prev', False) + # The watcher interval changed after it started; -1 is illegal + self.assertNotEqual(self.watcher.interval, -1) + + def test_unlink(self): + self._wait_on_greenlet(os.unlink, self.temp_path) + + self._check_attr('attr', True) + self._check_attr('prev', False) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_timer.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_timer.py new file mode 100644 index 0000000000000000000000000000000000000000..97caa75470dcef280164c131f9759d9c4b28216c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_timer.py @@ -0,0 +1,157 @@ +from __future__ import print_function +from gevent import config + +import gevent.testing as greentest +from gevent.testing import TestCase +from gevent.testing import LARGE_TIMEOUT +from gevent.testing.sysinfo import CFFI_BACKEND +from gevent.testing.flaky import reraises_flaky_timeout + + +class Test(TestCase): + __timeout__ = LARGE_TIMEOUT + + repeat = 0 + timer_duration = 0.001 + + def setUp(self): + super(Test, self).setUp() + self.called = [] + self.loop = config.loop(default=False) + self.timer = self.loop.timer(self.timer_duration, repeat=self.repeat) + assert not self.loop.default + + def cleanup(self): + # cleanup instead of tearDown to cooperate well with + # leakcheck.py + self.timer.close() + # cycle the loop so libuv close callbacks fire + self.loop.run() + self.loop.destroy() + self.loop = None + self.timer = None + + def f(self, x=None): + self.called.append(1) + if x is not None: + x.stop() + + def assertTimerInKeepalive(self): + if CFFI_BACKEND: + self.assertIn(self.timer, self.loop._keepaliveset) + + def assertTimerNotInKeepalive(self): + if CFFI_BACKEND: + self.assertNotIn(self.timer, self.loop._keepaliveset) + + def test_main(self): + loop = self.loop + x = self.timer + x.start(self.f) + self.assertTimerInKeepalive() + self.assertTrue(x.active, x) + + with self.assertRaises((AttributeError, ValueError)): + x.priority = 1 + + loop.run() + self.assertEqual(x.pending, 0) + self.assertEqual(self.called, [1]) + self.assertIsNone(x.callback) + self.assertIsNone(x.args) + + if x.priority is not None: + self.assertEqual(x.priority, 0) + x.priority = 1 + self.assertEqual(x.priority, 1) + + x.stop() + self.assertTimerNotInKeepalive() + +class TestAgain(Test): + repeat = 1 + + def test_main(self): + # Again works for a new timer + x = self.timer + x.again(self.f, x) + self.assertTimerInKeepalive() + + self.assertEqual(x.args, (x,)) + + # XXX: On libev, this takes 1 second. On libuv, + # it takes the expected time. + self.loop.run() + + self.assertEqual(self.called, [1]) + + x.stop() + self.assertTimerNotInKeepalive() + + +class TestTimerResolution(Test): + + # On CI, with *all* backends, sometimes we get timer values of + # 0.02 or higher. + @reraises_flaky_timeout(AssertionError) + def test_resolution(self): # pylint:disable=too-many-locals + # Make sure that having an active IO watcher + # doesn't badly throw off our timer resolution. + # (This was a specific problem with libuv) + + # https://github.com/gevent/gevent/pull/1194 + from gevent._compat import perf_counter + + import socket + s = socket.socket() + self._close_on_teardown(s) + fd = s.fileno() + + ran_at_least_once = False + fired_at = [] + + def timer_counter(): + fired_at.append(perf_counter()) + + loop = self.loop + + timer_multiplier = 11 + max_time = self.timer_duration * timer_multiplier + assert max_time < 0.3 + + for _ in range(150): + # in libuv, our signal timer fires every 300ms; depending on + # when this runs, we could artificially get a better + # resolution than we expect. Run it multiple times to be more sure. + io = loop.io(fd, 1) + io.start(lambda events=None: None) + + + now = perf_counter() + del fired_at[:] + timer = self.timer + timer.start(timer_counter) + + loop.run(once=True) + + io.stop() + io.close() + + timer.stop() + + if fired_at: + ran_at_least_once = True + self.assertEqual(1, len(fired_at)) + self.assertTimeWithinRange(fired_at[0] - now, + 0, + max_time) + + + if not greentest.RUNNING_ON_CI: + # Hmm, this always fires locally on mocOS but + # not an Travis? + self.assertTrue(ran_at_least_once) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_watcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..bd52805c7d0257d9c4cf141d3ea194bb9d60ece1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__core_watcher.py @@ -0,0 +1,124 @@ +from __future__ import absolute_import, print_function + +import gevent.testing as greentest +from gevent import config +from gevent.testing.sysinfo import CFFI_BACKEND + +from gevent.core import READ # pylint:disable=no-name-in-module +from gevent.core import WRITE # pylint:disable=no-name-in-module + + +class Test(greentest.TestCase): + + __timeout__ = None + + def setUp(self): + super(Test, self).setUp() + self.loop = config.loop(default=False) + self.timer = self.loop.timer(0.01) + + def tearDown(self): + if self.timer is not None: + self.timer.close() + if self.loop is not None: + self.loop.destroy() + self.loop = self.timer = None + super(Test, self).tearDown() + + def test_non_callable_to_start(self): + # test that cannot pass non-callable thing to start() + self.assertRaises(TypeError, self.timer.start, None) + self.assertRaises(TypeError, self.timer.start, 5) + + def test_non_callable_after_start(self): + # test that cannot set 'callback' to non-callable thing later either + lst = [] + timer = self.timer + timer.start(lst.append) + + + with self.assertRaises(TypeError): + timer.callback = False + + with self.assertRaises(TypeError): + timer.callback = 5 + + def test_args_can_be_changed_after_start(self): + lst = [] + timer = self.timer + self.timer.start(lst.append) + self.assertEqual(timer.args, ()) + timer.args = (1, 2, 3) + self.assertEqual(timer.args, (1, 2, 3)) + + # Only tuple can be args + with self.assertRaises(TypeError): + timer.args = 5 + with self.assertRaises(TypeError): + timer.args = [4, 5] + + self.assertEqual(timer.args, (1, 2, 3)) + + # None also works, means empty tuple + # XXX why? + timer.args = None + self.assertEqual(timer.args, None) + + + def test_run(self): + loop = self.loop + lst = [] + + self.timer.start(lambda *args: lst.append(args)) + + loop.run() + loop.update_now() + + self.assertEqual(lst, [()]) + + # Even if we lose all references to it, the ref in the callback + # keeps it alive + self.timer.start(reset, self.timer, lst) + self.timer = None + loop.run() + self.assertEqual(lst, [(), 25]) + + def test_invalid_fd(self): + loop = self.loop + + # Negative case caught everywhere. ValueError + # on POSIX, OSError on Windows Py3, IOError on Windows Py2 + with self.assertRaises((ValueError, OSError, IOError)): + loop.io(-1, READ) + + + @greentest.skipOnWindows("Stdout can't be watched on Win32") + def test_reuse_io(self): + loop = self.loop + + # Watchers aren't reused once all outstanding + # refs go away BUT THEY MUST BE CLOSED + tty_watcher = loop.io(1, WRITE) + watcher_handle = tty_watcher._watcher if CFFI_BACKEND else tty_watcher + tty_watcher.close() + del tty_watcher + # XXX: Note there is a cycle in the CFFI code + # from watcher_handle._handle -> watcher_handle. + # So it doesn't go away until a GC runs. + import gc + gc.collect() + + tty_watcher = loop.io(1, WRITE) + self.assertIsNot(tty_watcher._watcher if CFFI_BACKEND else tty_watcher, watcher_handle) + tty_watcher.close() + + +def reset(watcher, lst): + watcher.args = None + watcher.callback = lambda: None + lst.append(25) + watcher.close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy.py new file mode 100644 index 0000000000000000000000000000000000000000..0c37c4a04d34b71f21c95672ec2e1230c8d40a65 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy.py @@ -0,0 +1,52 @@ +from __future__ import absolute_import, print_function + +import gevent +import unittest + +class TestDestroyHub(unittest.TestCase): + + def test_destroy_hub(self): + # Loop of initial Hub is default loop. + hub = gevent.get_hub() + self.assertTrue(hub.loop.default) + + # Save `gevent.core.loop` object for later comparison. + initloop = hub.loop + + # Increase test complexity via threadpool creation. + # Implicitly creates fork watcher connected to the current event loop. + tp = hub.threadpool + self.assertIsNotNone(tp) + + # Destroy hub. Does not destroy libev default loop if not explicitly told to. + hub.destroy() + + # Create new hub. Must re-use existing libev default loop. + hub = gevent.get_hub() + self.assertTrue(hub.loop.default) + + # Ensure that loop object is identical to the initial one. + self.assertIs(hub.loop, initloop) + + # Destroy hub including default loop. + hub.destroy(destroy_loop=True) + + # Create new hub and explicitly request creation of a new default loop. + # (using default=True, but that's no longer possible.) + hub = gevent.get_hub() + self.assertTrue(hub.loop.default) + + # `gevent.core.loop` objects as well as libev loop pointers must differ. + self.assertIsNot(hub.loop, initloop) + self.assertIsNot(hub.loop.ptr, initloop.ptr) + self.assertNotEqual(hub.loop.ptr, initloop.ptr) + + # Destroy hub including default loop. The default loop regenerates. + hub.destroy(destroy_loop=True) + hub = gevent.get_hub() + self.assertTrue(hub.loop.default) + + hub.destroy() + +if __name__ == '__main__': + unittest.main() # pragma: testrunner-no-combine diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy_default_loop.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy_default_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..79bcd633e81672cc6412ef9e0e6fb848512e296d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__destroy_default_loop.py @@ -0,0 +1,72 @@ +from __future__ import print_function +import gevent + +import unittest + +class TestDestroyDefaultLoop(unittest.TestCase): + + def tearDown(self): + self._reset_hub() + super(TestDestroyDefaultLoop, self).tearDown() + + def _reset_hub(self): + from gevent._hub_local import set_hub + from gevent._hub_local import set_loop + from gevent._hub_local import get_hub_if_exists + hub = get_hub_if_exists() + if hub is not None: + hub.destroy(destroy_loop=True) + set_hub(None) + set_loop(None) + + def test_destroy_gc(self): + # Issue 1098: destroying the default loop + # while using the C extension could crash + # the interpreter when it exits + + # Create the hub greenlet. This creates one loop + # object pointing to the default loop. + gevent.get_hub() + + # Get a new loop object, but using the default + # C loop + loop = gevent.config.loop(default=True) + self.assertTrue(loop.default) + # Destroy it + + loop.destroy() + # It no longer claims to be the default + self.assertFalse(loop.default) + + # Delete it + del loop + # Delete the hub. This prompts garbage + # collection of it and its loop object. + # (making this test more repeatable; the exit + # crash only happened when that greenlet object + # was collected at exit time, which was most common + # in CPython 3.5) + self._reset_hub() + + def test_destroy_two(self): + # Get two new loop object, but using the default + # C loop + loop1 = gevent.config.loop(default=True) + loop2 = gevent.config.loop(default=True) + self.assertTrue(loop1.default) + self.assertTrue(loop2.default) + # Destroy the first + loop1.destroy() + # It no longer claims to be the default + self.assertFalse(loop1.default) + + # Destroy the second. This doesn't crash. + loop2.destroy() + self.assertFalse(loop2.default) + self.assertFalse(loop2.ptr) + self._reset_hub() + self.assertTrue(gevent.get_hub().loop.ptr) + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__doctests.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__doctests.py new file mode 100644 index 0000000000000000000000000000000000000000..731a9ee8892af4982099c07188817c023472e853 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__doctests.py @@ -0,0 +1,133 @@ +from __future__ import print_function + +import doctest +import functools +import os +import re +import sys +import unittest + + + +# Ignore tracebacks: ZeroDivisionError + + +def myfunction(*_args, **_kwargs): + pass + + +class RENormalizingOutputChecker(doctest.OutputChecker): + """ + Pattern-normalizing output checker. Inspired by one used in zope.testing. + """ + + def __init__(self, patterns): + self.transformers = [functools.partial(re.sub, replacement) for re, replacement in patterns] + + def check_output(self, want, got, optionflags): + if got == want: + return True + + for transformer in self.transformers: + want = transformer(want) + got = transformer(got) + + return doctest.OutputChecker.check_output(self, want, got, optionflags) + +FORBIDDEN_MODULES = set() + + +class Modules(object): + + def __init__(self, allowed_modules): + from gevent.testing import walk_modules + self.allowed_modules = allowed_modules + self.modules = set() + + for path, module in walk_modules(recursive=True): + self.add_module(module, path) + + + def add_module(self, name, path): + if self.allowed_modules and name not in self.allowed_modules: + return + if name in FORBIDDEN_MODULES: + return + self.modules.add((name, path)) + + def __bool__(self): + return bool(self.modules) + + __nonzero__ = __bool__ + + def __iter__(self): + return iter(self.modules) + + +def main(): # pylint:disable=too-many-locals + cwd = os.getcwd() + # Use pure_python to get the correct module source and docstrings + os.environ['PURE_PYTHON'] = '1' + + import gevent + from gevent import socket + + + from gevent.testing import util + from gevent.testing import sysinfo + + if sysinfo.WIN: + FORBIDDEN_MODULES.update({ + # Uses commands only found on posix + 'gevent.subprocess', + }) + + try: + allowed_modules = sys.argv[1:] + sys.path.append('.') + + globs = { + 'myfunction': myfunction, + 'gevent': gevent, + 'socket': socket, + } + + modules = Modules(allowed_modules) + + if not modules: + sys.exit('No modules found matching %s' % ' '.join(allowed_modules)) + + suite = unittest.TestSuite() + checker = RENormalizingOutputChecker(( + # Normalize subprocess.py: BSD ls is in the example, gnu ls outputs + # 'cannot access' + (re.compile( + "ls: cannot access 'non_existent_file': No such file or directory"), + "ls: non_existent_file: No such file or directory"), + # Python 3 bytes add a "b". + (re.compile(r'b(".*?")'), r"\1"), + (re.compile(r"b('.*?')"), r"\1"), + )) + + tests_count = 0 + modules_count = 0 + for m, path in sorted(modules): + with open(path, 'rb') as f: + contents = f.read() + if re.search(br'^\s*>>> ', contents, re.M): + s = doctest.DocTestSuite(m, extraglobs=globs, checker=checker) + test_count = len(s._tests) + util.log('%s (from %s): %s tests', m, path, test_count) + suite.addTest(s) + modules_count += 1 + tests_count += test_count + + util.log('Total: %s tests in %s modules', tests_count, modules_count) + # TODO: Pass this off to unittest.main() + runner = unittest.TextTestRunner(verbosity=2) + runner.run(suite) + finally: + os.chdir(cwd) + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__environ.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__environ.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb91661bc782c925a3404a951df6bdf140fc274 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__environ.py @@ -0,0 +1,19 @@ +import os +import sys +import gevent +import gevent.core +import subprocess + +if not sys.argv[1:]: + os.environ['GEVENT_BACKEND'] = 'select' + # (not in Py2) pylint:disable=consider-using-with + popen = subprocess.Popen([sys.executable, __file__, '1']) + assert popen.wait() == 0, popen.poll() +else: # pragma: no cover + hub = gevent.get_hub() + # pylint:disable-next=no-member + if 'select' in gevent.core.supported_backends(): + assert hub.loop.backend == 'select', hub.loop.backend + else: + # libuv isn't configurable + assert hub.loop.backend == 'default', hub.loop.backend diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__event.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__event.py new file mode 100644 index 0000000000000000000000000000000000000000..5d59992a07ddce7f166dea517f9972933b47d077 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__event.py @@ -0,0 +1,448 @@ +from __future__ import absolute_import +from __future__ import print_function +from __future__ import division + +import weakref + +import gevent +from gevent.event import Event, AsyncResult + +import gevent.testing as greentest + +from gevent.testing.six import xrange +from gevent.testing.timing import AbstractGenericGetTestCase +from gevent.testing.timing import AbstractGenericWaitTestCase +from gevent.testing.timing import SMALL_TICK +from gevent.testing.timing import SMALL_TICK_MAX_ADJ + +DELAY = SMALL_TICK + SMALL_TICK_MAX_ADJ + + +class TestEventWait(AbstractGenericWaitTestCase): + + def wait(self, timeout): + Event().wait(timeout=timeout) + + def test_cover(self): + str(Event()) + + +class TestGeventWaitOnEvent(AbstractGenericWaitTestCase): + + def wait(self, timeout): + gevent.wait([Event()], timeout=timeout) + + def test_set_during_wait(self): + # https://github.com/gevent/gevent/issues/771 + # broke in the refactoring. we must not add new links + # while we're running the callback + + event = Event() + + def setter(): + event.set() + + def waiter(): + s = gevent.spawn(setter) + # let the setter set() the event; + # when this method returns we'll be running in the Event._notify_links callback + # (that is, it switched to us) + res = event.wait() + self.assertTrue(res) + self.assertTrue(event.ready()) + s.join() # make sure it's dead + # Clear the event. Now we can't wait for the event without + # another set to happen. + event.clear() + self.assertFalse(event.ready()) + + # Before the bug fix, this would return "immediately" with + # event in the result list, because the _notify_links loop would + # immediately add the waiter and call it + o = gevent.wait((event,), timeout=0.01) + self.assertFalse(event.ready()) + self.assertNotIn(event, o) + + gevent.spawn(waiter).join() + + +class TestAsyncResultWait(AbstractGenericWaitTestCase): + + def wait(self, timeout): + AsyncResult().wait(timeout=timeout) + + +class TestWaitAsyncResult(AbstractGenericWaitTestCase): + + def wait(self, timeout): + gevent.wait([AsyncResult()], timeout=timeout) + + +class TestAsyncResultGet(AbstractGenericGetTestCase): + + def wait(self, timeout): + AsyncResult().get(timeout=timeout) + +class MyException(Exception): + pass + +class TestAsyncResult(greentest.TestCase): + + def test_link(self): + ar = AsyncResult() + self.assertRaises(TypeError, ar.rawlink, None) + ar.unlink(None) # doesn't raise + ar.unlink(None) # doesn't raise + str(ar) # cover + + def test_set_exc(self): + log = [] + e = AsyncResult() + self.assertEqual(e.exc_info, ()) + self.assertEqual(e.exception, None) + + def waiter(): + with self.assertRaises(MyException) as exc: + e.get() + log.append(('caught', exc.exception)) + gevent.spawn(waiter) + obj = MyException() + e.set_exception(obj) + gevent.sleep(0) + self.assertEqual(log, [('caught', obj)]) + + def test_set(self): + event1 = AsyncResult() + timer_exc = MyException('interrupted') + + # Notice that this test is racy: + # After DELAY, we set the event. We also try to immediately + # raise the exception with a timer of 0 --- but that depends + # on cycling the loop. Hence the fairly large value for DELAY. + g = gevent.spawn_later(DELAY, event1.set, 'hello event1') + self._close_on_teardown(g.kill) + with gevent.Timeout.start_new(0, timer_exc): + with self.assertRaises(MyException) as exc: + event1.get() + self.assertIs(timer_exc, exc.exception) + + def test_set_with_timeout(self): + event2 = AsyncResult() + + X = object() + result = gevent.with_timeout(DELAY, event2.get, timeout_value=X) + self.assertIs( + result, X, + 'Nobody sent anything to event2 yet it received %r' % (result, )) + + def test_nonblocking_get(self): + ar = AsyncResult() + self.assertRaises(gevent.Timeout, ar.get, block=False) + self.assertRaises(gevent.Timeout, ar.get_nowait) + +class TestAsyncResultCrossThread(greentest.TestCase): + + def _makeOne(self): + return AsyncResult() + + def _setOne(self, one): + one.set('from main') + + BG_WAIT_DELAY = 60 + + def _check_pypy_switch(self): + # On PyPy 7.3.3, switching to the main greenlet of a thread from a + # different thread silently does nothing. We can't detect the cross-thread + # switch, and so this test breaks + # https://foss.heptapod.net/pypy/pypy/-/issues/3381 + if greentest.PYPY: + import sys + if sys.pypy_version_info[:3] <= (7, 3, 3): # pylint:disable=no-member + self.skipTest("PyPy bug: https://foss.heptapod.net/pypy/pypy/-/issues/3381") + + @greentest.ignores_leakcheck + def test_cross_thread_use(self, timed_wait=False, wait_in_bg=False): + # Issue 1739. + # AsyncResult has *never* been thread safe, and using it from one + # thread to another is not safe. However, in some very careful use cases + # that can actually work. + # + # This test makes sure it doesn't hang in one careful use + # scenario. + self.assertNotMonkeyPatched() # Need real threads, event objects + from threading import Thread as NativeThread + from threading import Event as NativeEvent + + if not wait_in_bg: + self._check_pypy_switch() + + test = self + class Thread(NativeThread): + def __init__(self): + NativeThread.__init__(self) + self.daemon = True + self.running_event = NativeEvent() + self.finished_event = NativeEvent() + + self.async_result = test._makeOne() + self.result = '' + + def run(self): + # Give the loop in this thread something to do + g_event = Event() + def spin(): + while not g_event.is_set(): + g_event.wait(DELAY * 2) + glet = gevent.spawn(spin) + + def work(): + self.running_event.set() + # If we use a timed wait(), the bug doesn't manifest. + # This is probably because the loop wakes up to handle the timer, + # and notices the callback. + # See https://github.com/gevent/gevent/issues/1735 + if timed_wait: + self.result = self.async_result.wait(test.BG_WAIT_DELAY) + else: + self.result = self.async_result.wait() + + if wait_in_bg: + # This results in a separate code path + worker = gevent.spawn(work) + worker.join() + del worker + else: + work() + + g_event.set() + glet.join() + del glet + self.finished_event.set() + gevent.get_hub().destroy(destroy_loop=True) + + thread = Thread() + thread.start() + try: + thread.running_event.wait() + self._setOne(thread.async_result) + thread.finished_event.wait(DELAY * 5) + finally: + thread.join(DELAY * 15) + + self._check_result(thread.result) + + def _check_result(self, result): + self.assertEqual(result, 'from main') + + def test_cross_thread_use_bg(self): + self.test_cross_thread_use(timed_wait=False, wait_in_bg=True) + + def test_cross_thread_use_timed(self): + self.test_cross_thread_use(timed_wait=True, wait_in_bg=False) + + def test_cross_thread_use_timed_bg(self): + self.test_cross_thread_use(timed_wait=True, wait_in_bg=True) + + @greentest.ignores_leakcheck + def test_cross_thread_use_set_in_bg(self): + self.assertNotMonkeyPatched() # Need real threads, event objects + from threading import Thread as NativeThread + from threading import Event as NativeEvent + + self._check_pypy_switch() + test = self + class Thread(NativeThread): + def __init__(self): + NativeThread.__init__(self) + self.daemon = True + self.running_event = NativeEvent() + self.finished_event = NativeEvent() + + self.async_result = test._makeOne() + self.result = '' + + def run(self): + self.running_event.set() + test._setOne(self.async_result) + + self.finished_event.set() + gevent.get_hub().destroy(destroy_loop=True) + + thread = Thread() + glet = None + try: + glet = gevent.spawn(thread.start) + result = thread.async_result.wait(self.BG_WAIT_DELAY) + finally: + thread.join(DELAY * 15) + if glet is not None: + glet.join(DELAY) + self._check_result(result) + + @greentest.ignores_leakcheck + def test_cross_thread_use_set_in_bg2(self): + # Do it again to make sure it works multiple times. + self.test_cross_thread_use_set_in_bg() + +class TestEventCrossThread(TestAsyncResultCrossThread): + + def _makeOne(self): + return Event() + + def _setOne(self, one): + one.set() + + def _check_result(self, result): + self.assertTrue(result) + + +class TestAsyncResultAsLinkTarget(greentest.TestCase): + error_fatal = False + + def test_set(self): + g = gevent.spawn(lambda: 1) + s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult() + g.link(s1) + g.link_value(s2) + g.link_exception(s3) + self.assertEqual(s1.get(), 1) + self.assertEqual(s2.get(), 1) + X = object() + result = gevent.with_timeout(DELAY, s3.get, timeout_value=X) + self.assertIs(result, X) + + def test_set_exception(self): + def func(): + raise greentest.ExpectedException('TestAsyncResultAsLinkTarget.test_set_exception') + g = gevent.spawn(func) + s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult() + g.link(s1) + g.link_value(s2) + g.link_exception(s3) + self.assertRaises(greentest.ExpectedException, s1.get) + X = object() + result = gevent.with_timeout(DELAY, s2.get, timeout_value=X) + self.assertIs(result, X) + self.assertRaises(greentest.ExpectedException, s3.get) + + +class TestEvent_SetThenClear(greentest.TestCase): + N = 1 + + def test(self): + e = Event() + waiters = [gevent.spawn(e.wait) for i in range(self.N)] + gevent.sleep(0.001) + e.set() + e.clear() + for greenlet in waiters: + greenlet.join() + + +class TestEvent_SetThenClear100(TestEvent_SetThenClear): + N = 100 + + +class TestEvent_SetThenClear1000(TestEvent_SetThenClear): + N = 1000 + + +class TestWait(greentest.TestCase): + N = 5 + count = None + timeout = 1 + period = timeout / 100.0 + + def _sender(self, events, asyncs): + while events or asyncs: + gevent.sleep(self.period) + if events: + events.pop().set() + gevent.sleep(self.period) + if asyncs: + asyncs.pop().set() + + @greentest.skipOnAppVeyor("Not all results have arrived sometimes due to timer issues") + def test(self): + events = [Event() for _ in xrange(self.N)] + asyncs = [AsyncResult() for _ in xrange(self.N)] + max_len = len(events) + len(asyncs) + sender = gevent.spawn(self._sender, events, asyncs) + results = gevent.wait(events + asyncs, count=self.count, timeout=self.timeout) + if self.timeout is None: + expected_len = max_len + else: + expected_len = min(max_len, self.timeout / self.period) + if self.count is None: + self.assertTrue(sender.ready(), sender) + else: + expected_len = min(self.count, expected_len) + self.assertFalse(sender.ready(), sender) + sender.kill() + self.assertEqual(expected_len, len(results), (expected_len, len(results), results)) + + +class TestWait_notimeout(TestWait): + timeout = None + + +class TestWait_count1(TestWait): + count = 1 + + +class TestWait_count2(TestWait): + count = 2 + +class TestEventBasics(greentest.TestCase): + + def test_weakref(self): + # Event objects should allow weakrefs + e = Event() + r = weakref.ref(e) + self.assertIs(e, r()) + del e + del r + + def test_wait_while_notifying(self): + # If someone calls wait() on an Event that is + # ready, and notifying other waiters, that new + # waiter still runs at the end, but this does not + # require a trip around the event loop. + # See https://github.com/gevent/gevent/issues/1520 + event = Event() + results = [] + + def wait_then_append(arg): + event.wait() + results.append(arg) + + gevent.spawn(wait_then_append, 1) + gevent.spawn(wait_then_append, 2) + gevent.idle() + self.assertEqual(2, event.linkcount()) + check = gevent.get_hub().loop.check() + check.start(results.append, 4) + event.set() + wait_then_append(3) + self.assertEqual(results, [1, 2, 3]) + # Note that the check event DID NOT run. + check.stop() + check.close() + + def test_gevent_wait_twice_when_already_set(self): + event = Event() + event.set() + # First one works fine. + result = gevent.wait([event]) + self.assertEqual(result, [event]) + # Second one used to fail with an AssertionError, + # now it passes + result = gevent.wait([event]) + self.assertEqual(result, [event]) + + +del AbstractGenericGetTestCase +del AbstractGenericWaitTestCase + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__events.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__events.py new file mode 100644 index 0000000000000000000000000000000000000000..d5af423cf50a6495e9c6c5d61fc1e6d561095b3e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__events.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2018 gevent. See LICENSE. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +import unittest + +from gevent import events + +try: + from zope.interface import verify +except ImportError: + verify = None + +try: + from zope import event +except ImportError: + event = None + + +@unittest.skipIf(verify is None, "Needs zope.interface") +class TestImplements(unittest.TestCase): + + def test_event_loop_blocked(self): + verify.verifyClass(events.IEventLoopBlocked, events.EventLoopBlocked) + + def test_mem_threshold(self): + verify.verifyClass(events.IMemoryUsageThresholdExceeded, + events.MemoryUsageThresholdExceeded) + verify.verifyObject(events.IMemoryUsageThresholdExceeded, + events.MemoryUsageThresholdExceeded(0, 0, 0)) + + def test_mem_decreased(self): + verify.verifyClass(events.IMemoryUsageUnderThreshold, + events.MemoryUsageUnderThreshold) + verify.verifyObject(events.IMemoryUsageUnderThreshold, + events.MemoryUsageUnderThreshold(0, 0, 0, 0)) + + +@unittest.skipIf(event is None, "Needs zope.event") +class TestEvents(unittest.TestCase): + + def test_is_zope(self): + self.assertIs(events.subscribers, event.subscribers) + self.assertIs(events.notify, event.notify) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_echoserver.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_echoserver.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad822933ebe0ca21b4b4900cc08d01ea98ceda7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_echoserver.py @@ -0,0 +1,40 @@ +from gevent.socket import create_connection, timeout +import gevent.testing as greentest +import gevent + +from gevent.testing import util +from gevent.testing import params + +class Test(util.TestServer): + example = 'echoserver.py' + + def _run_all_tests(self): + def test_client(message): + if greentest.PY3: + kwargs = {'buffering': 1} + else: + kwargs = {'bufsize': 1} + kwargs['mode'] = 'rb' + conn = create_connection((params.DEFAULT_LOCAL_HOST_ADDR, 16000)) + conn.settimeout(greentest.DEFAULT_XPC_SOCKET_TIMEOUT) + rfile = conn.makefile(**kwargs) + + welcome = rfile.readline() + self.assertIn(b'Welcome', welcome) + + conn.sendall(message) + received = rfile.read(len(message)) + self.assertEqual(received, message) + + self.assertRaises(timeout, conn.recv, 1) + + rfile.close() + conn.close() + + client1 = gevent.spawn(test_client, b'hello\r\n') + client2 = gevent.spawn(test_client, b'world\r\n') + gevent.joinall([client1, client2], raise_error=True) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_portforwarder.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_portforwarder.py new file mode 100644 index 0000000000000000000000000000000000000000..6910b3b9b934180a7173ac824ef4ad446b393363 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_portforwarder.py @@ -0,0 +1,67 @@ +from __future__ import print_function, absolute_import +from gevent import monkey; monkey.patch_all() +import signal + +import socket +from time import sleep + +import gevent +from gevent.server import StreamServer + +import gevent.testing as greentest +from gevent.testing import util + +@greentest.skipOnLibuvOnCIOnPyPy("Timing issues sometimes lead to connection refused") +class Test(util.TestServer): + example = 'portforwarder.py' + # [listen on, forward to] + example_args = ['127.0.0.1:10011', '127.0.0.1:10012'] + + if greentest.WIN: + from subprocess import CREATE_NEW_PROCESS_GROUP + # Must be in a new process group to use CTRL_C_EVENT, otherwise + # we get killed too + start_kwargs = {'creationflags': CREATE_NEW_PROCESS_GROUP} + + def after(self): + if greentest.WIN: + self.assertIsNotNone(self.popen.poll()) + else: + self.assertEqual(self.popen.poll(), 0) + + def _run_all_tests(self): + log = [] + + def handle(sock, _address): + while True: + data = sock.recv(1024) + print('got %r' % data) + if not data: + break + log.append(data) + + server = StreamServer(self.example_args[1], handle) + server.start() + try: + conn = socket.create_connection(('127.0.0.1', 10011)) + conn.sendall(b'msg1') + sleep(0.1) + # On Windows, SIGTERM actually abruptly terminates the process; + # it can't be caught. However, CTRL_C_EVENT results in a KeyboardInterrupt + # being raised, so we can shut down properly. + self.popen.send_signal(getattr(signal, 'CTRL_C_EVENT', signal.SIGTERM)) + sleep(0.1) + + conn.sendall(b'msg2') + conn.close() + + with gevent.Timeout(2.1): + self.popen.wait() + finally: + server.close() + + self.assertEqual([b'msg1', b'msg2'], log) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_client.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ac27af136683e056becdf868f727a78a0684d0b8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_client.py @@ -0,0 +1,35 @@ +from gevent import monkey +monkey.patch_all() + + +from gevent.server import DatagramServer + +from gevent.testing import util +from gevent.testing import main + +class Test_udp_client(util.TestServer): + + start_kwargs = {'timeout': 10} + example = 'udp_client.py' + example_args = ['Test_udp_client'] + + def test(self): + log = [] + + def handle(message, address): + log.append(message) + server.sendto(b'reply-from-server', address) + + server = DatagramServer('127.0.0.1:9001', handle) + server.start() + try: + self.run_example() + finally: + server.close() + self.assertEqual(log, [b'Test_udp_client']) + + +if __name__ == '__main__': + # Running this following test__example_portforwarder on Appveyor + # doesn't work in the same process for some reason. + main() # pragma: testrunner-no-combine diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_server.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a6db02feb62ebfd0d7275c5eedd6b35d3f5980 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_udp_server.py @@ -0,0 +1,22 @@ +import socket + +from gevent.testing import util +from gevent.testing import main + + +class Test(util.TestServer): + example = 'udp_server.py' + + def _run_all_tests(self): + sock = socket.socket(type=socket.SOCK_DGRAM) + try: + sock.connect(('127.0.0.1', 9000)) + sock.send(b'Test udp_server') + data, _address = sock.recvfrom(8192) + self.assertEqual(data, b'Received 15 bytes') + finally: + sock.close() + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_webproxy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_webproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9ae6302ac744ab660258016017499fec39945f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_webproxy.py @@ -0,0 +1,29 @@ +from unittest import SkipTest + + +import gevent.testing as greentest + +from . import test__example_wsgiserver + + +@greentest.skipOnCI("Timing issues sometimes lead to a connection refused") +@greentest.skipWithoutExternalNetwork("Tries to reach google.com") +class Test_webproxy(test__example_wsgiserver.Test_wsgiserver): + example = 'webproxy.py' + + def _run_all_tests(self): + status, data = self.read('/') + self.assertEqual(status, '200 OK') + self.assertIn(b"gevent example", data) + status, data = self.read('/http://www.google.com') + self.assertEqual(status, '200 OK') + self.assertIn(b'google', data.lower()) + + def test_a_blocking_client(self): + # Not applicable + raise SkipTest("Not applicable") + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver.py new file mode 100644 index 0000000000000000000000000000000000000000..367ec40f32a73b06a1afdfd533d980d2fd5b2930 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver.py @@ -0,0 +1,94 @@ +import sys + +try: + from urllib import request as urllib2 +except ImportError: + import urllib2 + + +import socket +import ssl + +import gevent.testing as greentest +from gevent.testing import DEFAULT_XPC_SOCKET_TIMEOUT +from gevent.testing import util +from gevent.testing import params + +@greentest.skipOnCI("Timing issues sometimes lead to a connection refused") +class Test_wsgiserver(util.TestServer): + example = 'wsgiserver.py' + URL = 'http://%s:8088' % (params.DEFAULT_LOCAL_HOST_ADDR,) + PORT = 8088 + not_found_message = b'

Not Found

' + ssl_ctx = None + _use_ssl = False + + def read(self, path='/'): + url = self.URL + path + try: + kwargs = {} + if self.ssl_ctx is not None: + kwargs = {'context': self.ssl_ctx} + + response = urllib2.urlopen(url, None, + DEFAULT_XPC_SOCKET_TIMEOUT, + **kwargs) + except urllib2.HTTPError: + response = sys.exc_info()[1] + result = '%s %s' % (response.code, response.msg), response.read() + # XXX: It looks like under PyPy this isn't directly closing the socket + # when SSL is in use. It takes a GC cycle to make that true. + response.close() + return result + + def _test_hello(self): + status, data = self.read('/') + self.assertEqual(status, '200 OK') + self.assertEqual(data, b"hello world") + + def _test_not_found(self): + status, data = self.read('/xxx') + self.assertEqual(status, '404 Not Found') + self.assertEqual(data, self.not_found_message) + + def _do_test_a_blocking_client(self): + # We spawn this in a separate server because if it's broken + # the whole server hangs + with self.running_server(): + # First, make sure we can talk to it. + self._test_hello() + # Now create a connection and only partway finish + # the transaction + sock = socket.create_connection((params.DEFAULT_LOCAL_HOST_ADDR, self.PORT)) + ssl_sock = None + if self._use_ssl: + context = ssl.SSLContext() + ssl_sock = context.wrap_socket(sock) + sock_file = ssl_sock.makefile(mode='rwb') + else: + sock_file = sock.makefile(mode='rwb') + # write an incomplete request + sock_file.write(b'GET /xxx HTTP/1.0\r\n') + sock_file.flush() + # Leave it open and not doing anything + # while the other request runs to completion. + # This demonstrates that a blocking client + # doesn't hang the whole server + self._test_hello() + + # now finish the original request + sock_file.write(b'\r\n') + sock_file.flush() + line = sock_file.readline() + self.assertEqual(line, b'HTTP/1.1 404 Not Found\r\n') + + sock_file.close() + if ssl_sock is not None: + ssl_sock.close() + sock.close() + + def test_a_blocking_client(self): + self._do_test_a_blocking_client() + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver_ssl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bdec3b5b9e5c7eba0e53f24ab5947b7ddbd71a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__example_wsgiserver_ssl.py @@ -0,0 +1,24 @@ +import ssl + +import gevent.testing as greentest + +from gevent.testing import params + +from . import test__example_wsgiserver + + +@greentest.skipOnCI("Timing issues sometimes lead to a connection refused") +class Test_wsgiserver_ssl(test__example_wsgiserver.Test_wsgiserver): + example = 'wsgiserver_ssl.py' + URL = 'https://%s:8443' % (params.DEFAULT_LOCAL_HOST_ADDR,) + PORT = 8443 + _use_ssl = True + + if hasattr(ssl, '_create_unverified_context'): + # Disable verification for our self-signed cert + # on Python >= 2.7.9 and 3.4 + ssl_ctx = ssl._create_unverified_context() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__examples.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__examples.py new file mode 100644 index 0000000000000000000000000000000000000000..e428349dc4fdd3b8f8d9a9779115b8ae97e79b7e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__examples.py @@ -0,0 +1,109 @@ +""" +Test the contents of the ``examples/`` directory. + +If an existing test in *this* directory named ``test__example_.py`` exists, +where ```` is the base filename of an example file, it will not be tested +here. + +Examples can specify that they need particular test resources to be enabled +by commenting (one per line) ``# gevent-test-requires-resource: ``; +most commonly the resource will be ``network``. You can use this technique to specify +non-existant resources for things that should never be tested. +""" +import re +import os +import glob +import time +import unittest + +import gevent.testing as greentest +from gevent.testing import util + +this_dir = os.path.dirname(__file__) + +def _find_files_to_ignore(): + old_dir = os.getcwd() + try: + os.chdir(this_dir) + + result = [x[14:] for x in glob.glob('test__example_*.py')] + if greentest.PYPY and greentest.RUNNING_ON_APPVEYOR: + # For some reason on Windows with PyPy, this times out, + # when it should be very fast. + result.append("processes.py") + finally: + os.chdir(old_dir) + + return result + +default_time_range = (2, 10) +time_ranges = { # what is this even supposed to mean? pylint:disable=consider-using-namedtuple-or-dataclass + 'concurrent_download.py': (0, 30), + 'processes.py': (0, default_time_range[-1]) +} + +class _AbstractTestMixin(util.ExampleMixin): + time_range = default_time_range + example = None + + def _check_resources(self): + from gevent.testing import resources + + # pylint:disable=unspecified-encoding + with open(os.path.join(self.cwd, self.example), 'r') as f: + contents = f.read() + + pattern = re.compile('^# gevent-test-requires-resource: (.*)$', re.MULTILINE) + resources_needed = re.finditer(pattern, contents) + for match in resources_needed: + needed = contents[match.start(1):match.end(1)] + resources.skip_without_resource(needed) + + def test_runs(self): + self._check_resources() + + start = time.time() + min_time, max_time = self.time_range + self.start_kwargs = { + 'timeout': max_time, + 'quiet': True, + 'buffer_output': True, + 'nested': True, + 'setenv': {'GEVENT_DEBUG': 'error'} + } + if not self.run_example(): + self.fail("Failed example: " + self.example) + else: + took = time.time() - start + self.assertGreaterEqual(took, min_time) + +def _build_test_classes(): + result = {} + try: + example_dir = util.ExampleMixin().cwd + except unittest.SkipTest: + util.log("WARNING: No examples dir found", color='suboptimal-behaviour') + return result + + ignore = _find_files_to_ignore() + for filename in glob.glob(example_dir + '/*.py'): + bn = os.path.basename(filename) + if bn in ignore: + continue + + tc = type( + 'Test_' + bn, + (_AbstractTestMixin, greentest.TestCase), + { + 'example': bn, + 'time_range': time_ranges.get(bn, _AbstractTestMixin.time_range) + } + ) + result[tc.__name__] = tc + return result + +for k, v in _build_test_classes().items(): + locals()[k] = v + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__exc_info.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__exc_info.py new file mode 100644 index 0000000000000000000000000000000000000000..8346bd6d3b8a105d48706c8fdb7003f1ab7c57f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__exc_info.py @@ -0,0 +1,58 @@ +import gevent +import sys +import gevent.testing as greentest +from gevent.testing import six +from gevent.testing import ExpectedException as ExpectedError + +if six.PY2: + sys.exc_clear() + +class RawException(Exception): + pass + + +def hello(err): + assert sys.exc_info() == (None, None, None), sys.exc_info() + raise err + + +def hello2(): + try: + hello(ExpectedError('expected exception in hello')) + except ExpectedError: + pass + + +class Test(greentest.TestCase): + + def test1(self): + error = RawException('hello') + expected_error = ExpectedError('expected exception in hello') + try: + raise error + except RawException: + self.expect_one_error() + g = gevent.spawn(hello, expected_error) + g.join() + self.assert_error(ExpectedError, expected_error) + self.assertIsInstance(g.exception, ExpectedError) + + try: + raise + except: # pylint:disable=bare-except + ex = sys.exc_info()[1] + self.assertIs(ex, error) + + def test2(self): + timer = gevent.get_hub().loop.timer(0) + timer.start(hello2) + try: + gevent.sleep(0.1) + self.assertEqual(sys.exc_info(), (None, None, None)) + finally: + timer.close() + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__execmodules.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__execmodules.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0058346055696a0a53230c0ecdb5500e680020 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__execmodules.py @@ -0,0 +1,55 @@ +import unittest +import warnings + +from gevent.testing import modules +from gevent.testing import main +from gevent.testing.sysinfo import NON_APPLICABLE_SUFFIXES +from gevent.testing import six + +import pathlib + +def make_exec_test(path, module): + path = pathlib.Path(path) + + def test(_): + + with open(path, 'rb') as f: + src = f.read() + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + globs = {'__file__': path, '__name__': module} + if path.name == '__init__.py': + globs['__path__'] = [path] + globs['__package__'] = module + elif '.' in module: + globs['__package__'] = module.rsplit('.', 1)[0] + try: + six.exec_(src, globs) + except ImportError: + if module in modules.OPTIONAL_MODULES: + raise unittest.SkipTest("Unable to import optional module %s" % module) + raise + + name = "test_" + module.replace(".", "_") + test.__name__ = name + return test + +def make_all_tests(cls): + for path, module in modules.walk_modules(recursive=True, check_optional=False): + if module.endswith(NON_APPLICABLE_SUFFIXES): + continue + test = make_exec_test(path, module) + setattr(cls, test.__name__, test) + return cls + + +@make_all_tests +class Test(unittest.TestCase): + pass + + +if __name__ == '__main__': + # This should not be combined with other tests in the same process + # because it messes with global shared state. + # pragma: testrunner-no-combine + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__fileobject.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__fileobject.py new file mode 100644 index 0000000000000000000000000000000000000000..bdef5763a201e513abf942ca83203f328878640f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__fileobject.py @@ -0,0 +1,562 @@ +from __future__ import print_function +from __future__ import absolute_import + +import functools +import gc +import io +import os +import sys +import tempfile +import unittest + +import gevent +from gevent import fileobject +from gevent._fileobjectcommon import OpenDescriptor +try: + from gevent._fileobjectposix import GreenOpenDescriptor +except ImportError: + GreenOpenDescriptor = None + + +import gevent.testing as greentest +from gevent.testing import sysinfo + + +# pylint:disable=unspecified-encoding + +def Writer(fobj, line): + for character in line: + fobj.write(character) + fobj.flush() + fobj.close() + + +def close_fd_quietly(fd): + try: + os.close(fd) + except OSError: + pass + +def skipUnlessWorksWithRegularFiles(func): + @functools.wraps(func) + def f(self): + if not self.WORKS_WITH_REGULAR_FILES: + self.skipTest("Doesn't work with regular files") + func(self) + return f + + +class CleanupMixin(object): + def _mkstemp(self, suffix): + fileno, path = tempfile.mkstemp(suffix) + self.addCleanup(os.remove, path) + self.addCleanup(close_fd_quietly, fileno) + return fileno, path + + def _pipe(self): + r, w = os.pipe() + self.addCleanup(close_fd_quietly, r) + self.addCleanup(close_fd_quietly, w) + return r, w + + +class TestFileObjectBlock(CleanupMixin, + greentest.TestCase): + # serves as a base for the concurrent tests too + + WORKS_WITH_REGULAR_FILES = True + + def _getTargetClass(self): + return fileobject.FileObjectBlock + + def _makeOne(self, *args, **kwargs): + return self._getTargetClass()(*args, **kwargs) + + def _test_del(self, **kwargs): + r, w = self._pipe() + self._do_test_del((r, w), **kwargs) + + def _do_test_del(self, pipe, **kwargs): + r, w = pipe + s = self._makeOne(w, 'wb', **kwargs) + s.write(b'x') + try: + s.flush() + except IOError: + # Sometimes seen on Windows/AppVeyor + print("Failed flushing fileobject", repr(s), file=sys.stderr) + import traceback + traceback.print_exc() + + import warnings + with warnings.catch_warnings(): + warnings.simplefilter('ignore', ResourceWarning) + # Deliberately getting ResourceWarning with FileObject(Thread) under Py3 + del s + gc.collect() # PyPy + + if kwargs.get("close", True): + with self.assertRaises((OSError, IOError)): + # expected, because FileObject already closed it + os.close(w) + else: + os.close(w) + + with self._makeOne(r, 'rb') as fobj: + self.assertEqual(fobj.read(), b'x') + + def test_del(self): + # Close should be true by default + self._test_del() + + def test_del_close(self): + self._test_del(close=True) + + + @skipUnlessWorksWithRegularFiles + def test_seek(self): + fileno, path = self._mkstemp('.gevent.test__fileobject.test_seek') + + s = b'a' * 1024 + os.write(fileno, b'B' * 15) + os.write(fileno, s) + os.close(fileno) + + with open(path, 'rb') as f: + f.seek(15) + native_data = f.read(1024) + + with open(path, 'rb') as f_raw: + f = self._makeOne(f_raw, 'rb', close=False) + # On Python 3, all objects should have seekable. + # On Python 2, only our custom objects do. + self.assertTrue(f.seekable()) + f.seek(15) + self.assertEqual(15, f.tell()) + + # Note that a duplicate close() of the underlying + # file descriptor can look like an OSError from this line + # as we exit the with block + fileobj_data = f.read(1024) + + self.assertEqual(native_data, s) + self.assertEqual(native_data, fileobj_data) + + def __check_native_matches(self, byte_data, open_mode, + meth='read', open_path=True, + **open_kwargs): + fileno, path = self._mkstemp('.gevent_test_' + open_mode) + + os.write(fileno, byte_data) + os.close(fileno) + + with io.open(path, open_mode, **open_kwargs) as f: + native_data = getattr(f, meth)() + + if open_path: + with self._makeOne(path, open_mode, **open_kwargs) as f: + gevent_data = getattr(f, meth)() + else: + # Note that we don't use ``io.open()`` for the raw file, + # on Python 2. We want 'r' to mean what the usual call to open() means. + opener = io.open + with opener(path, open_mode, **open_kwargs) as raw: + with self._makeOne(raw) as f: + gevent_data = getattr(f, meth)() + + self.assertEqual(native_data, gevent_data) + return gevent_data + + @skipUnlessWorksWithRegularFiles + def test_str_default_to_native(self): + # With no 'b' or 't' given, read and write native str. + gevent_data = self.__check_native_matches(b'abcdefg', 'r') + self.assertIsInstance(gevent_data, str) + + @skipUnlessWorksWithRegularFiles + def test_text_encoding(self): + gevent_data = self.__check_native_matches( + u'\N{SNOWMAN}'.encode('utf-8'), + 'r+', + buffering=5, encoding='utf-8' + ) + self.assertIsInstance(gevent_data, str) + + @skipUnlessWorksWithRegularFiles + def test_does_not_leak_on_exception(self): + # If an exception occurs during opening, + # everything still gets cleaned up. + pass + + @skipUnlessWorksWithRegularFiles + def test_rbU_produces_bytes_readline(self): + if sys.version_info > (3, 11): + self.skipTest("U file mode was removed in 3.11") + # Including U in rb still produces bytes. + # Note that the universal newline behaviour is + # essentially ignored in explicit bytes mode. + gevent_data = self.__check_native_matches( + b'line1\nline2\r\nline3\rlastline\n\n', + 'rbU', + meth='readlines', + ) + self.assertIsInstance(gevent_data[0], bytes) + self.assertEqual(len(gevent_data), 4) + + @skipUnlessWorksWithRegularFiles + def test_rU_produces_native(self): + if sys.version_info > (3, 11): + self.skipTest("U file mode was removed in 3.11") + gevent_data = self.__check_native_matches( + b'line1\nline2\r\nline3\rlastline\n\n', + 'rU', + meth='readlines', + ) + self.assertIsInstance(gevent_data[0], str) + + @skipUnlessWorksWithRegularFiles + def test_r_readline_produces_native(self): + gevent_data = self.__check_native_matches( + b'line1\n', + 'r', + meth='readline', + ) + self.assertIsInstance(gevent_data, str) + + @skipUnlessWorksWithRegularFiles + def test_r_readline_on_fobject_produces_native(self): + gevent_data = self.__check_native_matches( + b'line1\n', + 'r', + meth='readline', + open_path=False, + ) + self.assertIsInstance(gevent_data, str) + + def test_close_pipe(self): + # Issue #190, 203 + r, w = os.pipe() + x = self._makeOne(r) + y = self._makeOne(w, 'w') + x.close() + y.close() + + @skipUnlessWorksWithRegularFiles + @greentest.ignores_leakcheck + def test_name_after_close(self): + fileno, path = self._mkstemp('.gevent_test_named_path_after_close') + + # Passing the fileno; the name is the same as the fileno, and + # doesn't change when closed. + f = self._makeOne(fileno) + nf = os.fdopen(fileno) + # On Python 2, os.fdopen() produces a name of ; + # we follow the Python 3 semantics everywhere. + nf_name = '' if greentest.PY2 else fileno + self.assertEqual(f.name, fileno) + self.assertEqual(nf.name, nf_name) + + # A file-like object that has no name; we'll close the + # `f` after this because we reuse the fileno, which + # gets passed to fcntl and so must still be valid + class Nameless(object): + def fileno(self): + return fileno + close = flush = isatty = closed = writable = lambda self: False + seekable = readable = lambda self: True + + nameless = self._makeOne(Nameless(), 'rb') + with self.assertRaises(AttributeError): + getattr(nameless, 'name') + nameless.close() + with self.assertRaises(AttributeError): + getattr(nameless, 'name') + + f.close() + try: + nf.close() + except OSError: + # OSError: Py3, IOError: Py2 + pass + self.assertEqual(f.name, fileno) + self.assertEqual(nf.name, nf_name) + + def check(arg): + f = self._makeOne(arg) + self.assertEqual(f.name, path) + f.close() + # Doesn't change after closed. + self.assertEqual(f.name, path) + + # Passing the string + check(path) + + # Passing an opened native object + with open(path) as nf: + check(nf) + + # An io object + with io.open(path) as nf: + check(nf) + + @skipUnlessWorksWithRegularFiles + def test_readinto_serial(self): + fileno, path = self._mkstemp('.gevent_test_readinto') + os.write(fileno, b'hello world') + os.close(fileno) + + buf = bytearray(32) + mbuf = memoryview(buf) + + def assertReadInto(byte_count, expected_data): + bytes_read = f.readinto(mbuf[:byte_count]) + self.assertEqual(bytes_read, len(expected_data)) + self.assertEqual(buf[:bytes_read], expected_data) + + with self._makeOne(path, 'rb') as f: + assertReadInto(2, b'he') + assertReadInto(1, b'l') + assertReadInto(32, b'lo world') + assertReadInto(32, b'') + + +class ConcurrentFileObjectMixin(object): + # Additional tests for fileobjects that cooperate + # and we have full control of the implementation + + def test_read1_binary_present(self): + # Issue #840 + r, w = self._pipe() + reader = self._makeOne(r, 'rb') + self._close_on_teardown(reader) + writer = self._makeOne(w, 'w') + self._close_on_teardown(writer) + self.assertTrue(hasattr(reader, 'read1'), dir(reader)) + + def test_read1_text_not_present(self): + # Only defined for binary. + r, w = self._pipe() + reader = self._makeOne(r, 'rt') + self._close_on_teardown(reader) + self.addCleanup(os.close, w) + self.assertFalse(hasattr(reader, 'read1'), dir(reader)) + + def test_read1_default(self): + # If just 'r' is given, whether it has one or not + # depends on if we're Python 2 or 3. + r, w = self._pipe() + self.addCleanup(os.close, w) + reader = self._makeOne(r) + self._close_on_teardown(reader) + self.assertFalse(hasattr(reader, 'read1')) + + def test_bufsize_0(self): + # Issue #840 + r, w = self._pipe() + x = self._makeOne(r, 'rb', bufsize=0) + y = self._makeOne(w, 'wb', bufsize=0) + self._close_on_teardown(x) + self._close_on_teardown(y) + y.write(b'a') + b = x.read(1) + self.assertEqual(b, b'a') + + y.writelines([b'2']) + b = x.read(1) + self.assertEqual(b, b'2') + + def test_newlines(self): + import warnings + r, w = self._pipe() + lines = [b'line1\n', b'line2\r', b'line3\r\n', b'line4\r\nline5', b'\nline6'] + g = gevent.spawn(Writer, self._makeOne(w, 'wb'), lines) + + try: + with warnings.catch_warnings(): + if sys.version_info > (3, 11): + # U is removed in Python 3.11 + mode = 'r' + self.skipTest("U file mode was removed in 3.11") + else: + # U is deprecated in Python 3, shows up on FileObjectThread + warnings.simplefilter('ignore', DeprecationWarning) + mode = 'rU' + fobj = self._makeOne(r, mode) + result = fobj.read() + fobj.close() + self.assertEqual('line1\nline2\nline3\nline4\nline5\nline6', result) + finally: + g.kill() + + def test_readinto(self): + # verify that .readinto() is cooperative. + # if .readinto() is not cooperative spawned greenlet will not be able + # to run and call to .readinto() will block forever. + r, w = self._pipe() + rf = self._close_on_teardown(self._makeOne(r, 'rb')) + wf = self._close_on_teardown(self._makeOne(w, 'wb')) + g = gevent.spawn(Writer, wf, [b'hello']) + + try: + buf1 = bytearray(32) + buf2 = bytearray(32) + + n1 = rf.readinto(buf1) + n2 = rf.readinto(buf2) + + self.assertEqual(n1, 5) + self.assertEqual(buf1[:n1], b'hello') + self.assertEqual(n2, 0) + finally: + g.kill() + + +class TestFileObjectThread(ConcurrentFileObjectMixin, # pylint:disable=too-many-ancestors + TestFileObjectBlock): + + def _getTargetClass(self): + return fileobject.FileObjectThread + + def test_del_noclose(self): + # In the past, we used os.fdopen() when given a file descriptor, + # and that has a destructor that can't be bypassed, so + # close=false wasn't allowed. Now that we do everything with the + # io module, it is allowed. + self._test_del(close=False) + + # We don't test this with FileObjectThread. Sometimes the + # visibility of the 'close' operation, which happens in a + # background thread, doesn't make it to the foreground + # thread in a timely fashion, leading to 'os.close(4) must + # not succeed' in test_del_close. We have the same thing + # with flushing and closing in test_newlines. Both of + # these are most commonly (only?) observed on Py27/64-bit. + # They also appear on 64-bit 3.6 with libuv + + def test_del(self): + raise unittest.SkipTest("Race conditions") + + def test_del_close(self): + raise unittest.SkipTest("Race conditions") + + +@unittest.skipUnless( + hasattr(fileobject, 'FileObjectPosix'), + "Needs FileObjectPosix" +) +class TestFileObjectPosix(ConcurrentFileObjectMixin, # pylint:disable=too-many-ancestors + TestFileObjectBlock): + + if sysinfo.LIBUV and sysinfo.LINUX: + # On Linux, initializing the watcher for a regular + # file results in libuv raising EPERM. But that works + # fine on other platforms. + WORKS_WITH_REGULAR_FILES = False + + def _getTargetClass(self): + return fileobject.FileObjectPosix + + def test_seek_raises_ioerror(self): + # https://github.com/gevent/gevent/issues/1323 + + # Get a non-seekable file descriptor + r, _w = self._pipe() + + with self.assertRaises(OSError) as ctx: + os.lseek(r, 0, os.SEEK_SET) + os_ex = ctx.exception + + with self.assertRaises(IOError) as ctx: + f = self._makeOne(r, 'r', close=False) + # Seek directly using the underlying GreenFileDescriptorIO; + # the buffer may do different things, depending + # on the version of Python (especially 3.7+) + f.fileio.seek(0) + io_ex = ctx.exception + + self.assertEqual(io_ex.errno, os_ex.errno) + self.assertEqual(io_ex.strerror, os_ex.strerror) + self.assertEqual(io_ex.args, os_ex.args) + self.assertEqual(str(io_ex), str(os_ex)) + +class TestTextMode(CleanupMixin, unittest.TestCase): + + def test_default_mode_writes_linesep(self): + # See https://github.com/gevent/gevent/issues/1282 + # libuv 1.x interferes with the default line mode on + # Windows. + # First, make sure we initialize gevent + gevent.get_hub() + + fileno, path = self._mkstemp('.gevent.test__fileobject.test_default') + os.close(fileno) + + with open(path, "w") as f: + f.write("\n") + + with open(path, "rb") as f: + data = f.read() + + self.assertEqual(data, os.linesep.encode('ascii')) + +class TestOpenDescriptor(CleanupMixin, greentest.TestCase): + + def _getTargetClass(self): + return OpenDescriptor + + def _makeOne(self, *args, **kwargs): + return self._getTargetClass()(*args, **kwargs) + + def _check(self, regex, kind, *args, **kwargs): + with self.assertRaisesRegex(kind, regex): + self._makeOne(*args, **kwargs) + + case = lambda re, **kwargs: (re, TypeError, kwargs) + vase = lambda re, **kwargs: (re, ValueError, kwargs) + CASES = ( + case('mode', mode=42), + case('buffering', buffering='nope'), + case('encoding', encoding=42), + case('errors', errors=42), + vase('mode', mode='aoeug'), + vase('mode U cannot be combined', mode='wU'), + vase('text and binary', mode='rtb'), + vase('append mode at once', mode='rw'), + vase('exactly one', mode='+'), + vase('take an encoding', mode='rb', encoding='ascii'), + vase('take an errors', mode='rb', errors='strict'), + vase('take a newline', mode='rb', newline='\n'), + ) + + def test_atomicwrite_fd(self): + from gevent._fileobjectcommon import WriteallMixin + # It basically only does something when buffering is otherwise disabled + fileno, _w = self._pipe() + desc = self._makeOne(fileno, 'wb', + buffering=0, + closefd=False, + atomic_write=True) + self.assertTrue(desc.atomic_write) + + fobj = desc.opened() + self.assertIsInstance(fobj, WriteallMixin) + os.close(fileno) + +def pop(): + for regex, kind, kwargs in TestOpenDescriptor.CASES: + setattr( + TestOpenDescriptor, 'test_' + regex.replace(' ', '_'), + lambda self, _re=regex, _kind=kind, _kw=kwargs: self._check(_re, _kind, 1, **_kw) + ) +pop() + +@unittest.skipIf(GreenOpenDescriptor is None, "No support for non-blocking IO") +class TestGreenOpenDescripton(TestOpenDescriptor): + def _getTargetClass(self): + return GreenOpenDescriptor + + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__getaddrinfo_import.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__getaddrinfo_import.py new file mode 100644 index 0000000000000000000000000000000000000000..182501c92acf226d74eb8f76f278c890ff00602b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__getaddrinfo_import.py @@ -0,0 +1,11 @@ +# On Python 2, a deadlock is possible if we import a module that runs gevent's getaddrinfo +# with a unicode hostname, which starts Python's getaddrinfo on a thread, which +# attempts to import encodings.idna but blocks on the import lock. Verify +# that gevent avoids this deadlock. + +try: + import getaddrinfo_module # pylint:disable=import-error +except ModuleNotFoundError: + from gevent.tests import getaddrinfo_module + +del getaddrinfo_module # fix pyflakes diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenio.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenio.py new file mode 100644 index 0000000000000000000000000000000000000000..f89123add8f615d35d6857e76cab33ba0cd9f047 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenio.py @@ -0,0 +1,146 @@ +# Copyright (c) 2006-2007, Linden Research, Inc. +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +import sys + +import gevent +from gevent import socket + +from gevent import testing as greentest +from gevent.testing import TestCase, tcp_listener +from gevent.testing import gc_collect_if_needed +from gevent.testing import skipOnPyPy +from gevent.testing import params + + +PY3 = sys.version_info[0] >= 3 + + +def _write_to_closed(f, s): + try: + r = f.write(s) + except ValueError: + assert PY3 + else: + assert r is None, r + + +class TestGreenIo(TestCase): + + def test_close_with_makefile(self): + + def accept_close_early(listener): + # verify that the makefile and the socket are truly independent + # by closing the socket prior to using the made file + try: + conn, _ = listener.accept() + fd = conn.makefile(mode='wb') + conn.close() + fd.write(b'hello\n') + fd.close() + _write_to_closed(fd, b'a') + self.assertRaises(socket.error, conn.send, b'b') + finally: + listener.close() + + def accept_close_late(listener): + # verify that the makefile and the socket are truly independent + # by closing the made file and then sending a character + try: + conn, _ = listener.accept() + fd = conn.makefile(mode='wb') + fd.write(b'hello') + fd.close() + conn.send(b'\n') + conn.close() + _write_to_closed(fd, b'a') + self.assertRaises(socket.error, conn.send, b'b') + finally: + listener.close() + + def did_it_work(server): + client = socket.create_connection((params.DEFAULT_CONNECT, server.getsockname()[1])) + fd = client.makefile(mode='rb') + client.close() + self.assertEqual(fd.readline(), b'hello\n') + self.assertFalse(fd.read()) + fd.close() + + server = tcp_listener() + server_greenlet = gevent.spawn(accept_close_early, server) + did_it_work(server) + server_greenlet.kill() + + server = tcp_listener() + server_greenlet = gevent.spawn(accept_close_late, server) + did_it_work(server) + server_greenlet.kill() + + @skipOnPyPy("Takes multiple GCs and issues a warning we can't catch") + def test_del_closes_socket(self): + import warnings + def accept_once(listener): + # delete/overwrite the original conn + # object, only keeping the file object around + # closing the file object should close everything + + # This is not *exactly* true on Python 3. This produces + # a ResourceWarning, which we silence below. (Previously we actually + # *saved* a reference to the socket object, so we + # weren't testing what we thought we were.) + + # It's definitely not true on PyPy, which needs GC to + # reliably close everything; sometimes this is more than + # one collection cycle. And PyPy issues a warning with -X + # track-resources that we cannot catch. + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + + try: + conn = listener.accept()[0] + # Note that we overwrite the original variable, + # losing our reference to the socket. + conn = conn.makefile(mode='wb') + conn.write(b'hello\n') + conn.close() + _write_to_closed(conn, b'a') + finally: + listener.close() + del listener + del conn + gc_collect_if_needed() + gc_collect_if_needed() + + server = tcp_listener() + gevent.spawn(accept_once, server) + client = socket.create_connection((params.DEFAULT_CONNECT, server.getsockname()[1])) + with gevent.Timeout.start_new(0.5): + fd = client.makefile() + client.close() + self.assertEqual(fd.read(), 'hello\n') + # If the socket isn't closed when 'accept_once' finished, + # then this will hang and exceed the timeout + self.assertEqual(fd.read(), '') + + fd.close() + del client + del fd + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenlet.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenlet.py new file mode 100644 index 0000000000000000000000000000000000000000..d072d787cfacd04c5a43987e3e172483a9f01528 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenlet.py @@ -0,0 +1,1034 @@ +# Copyright (c) 2008-2009 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +import functools +import unittest +from unittest.mock import patch as Patch + +import gevent.testing as greentest +import gevent + +from gevent import sleep, with_timeout, getcurrent +from gevent import greenlet +from gevent.event import AsyncResult +from gevent.queue import Queue, Channel + +from gevent.testing.timing import AbstractGenericWaitTestCase +from gevent.testing.timing import AbstractGenericGetTestCase +from gevent.testing import timing +from gevent.testing import ignores_leakcheck + +DELAY = timing.SMALL_TICK +greentest.TestCase.error_fatal = False + + +class ExpectedError(greentest.ExpectedException): + pass + +class ExpectedJoinError(ExpectedError): + pass + +class SuiteExpectedException(ExpectedError): + pass + +class GreenletRaisesJoin(gevent.Greenlet): + killed = False + joined = False + raise_on_join = True + + def join(self, timeout=None): + self.joined += 1 + if self.raise_on_join: + raise ExpectedJoinError + return gevent.Greenlet.join(self, timeout) + + def kill(self, *args, **kwargs): # pylint:disable=signature-differs + self.killed += 1 + return gevent.Greenlet.kill(self, *args, **kwargs) + +class TestLink(greentest.TestCase): + + def test_link_to_asyncresult(self): + p = gevent.spawn(lambda: 100) + event = AsyncResult() + p.link(event) + self.assertEqual(event.get(), 100) + + for _ in range(3): + event2 = AsyncResult() + p.link(event2) + self.assertEqual(event2.get(), 100) + + def test_link_to_asyncresult_exception(self): + err = ExpectedError('test_link_to_asyncresult_exception') + p = gevent.spawn(lambda: getcurrent().throw(err)) + event = AsyncResult() + p.link(event) + with self.assertRaises(ExpectedError) as exc: + event.get() + + self.assertIs(exc.exception, err) + + for _ in range(3): + event2 = AsyncResult() + p.link(event2) + with self.assertRaises(ExpectedError) as exc: + event2.get() + self.assertIs(exc.exception, err) + + def test_link_to_queue(self): + p = gevent.spawn(lambda: 100) + q = Queue() + p.link(q.put) + self.assertEqual(q.get().get(), 100) + + for _ in range(3): + p.link(q.put) + self.assertEqual(q.get().get(), 100) + + def test_link_to_channel(self): + p1 = gevent.spawn(lambda: 101) + p2 = gevent.spawn(lambda: 102) + p3 = gevent.spawn(lambda: 103) + q = Channel() + p1.link(q.put) + p2.link(q.put) + p3.link(q.put) + results = [q.get().get(), q.get().get(), q.get().get()] + self.assertEqual(sorted(results), [101, 102, 103], results) + + +class TestUnlink(greentest.TestCase): + switch_expected = False + + def _test_func(self, p, link): + link(dummy_test_func) + self.assertEqual(1, p.has_links()) + + p.unlink(dummy_test_func) + self.assertEqual(0, p.has_links()) + + link(self.setUp) + self.assertEqual(1, p.has_links()) + + p.unlink(self.setUp) + self.assertEqual(0, p.has_links()) + + p.kill() + + def test_func_link(self): + p = gevent.spawn(dummy_test_func) + self._test_func(p, p.link) + + def test_func_link_value(self): + p = gevent.spawn(dummy_test_func) + self._test_func(p, p.link_value) + + def test_func_link_exception(self): + p = gevent.spawn(dummy_test_func) + self._test_func(p, p.link_exception) + + +class LinksTestCase(greentest.TestCase): + + link_method = None + + def link(self, p, listener=None): + getattr(p, self.link_method)(listener) + + def set_links(self, p): + event = AsyncResult() + self.link(p, event) + + queue = Queue(1) + self.link(p, queue.put) + + callback_flag = ['initial'] + self.link(p, lambda *args: callback_flag.remove('initial')) + + for _ in range(10): + self.link(p, AsyncResult()) + self.link(p, Queue(1).put) + + return event, queue, callback_flag + + def set_links_timeout(self, link): + # stuff that won't be touched + event = AsyncResult() + link(event) + + queue = Channel() + link(queue.put) + return event, queue + + def check_timed_out(self, event, queue): + got = with_timeout(DELAY, event.get, timeout_value=X) + self.assertIs(got, X) + got = with_timeout(DELAY, queue.get, timeout_value=X) + self.assertIs(got, X) + + +def return25(): + return 25 + + + +class TestReturn_link(LinksTestCase): + link_method = 'link' + + p = None + + def cleanup(self): + self.p.unlink_all() + self.p = None + + def test_return(self): + self.p = gevent.spawn(return25) + for _ in range(3): + self._test_return(self.p, 25) + self.p.kill() + + def _test_return(self, p, result): + event, queue, callback_flag = self.set_links(p) + + # stuff that will time out because there's no unhandled exception: + xxxxx = self.set_links_timeout(p.link_exception) + + sleep(DELAY * 2) + self.assertFalse(p) + + self.assertEqual(event.get(), result) + self.assertEqual(queue.get().get(), result) + + sleep(DELAY) + self.assertFalse(callback_flag) + + self.check_timed_out(*xxxxx) + + def _test_kill(self, p): + event, queue, callback_flag = self.set_links(p) + xxxxx = self.set_links_timeout(p.link_exception) + + p.kill() + sleep(DELAY) + self.assertFalse(p) + + + self.assertIsInstance(event.get(), gevent.GreenletExit) + self.assertIsInstance(queue.get().get(), gevent.GreenletExit) + + sleep(DELAY) + self.assertFalse(callback_flag) + + self.check_timed_out(*xxxxx) + + def test_kill(self): + p = self.p = gevent.spawn(sleep, DELAY) + for _ in range(3): + self._test_kill(p) + + +class TestReturn_link_value(TestReturn_link): + link_method = 'link_value' + + +class TestRaise_link(LinksTestCase): + link_method = 'link' + + def _test_raise(self, p): + event, queue, callback_flag = self.set_links(p) + xxxxx = self.set_links_timeout(p.link_value) + + sleep(DELAY) + self.assertFalse(p, p) + + self.assertRaises(ExpectedError, event.get) + self.assertEqual(queue.get(), p) + sleep(DELAY) + self.assertFalse(callback_flag, callback_flag) + + self.check_timed_out(*xxxxx) + + def test_raise(self): + p = gevent.spawn(lambda: getcurrent().throw(ExpectedError('test_raise'))) + for _ in range(3): + self._test_raise(p) + + +class TestRaise_link_exception(TestRaise_link): + link_method = 'link_exception' + + +class TestStuff(greentest.TestCase): + + def test_minimal_id(self): + g = gevent.spawn(lambda: 1) + self.assertGreaterEqual(g.minimal_ident, 0) + self.assertGreaterEqual(g.parent.minimal_ident, 0) + g.join() # don't leave dangling, breaks the leak checks + + def test_wait_noerrors(self): + x = gevent.spawn(lambda: 1) + y = gevent.spawn(lambda: 2) + z = gevent.spawn(lambda: 3) + gevent.joinall([x, y, z], raise_error=True) + self.assertEqual([x.value, y.value, z.value], [1, 2, 3]) + e = AsyncResult() + x.link(e) + self.assertEqual(e.get(), 1) + x.unlink(e) + e = AsyncResult() + x.link(e) + self.assertEqual(e.get(), 1) + + @ignores_leakcheck + def test_wait_error(self): + + def x(): + sleep(DELAY) + return 1 + x = gevent.spawn(x) + y = gevent.spawn(lambda: getcurrent().throw(ExpectedError('test_wait_error'))) + self.assertRaises(ExpectedError, gevent.joinall, [x, y], raise_error=True) + self.assertRaises(ExpectedError, gevent.joinall, [y], raise_error=True) + x.join() + + @ignores_leakcheck + def test_joinall_exception_order(self): + # if there're several exceptions raised, the earliest one must be raised by joinall + def first(): + sleep(0.1) + raise ExpectedError('first') + a = gevent.spawn(first) + b = gevent.spawn(lambda: getcurrent().throw(ExpectedError('second'))) + with self.assertRaisesRegex(ExpectedError, 'second'): + gevent.joinall([a, b], raise_error=True) + + gevent.joinall([a, b]) + + def test_joinall_count_raise_error(self): + # When joinall is asked not to raise an error, the 'count' param still + # works. + def raises_but_ignored(): + raise ExpectedError("count") + + def sleep_forever(): + while True: + sleep(0.1) + + sleeper = gevent.spawn(sleep_forever) + raiser = gevent.spawn(raises_but_ignored) + + gevent.joinall([sleeper, raiser], raise_error=False, count=1) + self.assert_greenlet_ready(raiser) + self.assert_greenlet_not_ready(sleeper) + + # Clean up our mess + sleeper.kill() + self.assert_greenlet_ready(sleeper) + + def test_multiple_listeners_error(self): + # if there was an error while calling a callback + # it should not prevent the other listeners from being called + # also, all of the errors should be logged, check the output + # manually that they are + p = gevent.spawn(lambda: 5) + results = [] + + def listener1(*_args): + results.append(10) + raise ExpectedError('listener1') + + def listener2(*_args): + results.append(20) + raise ExpectedError('listener2') + + def listener3(*_args): + raise ExpectedError('listener3') + + p.link(listener1) + p.link(listener2) + p.link(listener3) + sleep(DELAY * 10) + self.assertIn(results, [[10, 20], [20, 10]]) + + p = gevent.spawn(lambda: getcurrent().throw(ExpectedError('test_multiple_listeners_error'))) + results = [] + p.link(listener1) + p.link(listener2) + p.link(listener3) + sleep(DELAY * 10) + self.assertIn(results, [[10, 20], [20, 10]]) + + class Results(object): + + def __init__(self): + self.results = [] + + def listener1(self, p): + p.unlink(self.listener2) + self.results.append(5) + raise ExpectedError('listener1') + + def listener2(self, p): + p.unlink(self.listener1) + self.results.append(5) + raise ExpectedError('listener2') + + def listener3(self, _p): + raise ExpectedError('listener3') + + def _test_multiple_listeners_error_unlink(self, _p, link): + # notification must not happen after unlink even + # though notification process has been already started + results = self.Results() + + link(results.listener1) + link(results.listener2) + link(results.listener3) + sleep(DELAY * 10) + self.assertEqual([5], results.results) + + + def test_multiple_listeners_error_unlink_Greenlet_link(self): + p = gevent.spawn(lambda: 5) + self._test_multiple_listeners_error_unlink(p, p.link) + p.kill() + + def test_multiple_listeners_error_unlink_Greenlet_rawlink(self): + p = gevent.spawn(lambda: 5) + self._test_multiple_listeners_error_unlink(p, p.rawlink) + + def test_multiple_listeners_error_unlink_AsyncResult_rawlink(self): + e = AsyncResult() + gevent.spawn(e.set, 6) + self._test_multiple_listeners_error_unlink(e, e.rawlink) + + +def dummy_test_func(*_args): + pass + + +class A(object): + + def method(self): + pass + +class Subclass(gevent.Greenlet): + pass + +class TestStr(greentest.TestCase): + + def test_function(self): + g = gevent.Greenlet.spawn(dummy_test_func) + self.assert_nstr_endswith(g, 'at X: dummy_test_func>') + self.assert_greenlet_not_ready(g) + g.join() + self.assert_greenlet_ready(g) + self.assert_nstr_endswith(g, 'at X: dummy_test_func>') + + + def test_method(self): + g = gevent.Greenlet.spawn(A().method) + self.assert_nstr_startswith(g, '>>') + self.assert_greenlet_not_ready(g) + g.join() + self.assert_greenlet_ready(g) + self.assert_nstr_endswith(g, 'at X: >>') + + def test_subclass(self): + g = Subclass() + self.assert_nstr_startswith(g, '') + + g = Subclass(None, 'question', answer=42) + self.assert_nstr_endswith(g, " at X: _run('question', answer=42)>") + + +class TestJoin(AbstractGenericWaitTestCase): + + def wait(self, timeout): + g = gevent.spawn(gevent.sleep, 10) + try: + return g.join(timeout=timeout) + finally: + g.kill() + + +class TestGet(AbstractGenericGetTestCase): + + def wait(self, timeout): + g = gevent.spawn(gevent.sleep, 10) + try: + return g.get(timeout=timeout) + finally: + g.kill() + + +class TestJoinAll0(AbstractGenericWaitTestCase): + + g = gevent.Greenlet() + + def wait(self, timeout): + gevent.joinall([self.g], timeout=timeout) + + +class TestJoinAll(AbstractGenericWaitTestCase): + + def wait(self, timeout): + g = gevent.spawn(gevent.sleep, 10) + try: + gevent.joinall([g], timeout=timeout) + finally: + g.kill() + + +class TestBasic(greentest.TestCase): + + def test_spawn_non_callable(self): + self.assertRaises(TypeError, gevent.spawn, 1) + self.assertRaises(TypeError, gevent.spawn_raw, 1) + + # Not passing the run argument, just the seconds argument + self.assertRaises(TypeError, gevent.spawn_later, 1) + # Passing both, but not implemented + self.assertRaises(TypeError, gevent.spawn_later, 1, 1) + + def test_spawn_raw_kwargs(self): + value = [] + + def f(*args, **kwargs): + value.append(args) + value.append(kwargs) + + g = gevent.spawn_raw(f, 1, name='value') + gevent.sleep(0.01) + self.assertFalse(g) + self.assertEqual(value[0], (1,)) + self.assertEqual(value[1], {'name': 'value'}) + + def test_simple_exit(self): + link_test = [] + + def func(delay, return_value=4): + gevent.sleep(delay) + return return_value + + g = gevent.Greenlet(func, 0.01, return_value=5) + g.rawlink(link_test.append) # use rawlink to avoid timing issues on Appveyor/Travis (not always successful) + self.assertFalse(g, g) + self.assertFalse(g.dead, g) + self.assertFalse(g.started, g) + self.assertFalse(g.ready(), g) + self.assertFalse(g.successful(), g) + self.assertIsNone(g.value, g) + self.assertIsNone(g.exception, g) + + g.start() + self.assertTrue(g, g) # changed + self.assertFalse(g.dead, g) + self.assertTrue(g.started, g) # changed + self.assertFalse(g.ready(), g) + self.assertFalse(g.successful(), g) + self.assertIsNone(g.value, g) + self.assertIsNone(g.exception, g) + + gevent.sleep(0.001) + self.assertTrue(g) + self.assertFalse(g.dead, g) + self.assertTrue(g.started, g) + self.assertFalse(g.ready(), g) + self.assertFalse(g.successful(), g) + self.assertIsNone(g.value, g) + self.assertIsNone(g.exception, g) + self.assertFalse(link_test) + + gevent.sleep(0.02) + self.assertFalse(g, g) # changed + self.assertTrue(g.dead, g) # changed + self.assertFalse(g.started, g) # changed + self.assertTrue(g.ready(), g) # changed + self.assertTrue(g.successful(), g) # changed + self.assertEqual(g.value, 5) # changed + self.assertIsNone(g.exception, g) + + self._check_flaky_eq(link_test, g) + + def _check_flaky_eq(self, link_test, g): + if not greentest.RUNNING_ON_CI: + # TODO: Change this to assertEqualFlakyRaceCondition and figure + # out what the CI issue is. + self.assertEqual(link_test, [g]) # changed + + def test_error_exit(self): + link_test = [] + + def func(delay, return_value=4): + gevent.sleep(delay) + error = ExpectedError('test_error_exit') + setattr(error, 'myattr', return_value) + raise error + + g = gevent.Greenlet(func, timing.SMALLEST_RELIABLE_DELAY, return_value=5) + # use rawlink to avoid timing issues on Appveyor (not always successful) + g.rawlink(link_test.append) + g.start() + gevent.sleep() + gevent.sleep(timing.LARGE_TICK) + self.assertFalse(g) + self.assertTrue(g.dead) + self.assertFalse(g.started) + self.assertTrue(g.ready()) + self.assertFalse(g.successful()) + self.assertIsNone(g.value) # not changed + self.assertEqual(g.exception.myattr, 5) + self._check_flaky_eq(link_test, g) + + def test_exc_info_no_error(self): + # Before running + self.assertFalse(greenlet.Greenlet().exc_info) + g = greenlet.Greenlet(gevent.sleep) + g.start() + g.join() + self.assertFalse(g.exc_info) + + @greentest.skipOnCI( + "Started getting a Fatal Python error on " + "Github Actions on 2020-12-18, even with recursion limits " + "in place. It was fine before that." + ) + def test_recursion_error(self): + # https://github.com/gevent/gevent/issues/1704 + # A RuntimeError: recursion depth exceeded + # does not break things. + # + # However, sometimes, on some interpreter versions on some + # systems, actually exhausting the stack results in "Fatal + # Python error: Cannot recover from stack overflow.". So we + # need to use a low recursion limit so that doesn't happen. + # Doesn't seem to help though. + # See https://github.com/gevent/gevent/runs/1577692901?check_suite_focus=true#step:21:46 + import sys + limit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, limit) + sys.setrecursionlimit(limit // 4) + def recur(): + recur() # This is expected to raise RecursionError + + errors = [] + def handle_error(glet, t, v, tb): + errors.append((glet, t, v, tb)) + + try: + gevent.get_hub().handle_error = handle_error + + g = gevent.spawn(recur) + def wait(): + return gevent.joinall([g]) + + g2 = gevent.spawn(wait) + + gevent.joinall([g2]) + finally: + del gevent.get_hub().handle_error + + try: + expected_exc = RecursionError + except NameError: + expected_exc = RuntimeError + with self.assertRaises(expected_exc): + g.get() + + self.assertFalse(g.successful()) + self.assertTrue(g.dead) + + self.assertTrue(errors) + self.assertEqual(1, len(errors)) + self.assertIs(errors[0][0], g) + self.assertEqual(errors[0][1], expected_exc) + del errors[:] + + + def test_tree_locals(self): + g = g2 = None + def func(): + child = greenlet.Greenlet() + self.assertIs(child.spawn_tree_locals, getcurrent().spawn_tree_locals) + self.assertIs(child.spawning_greenlet(), getcurrent()) + g = greenlet.Greenlet(func) + g2 = greenlet.Greenlet(func) + # Creating those greenlets did not give the main greenlet + # a locals dict. + self.assertFalse(hasattr(getcurrent(), 'spawn_tree_locals'), + getcurrent()) + self.assertIsNot(g.spawn_tree_locals, g2.spawn_tree_locals) + g.start() + g.join() + + raw = gevent.spawn_raw(func) + self.assertIsNotNone(raw.spawn_tree_locals) + self.assertIsNot(raw.spawn_tree_locals, g.spawn_tree_locals) + self.assertIs(raw.spawning_greenlet(), getcurrent()) + while not raw.dead: + gevent.sleep(0.01) + + def test_add_spawn_callback(self): + called = {'#': 0} + + def cb(gr): + called['#'] += 1 + gr._called_test = True + + gevent.Greenlet.add_spawn_callback(cb) + try: + g = gevent.spawn(lambda: None) + self.assertTrue(hasattr(g, '_called_test')) + g.join() + self.assertEqual(called['#'], 1) + + g = gevent.spawn_later(1e-5, lambda: None) + self.assertTrue(hasattr(g, '_called_test')) + g.join() + self.assertEqual(called['#'], 2) + + g = gevent.Greenlet(lambda: None) + g.start() + self.assertTrue(hasattr(g, '_called_test')) + g.join() + self.assertEqual(called['#'], 3) + + gevent.Greenlet.remove_spawn_callback(cb) + g = gevent.spawn(lambda: None) + self.assertFalse(hasattr(g, '_called_test')) + g.join() + self.assertEqual(called['#'], 3) + finally: + gevent.Greenlet.remove_spawn_callback(cb) + + def test_getframe_value_error(self): + def get(): + raise ValueError("call stack is not deep enough") + try: + ogf = greenlet.sys_getframe + except AttributeError: # pragma: no cover + # Must be running cython compiled + raise unittest.SkipTest("Cannot mock when Cython compiled") + greenlet.sys_getframe = get + try: + child = greenlet.Greenlet() + self.assertIsNone(child.spawning_stack) + finally: + greenlet.sys_getframe = ogf + + def test_minimal_ident_parent_not_hub(self): + + g = gevent.spawn(lambda: 1) + self.assertIs(g.parent, gevent.get_hub()) + g.parent = getcurrent() + try: + self.assertIsNot(g.parent, gevent.get_hub()) + + with self.assertRaisesRegex((TypeError, # Cython + AttributeError), # PyPy + 'Cannot convert|ident_registry'): + getattr(g, 'minimal_ident') + finally: + # Attempting to switch into this later, when we next cycle the + # loop, would raise an InvalidSwitchError if we don't put + # things back the way they were (or kill the greenlet) + g.parent = gevent.get_hub() + g.kill() + + +class TestKill(greentest.TestCase): + + def setUp(self): + super().setUp() + hub = gevent.get_hub() + patcher = Patch.object(hub, 'print_exception', autospec=True) + patcher.start() + self.addCleanup(patcher.stop) + + + def __assertKilled(self, g, successful): + self.assertFalse(g) + self.assertTrue(g.dead) + self.assertFalse(g.started) + self.assertTrue(g.ready()) + if successful: + self.assertTrue(g.successful(), (repr(g), g.value, g.exception)) + self.assertIsInstance(g.value, gevent.GreenletExit) + self.assertIsNone(g.exception) + else: + self.assertFalse(g.successful(), (repr(g), g.value, g.exception)) + self.assertNotIsInstance(g.value, gevent.GreenletExit) + self.assertIsNotNone(g.exception) + + def assertKilled(self, g, successful=True): + self.__assertKilled(g, successful) + gevent.sleep(0.01) # spin the loop to make sure it doesn't run. + self.__assertKilled(g, successful) + + def __kill_greenlet(self, g, block, killall, exc=None): + if exc is None: + exc = gevent.GreenletExit + if killall: + killer = functools.partial(gevent.killall, [g], + exception=exc, block=block) + else: + killer = functools.partial(g.kill, exception=exc, block=block) + killer() + if not block: + # Must spin the loop to take effect (if it was scheduled) + gevent.sleep(timing.SMALLEST_RELIABLE_DELAY) + + successful = exc is None or (isinstance(exc, type) and issubclass(exc, gevent.GreenletExit)) + self.assertKilled(g, successful) + # kill second time must not hurt + killer() + self.assertKilled(g, successful) + + @staticmethod + def _run_in_greenlet(result_collector): + result_collector.append(1) + + def _start_greenlet(self, g): + """ + Subclasses should override. This doesn't actually start a greenlet. + """ + + _after_kill_greenlet = _start_greenlet + + + def _do_test(self, block, killall, exc=None): + link_test = [] + result = [] + g = gevent.Greenlet(self._run_in_greenlet, result) + g.link(link_test.append) + + self._start_greenlet(g) + + self.__kill_greenlet(g, block, killall, exc) + + self._after_kill_greenlet(g) + + self.assertFalse(result) + self.assertEqual(link_test, [g]) + + def test_block(self): + self._do_test(block=True, killall=False) + + def test_non_block(self): + self._do_test(block=False, killall=False) + + def test_block_killall(self): + self._do_test(block=True, killall=True) + + def test_non_block_killal(self): + self._do_test(block=False, killall=True) + + def test_non_type_exception(self): + self._do_test(block=True, killall=False, exc=Exception()) + + def test_non_type_exception_non_block(self): + self._do_test(block=False, killall=False, exc=Exception()) + + def test_non_type_exception_killall(self): + self._do_test(block=True, killall=True, exc=Exception()) + + def test_non_type_exception_killall_non_block(self): + self._do_test(block=False, killall=True, exc=Exception()) + + def test_non_exc_exception(self): + self._do_test(block=True, killall=False, exc=42) + + def test_non_exc_exception_non_block(self): + self._do_test(block=False, killall=False, exc=42) + + def test_non_exc_exception_killall(self): + self._do_test(block=True, killall=True, exc=42) + + def test_non_exc_exception_killall_non_block(self): + self._do_test(block=False, killall=True, exc=42) + + +class TestKillAfterStart(TestKill): + + def _start_greenlet(self, g): + g.start() + +class TestKillAfterStartLater(TestKill): + + def _start_greenlet(self, g): + g.start_later(timing.LARGE_TICK) + +class TestKillWhileRunning(TestKill): + + @staticmethod + def _run_in_greenlet(result_collector): + gevent.sleep(10) + # The above should die with the GreenletExit exception, + # so this should never run + TestKill._run_in_greenlet(result_collector) + + def _after_kill_greenlet(self, g): + TestKill._after_kill_greenlet(self, g) + gevent.sleep(0.01) + +class TestKillallRawGreenlet(greentest.TestCase): + + def test_killall_raw(self): + g = gevent.spawn_raw(lambda: 1) + gevent.killall([g]) + + +class TestContextManager(greentest.TestCase): + + def test_simple(self): + with gevent.spawn(gevent.sleep, timing.SMALL_TICK) as g: + self.assert_greenlet_spawned(g) + # It is completed after the suite + self.assert_greenlet_finished(g) + + def test_wait_in_suite(self): + with gevent.spawn(self._raise_exception) as g: + with self.assertRaises(greentest.ExpectedException): + g.get() + self.assert_greenlet_finished(g) + + @staticmethod + def _raise_exception(): + raise greentest.ExpectedException + + def test_greenlet_raises(self): + with gevent.spawn(self._raise_exception) as g: + pass + + self.assert_greenlet_finished(g) + with self.assertRaises(greentest.ExpectedException): + g.get() + + def test_join_raises(self): + suite_ran = 0 + with self.assertRaises(ExpectedJoinError): + with GreenletRaisesJoin.spawn(gevent.sleep, timing.SMALL_TICK) as g: + self.assert_greenlet_spawned(g) + suite_ran = 1 + + self.assertTrue(suite_ran) + self.assert_greenlet_finished(g) + self.assertTrue(g.killed) + + def test_suite_body_raises(self, delay=None): + greenlet_sleep = timing.SMALL_TICK if not delay else timing.LARGE_TICK + with self.assertRaises(SuiteExpectedException): + with GreenletRaisesJoin.spawn(gevent.sleep, greenlet_sleep) as g: + self.assert_greenlet_spawned(g) + if delay: + g.raise_on_join = False + gevent.sleep(delay) + raise SuiteExpectedException + + self.assert_greenlet_finished(g) + self.assertTrue(g.killed) + if delay: + self.assertTrue(g.joined) + else: + self.assertFalse(g.joined) + self.assertFalse(g.successful()) + + with self.assertRaises(SuiteExpectedException): + g.get() + + def test_suite_body_raises_with_delay(self): + self.test_suite_body_raises(delay=timing.SMALL_TICK) + +class TestStart(greentest.TestCase): + + def test_start(self): + g = gevent.spawn(gevent.sleep, timing.SMALL_TICK) + self.assert_greenlet_spawned(g) + + g.start() + self.assert_greenlet_started(g) + + g.join() + self.assert_greenlet_finished(g) + + # cannot start again + g.start() + self.assert_greenlet_finished(g) + + +class TestRef(greentest.TestCase): + + def test_init(self): + self.switch_expected = False + # in python-dbg mode this will check that Greenlet() does not create any circular refs + gevent.Greenlet() + + def test_kill_scheduled(self): + gevent.spawn(gevent.sleep, timing.LARGE_TICK).kill() + + def test_kill_started(self): + g = gevent.spawn(gevent.sleep, timing.LARGE_TICK) + try: + gevent.sleep(timing.SMALLEST_RELIABLE_DELAY) + finally: + g.kill() + + +@greentest.skipOnPurePython("Needs C extension") +class TestCExt(greentest.TestCase): # pragma: no cover (we only do coverage on pure-Python) + + def test_c_extension(self): + self.assertEqual(greenlet.Greenlet.__module__, + 'gevent._gevent_cgreenlet') + self.assertEqual(greenlet.SpawnedLink.__module__, + 'gevent._gevent_cgreenlet') + +@greentest.skipWithCExtensions("Needs pure python") +class TestPure(greentest.TestCase): + + def test_pure(self): + self.assertEqual(greenlet.Greenlet.__module__, + 'gevent.greenlet') + self.assertEqual(greenlet.SpawnedLink.__module__, + 'gevent.greenlet') + + +X = object() + +del AbstractGenericGetTestCase +del AbstractGenericWaitTestCase + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenletset.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenletset.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d544f027efaae2bcb6d65ff4fdd86bbd501dad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenletset.py @@ -0,0 +1,183 @@ +from __future__ import print_function, division, absolute_import +import time +import gevent.testing as greentest + +from gevent.testing import timing +import gevent +from gevent import pool +from gevent.timeout import Timeout + +DELAY = timing.LARGE_TICK + + +class SpecialError(Exception): + pass + + +class Undead(object): + + def __init__(self): + self.shot_count = 0 + + def __call__(self): + while True: + try: + gevent.sleep(1) + except SpecialError: + break + except: # pylint:disable=bare-except + self.shot_count += 1 + + +class Test(greentest.TestCase): + + __timeout__ = greentest.LARGE_TIMEOUT + + def test_basic(self): + s = pool.Group() + s.spawn(gevent.sleep, timing.LARGE_TICK) + self.assertEqual(len(s), 1, s) + s.spawn(gevent.sleep, timing.LARGE_TICK * 5) + self.assertEqual(len(s), 2, s) + gevent.sleep() + gevent.sleep(timing.LARGE_TICK * 2 + timing.LARGE_TICK_MIN_ADJ) + self.assertEqual(len(s), 1, s) + gevent.sleep(timing.LARGE_TICK * 5 + timing.LARGE_TICK_MIN_ADJ) + self.assertFalse(s) + + def test_waitall(self): + s = pool.Group() + s.spawn(gevent.sleep, DELAY) + s.spawn(gevent.sleep, DELAY * 2) + assert len(s) == 2, s + start = time.time() + s.join(raise_error=True) + delta = time.time() - start + self.assertFalse(s) + self.assertEqual(len(s), 0) + self.assertTimeWithinRange(delta, DELAY * 1.9, DELAY * 2.5) + + def test_kill_block(self): + s = pool.Group() + s.spawn(gevent.sleep, DELAY) + s.spawn(gevent.sleep, DELAY * 2) + assert len(s) == 2, s + start = time.time() + s.kill() + self.assertFalse(s) + self.assertEqual(len(s), 0) + delta = time.time() - start + assert delta < DELAY * 0.8, delta + + def test_kill_noblock(self): + s = pool.Group() + s.spawn(gevent.sleep, DELAY) + s.spawn(gevent.sleep, DELAY * 2) + assert len(s) == 2, s + s.kill(block=False) + assert len(s) == 2, s + gevent.sleep(0.0001) + self.assertFalse(s) + self.assertEqual(len(s), 0) + + def test_kill_fires_once(self): + u1 = Undead() + u2 = Undead() + p1 = gevent.spawn(u1) + p2 = gevent.spawn(u2) + + def check(count1, count2): + self.assertTrue(p1) + self.assertTrue(p2) + self.assertFalse(p1.dead, p1) + self.assertFalse(p2.dead, p2) + self.assertEqual(u1.shot_count, count1) + self.assertEqual(u2.shot_count, count2) + + gevent.sleep(0.01) + s = pool.Group([p1, p2]) + self.assertEqual(len(s), 2, s) + check(0, 0) + s.killone(p1, block=False) + check(0, 0) + gevent.sleep(0) + check(1, 0) + s.killone(p1) + check(1, 0) + s.killone(p1) + check(1, 0) + s.kill(block=False) + s.kill(block=False) + s.kill(block=False) + check(1, 0) + gevent.sleep(DELAY) + check(1, 1) + X = object() + kill_result = gevent.with_timeout(DELAY, s.kill, block=True, timeout_value=X) + assert kill_result is X, repr(kill_result) + assert len(s) == 2, s + check(1, 1) + + p1.kill(SpecialError) + p2.kill(SpecialError) + + def test_killall_subclass(self): + p1 = GreenletSubclass.spawn(lambda: 1 / 0) + p2 = GreenletSubclass.spawn(lambda: gevent.sleep(10)) + s = pool.Group([p1, p2]) + s.kill() + + def test_killall_iterable_argument_non_block(self): + p1 = GreenletSubclass.spawn(lambda: gevent.sleep(0.5)) + p2 = GreenletSubclass.spawn(lambda: gevent.sleep(0.5)) + s = set() + s.add(p1) + s.add(p2) + gevent.killall(s, block=False) + gevent.sleep(0.5) + for g in s: + assert g.dead + + def test_killall_iterable_argument_timeout_not_started(self): + def f(): + try: + gevent.sleep(1.5) + except: # pylint:disable=bare-except + gevent.sleep(1) + p1 = GreenletSubclass.spawn(f) + p2 = GreenletSubclass.spawn(f) + s = set() + s.add(p1) + s.add(p2) + gevent.killall(s, timeout=0.5) + + for g in s: + self.assertTrue(g.dead, g) + + def test_killall_iterable_argument_timeout_started(self): + def f(): + try: + gevent.sleep(1.5) + except: # pylint:disable=bare-except + gevent.sleep(1) + p1 = GreenletSubclass.spawn(f) + p2 = GreenletSubclass.spawn(f) + + s = set() + s.add(p1) + s.add(p2) + # Get them both running. + gevent.sleep(timing.SMALLEST_RELIABLE_DELAY) + with self.assertRaises(Timeout): + gevent.killall(s, timeout=0.5) + + for g in s: + self.assertFalse(g.dead, g) + + +class GreenletSubclass(gevent.Greenlet): + pass + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenness.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenness.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0cb1fa2d79b18fad89b07b43f20a580066f1a1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__greenness.py @@ -0,0 +1,87 @@ +# Copyright (c) 2008 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +""" +Trivial test that a single process (and single thread) can both read +and write from green sockets (when monkey patched). +""" +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division + +from gevent import monkey +monkey.patch_all() + + +import gevent.testing as greentest + +try: + from urllib import request as urllib2 + from http.server import HTTPServer + from http.server import SimpleHTTPRequestHandler +except ImportError: + # Python 2 + import urllib2 + from BaseHTTPServer import HTTPServer + from SimpleHTTPServer import SimpleHTTPRequestHandler + + +import gevent +from gevent.testing import params + +class QuietHandler(SimpleHTTPRequestHandler, object): + + def log_message(self, *args): # pylint:disable=arguments-differ + self.server.messages += ((args,),) + +class Server(HTTPServer, object): + + messages = () + requests_handled = 0 + + def __init__(self): + HTTPServer.__init__(self, + params.DEFAULT_BIND_ADDR_TUPLE, + QuietHandler) + + def handle_request(self): + HTTPServer.handle_request(self) + self.requests_handled += 1 + + +class TestGreenness(greentest.TestCase): + check_totalrefcount = False + + def test_urllib2(self): + httpd = Server() + server_greenlet = gevent.spawn(httpd.handle_request) + + port = httpd.socket.getsockname()[1] + rsp = urllib2.urlopen('http://127.0.0.1:%s' % port) + rsp.read() + rsp.close() + server_greenlet.join() + self.assertEqual(httpd.requests_handled, 1) + httpd.server_close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub.py new file mode 100644 index 0000000000000000000000000000000000000000..4c29df7398e6c63165c684890a10247dfbe5dce1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub.py @@ -0,0 +1,404 @@ +# Copyright (c) 2009 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import re +import time +import unittest + +import gevent.testing as greentest +import gevent.testing.timing + +import gevent +from gevent import socket +from gevent.hub import Waiter, get_hub +from gevent._compat import NativeStrIO +from gevent._compat import get_this_psutil_process + +DELAY = 0.1 + + +class TestCloseSocketWhilePolling(greentest.TestCase): + + def test(self): + sock = socket.socket() + self._close_on_teardown(sock) + t = get_hub().loop.timer(0) + t.start(sock.close) + with self.assertRaises(socket.error): + try: + sock.connect(('python.org', 81)) + finally: + t.close() + + gevent.sleep(0) + + +class TestExceptionInMainloop(greentest.TestCase): + + def test_sleep(self): + # even if there was an error in the mainloop, the hub should continue to work + start = time.time() + gevent.sleep(DELAY) + delay = time.time() - start + + delay_range = DELAY * 0.9 + self.assertTimeWithinRange(delay, DELAY - delay_range, DELAY + delay_range) + + error = greentest.ExpectedException('TestExceptionInMainloop.test_sleep/fail') + + def fail(): + raise error + + with get_hub().loop.timer(0.001) as t: + t.start(fail) + + self.expect_one_error() + + start = time.time() + gevent.sleep(DELAY) + delay = time.time() - start + + self.assert_error(value=error) + self.assertTimeWithinRange(delay, DELAY - delay_range, DELAY + delay_range) + + + +class TestSleep(gevent.testing.timing.AbstractGenericWaitTestCase): + + def wait(self, timeout): + gevent.sleep(timeout) + + def test_simple(self): + gevent.sleep(0) + + +class TestWaiterGet(gevent.testing.timing.AbstractGenericWaitTestCase): + + def setUp(self): + super(TestWaiterGet, self).setUp() + self.waiter = Waiter() + + def wait(self, timeout): + with get_hub().loop.timer(timeout) as evt: + evt.start(self.waiter.switch, None) + return self.waiter.get() + + +class TestWaiter(greentest.TestCase): + + def test(self): + waiter = Waiter() + self.assertEqual(str(waiter), '') + waiter.switch(25) + self.assertEqual(str(waiter), '') + self.assertEqual(waiter.get(), 25) + + waiter = Waiter() + waiter.throw(ZeroDivisionError) + assert re.match('^ count_before: + # We could be off by exactly 1. Not entirely clear where. + # But it only happens the first time. + count_after -= 1 + # If we were run in multiple process, our count could actually have + # gone down due to the GC's we did. + self.assertEqual(count_after, count_before) + + @ignores_leakcheck + def test_join_in_new_thread_doesnt_leak_hub_or_greenlet(self): + # https://github.com/gevent/gevent/issues/1601 + import threading + clean = self.__clean + + def thread_main(): + g = gevent.Greenlet(run=lambda: 0) + g.start() + g.join() + hub = gevent.get_hub() + hub.join() + hub.destroy(destroy_loop=True) + del hub + + def tester(main): + t = threading.Thread(target=main) + t.start() + t.join() + + clean() + + with self.assert_no_greenlet_growth(): + for _ in range(10): + tester(thread_main) + + del tester + del thread_main + + @ignores_leakcheck + def test_destroy_in_main_thread_from_new_thread(self): + # https://github.com/gevent/gevent/issues/1631 + import threading + + clean = self.__clean + class Thread(threading.Thread): + hub = None + def run(self): + g = gevent.Greenlet(run=lambda: 0) + g.start() + g.join() + del g + hub = gevent.get_hub() + hub.join() + self.hub = hub + + def tester(Thread, clean): + t = Thread() + t.start() + t.join() + t.hub.destroy(destroy_loop=True) + t.hub = None + del t + clean() + + # Unfortunately, this WILL leak greenlets, + # at least on CPython. The frames of the dead threads + # are referenced by the hub in some sort of cycle, and + # greenlets don't particpate in GC. + for _ in range(10): + tester(Thread, clean) + + del tester + del Thread + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub_join_timeout.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub_join_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..b80457a41343c463ec5c1b685c1cecba0ddb443e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__hub_join_timeout.py @@ -0,0 +1,99 @@ +import functools +import unittest + +import gevent +import gevent.core +from gevent.event import Event + +from gevent.testing.testcase import TimeAssertMixin + +SMALL_TICK = 0.05 + +# setting up signal does not affect join() +gevent.signal_handler(1, lambda: None) # wouldn't work on windows + + +def repeated(func, repetitions=2): + @functools.wraps(func) + def f(self): + for _ in range(repetitions): + func(self) + return f + +class Test(TimeAssertMixin, unittest.TestCase): + + @repeated + def test_callback(self): + # exiting because the spawned greenlet finished execution (spawn (=callback) variant) + x = gevent.spawn(lambda: 5) + with self.runs_in_no_time(): + result = gevent.wait(timeout=10) + self.assertTrue(result) + self.assertTrue(x.dead, x) + self.assertEqual(x.value, 5) + + @repeated + def test_later(self): + # exiting because the spawned greenlet finished execution (spawn_later (=timer) variant) + x = gevent.spawn_later(SMALL_TICK, lambda: 5) + with self.runs_in_given_time(SMALL_TICK): + result = gevent.wait(timeout=10) + self.assertTrue(result) + self.assertTrue(x.dead, x) + + @repeated + def test_timeout(self): + # exiting because of timeout (the spawned greenlet still runs) + x = gevent.spawn_later(10, lambda: 5) + with self.runs_in_given_time(SMALL_TICK): + result = gevent.wait(timeout=SMALL_TICK) + self.assertFalse(result) + self.assertFalse(x.dead, x) + x.kill() + with self.runs_in_no_time(): + result = gevent.wait() + + self.assertTrue(result) + + @repeated + def test_event(self): + # exiting because of event (the spawned greenlet still runs) + x = gevent.spawn_later(10, lambda: 5) + event = Event() + event_set = gevent.spawn_later(SMALL_TICK, event.set) + with self.runs_in_given_time(SMALL_TICK): + result = gevent.wait([event]) + self.assertEqual(result, [event]) + self.assertFalse(x.dead, x) + self.assertTrue(event_set.dead) + self.assertTrue(event.is_set) + x.kill() + with self.runs_in_no_time(): + result = gevent.wait() + + self.assertTrue(result) + + @repeated + def test_ref_arg(self): + # checking "ref=False" argument + gevent.get_hub().loop.timer(10, ref=False).start(lambda: None) + with self.runs_in_no_time(): + result = gevent.wait() + self.assertTrue(result) + + @repeated + def test_ref_attribute(self): + # checking "ref=False" attribute + w = gevent.get_hub().loop.timer(10) + w.start(lambda: None) + w.ref = False + with self.runs_in_no_time(): + result = gevent.wait() + self.assertTrue(result) + + +class TestAgain(Test): + "Repeat the same tests" + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_blocking_in_greenlet.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_blocking_in_greenlet.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf0a1134bc28502e07ddb49f868c8595bcf4810 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_blocking_in_greenlet.py @@ -0,0 +1,42 @@ +#!/usr/bin/python +# See https://github.com/gevent/gevent/issues/108 +import gevent +from gevent import monkey + +import_errors = [] + + +def some_func(): + try: + from _blocks_at_top_level import x + assert x == 'done' + except ImportError as e: + import_errors.append(e) + raise + +if __name__ == '__main__': + import sys + if sys.version_info[:2] == (3, 13): + import unittest + class Test(unittest.TestCase): + def test_it(self): + self.skipTest( + 'On Python 3.13, no matter how I arrange the PYTHONPATH/sys.path ' + 'we get "cannot import name x from partially initialized module ' + '_blocks_at_top_level". It is unclear why. Limiting the scope of ' + 'the exclusion for now.' + ) + unittest.main() + else: + + monkey.patch_all() + import sys + import os + p = os.path.dirname(__file__) + sys.path.insert(0, p) + + + gs = [gevent.spawn(some_func) for i in range(2)] + gevent.joinall(gs) + + assert not import_errors, import_errors diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_wait.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_wait.py new file mode 100644 index 0000000000000000000000000000000000000000..e0856599338659f72604bf8cccada5ade17653a2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__import_wait.py @@ -0,0 +1,10 @@ +# https://github.com/gevent/gevent/issues/652 and 651 +from gevent import monkey +monkey.patch_all() + +try: + import _import_wait # pylint:disable=import-error +except ModuleNotFoundError: + from gevent.tests import _import_wait + +assert _import_wait.x diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue112.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue112.py new file mode 100644 index 0000000000000000000000000000000000000000..df2be0c1b6b551c47c4edc6e936aa75ff65fff90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue112.py @@ -0,0 +1,19 @@ +import sys +import unittest +import threading +import gevent +import gevent.monkey +gevent.monkey.patch_all() + + +@unittest.skipUnless( + sys.version_info[0] == 2, + "Only on Python 2" +) +class Test(unittest.TestCase): + + def test(self): + self.assertIs(threading._sleep, gevent.sleep) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1686.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1686.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb1893e8f613bb85cda9d1d909b12609d954e20 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1686.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +""" +Tests for https://github.com/gevent/gevent/issues/1686 +which is about destroying a hub when there are active +callbacks or IO in operation. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import unittest + +from gevent import testing as greentest + +# Don't let the testrunner put us in a process with other +# tests; we are strict on the state of the hub and greenlets. +# pragma: testrunner-no-combine + +@greentest.skipOnWindows("Uses os.fork") +class TestDestroyInChildWithActiveSpawn(unittest.TestCase): + + def test(self): # pylint:disable=too-many-locals + # If this test is broken, there are a few failure modes. + # - In the original examples, the parent process just hangs, because the + # child has raced ahead, spawned the greenlet and read the data. When the + # greenlet goes to read in the parent, it blocks, and the hub and loop + # wait for it. + # - Here, our child detects the greenlet ran when it shouldn't and + # raises an error, which translates to a non-zero exit status, + # which the parent checks for and fails by raising an exception before + # returning control to the hub. We can replicate the hang by removing the + # assertion in the child. + from time import sleep as hang + + from gevent import get_hub + from gevent import spawn + from gevent.socket import wait_read + from gevent.os import nb_read + from gevent.os import nb_write + from gevent.os import make_nonblocking + from gevent.os import fork + from gevent.os import waitpid + + pipe_read_fd, pipe_write_fd = os.pipe() + make_nonblocking(pipe_read_fd) + make_nonblocking(pipe_write_fd) + + run = [] + + def reader(): + run.append(1) + return nb_read(pipe_read_fd, 4096) + + # Put data in the pipe + DATA = b'test' + nb_write(pipe_write_fd, DATA) + # Make sure we're ready to read it + wait_read(pipe_read_fd) + + # Schedule a greenlet to start + reader = spawn(reader) + + hub = get_hub() + pid = fork() + if pid == 0: + # Child destroys the hub. The reader should not have run. + hub.destroy(destroy_loop=True) + self.assertFalse(run) + os._exit(0) + return # pylint:disable=unreachable + + # The parent. + # Briefly prevent us from spinning our event loop. + hang(0.5) + wait_child_result = waitpid(pid, 0) + self.assertEqual(wait_child_result, (pid, 0)) + # We should get the data; the greenlet only runs in the parent. + data = reader.get() + self.assertEqual(run, [1]) + self.assertEqual(data, DATA) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1864.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1864.py new file mode 100644 index 0000000000000000000000000000000000000000..dccef302a782a481757d9d1018ffee5ddc0534cc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue1864.py @@ -0,0 +1,28 @@ +import sys +import unittest +from gevent import testing as greentest + + +class TestSubnormalFloatsAreNotDisabled(unittest.TestCase): + + @greentest.skipOnCI('Some of our tests we compile with -Ofast, which breaks this.') + def test_subnormal_is_not_zero(self): + # Enabling the -Ofast compiler flag resulted in subnormal floats getting + # disabled the moment when gevent was imported. This impacted libraries + # that expect subnormal floats to be enabled. + # + # NOTE: This test is supposed to catch that. It doesn't seem to work perfectly, though. + # The test passes under Python 2 on macOS no matter whether -ffast-math is given or not; + # perhaps this is a difference in clang vs gcc? In contrast, the test on Python 2.7 always + # *fails* on GitHub actions (in both CPython 2.7 and PyPy). We're far past the EOL of + # Python 2.7 so I'm not going to spend much time investigating. + __import__('gevent') + + # `sys.float_info.min` is the minimum representable positive normalized + # float, so dividing it by two gives us a positive subnormal float, + # as long as subnormals floats are not disabled. + self.assertGreater(sys.float_info.min / 2, 0.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue230.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue230.py new file mode 100644 index 0000000000000000000000000000000000000000..d17582c7a50a095088f5f94f31706e5868f66f63 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue230.py @@ -0,0 +1,27 @@ +import gevent.monkey +gevent.monkey.patch_all() + +import socket +import multiprocessing + +from gevent import testing as greentest + +# Make sure that using the resolver in a forked process +# doesn't hang forever. + + +def block(): + socket.getaddrinfo('localhost', 8001) + + + +class Test(greentest.TestCase): + def test(self): + socket.getaddrinfo('localhost', 8001) + + p = multiprocessing.Process(target=block) + p.start() + p.join() + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue330.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue330.py new file mode 100644 index 0000000000000000000000000000000000000000..5005ed6ac0736f043e23f91a1bd10f0781cd1504 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue330.py @@ -0,0 +1,82 @@ +# A greenlet that's killed before it is ever started +# should never be switched to +import gevent +import gevent.testing as greentest + + +class MyException(Exception): + pass + +class TestSwitch(greentest.TestCase): + + def setUp(self): + super(TestSwitch, self).setUp() + self.switched_to = [False, False] + self.caught = None + + def should_never_run(self, i): # pragma: no cover + self.switched_to[i] = True + + def check(self, g, g2): + gevent.joinall((g, g2)) + self.assertEqual([False, False], self.switched_to) + + # They both have a GreenletExit as their value + self.assertIsInstance(g.value, gevent.GreenletExit) + self.assertIsInstance(g2.value, gevent.GreenletExit) + + # They both have no reported exc_info + self.assertIsNone(g.exc_info) + self.assertIsNone(g2.exc_info) + self.assertIsNone(g.exception) + self.assertIsNone(g2.exception) + + + def test_gevent_kill(self): + g = gevent.spawn(self.should_never_run, 0) # create but do not switch to + g2 = gevent.spawn(self.should_never_run, 1) # create but do not switch to + # Using gevent.kill + gevent.kill(g) + gevent.kill(g2) + self.check(g, g2) + + def test_greenlet_kill(self): + # killing directly + g = gevent.spawn(self.should_never_run, 0) + g2 = gevent.spawn(self.should_never_run, 1) + g.kill() + g2.kill() + self.check(g, g2) + + def test_throw(self): + # throwing + g = gevent.spawn(self.should_never_run, 0) + g2 = gevent.spawn(self.should_never_run, 1) + g.throw(gevent.GreenletExit) + g2.throw(gevent.GreenletExit) + self.check(g, g2) + + + def catcher(self): + try: + while True: + gevent.sleep(0) + except MyException as e: + self.caught = e + + def test_kill_exception(self): + # Killing with gevent.kill gets the right exception, + # and we can pass exception objects, not just exception classes. + + g = gevent.spawn(self.catcher) + g.start() + gevent.sleep() + gevent.kill(g, MyException()) + gevent.sleep() + + self.assertIsInstance(self.caught, MyException) + self.assertIsNone(g.exception, MyException) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue467.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue467.py new file mode 100644 index 0000000000000000000000000000000000000000..abee04fbf1af64444fa88737ba056e46099dbf9e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue467.py @@ -0,0 +1,40 @@ +import gevent +from gevent import testing as greentest + +#import socket # on windows + +# iwait should not raise `LoopExit: This operation would block forever` +# or `AssertionError: Invalid switch into ...` +# if the caller of iwait causes greenlets to switch in between +# return values + + +def worker(i): + # Have one of them raise an exception to test that case + if i == 2: + raise ValueError(i) + return i + +class Test(greentest.TestCase): + def test(self): + finished = 0 + # Wait on a group that includes one that will already be + # done, plus some that will finish as we watch + done_worker = gevent.spawn(worker, "done") + gevent.joinall((done_worker,)) + + workers = [gevent.spawn(worker, i) for i in range(3)] + workers.append(done_worker) + for _ in gevent.iwait(workers): + finished += 1 + # Simulate doing something that causes greenlets to switch; + # a non-zero timeout is crucial + try: + gevent.sleep(0.01) + except ValueError as ex: + self.assertEqual(ex.args[0], 2) + + self.assertEqual(finished, 4) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue6.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue6.py new file mode 100644 index 0000000000000000000000000000000000000000..8faaf1e15466624f54db633a91ff8f650ad436d6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue6.py @@ -0,0 +1,39 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division + +import sys + +if not sys.argv[1:]: + from subprocess import Popen, PIPE + # not on Py2 pylint:disable=consider-using-with + p = Popen([sys.executable, __file__, 'subprocess'], stdin=PIPE, stdout=PIPE, stderr=PIPE) + out, err = p.communicate(b'hello world\n') + code = p.poll() + assert p.poll() == 0, (out, err, code) + assert out.strip() == b'11 chars.', (out, err, code) + # XXX: This is seen sometimes to fail on Travis with the following value in err but a code of 0; + # it seems load related: + # 'Unhandled exception in thread started by \nsys.excepthook is missing\nlost sys.stderr\n'. + # If warnings are enabled, Python 3 has started producing this: + # '...importlib/_bootstrap.py:219: ImportWarning: can't resolve package from __spec__ + # or __package__, falling back on __name__ and __path__\n return f(*args, **kwds)\n' + assert err == b'' or b'sys.excepthook' in err or b'Warning' in err, (out, err, code) + +elif sys.argv[1:] == ['subprocess']: # pragma: no cover + import gevent + import gevent.monkey + gevent.monkey.patch_all(sys=True) + + def printline(): + try: + line = raw_input() + except NameError: + line = input() # pylint:disable=bad-builtin + print('%s chars.' % len(line)) + sys.stdout.flush() + + gevent.spawn(printline).join() + +else: # pragma: no cover + sys.exit('Invalid arguments: %r' % (sys.argv, )) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue600.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue600.py new file mode 100644 index 0000000000000000000000000000000000000000..19d10ed3daf720c7a2c93aced3dbb4864510b0d1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue600.py @@ -0,0 +1,48 @@ +# Make sure that libev child watchers, implicitly installed through the use +# of subprocess, do not cause waitpid() to fail to poll for processes. +# NOTE: This was only reproducible under python 2. +from __future__ import print_function +import gevent +from gevent import monkey +monkey.patch_all() + +import sys +from multiprocessing import Process +from subprocess import Popen, PIPE + +from gevent import testing as greentest + +def f(sleep_sec): + gevent.sleep(sleep_sec) + + + +class TestIssue600(greentest.TestCase): + + __timeout__ = greentest.LARGE_TIMEOUT + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_invoke(self): + # Run a subprocess through Popen to make sure + # libev is handling SIGCHLD. This could *probably* be simplified to use + # just hub.loop.install_sigchld + # (no __enter__/__exit__ on Py2) pylint:disable=consider-using-with + p = Popen([sys.executable, '-V'], stdout=PIPE, stderr=PIPE) + gevent.sleep(0) + p.communicate() + gevent.sleep(0) + + def test_process(self): + # Launch + p = Process(target=f, args=(0.5,)) + p.start() + + with gevent.Timeout(3): + # Poll for up to 10 seconds. If the bug exists, + # this will timeout because our subprocess should + # be long gone by now + p.join(10) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue607.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue607.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ab1c5845c1c52879d714c661a319dbe9b2e239 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue607.py @@ -0,0 +1,47 @@ +# A greenlet that's killed with an exception should fail. +import gevent.testing as greentest +import gevent + + +class ExpectedError(greentest.ExpectedException): + pass + + +def f(): + gevent.sleep(999) + + +class TestKillWithException(greentest.TestCase): + + def test_kill_without_exception(self): + g = gevent.spawn(f) + g.kill() + assert g.successful() + assert isinstance(g.get(), gevent.GreenletExit) + + def test_kill_with_exception(self): + # issue-607 pointed this case. + g = gevent.spawn(f) + with gevent.get_hub().ignoring_expected_test_error(): + # Hmm, this only needs the `with ignoring...` in + # PURE_PYTHON mode (or PyPy). + g.kill(ExpectedError) + self.assertFalse(g.successful()) + self.assertRaises(ExpectedError, g.get) + self.assertIsNone(g.value) + self.assertIsInstance(g.exception, ExpectedError) + + def test_kill_with_exception_after_started(self): + with gevent.get_hub().ignoring_expected_test_error(): + g = gevent.spawn(f) + g.join(0) + g.kill(ExpectedError) + + self.assertFalse(g.successful()) + self.assertRaises(ExpectedError, g.get) + self.assertIsNone(g.value) + self.assertIsInstance(g.exception, ExpectedError) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue639.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue639.py new file mode 100644 index 0000000000000000000000000000000000000000..935cab3c0dcb1424c6c93055390e2e2a8cf1b89e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue639.py @@ -0,0 +1,12 @@ +# Test idle +import gevent + +from gevent import testing as greentest + +class Test(greentest.TestCase): + def test(self): + gevent.sleep() + gevent.idle() + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue_728.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue_728.py new file mode 100644 index 0000000000000000000000000000000000000000..fc61fc2a38669010a0759dbd00e16da3500c4cab --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issue_728.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python +from gevent.monkey import patch_all +patch_all() + + +if __name__ == '__main__': + # Reproducing #728 requires a series of nested + # imports + __import__('_imports_imports_at_top_level') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issues461_471.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issues461_471.py new file mode 100644 index 0000000000000000000000000000000000000000..c7208da3e871a0f7036d47d180c8195977469ba6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__issues461_471.py @@ -0,0 +1,95 @@ +'''Test for GitHub issues 461 and 471. + +When moving to Python 3, handling of KeyboardInterrupt exceptions caused +by a Ctrl-C raised an exception while printing the traceback for a +greenlet preventing the process from exiting. This test tests for proper +handling of KeyboardInterrupt. +''' + +import sys + +if sys.argv[1:] == ['subprocess']: # pragma: no cover + import gevent + + def task(): + sys.stdout.write('ready\n') + sys.stdout.flush() + gevent.sleep(30) + + try: + gevent.spawn(task).get() + except KeyboardInterrupt: + pass + + sys.exit(0) + +else: + import signal + from subprocess import Popen, PIPE + import time + + import unittest + import gevent.testing as greentest + from gevent.testing.sysinfo import CFFI_BACKEND + from gevent.testing.sysinfo import RUN_COVERAGE + from gevent.testing.sysinfo import WIN + from gevent.testing.sysinfo import PYPY3 + + class Test(unittest.TestCase): + + @unittest.skipIf( + (CFFI_BACKEND and RUN_COVERAGE) or (PYPY3 and WIN), + "Interferes with the timing; times out waiting for the child") + def test_hang(self): + # XXX: Why does PyPy3 on Win fail to kill the child? (This was before we switched + # to pypy3w; perhaps that makes a difference?) + if WIN: + from subprocess import CREATE_NEW_PROCESS_GROUP + kwargs = {'creationflags': CREATE_NEW_PROCESS_GROUP} + else: + kwargs = {} + # (not on Py2) pylint:disable=consider-using-with + p = Popen([sys.executable, __file__, 'subprocess'], stdout=PIPE, **kwargs) + line = p.stdout.readline() + if not isinstance(line, str): + line = line.decode('ascii') + # Windows needs the \n in the string to write (because of buffering), but + # because of newline handling it doesn't make it through the read; whereas + # it does on other platforms. Universal newlines is broken on Py3, so the best + # thing to do is to strip it + line = line.strip() + self.assertEqual(line, 'ready') + # On Windows, we have to send the CTRL_BREAK_EVENT (which seems to terminate the process); SIGINT triggers + # "ValueError: Unsupported signal: 2". The CTRL_C_EVENT is ignored on Python 3 (but not Python 2). + # So this test doesn't test much on Windows. + signal_to_send = signal.SIGINT if not WIN else getattr(signal, 'CTRL_BREAK_EVENT') + p.send_signal(signal_to_send) + # Wait a few seconds for child process to die. Sometimes signal delivery is delayed + # or even swallowed by Python, so send the signal a few more times if necessary + wait_seconds = 25.0 + now = time.time() + midtime = now + (wait_seconds / 2.0) + endtime = time.time() + wait_seconds + while time.time() < endtime: + if p.poll() is not None: + break + if time.time() > midtime: + p.send_signal(signal_to_send) + midtime = endtime + 1 # only once + time.sleep(0.1) + else: + # Kill unresponsive child and exit with error 1 + p.terminate() + p.wait() + raise AssertionError("Failed to wait for child") + + # If we get here, it's because we caused the process to exit; it + # didn't hang. Under Windows, however, we have to use CTRL_BREAK_EVENT, + # which has an arbitrary returncode depending on versions (so does CTRL_C_EVENT + # on Python 2). We still + # count this as success. + self.assertEqual(p.returncode if not WIN else 0, 0) + p.stdout.close() + + if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__iwait.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__iwait.py new file mode 100644 index 0000000000000000000000000000000000000000..0976e40a20903d600bf21c6ad848ff6bf57ba664 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__iwait.py @@ -0,0 +1,42 @@ +import gevent +import gevent.testing as greentest +from gevent.lock import Semaphore + + +class Testiwait(greentest.TestCase): + + def test_noiter(self): + # Test that gevent.iwait returns objects which can be iterated upon + # without additional calls to iter() + + sem1 = Semaphore() + sem2 = Semaphore() + + gevent.spawn(sem1.release) + ready = next(gevent.iwait((sem1, sem2))) + self.assertEqual(sem1, ready) + + def test_iwait_partial(self): + # Test that the iwait context manager allows the iterator to be + # consumed partially without a memory leak. + + sem = Semaphore() + let = gevent.spawn(sem.release) + with gevent.iwait((sem,), timeout=0.01) as iterator: + self.assertEqual(sem, next(iterator)) + let.get() + + def test_iwait_nogarbage(self): + sem1 = Semaphore() + sem2 = Semaphore() + let = gevent.spawn(sem1.release) + with gevent.iwait((sem1, sem2)) as iterator: + self.assertEqual(sem1, next(iterator)) + self.assertEqual(sem2.linkcount(), 1) + + self.assertEqual(sem2.linkcount(), 0) + let.get() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__joinall.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__joinall.py new file mode 100644 index 0000000000000000000000000000000000000000..1651d9f708e56a6ff397cef8afeceface4e770ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__joinall.py @@ -0,0 +1,20 @@ +import gevent + +from gevent import testing as greentest + + +class Test(greentest.TestCase): + + def test(self): + + def func(): + pass + + + a = gevent.spawn(func) + b = gevent.spawn(func) + gevent.joinall([a, b, a]) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__local.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__local.py new file mode 100644 index 0000000000000000000000000000000000000000..0565860faf94443ae8d6f983a784c9466281afa1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__local.py @@ -0,0 +1,425 @@ +import gevent.testing as greentest +from copy import copy +# Comment the line below to see that the standard thread.local is working correct +from gevent import monkey; monkey.patch_all() + + +from threading import local +from threading import Thread + +from zope import interface + +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping # pylint:disable=deprecated-class + +class ReadProperty(object): + """A property that can be overridden""" + + # A non-data descriptor + + def __get__(self, inst, klass): + return 42 if inst is not None else self + + +class A(local): + __slots__ = ['initialized', 'obj'] + + path = '' + + type_path = 'MyPath' + + read_property = ReadProperty() + + def __init__(self, obj): + super(A, self).__init__() + if not hasattr(self, 'initialized'): + self.obj = obj + self.path = '' + + +class Obj(object): + pass + +# These next two classes have to be global to avoid the leakchecks +deleted_sentinels = [] +created_sentinels = [] + +class Sentinel(object): + def __del__(self): + deleted_sentinels.append(id(self)) + + +class MyLocal(local): + + CLASS_PROP = 42 + + def __init__(self): + local.__init__(self) + self.sentinel = Sentinel() + created_sentinels.append(id(self.sentinel)) + + @property + def desc(self): + return self + +class MyLocalSubclass(MyLocal): + pass + +class WithGetattr(local): + + def __getattr__(self, name): + if name == 'foo': + return 42 + return super(WithGetattr, self).__getattr__(name) # pylint:disable=no-member + +class LocalWithABC(local, Mapping): + + def __getitem__(self, name): + return self.d[name] + + def __iter__(self): + return iter(self.d) + + def __len__(self): + return len(self.d) + +class LocalWithStaticMethod(local): + + @staticmethod + def a_staticmethod(): + return 42 + +class LocalWithClassMethod(local): + + @classmethod + def a_classmethod(cls): + return cls + + + + +class TestGeventLocal(greentest.TestCase): + # pylint:disable=attribute-defined-outside-init,blacklisted-name + + def setUp(self): + del deleted_sentinels[:] + del created_sentinels[:] + + tearDown = setUp + + def test_create_local_subclass_init_args(self): + with self.assertRaisesRegex(TypeError, + "Initialization arguments are not supported"): + local("foo") + + with self.assertRaisesRegex(TypeError, + "Initialization arguments are not supported"): + local(kw="foo") + + + def test_local_opts_not_subclassed(self): + l = local() + l.attr = 1 + self.assertEqual(l.attr, 1) + + def test_cannot_set_delete_dict(self): + l = local() + with self.assertRaises(AttributeError): + l.__dict__ = 1 + + with self.assertRaises(AttributeError): + del l.__dict__ + + def test_delete_with_no_dict(self): + l = local() + with self.assertRaises(AttributeError): + delattr(l, 'thing') + + def del_local(): + with self.assertRaises(AttributeError): + delattr(l, 'thing') + + t = Thread(target=del_local) + t.start() + t.join() + + def test_slot_and_type_attributes(self): + a = A(Obj()) + a.initialized = 1 + self.assertEqual(a.initialized, 1) + + # The slot is shared + def demonstrate_slots_shared(): + self.assertEqual(a.initialized, 1) + a.initialized = 2 + + greenlet = Thread(target=demonstrate_slots_shared) + greenlet.start() + greenlet.join() + + self.assertEqual(a.initialized, 2) + + # The slot overrides dict values + a.__dict__['initialized'] = 42 # pylint:disable=unsupported-assignment-operation + self.assertEqual(a.initialized, 2) + + # Deleting the slot deletes the slot, but not the dict + del a.initialized + self.assertFalse(hasattr(a, 'initialized')) + self.assertIn('initialized', a.__dict__) + + # We can delete the 'path' ivar + # and fall back to the type + del a.path + self.assertEqual(a.path, '') + + with self.assertRaises(AttributeError): + del a.path + + # A read property calls get + self.assertEqual(a.read_property, 42) + a.read_property = 1 + self.assertEqual(a.read_property, 1) + self.assertIsInstance(A.read_property, ReadProperty) + + # Type attributes can be read + self.assertEqual(a.type_path, 'MyPath') + self.assertNotIn('type_path', a.__dict__) + + # and replaced in the dict + a.type_path = 'Local' + self.assertEqual(a.type_path, 'Local') + self.assertIn('type_path', a.__dict__) + + def test_attribute_error(self): + # pylint:disable=attribute-defined-outside-init + a = A(Obj()) + with self.assertRaises(AttributeError): + getattr(a, 'fizz_buzz') + + def set_fizz_buzz(): + a.fizz_buzz = 1 + + greenlet = Thread(target=set_fizz_buzz) + greenlet.start() + greenlet.join() + + with self.assertRaises(AttributeError): + getattr(a, 'fizz_buzz') + + def test_getattr_called(self): + getter = WithGetattr() + self.assertEqual(42, getter.foo) + getter.foo = 'baz' + self.assertEqual('baz', getter.foo) + + + def test_copy(self): + a = A(Obj()) + a.path = '123' + a.obj.echo = 'test' + b = copy(a) + + # Copy makes a shallow copy. Meaning that the attribute path + # has to be independent in the original and the copied object because the + # value is a string, but the attribute obj should be just reference to + # the instance of the class Obj + + self.assertEqual(a.path, b.path, 'The values in the two objects must be equal') + self.assertEqual(a.obj, b.obj, 'The values must be equal') + + b.path = '321' + self.assertNotEqual(a.path, b.path, 'The values in the two objects must be different') + + a.obj.echo = "works" + self.assertEqual(a.obj, b.obj, 'The values must be equal') + + def test_copy_no_subclass(self): + + a = local() + setattr(a, 'thing', 42) + b = copy(a) + self.assertEqual(b.thing, 42) + self.assertIsNot(a.__dict__, b.__dict__) + + def test_objects(self): + # Test which failed in the eventlet?! + + a = A({}) + a.path = '123' + b = A({'one': 2}) + b.path = '123' + self.assertEqual(a.path, b.path, 'The values in the two objects must be equal') + + b.path = '321' + + self.assertNotEqual(a.path, b.path, 'The values in the two objects must be different') + + def test_class_attr(self, kind=MyLocal): + mylocal = kind() + self.assertEqual(42, mylocal.CLASS_PROP) + + mylocal.CLASS_PROP = 1 + self.assertEqual(1, mylocal.CLASS_PROP) + self.assertEqual(mylocal.__dict__['CLASS_PROP'], 1) # pylint:disable=unsubscriptable-object + + del mylocal.CLASS_PROP + self.assertEqual(42, mylocal.CLASS_PROP) + + self.assertIs(mylocal, mylocal.desc) + + def test_class_attr_subclass(self): + self.test_class_attr(kind=MyLocalSubclass) + + def test_locals_collected_when_greenlet_dead_but_still_referenced(self): + # https://github.com/gevent/gevent/issues/387 + import gevent + + my_local = MyLocal() + my_local.sentinel = None + greentest.gc_collect_if_needed() + + del created_sentinels[:] + del deleted_sentinels[:] + + def demonstrate_my_local(): + # Get the important parts + getattr(my_local, 'sentinel') + + # Create and reference greenlets + greenlets = [Thread(target=demonstrate_my_local) for _ in range(5)] + for t in greenlets: + t.start() + gevent.sleep() + + self.assertEqual(len(created_sentinels), len(greenlets)) + + for g in greenlets: + assert not g.is_alive() + gevent.sleep() # let the callbacks run + greentest.gc_collect_if_needed() + + # The sentinels should be gone too + self.assertEqual(len(deleted_sentinels), len(greenlets)) + + @greentest.skipOnLibuvOnPyPyOnWin("GC makes this non-deterministic, especially on Windows") + def test_locals_collected_when_unreferenced_even_in_running_greenlet(self): + # In fact only on Windows do we see GC being an issue; + # pypy2 5.0 on macos and travis don't have a problem. + # https://github.com/gevent/gevent/issues/981 + import gevent + import gc + gc.collect() + + count = 1000 + + running_greenlet = None + + def demonstrate_my_local(): + for _ in range(1000): + x = MyLocal() + self.assertIsNotNone(x.sentinel) + x = None + + gc.collect() + gc.collect() + + self.assertEqual(count, len(created_sentinels)) + # They're all dead, even though this greenlet is + # still running + self.assertEqual(count, len(deleted_sentinels)) + + # The links were removed as well. + self.assertFalse(running_greenlet.has_links()) + + + running_greenlet = gevent.spawn(demonstrate_my_local) + gevent.sleep() + running_greenlet.join() + + self.assertEqual(count, len(deleted_sentinels)) + + @greentest.ignores_leakcheck + def test_local_dicts_for_greenlet(self): + import gevent + from gevent.local import all_local_dicts_for_greenlet + + class MyGreenlet(gevent.Greenlet): + results = None + id_x = None + def _run(self): # pylint:disable=method-hidden + x = local() + x.foo = 42 + self.id_x = id(x) + self.results = all_local_dicts_for_greenlet(self) + + g = MyGreenlet() + g.start() + g.join() + self.assertTrue(g.successful, g) + self.assertEqual(g.results, + [((local, g.id_x), {'foo': 42})]) + + def test_local_with_abc(self): + # an ABC (or generally any non-exact-type) in the MRO doesn't + # break things. See https://github.com/gevent/gevent/issues/1201 + + x = LocalWithABC() + x.d = {'a': 1} + self.assertEqual({'a': 1}, x.d) + # The ABC part works + self.assertIn('a', x.d) + self.assertEqual(['a'], list(x.keys())) + + def test_local_with_staticmethod(self): + x = LocalWithStaticMethod() + self.assertEqual(42, x.a_staticmethod()) + + def test_local_with_classmethod(self): + x = LocalWithClassMethod() + self.assertIs(LocalWithClassMethod, x.a_classmethod()) + + +class TestLocalInterface(greentest.TestCase): + __timeout__ = None + + @greentest.ignores_leakcheck + def test_provides(self): + # https://github.com/gevent/gevent/issues/1122 + + # pylint:disable=inherit-non-class + class IFoo(interface.Interface): + pass + + @interface.implementer(IFoo) + class Base(object): + pass + + class Derived(Base, local): + pass + + d = Derived() + p = list(interface.providedBy(d)) + self.assertEqual([IFoo], p) + + + +@greentest.skipOnPurePython("Needs C extension") +class TestCExt(greentest.TestCase): # pragma: no cover + + def test_c_extension(self): + self.assertEqual(local.__module__, + 'gevent._gevent_clocal') + +@greentest.skipWithCExtensions("Needs pure-python") +class TestPure(greentest.TestCase): + + def test_extension(self): + self.assertEqual(local.__module__, + 'gevent.local') + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__lock.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__lock.py new file mode 100644 index 0000000000000000000000000000000000000000..2a172c9dab1f410e94279bede595fa69410633c1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__lock.py @@ -0,0 +1,33 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from gevent import lock + + +import gevent.testing as greentest +from gevent.tests import test__semaphore + + +class TestRLockMultiThread(test__semaphore.TestSemaphoreMultiThread): + + def _makeOne(self): + # If we don't set the hub before returning, + # there's a potential race condition, if the implementation + # isn't careful. If it's the background hub that winds up capturing + # the hub, it will ask the hub to switch back to itself and + # then switch to the hub, which will raise LoopExit (nothing + # for the background thread to do). What is supposed to happen + # is that the background thread realizes it's the background thread, + # starts an async watcher and then switches to the hub. + # + # So we deliberately don't set the hub to help test that condition. + return lock.RLock() + + def assertOneHasNoHub(self, sem): + self.assertIsNone(sem._block.hub) + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__loop_callback.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__loop_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..dca0656e17e641fbe86e0659b1887ff91cd4eaaa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__loop_callback.py @@ -0,0 +1,18 @@ +from gevent import get_hub +from gevent import testing as greentest + +class Test(greentest.TestCase): + def test(self): + count = [0] + + def incr(): + count[0] += 1 + + loop = get_hub().loop + loop.run_callback(incr) + loop.run() + self.assertEqual(count, [1]) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__makefile_ref.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__makefile_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..91f4dae785a4a0931837bb495e407b6d2f7b9ac8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__makefile_ref.py @@ -0,0 +1,549 @@ +from __future__ import print_function +import os +from gevent import monkey; monkey.patch_all() +import socket +import ssl +import threading +import errno +import weakref + + +import gevent.testing as greentest +from gevent.testing.params import DEFAULT_BIND_ADDR_TUPLE +from gevent.testing.params import DEFAULT_CONNECT +from gevent.testing.sockets import tcp_listener + +dirname = os.path.dirname(os.path.abspath(__file__)) +CERTFILE = os.path.join(dirname, '2_7_keycert.pem') +pid = os.getpid() + +PY3 = greentest.PY3 +PYPY = greentest.PYPY +CPYTHON = not PYPY +PY2 = not PY3 +fd_types = int + +WIN = greentest.WIN + +from gevent.testing import get_open_files +try: + import psutil +except ImportError: + psutil = None + +# wrap_socket() is considered deprecated in 3.9 +# pylint:disable=deprecated-method + +class Test(greentest.TestCase): + + extra_allowed_open_states = () + + def tearDown(self): + self.extra_allowed_open_states = () + super(Test, self).tearDown() + + def assert_raises_EBADF(self, func): + try: + result = func() + except OSError as ex: + # Windows/Py3 raises "OSError: [WinError 10038]" + if ex.args[0] == errno.EBADF: + return + if WIN and ex.args[0] == 10038: + return + raise + raise AssertionError('NOT RAISED EBADF: %r() returned %r' % (func, result)) + + if WIN or (PYPY and greentest.LINUX): + def __assert_fd_open(self, fileno): + # We can't detect open file descriptors on Windows. + # On PyPy 3.6-7.3 on Travis CI (linux), for some reason the + # client file descriptors don't always show as open. Don't know why, + # was fine in 7.2. + # On March 23 2020 we had to pin psutil back to a version + # for PyPy 2 (see setup.py) and this same problem started happening there. + # PyPy on macOS was unaffected. + pass + else: + def __assert_fd_open(self, fileno): + assert isinstance(fileno, fd_types) + open_files = get_open_files() + if fileno not in open_files: + raise AssertionError('%r is not open:\n%s' % (fileno, open_files['data'])) + + def assert_fd_closed(self, fileno): + assert isinstance(fileno, fd_types), repr(fileno) + assert fileno > 0, fileno + # Here, if we're in the process of closing, don't consider it open. + # This goes into details of psutil + open_files = get_open_files(count_closing_as_open=False) + if fileno in open_files: + raise AssertionError('%r is not closed:\n%s' % (fileno, open_files['data'])) + + def _assert_sock_open(self, sock): + # requires the psutil output + open_files = get_open_files() + sockname = sock.getsockname() + for x in open_files['data']: + if getattr(x, 'laddr', None) == sockname: + assert x.status in (psutil.CONN_LISTEN, psutil.CONN_ESTABLISHED) + self.extra_allowed_open_states, x.status + return + raise AssertionError("%r is not open:\n%s" % (sock, open_files['data'])) + + def assert_open(self, sock, *rest): + if isinstance(sock, fd_types): + self.__assert_fd_open(sock) + else: + fileno = sock.fileno() + assert isinstance(fileno, fd_types), fileno + sockname = sock.getsockname() + assert isinstance(sockname, tuple), sockname + if not WIN: + self.__assert_fd_open(fileno) + else: + self._assert_sock_open(sock) + if rest: + self.assert_open(rest[0], *rest[1:]) + + def assert_closed(self, sock, *rest): + if isinstance(sock, fd_types): + self.assert_fd_closed(sock) + else: + # Under Python3, the socket module returns -1 for a fileno + # of a closed socket; under Py2 it raises + if PY3: + self.assertEqual(sock.fileno(), -1) + else: + self.assert_raises_EBADF(sock.fileno) + self.assert_raises_EBADF(sock.getsockname) + self.assert_raises_EBADF(sock.accept) + if rest: + self.assert_closed(rest[0], *rest[1:]) + + def make_open_socket(self): + s = socket.socket() + try: + s.bind(DEFAULT_BIND_ADDR_TUPLE) + if WIN or greentest.LINUX: + # Windows and linux (with psutil) doesn't show as open until + # we call listen (linux with lsof accepts either) + s.listen(1) + self.assert_open(s, s.fileno()) + except: + s.close() + s = None + raise + return s + +# Sometimes its this one, sometimes it's test_ssl. No clue why or how. +@greentest.skipOnAppVeyor("This sometimes times out for no apparent reason.") +class TestSocket(Test): + + def test_simple_close(self): + with Closing() as closer: + s = closer(self.make_open_socket()) + fileno = s.fileno() + s.close() + self.assert_closed(s, fileno) + + def test_makefile1(self): + with Closing() as closer: + s = closer(self.make_open_socket()) + fileno = s.fileno() + f = closer(s.makefile()) + + self.assert_open(s, fileno) + # Under python 2, this closes socket wrapper object but not the file descriptor; + # under python 3, both stay open + s.close() + if PY3: + self.assert_open(s, fileno) + else: + self.assert_closed(s) + self.assert_open(fileno) + f.close() + self.assert_closed(s) + self.assert_closed(fileno) + + def test_makefile2(self): + with Closing() as closer: + s = closer(self.make_open_socket()) + fileno = s.fileno() + self.assert_open(s, fileno) + f = closer(s.makefile()) + self.assert_open(s) + self.assert_open(s, fileno) + f.close() + # closing fileobject does not close the socket + self.assert_open(s, fileno) + s.close() + self.assert_closed(s, fileno) + + def test_server_simple(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + + def connect(): + connector.connect((DEFAULT_CONNECT, port)) + + closer.running_task(threading.Thread(target=connect)) + + client_socket = closer.accept(listener) + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_closed(client_socket) + + def test_server_makefile1(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + + def connect(): + connector.connect((DEFAULT_CONNECT, port)) + + closer.running_task(threading.Thread(target=connect)) + + + client_socket = closer.accept(listener) + fileno = client_socket.fileno() + f = closer(client_socket.makefile()) + self.assert_open(client_socket, fileno) + client_socket.close() + # Under python 2, this closes socket wrapper object but not the file descriptor; + # under python 3, both stay open + if PY3: + self.assert_open(client_socket, fileno) + else: + self.assert_closed(client_socket) + self.assert_open(fileno) + f.close() + self.assert_closed(client_socket, fileno) + + def test_server_makefile2(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + + def connect(): + connector.connect((DEFAULT_CONNECT, port)) + + closer.running_task(threading.Thread(target=connect)) + client_socket = closer.accept(listener) + + fileno = client_socket.fileno() + f = closer(client_socket.makefile()) + self.assert_open(client_socket, fileno) + # closing fileobject does not close the socket + f.close() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_closed(client_socket, fileno) + + +@greentest.skipOnAppVeyor("This sometimes times out for no apparent reason.") +class TestSSL(Test): + + def _ssl_connect_task(self, connector, port, accepted_event): + connector.connect((DEFAULT_CONNECT, port)) + + try: + # Note: We get ResourceWarning about 'x' + # on Python 3 if we don't join the spawned thread + x = ssl.SSLContext().wrap_socket(connector) + # Wait to be fully accepted. We could otherwise raise ahead + # of the server and close ourself before it's ready to read. + accepted_event.wait() + except socket.error: + # Observed on Windows with PyPy2 5.9.0 and libuv: + # if we don't switch in a timely enough fashion, + # the server side runs ahead of us and closes + # our socket first, so this fails. + pass + else: + x.close() + + def _make_ssl_connect_task(self, connector, port): + accepted_event = threading.Event() + t = threading.Thread(target=self._ssl_connect_task, + args=(connector, port, accepted_event)) + t.daemon = True + t.accepted_event = accepted_event + return t + + def test_simple_close(self): + with Closing() as closer: + s = closer(self.make_open_socket()) + fileno = s.fileno() + s = closer(ssl.SSLContext().wrap_socket(s)) + fileno = s.fileno() + self.assert_open(s, fileno) + s.close() + self.assert_closed(s, fileno) + + def test_makefile1(self): + with Closing() as closer: + raw_s = closer(self.make_open_socket()) + s = closer(ssl.SSLContext().wrap_socket(raw_s)) + + fileno = s.fileno() + self.assert_open(s, fileno) + f = closer(s.makefile()) + self.assert_open(s, fileno) + s.close() + self.assert_open(s, fileno) + f.close() + raw_s.close() + self.assert_closed(s, fileno) + + def test_makefile2(self): + with Closing() as closer: + s = closer(self.make_open_socket()) + fileno = s.fileno() + + s = closer(ssl.SSLContext().wrap_socket(s)) + fileno = s.fileno() + self.assert_open(s, fileno) + f = closer(s.makefile()) + self.assert_open(s, fileno) + f.close() + # closing fileobject does not close the socket + self.assert_open(s, fileno) + s.close() + self.assert_closed(s, fileno) + + def _wrap_socket(self, sock, *, keyfile, certfile, server_side=False): + context = ssl.SSLContext() + context.load_cert_chain(certfile=certfile, keyfile=keyfile) + return context.wrap_socket(sock, server_side=server_side) + + def test_server_simple(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + + t = self._make_ssl_connect_task(connector, port) + closer.running_task(t) + + client_socket = closer.accept(listener) + t.accepted_event.set() + client_socket = closer( + self._wrap_socket(client_socket, keyfile=CERTFILE, certfile=CERTFILE, + server_side=True)) + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_closed(client_socket, fileno) + + def test_server_makefile1(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + + t = self._make_ssl_connect_task(connector, port) + closer.running_task(t) + + client_socket = closer.accept(listener) + t.accepted_event.set() + client_socket = closer( + self._wrap_socket(client_socket, keyfile=CERTFILE, certfile=CERTFILE, + server_side=True)) + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + f = client_socket.makefile() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_open(client_socket, fileno) + f.close() + self.assert_closed(client_socket, fileno) + + def test_server_makefile2(self): + with Closing() as closer: + listener = closer(tcp_listener(backlog=1)) + port = listener.getsockname()[1] + + connector = closer(socket.socket()) + t = self._make_ssl_connect_task(connector, port) + closer.running_task(t) + + t.accepted_event.set() + client_socket = closer.accept(listener) + client_socket = closer( + self._wrap_socket(client_socket, keyfile=CERTFILE, certfile=CERTFILE, + server_side=True)) + + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + f = client_socket.makefile() + self.assert_open(client_socket, fileno) + # Closing fileobject does not close SSLObject + f.close() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_closed(client_socket, fileno) + + def test_serverssl_makefile1(self): + raw_listener = tcp_listener(backlog=1) + fileno = raw_listener.fileno() + port = raw_listener.getsockname()[1] + listener = self._wrap_socket(raw_listener, keyfile=CERTFILE, certfile=CERTFILE) + + connector = socket.socket() + t = self._make_ssl_connect_task(connector, port) + t.start() + + with CleaningUp(t, listener, raw_listener, connector) as client_socket: + t.accepted_event.set() + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + f = client_socket.makefile() + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_open(client_socket, fileno) + f.close() + self.assert_closed(client_socket, fileno) + + def test_serverssl_makefile2(self): + raw_listener = tcp_listener(backlog=1) + port = raw_listener.getsockname()[1] + listener = self._wrap_socket(raw_listener, keyfile=CERTFILE, certfile=CERTFILE) + + accepted_event = threading.Event() + def connect(connector=socket.socket()): + try: + connector.connect((DEFAULT_CONNECT, port)) + s = ssl.SSLContext().wrap_socket(connector) + accepted_event.wait() + s.sendall(b'test_serverssl_makefile2') + s.shutdown(socket.SHUT_RDWR) + s.close() + finally: + connector.close() + + t = threading.Thread(target=connect) + t.daemon = True + t.start() + client_socket = None + with CleaningUp(t, listener, raw_listener) as client_socket: + accepted_event.set() + fileno = client_socket.fileno() + self.assert_open(client_socket, fileno) + f = client_socket.makefile() + self.assert_open(client_socket, fileno) + self.assertEqual(f.read(), 'test_serverssl_makefile2') + self.assertEqual(f.read(), '') + # Closing file object does not close the socket. + f.close() + if WIN and psutil: + # Hmm? + self.extra_allowed_open_states = (psutil.CONN_CLOSE_WAIT,) + + self.assert_open(client_socket, fileno) + client_socket.close() + self.assert_closed(client_socket, fileno) + + +class Closing(object): + + def __init__(self, *init): + self._objects = [] + for i in init: + self.closing(i) + self.task = None + + def accept(self, listener): + client_socket, _addr = listener.accept() + return self.closing(client_socket) + + def __enter__(self): + o = self.objects() + if len(o) == 1: + return o[0] + return self + + if PY2 and CPYTHON: + # This implementation depends or refcounting + # for things to close. Eww. + def closing(self, o): + self._objects.append(weakref.ref(o)) + return o + def objects(self): + return [r() for r in self._objects if r() is not None] + + else: + def objects(self): + # PyPy returns an object without __len__... + return list(reversed(self._objects)) + + def closing(self, o): + self._objects.append(o) + return o + + __call__ = closing + + def running_task(self, thread): + assert self.task is None + self.task = thread + self.task.start() + return self.task + + def __exit__(self, t, v, tb): + # workaround for test_server_makefile1, test_server_makefile2, + # test_server_simple, test_serverssl_makefile1. + + # On PyPy on Linux, it is important to join the SSL Connect + # Task FIRST, before closing the sockets. If we do it after + # (which makes more sense) we hang. It's not clear why, except + # that it has something to do with context switches. Inserting a call to + # gevent.sleep(0.1) instead of joining the task has the same + # effect. If the previous tests hang, then later tests can fail with + # SSLError: unknown alert type. + + # XXX: Why do those two things happen? + + # On PyPy on macOS, we don't have that problem and can use the + # more logical order. + try: + if self.task is not None: + self.task.join() + finally: + self.task = None + for o in self.objects(): + try: + o.close() + except Exception: # pylint:disable=broad-except + pass + + self._objects = () + +class CleaningUp(Closing): + + def __init__(self, task, listener, *other_sockets): + super(CleaningUp, self).__init__(listener, *other_sockets) + self.task = task + self.listener = listener + + def __enter__(self): + return self.accept(self.listener) + + def __exit__(self, t, v, tb): + try: + Closing.__exit__(self, t, v, tb) + finally: + self.listener = None + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__memleak.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__memleak.py new file mode 100644 index 0000000000000000000000000000000000000000..408a748895c28ce37c61c5d7097fe9d3d3f50841 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__memleak.py @@ -0,0 +1,47 @@ +import sys +import unittest + +from gevent.testing import TestCase +import gevent +from gevent.timeout import Timeout + +@unittest.skipUnless( + hasattr(sys, 'gettotalrefcount'), + "Needs debug build" +) +# XXX: This name makes no sense. What was this for originally? +class TestQueue(TestCase): # pragma: no cover + # pylint:disable=bare-except,no-member + + def test(self): + + refcounts = [] + for _ in range(15): + try: + Timeout.start_new(0.01) + gevent.sleep(0.1) + self.fail('must raise Timeout') + except Timeout: + pass + refcounts.append(sys.gettotalrefcount()) + + # Refcounts may go down, but not up + # XXX: JAM: I think this may just be broken. Each time we add + # a new integer to our list of refcounts, we'll be + # creating a new reference. This makes sense when we see the list + # go up by one each iteration: + # + # AssertionError: 530631 not less than or equal to 530630 + # : total refcount mismatch: + # [530381, 530618, 530619, 530620, 530621, + # 530622, 530623, 530624, 530625, 530626, + # 530627, 530628, 530629, 530630, 530631] + final = refcounts[-1] + previous = refcounts[-2] + self.assertLessEqual( + final, previous, + "total refcount mismatch: %s" % refcounts) + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..142d7e3d195a05055d2119b6080ac18318afc11a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey.py @@ -0,0 +1,168 @@ +from gevent import monkey +monkey.patch_all() + +import sys +import unittest +from gevent.testing.testcase import SubscriberCleanupMixin + +class TestMonkey(SubscriberCleanupMixin, unittest.TestCase): + + maxDiff = None + + def setUp(self): + super(TestMonkey, self).setUp() + + self.all_events = [] + self.addSubscriber(self.all_events.append) + self.orig_saved = orig_saved = {} + for k, v in monkey.saved.items(): + orig_saved[k] = v.copy() + + + def tearDown(self): + monkey.saved = self.orig_saved + del self.orig_saved + del self.all_events + super(TestMonkey, self).tearDown() + + def test_time(self): + import time + from gevent import time as gtime + self.assertIs(time.sleep, gtime.sleep) + + def test_thread(self): + import _thread as thread + import threading + + from gevent import thread as gthread + self.assertIs(thread.start_new_thread, gthread.start_new_thread) + if sys.version_info[:2] < (3, 13): + self.assertIs(threading._start_new_thread, gthread.start_new_thread) + else: + self.assertIs(threading._start_joinable_thread, gthread.start_joinable_thread) + + # Event patched by default + self.assertTrue(monkey.is_object_patched('threading', 'Event')) + + if sys.version_info[0] == 2: + from gevent import threading as gthreading + from gevent.event import Event as GEvent + self.assertIs(threading._sleep, gthreading._sleep) + self.assertTrue(monkey.is_object_patched('threading', '_Event')) + self.assertIs(threading._Event, GEvent) + + def test_socket(self): + import socket + from gevent import socket as gevent_socket + self.assertIs(socket.create_connection, gevent_socket.create_connection) + + def test_os(self): + import os + import types + from gevent import os as gos + for name in ('fork', 'forkpty'): + if hasattr(os, name): + attr = getattr(os, name) + self.assertNotIn('built-in', repr(attr)) + self.assertNotIsInstance(attr, types.BuiltinFunctionType) + self.assertIsInstance(attr, types.FunctionType) + self.assertIs(attr, getattr(gos, name)) + + def test_saved(self): + self.assertTrue(monkey.saved) + for modname, objects in monkey.saved.items(): + self.assertTrue(monkey.is_module_patched(modname)) + + for objname in objects: + self.assertTrue(monkey.is_object_patched(modname, objname)) + + def test_patch_subprocess_twice(self): + Popen = monkey.get_original('subprocess', 'Popen') + self.assertNotIn('gevent', repr(Popen)) + self.assertIs(Popen, monkey.get_original('subprocess', 'Popen')) + monkey.patch_subprocess() + self.assertIs(Popen, monkey.get_original('subprocess', 'Popen')) + + def test_patch_twice_warnings_events(self): + import warnings + + all_events = self.all_events + + with warnings.catch_warnings(record=True) as issued_warnings: + # Patch again, triggering just one warning, for + # a different set of arguments. Because we're going to False instead of + # turning something on, nothing is actually done, no events are issued. + monkey.patch_all(os=False, extra_kwarg=42) + self.assertEqual(len(issued_warnings), 1) + self.assertIn('more than once', str(issued_warnings[0].message)) + self.assertEqual(all_events, []) + + # Same warning again, but still nothing is done. + del issued_warnings[:] + monkey.patch_all(os=False) + self.assertEqual(len(issued_warnings), 1) + self.assertIn('more than once', str(issued_warnings[0].message)) + self.assertEqual(all_events, []) + self.orig_saved['_gevent_saved_patch_all_module_settings'] = monkey.saved[ + '_gevent_saved_patch_all_module_settings'] + + # Make sure that re-patching did not change the monkey.saved + # attribute, overwriting the original functions. + if 'logging' in monkey.saved and 'logging' not in self.orig_saved: + # some part of the warning or unittest machinery imports logging + self.orig_saved['logging'] = monkey.saved['logging'] + self.assertEqual(self.orig_saved, monkey.saved) + + # Make sure some problematic attributes stayed correct. + # NOTE: This was only a problem if threading was not previously imported. + for k, v in monkey.saved['threading'].items(): + self.assertNotIn('gevent', str(v), (k, v)) + + def test_patch_events(self): + from gevent import events + from gevent.testing import verify + all_events = self.all_events + + def veto(event): + if isinstance(event, events.GeventWillPatchModuleEvent) and event.module_name == 'ssl': + raise events.DoNotPatch + self.addSubscriber(veto) + + monkey.saved = {} # Reset + monkey.patch_all(thread=False, select=False, extra_kwarg=42) # Go again + + self.assertIsInstance(all_events[0], events.GeventWillPatchAllEvent) + self.assertEqual({'extra_kwarg': 42}, all_events[0].patch_all_kwargs) + verify.verifyObject(events.IGeventWillPatchAllEvent, all_events[0]) + + self.assertIsInstance(all_events[1], events.GeventWillPatchModuleEvent) + verify.verifyObject(events.IGeventWillPatchModuleEvent, all_events[1]) + + self.assertIsInstance(all_events[2], events.GeventDidPatchModuleEvent) + verify.verifyObject(events.IGeventWillPatchModuleEvent, all_events[1]) + + self.assertIsInstance(all_events[-2], events.GeventDidPatchBuiltinModulesEvent) + verify.verifyObject(events.IGeventDidPatchBuiltinModulesEvent, all_events[-2]) + + self.assertIsInstance(all_events[-1], events.GeventDidPatchAllEvent) + verify.verifyObject(events.IGeventDidPatchAllEvent, all_events[-1]) + + for e in all_events: + self.assertFalse(isinstance(e, events.GeventDidPatchModuleEvent) + and e.module_name == 'ssl') + + def test_patch_queue(self): + try: + import queue + except ImportError: + # Python 2 called this Queue. Note that having + # python-future installed gives us a queue module on + # Python 2 as well. + queue = None + if not hasattr(queue, 'SimpleQueue'): + raise unittest.SkipTest("Needs SimpleQueue") + # pylint:disable=no-member + self.assertIs(queue.SimpleQueue, queue._PySimpleQueue) + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_builtins_future.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_builtins_future.py new file mode 100644 index 0000000000000000000000000000000000000000..599253dc6aabbee9292d0babf6883008a2f50c62 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_builtins_future.py @@ -0,0 +1,16 @@ +# Under Python 2, if the `future` module is installed, we get +# a `builtins` module, which mimics the `builtins` module from +# Python 3, but does not have the __import__ and some other functions. +# Make sure we can still run in that case. +import sys +try: + # fake out a "broken" builtins module + import builtins +except ImportError: + class builtins(object): + pass + sys.modules['builtins'] = builtins() + +if not hasattr(builtins, '__import__'): + import gevent.monkey + gevent.monkey.patch_builtins() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_hub_in_thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_hub_in_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..981ca6cdeba41d23bceacc3b4bc68e1b147fd0cc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_hub_in_thread.py @@ -0,0 +1,28 @@ +from gevent.monkey import patch_all +patch_all(thread=False) +from threading import Thread +import time + +# The first time we init the hub is in the native +# thread with time.sleep(), needing multiple +# threads at the same time. Note: this is very timing +# dependent. +# See #687 + + +def func(): + time.sleep() + + +def main(): + threads = [] + for _ in range(3): + th = Thread(target=func) + th.start() + threads.append(th) + for th in threads: + th.join() + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_logging.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..7089444d832bfb6855eec4d0e067b5ff2683f815 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_logging.py @@ -0,0 +1,57 @@ +# If the logging module is imported *before* monkey patching, +# the existing handlers are correctly monkey patched to use gevent locks +import logging +logging.basicConfig() + +import threading + + +def _inner_lock(lock): + try: + return lock._block + except AttributeError: + return None + + +def _check_type(root, lock, inner_semaphore, kind): + if not isinstance(inner_semaphore, kind): + raise AssertionError( + "Expected .[_]lock._block to be of type %s, " + "but it was of type %s.\n" + "\t.[_]lock=%r\n" + "\t.[_]lock._block=%r\n" + "\t=%r" % ( + kind, + type(inner_semaphore), + lock, + inner_semaphore, + root + ) + ) + +def checkLocks(kind, ignore_none=True): + handlers = logging._handlerList + assert handlers + + for weakref in handlers: + # In py26, these are actual handlers, not weakrefs + handler = weakref() if callable(weakref) else weakref + block = _inner_lock(handler.lock) + if block is None and ignore_none: + continue + _check_type(handler, handler.lock, block, kind) + + attr = _inner_lock(logging._lock) + if attr is None and ignore_none: + return + _check_type(logging, logging._lock, attr, kind) + +checkLocks(type(threading._allocate_lock())) + +import gevent.monkey +gevent.monkey.patch_all() + +import gevent.lock +import gevent.thread + +checkLocks(type(gevent.thread.allocate_lock()), ignore_none=False) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_module_run.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_module_run.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7d51bf432ce8baaecd90bfa6ef77ed1e2b892d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_module_run.py @@ -0,0 +1,127 @@ +""" +Tests for running ``gevent.monkey`` as a module to launch a +patched script. + +Uses files in the ``monkey_package/`` directory. +""" +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division + + +import os +import os.path +import sys + +from gevent import testing as greentest +from gevent.testing.util import absolute_pythonpath +from gevent.testing.util import run + +class TestRun(greentest.TestCase): + maxDiff = None + + def setUp(self): + self.abs_pythonpath = absolute_pythonpath() # before we cd + self.cwd = os.getcwd() + os.chdir(os.path.dirname(__file__)) + + def tearDown(self): + os.chdir(self.cwd) + + def _run(self, script, module=False): + env = os.environ.copy() + env['PYTHONWARNINGS'] = 'ignore' + if self.abs_pythonpath: + env['PYTHONPATH'] = self.abs_pythonpath + run_kwargs = dict( + buffer_output=True, + quiet=True, + nested=True, + env=env, + timeout=10, + ) + + args = [sys.executable, '-m', 'gevent.monkey'] + if module: + args.append('--module') + args += [script, 'patched'] + monkey_result = run( + args, + **run_kwargs + ) + self.assertTrue(monkey_result) + + if module: + args = [sys.executable, "-m", script, 'stdlib'] + else: + args = [sys.executable, script, 'stdlib'] + std_result = run( + args, + **run_kwargs + ) + self.assertTrue(std_result) + + monkey_out_lines = monkey_result.output_lines + std_out_lines = std_result.output_lines + self.assertEqual(monkey_out_lines, std_out_lines) + self.assertEqual(monkey_result.error, std_result.error) + + return monkey_out_lines + + def test_run_simple(self): + self._run(os.path.join('monkey_package', 'script.py')) + + def _run_package(self, module): + lines = self._run('monkey_package', module=module) + + self.assertTrue(lines[0].endswith(u'__main__.py'), lines[0]) + self.assertEqual(lines[1].strip(), u'__main__') + + def test_run_package(self): + # Run a __main__ inside a package, even without specifying -m + self._run_package(module=False) + + def test_run_module(self): + # Run a __main__ inside a package, when specifying -m + self._run_package(module=True) + + def test_issue_302(self): + monkey_lines = self._run(os.path.join('monkey_package', 'issue302monkey.py')) + + self.assertEqual(monkey_lines[0].strip(), u'True') + monkey_lines[1] = monkey_lines[1].replace(u'\\', u'/') # windows path + self.assertTrue(monkey_lines[1].strip().endswith(u'monkey_package/issue302monkey.py')) + self.assertEqual(monkey_lines[2].strip(), u'True', monkey_lines) + + # These three tests all sometimes fail on Py2 on CI, writing + # to stderr: + # Unhandled exception in thread started by \n + # sys.excepthook is missing\n + # lost sys.stderr\n + # Fatal Python error: PyImport_GetModuleDict: no module dictionary!\n' + # I haven't been able to produce this locally on macOS or Linux. + # The last line seems new with 2.7.17? + # Also, occasionally, they get '3' instead of '2' for the number of threads. + # That could have something to do with...? Most commonly that's PyPy, but + # sometimes CPython. Again, haven't reproduced. + # Not relevant since Py2 has been dropped. + def test_threadpool_in_patched_after_patch(self): + # Issue 1484 + # If we don't have this correct, then we get exceptions + out = self._run(os.path.join('monkey_package', 'threadpool_monkey_patches.py')) + self.assertEqual(out, ['False', '2']) + + def test_threadpool_in_patched_after_patch_module(self): + # Issue 1484 + # If we don't have this correct, then we get exceptions + out = self._run('monkey_package.threadpool_monkey_patches', module=True) + self.assertEqual(out, ['False', '2']) + + def test_threadpool_not_patched_after_patch_module(self): + # Issue 1484 + # If we don't have this correct, then we get exceptions + out = self._run('monkey_package.threadpool_no_monkey', module=True) + self.assertEqual(out, ['False', 'False', '2']) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_multiple_imports.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_multiple_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..576062e37d5087688fed3488c4880a1ff87454b6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_multiple_imports.py @@ -0,0 +1,6 @@ +# https://github.com/gevent/gevent/issues/615 +# Under Python 3, with its use of importlib, +# if the monkey patch is done when the importlib import lock is held +# (e.g., during recursive imports) we could fail to release the lock. +# This is surprisingly common. +__import__('_import_import_patch') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_queue.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f240abf015993bae0b458175764d89f8a36360ed --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_queue.py @@ -0,0 +1,331 @@ +# Some simple queue module tests, plus some failure conditions +# to ensure the Queue locks remain stable. +from gevent import monkey +monkey.patch_all() + +from gevent import queue as Queue +import threading +import time +import unittest + + +QUEUE_SIZE = 5 + +# A thread to run a function that unclogs a blocked Queue. +class _TriggerThread(threading.Thread): + def __init__(self, fn, args): + self.fn = fn + self.args = args + #self.startedEvent = threading.Event() + from gevent.event import Event + self.startedEvent = Event() + threading.Thread.__init__(self) + + def run(self): + # The sleep isn't necessary, but is intended to give the blocking + # function in the main thread a chance at actually blocking before + # we unclog it. But if the sleep is longer than the timeout-based + # tests wait in their blocking functions, those tests will fail. + # So we give them much longer timeout values compared to the + # sleep here (I aimed at 10 seconds for blocking functions -- + # they should never actually wait that long - they should make + # progress as soon as we call self.fn()). + time.sleep(0.01) + self.startedEvent.set() + self.fn(*self.args) + + +# Execute a function that blocks, and in a separate thread, a function that +# triggers the release. Returns the result of the blocking function. Caution: +# block_func must guarantee to block until trigger_func is called, and +# trigger_func must guarantee to change queue state so that block_func can make +# enough progress to return. In particular, a block_func that just raises an +# exception regardless of whether trigger_func is called will lead to +# timing-dependent sporadic failures, and one of those went rarely seen but +# undiagnosed for years. Now block_func must be unexceptional. If block_func +# is supposed to raise an exception, call do_exceptional_blocking_test() +# instead. + +class BlockingTestMixin(object): + + def do_blocking_test(self, block_func, block_args, trigger_func, trigger_args): + self.t = _TriggerThread(trigger_func, trigger_args) + self.t.start() + self.result = block_func(*block_args) + # If block_func returned before our thread made the call, we failed! + if not self.t.startedEvent.isSet(): + self.fail("blocking function '%r' appeared not to block" % + block_func) + self.t.join(10) # make sure the thread terminates + if self.t.is_alive(): + self.fail("trigger function '%r' appeared to not return" % + trigger_func) + return self.result + + # Call this instead if block_func is supposed to raise an exception. + def do_exceptional_blocking_test(self, block_func, block_args, trigger_func, + trigger_args, expected_exception_class): + self.t = _TriggerThread(trigger_func, trigger_args) + self.t.start() + try: + with self.assertRaises(expected_exception_class): + block_func(*block_args) + finally: + self.t.join(10) # make sure the thread terminates + if self.t.is_alive(): + self.fail("trigger function '%r' appeared to not return" % + trigger_func) + if not self.t.startedEvent.isSet(): + self.fail("trigger thread ended but event never set") + + +class BaseQueueTest(unittest.TestCase, BlockingTestMixin): + type2test = Queue.Queue + + def setUp(self): + self.cum = 0 + self.cumlock = threading.Lock() + + def simple_queue_test(self, q): + if not q.empty(): + raise RuntimeError("Call this function with an empty queue") + # I guess we better check things actually queue correctly a little :) + q.put(111) + q.put(333) + q.put(222) + q.put(444) + target_first_items = dict( + Queue=111, + LifoQueue=444, + PriorityQueue=111) + actual_first_item = (q.peek(), q.get()) + self.assertEqual(actual_first_item, + (target_first_items[q.__class__.__name__], + target_first_items[q.__class__.__name__]), + "q.peek() and q.get() are not equal!") + target_order = dict(Queue=[333, 222, 444], + LifoQueue=[222, 333, 111], + PriorityQueue=[222, 333, 444]) + actual_order = [q.get(), q.get(), q.get()] + self.assertEqual(actual_order, target_order[q.__class__.__name__], + "Didn't seem to queue the correct data!") + for i in range(QUEUE_SIZE-1): + q.put(i) + self.assertFalse(q.empty(), "Queue should not be empty") + self.assertFalse(q.full(), "Queue should not be full") + q.put(999) + self.assertTrue(q.full(), "Queue should be full") + try: + q.put(888, block=0) + self.fail("Didn't appear to block with a full queue") + except Queue.Full: + pass + try: + q.put(888, timeout=0.01) + self.fail("Didn't appear to time-out with a full queue") + except Queue.Full: + pass + self.assertEqual(q.qsize(), QUEUE_SIZE) + # Test a blocking put + self.do_blocking_test(q.put, (888,), q.get, ()) + self.do_blocking_test(q.put, (888, True, 10), q.get, ()) + # Empty it + for i in range(QUEUE_SIZE): + q.get() + self.assertTrue(q.empty(), "Queue should be empty") + try: + q.get(block=0) + self.fail("Didn't appear to block with an empty queue") + except Queue.Empty: + pass + try: + q.get(timeout=0.01) + self.fail("Didn't appear to time-out with an empty queue") + except Queue.Empty: + pass + # Test a blocking get + self.do_blocking_test(q.get, (), q.put, ('empty',)) + self.do_blocking_test(q.get, (True, 10), q.put, ('empty',)) + + def worker(self, q): + while True: + x = q.get() + if x is None: + q.task_done() + return + #with self.cumlock: + self.cum += x + q.task_done() + + def queue_join_test(self, q): + self.cum = 0 + for i in (0, 1): + threading.Thread(target=self.worker, args=(q,)).start() + for i in range(100): + q.put(i) + q.join() + self.assertEqual(self.cum, sum(range(100)), + "q.join() did not block until all tasks were done") + for i in (0, 1): + q.put(None) # instruct the threads to close + q.join() # verify that you can join twice + + def test_queue_task_done(self): + # Test to make sure a queue task completed successfully. + q = Queue.JoinableQueue() # self.type2test() + # XXX the same test in subclasses + try: + q.task_done() + except ValueError: + pass + else: + self.fail("Did not detect task count going negative") + + def test_queue_join(self): + # Test that a queue join()s successfully, and before anything else + # (done twice for insurance). + q = Queue.JoinableQueue() # self.type2test() + # XXX the same test in subclass + self.queue_join_test(q) + self.queue_join_test(q) + try: + q.task_done() + except ValueError: + pass + else: + self.fail("Did not detect task count going negative") + + def test_queue_task_done_with_items(self): + # Passing items to the constructor allows for as + # many task_done calls. Joining before all the task done + # are called returns false + # XXX the same test in subclass + l = [1, 2, 3] + q = Queue.JoinableQueue(items=l) + for i in l: + self.assertFalse(q.join(timeout=0.001)) + self.assertEqual(i, q.get()) + q.task_done() + + try: + q.task_done() + except ValueError: + pass + else: + self.fail("Did not detect task count going negative") + self.assertTrue(q.join(timeout=0.001)) + + def test_simple_queue(self): + # Do it a couple of times on the same queue. + # Done twice to make sure works with same instance reused. + q = self.type2test(QUEUE_SIZE) + self.simple_queue_test(q) + self.simple_queue_test(q) + +class LifoQueueTest(BaseQueueTest): + type2test = Queue.LifoQueue + +class PriorityQueueTest(BaseQueueTest): + type2test = Queue.PriorityQueue + + def test__init(self): + item1 = (2, 'b') + item2 = (1, 'a') + q = self.type2test(items=[item1, item2]) + self.assertTupleEqual(item2, q.get_nowait()) + self.assertTupleEqual(item1, q.get_nowait()) + + +# A Queue subclass that can provoke failure at a moment's notice :) +class FailingQueueException(Exception): + pass + +class FailingQueue(Queue.Queue): + def __init__(self, *args): + self.fail_next_put = False + self.fail_next_get = False + Queue.Queue.__init__(self, *args) + def _put(self, item): + if self.fail_next_put: + self.fail_next_put = False + raise FailingQueueException("You Lose") + return Queue.Queue._put(self, item) + def _get(self): + if self.fail_next_get: + self.fail_next_get = False + raise FailingQueueException("You Lose") + return Queue.Queue._get(self) + +class FailingQueueTest(unittest.TestCase, BlockingTestMixin): + + def failing_queue_test(self, q): + if not q.empty(): + raise RuntimeError("Call this function with an empty queue") + for i in range(QUEUE_SIZE-1): + q.put(i) + # Test a failing non-blocking put. + q.fail_next_put = True + with self.assertRaises(FailingQueueException): + q.put("oops", block=0) + + q.fail_next_put = True + with self.assertRaises(FailingQueueException): + q.put("oops", timeout=0.1) + q.put(999) + self.assertTrue(q.full(), "Queue should be full") + # Test a failing blocking put + q.fail_next_put = True + with self.assertRaises(FailingQueueException): + self.do_blocking_test(q.put, (888,), q.get, ()) + + # Check the Queue isn't damaged. + # put failed, but get succeeded - re-add + q.put(999) + # Test a failing timeout put + q.fail_next_put = True + self.do_exceptional_blocking_test(q.put, (888, True, 10), q.get, (), + FailingQueueException) + # Check the Queue isn't damaged. + # put failed, but get succeeded - re-add + q.put(999) + self.assertTrue(q.full(), "Queue should be full") + q.get() + self.assertFalse(q.full(), "Queue should not be full") + q.put(999) + self.assertTrue(q.full(), "Queue should be full") + # Test a blocking put + self.do_blocking_test(q.put, (888,), q.get, ()) + # Empty it + for i in range(QUEUE_SIZE): + q.get() + self.assertTrue(q.empty(), "Queue should be empty") + q.put("first") + q.fail_next_get = True + with self.assertRaises(FailingQueueException): + q.get() + + self.assertFalse(q.empty(), "Queue should not be empty") + q.fail_next_get = True + with self.assertRaises(FailingQueueException): + q.get(timeout=0.1) + self.assertFalse(q.empty(), "Queue should not be empty") + q.get() + self.assertTrue(q.empty(), "Queue should be empty") + q.fail_next_get = True + self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',), + FailingQueueException) + # put succeeded, but get failed. + self.assertFalse(q.empty(), "Queue should not be empty") + q.get() + self.assertTrue(q.empty(), "Queue should be empty") + + def test_failing_queue(self): + # Test to make sure a queue is functioning correctly. + # Done twice to the same instance. + q = FailingQueue(QUEUE_SIZE) + self.failing_queue_test(q) + self.failing_queue_test(q) + + +if __name__ == "__main__": + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_select.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_select.py new file mode 100644 index 0000000000000000000000000000000000000000..663afea6ee119a2316c638135cfad8ce2449e1f0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_select.py @@ -0,0 +1,32 @@ +# Tests for the monkey-patched select module. +from gevent import monkey +monkey.patch_all() + +import select + +import gevent.testing as greentest + + +class TestSelect(greentest.TestCase): + + def _make_test(name, ns): # pylint:disable=no-self-argument + def test(self): + self.assertIs(getattr(select, name, self), self) + self.assertFalse(hasattr(select, name)) + test.__name__ = 'test_' + name + '_removed' + ns[test.__name__] = test + + for name in ( + 'epoll', + 'kqueue', + 'kevent', + 'devpoll', + ): + _make_test(name, locals()) # pylint:disable=too-many-function-args + + del name + del _make_test + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_selectors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_selectors.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c5afc71a3bf52f698867e58faaf2dbeb7f08ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_selectors.py @@ -0,0 +1,79 @@ + +try: + # Do this before the patch to be sure we clean + # things up properly if the order is wrong. + import selectors +except ImportError: + import selectors2 as selectors + +from gevent.monkey import patch_all +import gevent.testing as greentest + +patch_all() + +from gevent.selectors import DefaultSelector +from gevent.selectors import GeventSelector +from gevent.tests.test__selectors import SelectorTestMixin + +class TestSelectors(SelectorTestMixin, greentest.TestCase): + + @greentest.skipOnWindows( + "SelectSelector._select is a normal function on Windows" + ) + def test_selectors_select_is_patched(self): + # https://github.com/gevent/gevent/issues/835 + _select = selectors.SelectSelector._select + self.assertIn('_gevent_monkey', dir(_select)) + + def test_default(self): + # Depending on the order of imports, gevent.select.poll may be defined but + # selectors.PollSelector may not be defined. + # https://github.com/gevent/gevent/issues/1466 + self.assertIs(DefaultSelector, GeventSelector) + self.assertIs(selectors.DefaultSelector, GeventSelector) + + def test_import_selectors(self): + # selectors can always be imported once monkey-patched. On Python 2, + # this is an alias for gevent.selectors. + __import__('selectors') + + def _make_test(name, kind): # pylint:disable=no-self-argument + if kind is None: + def m(self): + self.skipTest(name + ' is not defined') + else: + def m(self, k=kind): + with k() as sel: + self._check_selector(sel) + m.__name__ = 'test_selector_' + name + return m + + SelKind = SelKindName = None + for SelKindName in ( + # The subclass hierarchy changes between versions, and is + # complex (e.g, BaseSelector <- BaseSelectorImpl <- + # _PollLikSelector <- PollSelector) so its easier to check against + # names. + 'KqueueSelector', + 'EpollSelector', + 'DevpollSelector', + 'PollSelector', + 'SelectSelector', + GeventSelector, + ): + if not isinstance(SelKindName, type): + SelKind = getattr(selectors, SelKindName, None) + else: + SelKind = SelKindName + SelKindName = SelKind.__name__ + m = _make_test(SelKindName, SelKind) # pylint:disable=too-many-function-args + locals()[m.__name__] = m + + del SelKind + del SelKindName + del _make_test + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld.py new file mode 100644 index 0000000000000000000000000000000000000000..fbff0c9263b61202cdd30bcd98a6caceed55b065 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld.py @@ -0,0 +1,89 @@ +import errno +import os +import sys + +import gevent +import gevent.monkey +gevent.monkey.patch_all() + +pid = None +awaiting_child = [] + + +def handle_sigchld(*_args): + # Make sure we can do a blocking operation + gevent.sleep() + # Signal completion + awaiting_child.pop() + # Raise an ignored error + raise TypeError("This should be ignored but printed") + +# Try to produce output compatible with unittest output so +# our status parsing functions work. + +import signal +if hasattr(signal, 'SIGCHLD'): + # In Python 3.8.0 final, on both Travis CI/Linux and locally + # on macOS, the *child* process started crashing on exit with a memory + # error: + # + # Debug memory block at address p=0x7fcf5d6b5000: API '' + # 6508921152173528397 bytes originally requested + # The 7 pad bytes at p-7 are not all FORBIDDENBYTE (0xfd): + # + # When PYTHONDEVMODE is set. This happens even if we just simply fork + # the child process and don't have gevent even /imported/ in the most + # minimal test case. It's not clear what caused that. + if sys.version_info[:2] >= (3, 8) and os.environ.get("PYTHONDEVMODE"): + print("Ran 1 tests in 0.0s (skipped=1)") + sys.exit(0) + + + assert signal.getsignal(signal.SIGCHLD) == signal.SIG_DFL + signal.signal(signal.SIGCHLD, handle_sigchld) + handler = signal.getsignal(signal.SIGCHLD) + assert signal.getsignal(signal.SIGCHLD) is handle_sigchld, handler + + if hasattr(os, 'forkpty'): + def forkpty(): + # For printing in errors + return os.forkpty()[0] + funcs = (os.fork, forkpty) + else: + funcs = (os.fork,) + + for func in funcs: + awaiting_child = [True] + pid = func() + if not pid: + # child + gevent.sleep(0.3) + sys.exit(0) + else: + timeout = gevent.Timeout(1) + try: + while awaiting_child: + gevent.sleep(0.01) + # We should now be able to waitpid() for an arbitrary child + wpid, status = os.waitpid(-1, os.WNOHANG) + if wpid != pid: + raise AssertionError("Failed to wait on a child pid forked with a function", + wpid, pid, func) + + # And a second call should raise ECHILD + try: + wpid, status = os.waitpid(-1, os.WNOHANG) + raise AssertionError("Should not be able to wait again") + except OSError as e: + assert e.errno == errno.ECHILD + except gevent.Timeout as t: + if timeout is not t: + raise + raise AssertionError("Failed to wait using", func) + finally: + timeout.close() + print("Ran 1 tests in 0.0s") + sys.exit(0) +else: + print("No SIGCHLD, not testing") + print("Ran 1 tests in 0.0s (skipped=1)") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_2.py new file mode 100644 index 0000000000000000000000000000000000000000..51ca4fdb789edafe94b4263a8e50eab567688766 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_2.py @@ -0,0 +1,57 @@ +# Mimics what gunicorn workers do: monkey patch in the child process +# and try to reset signal handlers to SIG_DFL. +# NOTE: This breaks again when gevent.subprocess is used, or any child +# watcher. +import os +import sys + +import signal + +pid = None + +def handle(*_args): + if not pid: + # We only do this is the child so our + # parent's waitpid can get the status. + # This is the opposite of gunicorn. + os.waitpid(-1, os.WNOHANG) +# The signal watcher must be installed *before* monkey patching +if hasattr(signal, 'SIGCHLD'): + if sys.version_info[:2] >= (3, 8) and os.environ.get("PYTHONDEVMODE"): + # See test__monkey_sigchld.py + print("Ran 1 tests in 0.0s (skipped=1)") + sys.exit(0) + + # On Python 2, the signal handler breaks the platform + # module, because it uses os.popen. pkg_resources uses the platform + # module. + # Cache that info. + import platform + platform.uname() + signal.signal(signal.SIGCHLD, handle) + + pid = os.fork() + + if pid: # parent + try: + _, stat = os.waitpid(pid, 0) + except OSError: + # Interrupted system call + _, stat = os.waitpid(pid, 0) + assert stat == 0, stat + else: + # Under Python 2, os.popen() directly uses the popen call, and + # popen's file uses the pclose() system call to + # wait for the child. If it's already waited on, + # it raises the same exception. + # Python 3 uses the subprocess module directly which doesn't + # have this problem. + import gevent.monkey + gevent.monkey.patch_all() + signal.signal(signal.SIGCHLD, signal.SIG_DFL) + f = os.popen('true') + f.close() + + sys.exit(0) +else: + print("No SIGCHLD, not testing") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_3.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_3.py new file mode 100644 index 0000000000000000000000000000000000000000..2060c44e14160f9f9b4bb468c72af33f6c7a9a2b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_sigchld_3.py @@ -0,0 +1,59 @@ +# Mimics what gunicorn workers do *if* the arbiter is also monkey-patched: +# After forking from the master monkey-patched process, the child +# resets signal handlers to SIG_DFL. If we then fork and watch *again*, +# we shouldn't hang. (Note that we carefully handle this so as not to break +# os.popen) +from __future__ import print_function +# Patch in the parent process. +import gevent.monkey +gevent.monkey.patch_all() + +from gevent import get_hub + +import os +import sys + +import signal +import subprocess + +def _waitpid(p): + try: + _, stat = os.waitpid(p, 0) + except OSError: + # Interrupted system call + _, stat = os.waitpid(p, 0) + assert stat == 0, stat + +if hasattr(signal, 'SIGCHLD'): + if sys.version_info[:2] >= (3, 8) and os.environ.get("PYTHONDEVMODE"): + # See test__monkey_sigchld.py + print("Ran 1 tests in 0.0s (skipped=1)") + sys.exit(0) + + # Do what subprocess does and make sure we have the watcher + # in the parent + get_hub().loop.install_sigchld() + + + pid = os.fork() + + if pid: # parent + _waitpid(pid) + else: + # Child resets. + signal.signal(signal.SIGCHLD, signal.SIG_DFL) + + # Go through subprocess because we expect it to automatically + # set up the waiting for us. + # not on Py2 pylint:disable=consider-using-with + popen = subprocess.Popen([sys.executable, '-c', 'import sys'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + popen.stderr.read() + popen.stdout.read() + popen.wait() # This hangs if it doesn't. + popen.stderr.close() + popen.stdout.close() + sys.exit(0) +else: + print("No SIGCHLD, not testing") + print("Ran 1 tests in 0.0s (skipped=1)") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..6794e3da1648c6532edf87c0c119eae71903cca4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning.py @@ -0,0 +1,39 @@ +import unittest +import warnings + +# This file should only have this one test in it +# because we have to be careful about our imports +# and because we need to be careful about our patching. + +class Test(unittest.TestCase): + + def test_with_pkg_resources(self): + # Issue 1108: Python 2, importing pkg_resources, + # as is done for namespace packages, imports ssl, + # leading to an unwanted SSL warning. + # This is a deprecated API though. + with warnings.catch_warnings(): + try: + __import__('pkg_resources') + except ImportError: + self.skipTest('Uses pkg_resources (setuptools) which is not installed') + + from gevent import monkey + + self.assertFalse(monkey.saved) + + with warnings.catch_warnings(record=True) as issued_warnings: + warnings.simplefilter('always') + + monkey.patch_all() + monkey.patch_all() + + issued_warnings = [x for x in issued_warnings + if isinstance(x.message, monkey.MonkeyPatchWarning)] + + self.assertFalse(issued_warnings, [str(i) for i in issued_warnings]) + self.assertEqual(0, len(issued_warnings)) + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning2.py new file mode 100644 index 0000000000000000000000000000000000000000..c7c12399151fc85a738f1bf0bed981b164fd5bd5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning2.py @@ -0,0 +1,44 @@ +import unittest +import warnings +import sys + +# All supported python versions now provide SSLContext. +# We import it by name and subclass it here by name. +# compare with warning3.py +from ssl import SSLContext + +class MySubclass(SSLContext): + pass + +# This file should only have this one test in it +# because we have to be careful about our imports +# and because we need to be careful about our patching. + +class Test(unittest.TestCase): + + @unittest.skipIf(sys.version_info[:2] < (3, 6), + "Only on Python 3.6+") + def test_ssl_subclass_and_module_reference(self): + + from gevent import monkey + + self.assertFalse(monkey.saved) + + with warnings.catch_warnings(record=True) as issued_warnings: + warnings.simplefilter('always') + + monkey.patch_all() + monkey.patch_all() + + issued_warnings = [x for x in issued_warnings + if isinstance(x.message, monkey.MonkeyPatchWarning)] + + self.assertEqual(1, len(issued_warnings)) + message = issued_warnings[0].message + self.assertIn("Modules that had direct imports", str(message)) + self.assertIn("Subclasses (NOT patched)", str(message)) + + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning3.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning3.py new file mode 100644 index 0000000000000000000000000000000000000000..76b2a794605831289672f16af2343de084486b1c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__monkey_ssl_warning3.py @@ -0,0 +1,47 @@ +import unittest +import warnings +import sys + +# All supported python versions now provide SSLContext. +# We subclass without importing by name. Compare with +# warning2.py +import ssl + +class MySubclass(ssl.SSLContext): + pass + +# This file should only have this one test in it +# because we have to be careful about our imports +# and because we need to be careful about our patching. + +class Test(unittest.TestCase): + + @unittest.skipIf(sys.version_info[:2] < (3, 6), + "Only on Python 3.6+") + def test_ssl_subclass_and_module_reference(self): + + from gevent import monkey + + self.assertFalse(monkey.saved) + + with warnings.catch_warnings(record=True) as issued_warnings: + warnings.simplefilter('always') + + monkey.patch_all() + monkey.patch_all() + + issued_warnings = [x for x in issued_warnings + if isinstance(x.message, monkey.MonkeyPatchWarning)] + + self.assertEqual(1, len(issued_warnings)) + message = str(issued_warnings[0].message) + + self.assertNotIn("Modules that had direct imports", message) + self.assertIn("Subclasses (NOT patched)", message) + # the gevent subclasses should not be in here. + self.assertNotIn('gevent.', message) + + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__nondefaultloop.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__nondefaultloop.py new file mode 100644 index 0000000000000000000000000000000000000000..489ff52671040746a926233d39b1b8e6f5a81318 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__nondefaultloop.py @@ -0,0 +1,12 @@ +# test for issue #210 +from gevent import core +from gevent.testing.util import alarm + + +alarm(1) + +log = [] +loop = core.loop(default=False) +loop.run_callback(log.append, 1) +loop.run() +assert log == [1], log diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__order.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__order.py new file mode 100644 index 0000000000000000000000000000000000000000..83aa1c9e2e944d0dc9ee50322599a9b13c7071e5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__order.py @@ -0,0 +1,61 @@ +import gevent +import gevent.testing as greentest +from gevent.testing.six import xrange + + +class appender(object): + + def __init__(self, lst, item): + self.lst = lst + self.item = item + + def __call__(self, *args): + self.lst.append(self.item) + + +class Test(greentest.TestCase): + + count = 2 + + def test_greenlet_link(self): + lst = [] + + # test that links are executed in the same order as they were added + g = gevent.spawn(lst.append, 0) + + for i in xrange(1, self.count): + g.link(appender(lst, i)) + g.join() + self.assertEqual(lst, list(range(self.count))) + + +class Test3(Test): + count = 3 + + +class Test4(Test): + count = 4 + + +class TestM(Test): + count = 1000 + + +class TestSleep0(greentest.TestCase): + + def test(self): + lst = [] + gevent.spawn(sleep0, lst, '1') + gevent.spawn(sleep0, lst, '2') + gevent.wait() + self.assertEqual(' '.join(lst), '1A 2A 1B 2B') + + +def sleep0(lst, param): + lst.append(param + 'A') + gevent.sleep(0) + lst.append(param + 'B') + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__os.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__os.py new file mode 100644 index 0000000000000000000000000000000000000000..d31e1b436a985603116ddf42abc13c8d46b4adf4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__os.py @@ -0,0 +1,180 @@ +from __future__ import print_function, absolute_import, division + +import sys +from os import pipe + + +import gevent +from gevent import os +from gevent import Greenlet, joinall + +from gevent import testing as greentest +from gevent.testing import mock +from gevent.testing import six +from gevent.testing.skipping import skipOnLibuvOnPyPyOnWin + + +class TestOS_tp(greentest.TestCase): + + __timeout__ = greentest.LARGE_TIMEOUT + + def pipe(self): + return pipe() + + read = staticmethod(os.tp_read) + write = staticmethod(os.tp_write) + + @skipOnLibuvOnPyPyOnWin("Sometimes times out") + def _test_if_pipe_blocks(self, buffer_class): + r, w = self.pipe() + # set nbytes such that for sure it is > maximum pipe buffer + nbytes = 1000000 + block = b'x' * 4096 + buf = buffer_class(block) + # Lack of "nonlocal" keyword in Python 2.x: + bytesread = [0] + byteswritten = [0] + + def produce(): + while byteswritten[0] != nbytes: + bytesleft = nbytes - byteswritten[0] + byteswritten[0] += self.write(w, buf[:min(bytesleft, 4096)]) + + def consume(): + while bytesread[0] != nbytes: + bytesleft = nbytes - bytesread[0] + bytesread[0] += len(self.read(r, min(bytesleft, 4096))) + + producer = Greenlet(produce) + producer.start() + consumer = Greenlet(consume) + consumer.start_later(1) + # If patching was not succesful, the producer will have filled + # the pipe before the consumer starts, and would block the entire + # process. Therefore the next line would never finish. + joinall([producer, consumer]) + self.assertEqual(bytesread[0], nbytes) + self.assertEqual(bytesread[0], byteswritten[0]) + + if sys.version_info[0] < 3: + + def test_if_pipe_blocks_buffer(self): + self._test_if_pipe_blocks(six.builtins.buffer) + + if sys.version_info[:2] >= (2, 7): + + def test_if_pipe_blocks_memoryview(self): + self._test_if_pipe_blocks(six.builtins.memoryview) + + +@greentest.skipUnless(hasattr(os, 'make_nonblocking'), + "Only on POSIX") +class TestOS_nb(TestOS_tp): + + def read(self, fd, count): + return os.nb_read(fd, count) + + def write(self, fd, count): + return os.nb_write(fd, count) + + def pipe(self): + r, w = super(TestOS_nb, self).pipe() + os.make_nonblocking(r) + os.make_nonblocking(w) + return r, w + + def _make_ignored_oserror(self): + import errno + ignored_oserror = OSError() + ignored_oserror.errno = errno.EINTR + return ignored_oserror + + + def _check_hub_event_closed(self, mock_get_hub, fd, event): + mock_get_hub.assert_called_once_with() + hub = mock_get_hub.return_value + io = hub.loop.io + io.assert_called_once_with(fd, event) + + event = io.return_value + event.close.assert_called_once_with() + + def _test_event_closed_on_normal_io(self, nb_func, nb_arg, + mock_io, mock_get_hub, event): + mock_io.side_effect = [self._make_ignored_oserror(), 42] + + fd = 100 + result = nb_func(fd, nb_arg) + self.assertEqual(result, 42) + + self._check_hub_event_closed(mock_get_hub, fd, event) + + def _test_event_closed_on_io_error(self, nb_func, nb_arg, + mock_io, mock_get_hub, event): + mock_io.side_effect = [self._make_ignored_oserror(), ValueError()] + + fd = 100 + + with self.assertRaises(ValueError): + nb_func(fd, nb_arg) + + self._check_hub_event_closed(mock_get_hub, fd, event) + + @mock.patch('gevent.os.get_hub') + @mock.patch('gevent.os._write') + def test_event_closed_on_write(self, mock_write, mock_get_hub): + self._test_event_closed_on_normal_io(os.nb_write, b'buf', + mock_write, mock_get_hub, + 2) + + @mock.patch('gevent.os.get_hub') + @mock.patch('gevent.os._write') + def test_event_closed_on_write_error(self, mock_write, mock_get_hub): + self._test_event_closed_on_io_error(os.nb_write, b'buf', + mock_write, mock_get_hub, + 2) + + @mock.patch('gevent.os.get_hub') + @mock.patch('gevent.os._read') + def test_event_closed_on_read(self, mock_read, mock_get_hub): + self._test_event_closed_on_normal_io(os.nb_read, b'buf', + mock_read, mock_get_hub, + 1) + + @mock.patch('gevent.os.get_hub') + @mock.patch('gevent.os._read') + def test_event_closed_on_read_error(self, mock_read, mock_get_hub): + self._test_event_closed_on_io_error(os.nb_read, b'buf', + mock_read, mock_get_hub, + 1) + + +@greentest.skipUnless(hasattr(os, 'fork_and_watch'), + "Only on POSIX") +class TestForkAndWatch(greentest.TestCase): + + __timeout__ = greentest.LARGE_TIMEOUT + + def test_waitpid_all(self): + # Cover this specific case. + pid = os.fork_and_watch() + if pid: + os.waitpid(-1, 0) + # Can't assert on what the found pid actually was, + # our testrunner may have spawned multiple children. + os._reap_children(0) # make the leakchecker happy + else: # pragma: no cover + gevent.sleep(2) + # The test framework will catch a regular SystemExit + # from sys.exit(), we need to just kill the process. + os._exit(0) + + def test_waitpid_wrong_neg(self): + self.assertRaises(OSError, os.waitpid, -2, 0) + + def test_waitpid_wrong_pos(self): + self.assertRaises(OSError, os.waitpid, 1, 0) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pool.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pool.py new file mode 100644 index 0000000000000000000000000000000000000000..1081282e20f91468da9a38e67b51b898e297ebbb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pool.py @@ -0,0 +1,607 @@ +from time import time +import gevent +import gevent.pool +from gevent.event import Event +from gevent.queue import Queue + +import gevent.testing as greentest +import gevent.testing.timing +import random +from gevent.testing import ExpectedException + +import unittest + + +class TestCoroutinePool(unittest.TestCase): + klass = gevent.pool.Pool + + def test_apply_async(self): + done = Event() + + def some_work(_): + done.set() + + pool = self.klass(2) + pool.apply_async(some_work, ('x', )) + done.wait() + + def test_apply(self): + value = 'return value' + + def some_work(): + return value + + pool = self.klass(2) + result = pool.apply(some_work) + self.assertEqual(value, result) + + def test_apply_raises(self): + pool = self.klass(1) + + def raiser(): + raise ExpectedException() + try: + pool.apply(raiser) + except ExpectedException: + pass + else: + self.fail("Should have raised ExpectedException") + # Don't let the metaclass automatically force any error + # that reaches the hub from a spawned greenlet to become + # fatal; that defeats the point of the test. + test_apply_raises.error_fatal = False + + def test_multiple_coros(self): + evt = Event() + results = [] + + def producer(): + gevent.sleep(0.001) + results.append('prod') + evt.set() + + def consumer(): + results.append('cons1') + evt.wait() + results.append('cons2') + + pool = self.klass(2) + done = pool.spawn(consumer) + pool.apply_async(producer) + done.get() + self.assertEqual(['cons1', 'prod', 'cons2'], results) + + def dont_test_timer_cancel(self): + timer_fired = [] + + def fire_timer(): + timer_fired.append(True) + + def some_work(): + gevent.timer(0, fire_timer) # pylint:disable=no-member + + pool = self.klass(2) + pool.apply(some_work) + gevent.sleep(0) + self.assertEqual(timer_fired, []) + + def test_reentrant(self): + pool = self.klass(1) + result = pool.apply(pool.apply, (lambda a: a + 1, (5, ))) + self.assertEqual(result, 6) + evt = Event() + pool.apply_async(evt.set) + evt.wait() + + @greentest.skipOnPyPy("Does not work on PyPy") # Why? + def test_stderr_raising(self): + # testing that really egregious errors in the error handling code + # (that prints tracebacks to stderr) don't cause the pool to lose + # any members + import sys + pool = self.klass(size=1) + + # we're going to do this by causing the traceback.print_exc in + # safe_apply to raise an exception and thus exit _main_loop + normal_err = sys.stderr + try: + sys.stderr = FakeFile() + waiter = pool.spawn(crash) + with gevent.Timeout(2): + # Without the timeout, we can get caught...doing something? + # If we call PyErr_WriteUnraisable at a certain point, + # we appear to switch back to the hub and do nothing, + # meaning we sit forever. The timeout at least keeps us from + # doing that and fails the test if we mess up error handling. + self.assertRaises(RuntimeError, waiter.get) + # the pool should have something free at this point since the + # waiter returned + # pool.Pool change: if an exception is raised during execution of a link, + # the rest of the links are scheduled to be executed on the next hub iteration + # this introduces a delay in updating pool.sem which makes pool.free_count() report 0 + # therefore, sleep: + gevent.sleep(0) + self.assertEqual(pool.free_count(), 1) + # shouldn't block when trying to get + with gevent.Timeout.start_new(0.1): + pool.apply(gevent.sleep, (0, )) + finally: + sys.stderr = normal_err + pool.join() + + +def crash(*_args, **_kw): + raise RuntimeError("Raising an error from the crash() function") + + +class FakeFile(object): + + def write(self, *_args): + raise RuntimeError('Writing to the file failed') + + +class PoolBasicTests(greentest.TestCase): + klass = gevent.pool.Pool + + def test_execute_async(self): + p = self.klass(size=2) + self.assertEqual(p.free_count(), 2) + r = [] + + first = p.spawn(r.append, 1) + self.assertEqual(p.free_count(), 1) + first.get() + self.assertEqual(r, [1]) + gevent.sleep(0) + self.assertEqual(p.free_count(), 2) + + #Once the pool is exhausted, calling an execute forces a yield. + + p.apply_async(r.append, (2, )) + self.assertEqual(1, p.free_count()) + self.assertEqual(r, [1]) + + p.apply_async(r.append, (3, )) + self.assertEqual(0, p.free_count()) + self.assertEqual(r, [1]) + + p.apply_async(r.append, (4, )) + self.assertEqual(r, [1]) + gevent.sleep(0.01) + self.assertEqual(sorted(r), [1, 2, 3, 4]) + + def test_discard(self): + p = self.klass(size=1) + first = p.spawn(gevent.sleep, 1000) + p.discard(first) + first.kill() + self.assertFalse(first) + self.assertEqual(len(p), 0) + self.assertEqual(p._semaphore.counter, 1) + + def test_add_method(self): + p = self.klass(size=1) + first = gevent.spawn(gevent.sleep, 1000) + try: + second = gevent.spawn(gevent.sleep, 1000) + try: + self.assertEqual(p.free_count(), 1) + self.assertEqual(len(p), 0) + p.add(first) + self.assertEqual(p.free_count(), 0) + self.assertEqual(len(p), 1) + + with self.assertRaises(gevent.Timeout): + with gevent.Timeout(0.1): + p.add(second) + + self.assertEqual(p.free_count(), 0) + self.assertEqual(len(p), 1) + finally: + second.kill() + finally: + first.kill() + + @greentest.ignores_leakcheck + def test_add_method_non_blocking(self): + p = self.klass(size=1) + first = gevent.spawn(gevent.sleep, 1000) + try: + second = gevent.spawn(gevent.sleep, 1000) + try: + p.add(first) + with self.assertRaises(gevent.pool.PoolFull): + p.add(second, blocking=False) + finally: + second.kill() + finally: + first.kill() + + @greentest.ignores_leakcheck + def test_add_method_timeout(self): + p = self.klass(size=1) + first = gevent.spawn(gevent.sleep, 1000) + try: + second = gevent.spawn(gevent.sleep, 1000) + try: + p.add(first) + with self.assertRaises(gevent.pool.PoolFull): + p.add(second, timeout=0.100) + finally: + second.kill() + finally: + first.kill() + + @greentest.ignores_leakcheck + def test_start_method_timeout(self): + p = self.klass(size=1) + first = gevent.spawn(gevent.sleep, 1000) + try: + second = gevent.Greenlet(gevent.sleep, 1000) + try: + p.add(first) + with self.assertRaises(gevent.pool.PoolFull): + p.start(second, timeout=0.100) + finally: + second.kill() + finally: + first.kill() + + def test_apply(self): + p = self.klass() + result = p.apply(lambda a: ('foo', a), (1, )) + self.assertEqual(result, ('foo', 1)) + + def test_init_error(self): + self.switch_expected = False + self.assertRaises(ValueError, self.klass, -1) + +# +# tests from standard library test/test_multiprocessing.py + + +class TimingWrapper(object): + + def __init__(self, func): + self.func = func + self.elapsed = None + + def __call__(self, *args, **kwds): + t = time() + try: + return self.func(*args, **kwds) + finally: + self.elapsed = time() - t + + +def sqr(x, wait=0.0): + gevent.sleep(wait) + return x * x + + +def squared(x): + return x * x + + +def sqr_random_sleep(x): + gevent.sleep(random.random() * 0.1) + return x * x + + +def final_sleep(): + yield from range(3) + gevent.sleep(0.2) + + +TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.082, 0.035, 0.14 + + +SMALL_RANGE = 10 +LARGE_RANGE = 1000 + +if (greentest.PYPY and greentest.WIN) or greentest.RUN_LEAKCHECKS or greentest.RUN_COVERAGE: + # See comments in test__threadpool.py. + LARGE_RANGE = 25 +elif greentest.RUNNING_ON_CI or greentest.EXPECT_POOR_TIMER_RESOLUTION: + LARGE_RANGE = 100 + +class TestPool(greentest.TestCase): # pylint:disable=too-many-public-methods + __timeout__ = greentest.LARGE_TIMEOUT + size = 1 + + def setUp(self): + greentest.TestCase.setUp(self) + self.pool = gevent.pool.Pool(self.size) + + def cleanup(self): + self.pool.join() + + def test_apply(self): + papply = self.pool.apply + self.assertEqual(papply(sqr, (5,)), 25) + self.assertEqual(papply(sqr, (), {'x': 3}), 9) + + def test_map(self): + pmap = self.pool.map + self.assertEqual(pmap(sqr, range(SMALL_RANGE)), list(map(squared, range(SMALL_RANGE)))) + self.assertEqual(pmap(sqr, range(100)), list(map(squared, range(100)))) + + def test_async(self): + res = self.pool.apply_async(sqr, (7, TIMEOUT1,)) + get = TimingWrapper(res.get) + self.assertEqual(get(), 49) + self.assertTimeoutAlmostEqual(get.elapsed, TIMEOUT1, 1) + + def test_async_callback(self): + result = [] + res = self.pool.apply_async(sqr, (7, TIMEOUT1,), callback=result.append) + get = TimingWrapper(res.get) + self.assertEqual(get(), 49) + self.assertTimeoutAlmostEqual(get.elapsed, TIMEOUT1, 1) + gevent.sleep(0) # lets the callback run + self.assertEqual(result, [49]) + + def test_async_timeout(self): + res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 0.2)) + get = TimingWrapper(res.get) + self.assertRaises(gevent.Timeout, get, timeout=TIMEOUT2) + self.assertTimeoutAlmostEqual(get.elapsed, TIMEOUT2, 1) + self.pool.join() + + def test_imap_list_small(self): + it = self.pool.imap(sqr, range(SMALL_RANGE)) + self.assertEqual(list(it), list(map(sqr, range(SMALL_RANGE)))) + + def test_imap_it_small(self): + it = self.pool.imap(sqr, range(SMALL_RANGE)) + for i in range(SMALL_RANGE): + self.assertEqual(next(it), i * i) + self.assertRaises(StopIteration, next, it) + + def test_imap_it_large(self): + it = self.pool.imap(sqr, range(LARGE_RANGE)) + for i in range(LARGE_RANGE): + self.assertEqual(next(it), i * i) + self.assertRaises(StopIteration, next, it) + + def test_imap_random(self): + it = self.pool.imap(sqr_random_sleep, range(SMALL_RANGE)) + self.assertEqual(list(it), list(map(squared, range(SMALL_RANGE)))) + + def test_imap_unordered(self): + it = self.pool.imap_unordered(sqr, range(LARGE_RANGE)) + self.assertEqual(sorted(it), list(map(squared, range(LARGE_RANGE)))) + + it = self.pool.imap_unordered(sqr, range(LARGE_RANGE)) + self.assertEqual(sorted(it), list(map(squared, range(LARGE_RANGE)))) + + def test_imap_unordered_random(self): + it = self.pool.imap_unordered(sqr_random_sleep, range(SMALL_RANGE)) + self.assertEqual(sorted(it), list(map(squared, range(SMALL_RANGE)))) + + def test_empty_imap_unordered(self): + it = self.pool.imap_unordered(sqr, []) + self.assertEqual(list(it), []) + + def test_empty_imap(self): + it = self.pool.imap(sqr, []) + self.assertEqual(list(it), []) + + def test_empty_map(self): + self.assertEqual(self.pool.map(sqr, []), []) + + def test_terminate(self): + result = self.pool.map_async(gevent.sleep, [0.1] * ((self.size or 10) * 2)) + gevent.sleep(0.1) + kill = TimingWrapper(self.pool.kill) + kill() + self.assertTimeWithinRange(kill.elapsed, 0.0, 0.5) + result.join() + + def sleep(self, x): + gevent.sleep(float(x) / 10.) + return str(x) + + def test_imap_unordered_sleep(self): + # testing that imap_unordered returns items in competion order + result = list(self.pool.imap_unordered(self.sleep, [10, 1, 2])) + if self.pool.size == 1: + expected = ['10', '1', '2'] + else: + expected = ['1', '2', '10'] + self.assertEqual(result, expected) + + # https://github.com/gevent/gevent/issues/423 + def test_imap_no_stop(self): + q = Queue() + q.put(123) + gevent.spawn_later(0.1, q.put, StopIteration) + result = list(self.pool.imap(lambda _: _, q)) + self.assertEqual(result, [123]) + + def test_imap_unordered_no_stop(self): + q = Queue() + q.put(1234) + gevent.spawn_later(0.1, q.put, StopIteration) + result = list(self.pool.imap_unordered(lambda _: _, q)) + self.assertEqual(result, [1234]) + + # same issue, but different test: https://github.com/gevent/gevent/issues/311 + def test_imap_final_sleep(self): + result = list(self.pool.imap(sqr, final_sleep())) + self.assertEqual(result, [0, 1, 4]) + + def test_imap_unordered_final_sleep(self): + result = list(self.pool.imap_unordered(sqr, final_sleep())) + self.assertEqual(result, [0, 1, 4]) + + # Issue 638 + def test_imap_unordered_bounded_queue(self): + iterable = list(range(100)) + + running = [0] + + def short_running_func(i, _j): + running[0] += 1 + return i + + def make_reader(mapping): + # Simulate a long running reader. No matter how many workers + # we have, we will never have a queue more than size 1 + def reader(): + result = [] + for i, x in enumerate(mapping): + self.assertTrue(running[0] <= i + 2, running[0]) + result.append(x) + gevent.sleep(0.01) + self.assertTrue(len(mapping.queue) <= 2, len(mapping.queue)) + return result + return reader + + # Send two iterables to make sure varargs and kwargs are handled + # correctly + for meth in self.pool.imap_unordered, self.pool.imap: + running[0] = 0 + mapping = meth(short_running_func, iterable, iterable, + maxsize=1) + + reader = make_reader(mapping) + l = reader() + self.assertEqual(sorted(l), iterable) + +@greentest.ignores_leakcheck +class TestPool2(TestPool): + size = 2 + +@greentest.ignores_leakcheck +class TestPool3(TestPool): + size = 3 + +@greentest.ignores_leakcheck +class TestPool10(TestPool): + size = 10 + + +class TestPoolUnlimit(TestPool): + size = None + + +class TestPool0(greentest.TestCase): + size = 0 + + def test_wait_full(self): + p = gevent.pool.Pool(size=0) + self.assertEqual(0, p.free_count()) + self.assertTrue(p.full()) + self.assertEqual(0, p.wait_available(timeout=0.01)) + + +class TestJoinSleep(gevent.testing.timing.AbstractGenericWaitTestCase): + + def wait(self, timeout): + p = gevent.pool.Pool() + g = p.spawn(gevent.sleep, 10) + try: + p.join(timeout=timeout) + finally: + g.kill() + + +class TestJoinSleep_raise_error(gevent.testing.timing.AbstractGenericWaitTestCase): + + def wait(self, timeout): + p = gevent.pool.Pool() + g = p.spawn(gevent.sleep, 10) + try: + p.join(timeout=timeout, raise_error=True) + finally: + g.kill() + + +class TestJoinEmpty(greentest.TestCase): + switch_expected = False + + def test(self): + p = gevent.pool.Pool() + res = p.join() + self.assertTrue(res, "empty should return true") + + +class TestSpawn(greentest.TestCase): + switch_expected = True + + def test(self): + p = gevent.pool.Pool(1) + self.assertEqual(len(p), 0) + p.spawn(gevent.sleep, 0.1) + self.assertEqual(len(p), 1) + p.spawn(gevent.sleep, 0.1) # this spawn blocks until the old one finishes + self.assertEqual(len(p), 1) + gevent.sleep(0.19 if not greentest.EXPECT_POOR_TIMER_RESOLUTION else 0.5) + self.assertEqual(len(p), 0) + + def testSpawnAndWait(self): + p = gevent.pool.Pool(1) + self.assertEqual(len(p), 0) + p.spawn(gevent.sleep, 0.1) + self.assertEqual(len(p), 1) + res = p.join(0.01) + self.assertFalse(res, "waiting on a full pool should return false") + res = p.join() + self.assertTrue(res, "waiting to finish should be true") + self.assertEqual(len(p), 0) + +def error_iter(): + yield 1 + yield 2 + raise ExpectedException + + +class TestErrorInIterator(greentest.TestCase): + error_fatal = False + + def test(self): + p = gevent.pool.Pool(3) + self.assertRaises(ExpectedException, p.map, lambda x: None, error_iter()) + gevent.sleep(0.001) + + def test_unordered(self): + p = gevent.pool.Pool(3) + + def unordered(): + return list(p.imap_unordered(lambda x: None, error_iter())) + + self.assertRaises(ExpectedException, unordered) + gevent.sleep(0.001) + + +def divide_by(x): + return 1.0 / x + + +class TestErrorInHandler(greentest.TestCase): + error_fatal = False + + def test_map(self): + p = gevent.pool.Pool(3) + self.assertRaises(ZeroDivisionError, p.map, divide_by, [1, 0, 2]) + + def test_imap(self): + p = gevent.pool.Pool(1) + it = p.imap(divide_by, [1, 0, 2]) + self.assertEqual(next(it), 1.0) + self.assertRaises(ZeroDivisionError, next, it) + self.assertEqual(next(it), 0.5) + self.assertRaises(StopIteration, next, it) + + def test_imap_unordered(self): + p = gevent.pool.Pool(1) + it = p.imap_unordered(divide_by, [1, 0, 2]) + self.assertEqual(next(it), 1.0) + self.assertRaises(ZeroDivisionError, next, it) + self.assertEqual(next(it), 0.5) + self.assertRaises(StopIteration, next, it) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pywsgi.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pywsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..ae4bf9834fb28d82d12ed351585a772da3a8739b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__pywsgi.py @@ -0,0 +1,2065 @@ +# Copyright (c) 2007, Linden Research, Inc. +# Copyright (c) 2009-2010 gevent contributors +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# pylint: disable=too-many-lines,unused-argument,too-many-ancestors +from gevent import monkey + +monkey.patch_all() + +from contextlib import contextmanager +from urllib.parse import parse_qs +import os +import sys +from io import BytesIO as StringIO + +import weakref +import unittest +from wsgiref.validate import validator + +import gevent.testing as greentest +import gevent +from gevent.testing import PY3, PYPY +from gevent.testing.exception import ExpectedException +from gevent import socket +from gevent import pywsgi +from gevent.pywsgi import Input + + +class ExpectedAssertionError(ExpectedException, AssertionError): + """An expected assertion error""" + +CONTENT_LENGTH = 'Content-Length' +CONN_ABORTED_ERRORS = greentest.CONN_ABORTED_ERRORS + +REASONS = { + 200: 'OK', + 500: 'Internal Server Error' +} + + +class ConnectionClosed(Exception): + pass + + +def read_headers(fd): + response_line = fd.readline() + if not response_line: + raise ConnectionClosed + response_line = response_line.decode('latin-1') + headers = {} + while True: + line = fd.readline().strip() + if not line: + break + line = line.decode('latin-1') + try: + key, value = line.split(': ', 1) + except: + print('Failed to split: %r' % (line, )) + raise + assert key.lower() not in {x.lower() for x in headers}, 'Header %r:%r sent more than once: %r' % (key, value, headers) + headers[key] = value + return response_line, headers + + +def iread_chunks(fd): + while True: + line = fd.readline() + chunk_size = line.strip() + chunk_size = int(chunk_size, 16) + if chunk_size == 0: + crlf = fd.read(2) + assert crlf == b'\r\n', repr(crlf) + break + data = fd.read(chunk_size) + yield data + crlf = fd.read(2) + assert crlf == b'\r\n', repr(crlf) + + +class Response(object): + + def __init__(self, status_line, headers): + self.status_line = status_line + self.headers = headers + self.body = None + self.chunks = False + try: + version, code, self.reason = status_line[:-2].split(' ', 2) + self.code = int(code) + HTTP, self.version = version.split('/') + assert HTTP == 'HTTP', repr(HTTP) + assert self.version in ('1.0', '1.1'), repr(self.version) + except Exception: + print('Error: %r' % status_line) + raise + + def __iter__(self): + yield self.status_line + yield self.headers + yield self.body + + def __str__(self): + args = (self.__class__.__name__, self.status_line, self.headers, self.body, self.chunks) + return '<%s status_line=%r headers=%r body=%r chunks=%r>' % args + + def assertCode(self, code): + if hasattr(code, '__contains__'): + assert self.code in code, 'Unexpected code: %r (expected %r)\n%s' % (self.code, code, self) + else: + assert self.code == code, 'Unexpected code: %r (expected %r)\n%s' % (self.code, code, self) + + def assertReason(self, reason): + assert self.reason == reason, 'Unexpected reason: %r (expected %r)\n%s' % (self.reason, reason, self) + + def assertVersion(self, version): + assert self.version == version, 'Unexpected version: %r (expected %r)\n%s' % (self.version, version, self) + + def assertHeader(self, header, value): + real_value = self.headers.get(header, False) + assert real_value == value, \ + 'Unexpected header %r: %r (expected %r)\n%s' % (header, real_value, value, self) + + def assertBody(self, body): + if isinstance(body, str) and PY3: + body = body.encode("ascii") + assert self.body == body, 'Unexpected body: %r (expected %r)\n%s' % (self.body, body, self) + + @classmethod + def read(cls, fd, code=200, reason='default', version='1.1', + body=None, chunks=None, content_length=None): + """ + Read an HTTP response, optionally perform assertions, + and return the Response object. + """ + # pylint:disable=too-many-branches + _status_line, headers = read_headers(fd) + self = cls(_status_line, headers) + if code is not None: + self.assertCode(code) + if reason == 'default': + reason = REASONS.get(code) + if reason is not None: + self.assertReason(reason) + if version is not None: + self.assertVersion(version) + if self.code == 100: + return self + if content_length is not None: + if isinstance(content_length, int): + content_length = str(content_length) + self.assertHeader('Content-Length', content_length) + + if 'chunked' in headers.get('Transfer-Encoding', ''): + if CONTENT_LENGTH in headers: + print("WARNING: server used chunked transfer-encoding despite having Content-Length header (libevent 1.x's bug)") + self.chunks = list(iread_chunks(fd)) + self.body = b''.join(self.chunks) + elif CONTENT_LENGTH in headers: + num = int(headers[CONTENT_LENGTH]) + self.body = fd.read(num) + else: + self.body = fd.read() + + if body is not None: + self.assertBody(body) + if chunks is not None: + assert chunks == self.chunks, (chunks, self.chunks) + return self + +read_http = Response.read + + +class TestCase(greentest.TestCase): + server = None + validator = staticmethod(validator) + application = None + + # Bind to default address, which should give us ipv6 (when available) + # and ipv4. (see self.connect()) + listen_addr = greentest.DEFAULT_BIND_ADDR + # connect on ipv4, even though we bound to ipv6 too + # to prove ipv4 works...except on Windows, it apparently doesn't. + # So use the hostname. + connect_addr = greentest.DEFAULT_LOCAL_HOST_ADDR + + class handler_class(pywsgi.WSGIHandler): + ApplicationError = ExpectedAssertionError + + def init_logger(self): + import logging + logger = logging.getLogger('gevent.tests.pywsgi') + logger.setLevel(logging.CRITICAL) + return logger + + def init_server(self, application): + logger = self.logger = self.init_logger() + self.server = pywsgi.WSGIServer( + (self.listen_addr, 0), + application, + log=logger, error_log=logger, + handler_class=self.handler_class, + ) + + def setUp(self): + application = self.application + if self.validator is not None: + application = self.validator(application) + self.init_server(application) + self.server.start() + while not self.server.server_port: + print("Waiting on server port") + self.port = self.server.server_port + assert self.port + greentest.TestCase.setUp(self) + + if greentest.CPYTHON and greentest.PY2: + # Keeping raw sockets alive keeps SSL sockets + # from being closed too, at least on CPython2, so we + # need to use weakrefs. + + # In contrast, on PyPy, *only* having a weakref lets the + # original socket die and leak + + def _close_on_teardown(self, resource): + self.close_on_teardown.append(weakref.ref(resource)) + return resource + + def _tearDownCloseOnTearDown(self): + self.close_on_teardown = [r() for r in self.close_on_teardown if r() is not None] + super(TestCase, self)._tearDownCloseOnTearDown() + + def tearDown(self): + greentest.TestCase.tearDown(self) + if self.server is not None: + with gevent.Timeout.start_new(0.5): + self.server.stop() + self.server = None + if greentest.PYPY: + import gc + gc.collect() + gc.collect() + + + @contextmanager + def connect(self): + conn = socket.create_connection((self.connect_addr, self.port)) + result = conn + if PY3: + conn_makefile = conn.makefile + + def makefile(*args, **kwargs): + if 'bufsize' in kwargs: + kwargs['buffering'] = kwargs.pop('bufsize') + + if 'mode' in kwargs: + return conn_makefile(*args, **kwargs) + + # Under Python3, you can't read and write to the same + # makefile() opened in (default) r, and r+ is not allowed + kwargs['mode'] = 'rwb' + rconn = conn_makefile(*args, **kwargs) + _rconn_write = rconn.write + + def write(data): + if isinstance(data, str): + data = data.encode('ascii') + return _rconn_write(data) + rconn.write = write + self._close_on_teardown(rconn) + return rconn + + class proxy(object): + def __getattribute__(self, name): + if name == 'makefile': + return makefile + return getattr(conn, name) + result = proxy() + try: + yield result + finally: + result.close() + + @contextmanager + def makefile(self): + with self.connect() as sock: + try: + result = sock.makefile(bufsize=1) # pylint:disable=unexpected-keyword-arg + yield result + finally: + result.close() + + def urlopen(self, *args, **kwargs): + with self.connect() as sock: + with sock.makefile(bufsize=1) as fd: # pylint:disable=unexpected-keyword-arg + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') + return read_http(fd, *args, **kwargs) + + HTTP_CLIENT_VERSION = '1.1' + DEFAULT_EXTRA_CLIENT_HEADERS = {} + + def format_request(self, method='GET', path='/', **headers): + def_headers = self.DEFAULT_EXTRA_CLIENT_HEADERS.copy() + def_headers.update(headers) + headers = def_headers + + headers = '\r\n'.join('%s: %s' % item for item in headers.items()) + headers = headers + '\r\n' if headers else headers + result = ( + '%(method)s %(path)s HTTP/%(http_ver)s\r\n' + 'Host: localhost\r\n' + '%(headers)s' + '\r\n' + ) + result = result % dict( + method=method, + path=path, + http_ver=self.HTTP_CLIENT_VERSION, + headers=headers + ) + return result + + +class CommonTestMixin(object): + PIPELINE_NOT_SUPPORTED_EXS = () + EXPECT_CLOSE = False + EXPECT_KEEPALIVE = False + + def test_basic(self): + with self.makefile() as fd: + fd.write(self.format_request()) + response = read_http(fd, body='hello world') + if response.headers.get('Connection') == 'close': + self.assertTrue(self.EXPECT_CLOSE, "Server closed connection, not expecting that") + return response, None + + self.assertFalse(self.EXPECT_CLOSE) + if self.EXPECT_KEEPALIVE: + response.assertHeader('Connection', 'keep-alive') + fd.write(self.format_request(path='/notexist')) + dne_response = read_http(fd, code=404, reason='Not Found', body='not found') + fd.write(self.format_request()) + response = read_http(fd, body='hello world') + return response, dne_response + + + + def test_pipeline(self): + exception = AssertionError('HTTP pipelining not supported; the second request is thrown away') + with self.makefile() as fd: + fd.write(self.format_request() + self.format_request(path='/notexist')) + read_http(fd, body='hello world') + + try: + timeout = gevent.Timeout.start_new(0.5, exception=exception) + try: + read_http(fd, code=404, reason='Not Found', body='not found') + finally: + timeout.close() + except self.PIPELINE_NOT_SUPPORTED_EXS: + pass + except AssertionError as ex: + if ex is not exception: + raise + + def test_connection_close(self): + with self.makefile() as fd: + fd.write(self.format_request()) + response = read_http(fd) + if response.headers.get('Connection') == 'close': + self.assertTrue(self.EXPECT_CLOSE, "Server closed connection, not expecting that") + return + self.assertFalse(self.EXPECT_CLOSE) + if self.EXPECT_KEEPALIVE: + response.assertHeader('Connection', 'keep-alive') + + fd.write(self.format_request(Connection='close')) + read_http(fd) + fd.write(self.format_request()) + # This may either raise, or it may return an empty response, + # depend on timing and the Python version. + try: + result = fd.readline() + except socket.error as ex: + if ex.args[0] not in CONN_ABORTED_ERRORS: + raise + else: + self.assertFalse( + result, + 'The remote side is expected to close the connection, but it sent %r' + % (result,)) + + @unittest.skip("Not sure") + def test_006_reject_long_urls(self): + path_parts = [] + for _ in range(3000): + path_parts.append('path') + path = '/'.join(path_parts) + + with self.makefile() as fd: + request = 'GET /%s HTTP/1.0\r\nHost: localhost\r\n\r\n' % path + fd.write(request) + result = fd.readline() + status = result.split(' ')[1] + self.assertEqual(status, '414') + + +class TestNoChunks(CommonTestMixin, TestCase): + # when returning a list of strings a shortcut is employed by the server: + # it calculates the content-length and joins all the chunks before sending + validator = None + last_environ = None + + def _check_environ(self, input_terminated=True): + if input_terminated: + self.assertTrue(self.last_environ.get('wsgi.input_terminated')) + else: + self.assertFalse(self.last_environ['wsgi.input_terminated']) + + def application(self, env, start_response): + self.last_environ = env + path = env['PATH_INFO'] + if path == '/': + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [b'hello ', b'world'] + if path == '/websocket': + write = start_response('101 Switching Protocols', + [('Content-Type', 'text/plain'), + # Con:close is to make our simple client + # happy; otherwise it wants to read data from the + # body thot's being kept open. + ('Connection', 'close')]) + write(b'') # Trigger finalizing the headers now. + return [b'upgrading to', b'websocket'] + start_response('404 Not Found', [('Content-Type', 'text/plain')]) + return [b'not ', b'found'] + + def test_basic(self): + response, dne_response = super(TestNoChunks, self).test_basic() + self._check_environ() + self.assertFalse(response.chunks) + response.assertHeader('Content-Length', '11') + if dne_response is not None: + self.assertFalse(dne_response.chunks) + dne_response.assertHeader('Content-Length', '9') + + def test_dne(self): + with self.makefile() as fd: + fd.write(self.format_request(path='/notexist')) + response = read_http(fd, code=404, reason='Not Found', body='not found') + self.assertFalse(response.chunks) + self._check_environ() + response.assertHeader('Content-Length', '9') + +class TestConnectionUpgrades(TestNoChunks): + + def test_connection_upgrade(self): + with self.makefile() as fd: + fd.write(self.format_request(path='/websocket', Connection='upgrade')) + response = read_http(fd, code=101) + + self._check_environ(input_terminated=False) + self.assertFalse(response.chunks) + + def test_upgrade_websocket(self): + with self.makefile() as fd: + fd.write(self.format_request(path='/websocket', Upgrade='websocket')) + response = read_http(fd, code=101) + + self._check_environ(input_terminated=False) + self.assertFalse(response.chunks) + + +class TestNoChunks10(TestNoChunks): + HTTP_CLIENT_VERSION = '1.0' + PIPELINE_NOT_SUPPORTED_EXS = (ConnectionClosed,) + EXPECT_CLOSE = True + +class TestNoChunks10KeepAlive(TestNoChunks10): + DEFAULT_EXTRA_CLIENT_HEADERS = { + 'Connection': 'keep-alive', + } + EXPECT_CLOSE = False + EXPECT_KEEPALIVE = True + + +class TestExplicitContentLength(TestNoChunks): # pylint:disable=too-many-ancestors + # when returning a list of strings a shortcut is employed by the + # server - it caculates the content-length + + def application(self, env, start_response): + self.last_environ = env + self.assertTrue(env.get('wsgi.input_terminated')) + path = env['PATH_INFO'] + if path == '/': + start_response('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', '11')]) + return [b'hello ', b'world'] + + start_response('404 Not Found', [('Content-Type', 'text/plain'), ('Content-Length', '9')]) + return [b'not ', b'found'] + + +class TestYield(CommonTestMixin, TestCase): + + @staticmethod + def application(env, start_response): + path = env['PATH_INFO'] + if path == '/': + start_response('200 OK', [('Content-Type', 'text/plain')]) + yield b"hello world" + else: + start_response('404 Not Found', [('Content-Type', 'text/plain')]) + yield b"not found" + + +class TestBytearray(CommonTestMixin, TestCase): + + validator = None + + @staticmethod + def application(env, start_response): + path = env['PATH_INFO'] + if path == '/': + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [bytearray(b"hello "), bytearray(b"world")] + start_response('404 Not Found', [('Content-Type', 'text/plain')]) + return [bytearray(b"not found")] + + +class TestMultiLineHeader(TestCase): + @staticmethod + def application(env, start_response): + assert "test.submit" in env["CONTENT_TYPE"] + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [b"ok"] + + def test_multiline_116(self): + """issue #116""" + request = '\r\n'.join(( + 'POST / HTTP/1.0', + 'Host: localhost', + 'Content-Type: multipart/related; boundary="====XXXX====";', + ' type="text/xml";start="test.submit"', + 'Content-Length: 0', + '', '')) + with self.makefile() as fd: + fd.write(request) + read_http(fd) + + +class TestGetArg(TestCase): + + @staticmethod + def application(env, start_response): + body = env['wsgi.input'].read(3) + if PY3: + body = body.decode('ascii') + a = parse_qs(body).get('a', [1])[0] + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [('a is %s, body is %s' % (a, body)).encode('ascii')] + + def test_007_get_arg(self): + # define a new handler that does a get_arg as well as a read_body + + request = '\r\n'.join(( + 'POST / HTTP/1.0', + 'Host: localhost', + 'Content-Length: 3', + '', + 'a=a')) + with self.makefile() as fd: + fd.write(request) + + # send some junk after the actual request + fd.write('01234567890123456789') + read_http(fd, body='a is a, body is a=a') + + +class TestCloseIter(TestCase): + + # The *Validator* closes the iterators! + validator = None + + def application(self, env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + return self + + def __iter__(self): + yield bytearray(b"Hello World") + yield b"!" + + closed = False + + def close(self): + self.closed += 1 + + def test_close_is_called(self): + self.closed = False + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') + read_http(fd, body=b"Hello World!", chunks=[b'Hello World', b'!']) + # We got closed exactly once. + self.assertEqual(self.closed, 1) + +class TestChunkedApp(TestCase): + + chunks = [b'this', b'is', b'chunked'] + + def body(self): + return b''.join(self.chunks) + + def application(self, env, start_response): + self.assertTrue(env.get('wsgi.input_terminated')) + start_response('200 OK', [('Content-Type', 'text/plain')]) + yield from self.chunks + + def test_chunked_response(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + response = read_http(fd, body=self.body(), chunks=None) + + response.assertHeader('Transfer-Encoding', 'chunked') + self.assertEqual(response.chunks, self.chunks) + + def test_no_chunked_http_1_0(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.0\r\nHost: localhost\r\nConnection: close\r\n\r\n') + response = read_http(fd) + self.assertEqual(response.body, self.body()) + self.assertEqual(response.headers.get('Transfer-Encoding'), None) + content_length = response.headers.get('Content-Length') + if content_length is not None: + self.assertEqual(content_length, str(len(self.body()))) + + +class TestBigChunks(TestChunkedApp): + chunks = [b'a' * 8192] * 3 + + +class TestNegativeRead(TestCase): + + def application(self, env, start_response): + self.assertTrue(env.get('wsgi.input_terminated')) + start_response('200 OK', [('Content-Type', 'text/plain')]) + if env['PATH_INFO'] == '/read': + data = env['wsgi.input'].read(-1) + return [data] + + def test_negative_chunked_read(self): + data = (b'POST /read HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + def test_negative_nonchunked_read(self): + data = (b'POST /read HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Content-Length: 6\r\n\r\n' + b'oh hai') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + +class TestNegativeReadline(TestCase): + validator = None + + @staticmethod + def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + if env['PATH_INFO'] == '/readline': + data = env['wsgi.input'].readline(-1) + return [data] + + def test_negative_chunked_readline(self): + data = (b'POST /readline HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + def test_negative_nonchunked_readline(self): + data = (b'POST /readline HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Content-Length: 6\r\n\r\n' + b'oh hai') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + +class TestChunkedPost(TestCase): + + calls = 0 + + def setUp(self): + super().setUp() + self.calls = 0 + + def application(self, env, start_response): + self.calls += 1 + self.assertTrue(env.get('wsgi.input_terminated')) + start_response('200 OK', [('Content-Type', 'text/plain')]) + if env['PATH_INFO'] == '/a': + data = env['wsgi.input'].read(6) + return [data] + + if env['PATH_INFO'] == '/b': + lines = list(iter(lambda: env['wsgi.input'].read(6), b'')) + return lines + + if env['PATH_INFO'] == '/c': + return list(iter(lambda: env['wsgi.input'].read(1), b'')) + + return [b'We should not get here', env['PATH_INFO'].encode('ascii')] + + def test_014_chunked_post(self): + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + # self.close_opened() # XXX: Why? + + with self.makefile() as fd: + fd.write(data.replace(b'/a', b'/b')) + read_http(fd, body='oh hai') + + with self.makefile() as fd: + fd.write(data.replace(b'/a', b'/c')) + read_http(fd, body='oh hai') + + def test_229_incorrect_chunk_no_newline(self): + # Giving both a Content-Length and a Transfer-Encoding, + # TE is preferred. But if the chunking is bad from the client, + # missing its terminating newline, + # the server doesn't hang + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Content-Length: 12\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'{"hi": "ho"}') + with self.makefile() as fd: + fd.write(data) + read_http(fd, code=400) + + def test_229_incorrect_chunk_non_hex(self): + # Giving both a Content-Length and a Transfer-Encoding, + # TE is preferred. But if the chunking is bad from the client, + # the server doesn't hang + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Content-Length: 12\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'{"hi": "ho"}\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, code=400) + + def test_229_correct_chunk_quoted_ext(self): + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2;token="oh hi"\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + def test_229_correct_chunk_token_ext(self): + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2;token=oh_hi\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + + def test_229_incorrect_chunk_token_ext_too_long(self): + data = (b'POST /a HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + b'Transfer-Encoding: chunked\r\n\r\n' + b'2;token=oh_hi\r\noh\r\n4\r\n hai\r\n0\r\n\r\n') + data = data.replace(b'oh_hi', b'_oh_hi' * 4000) + with self.makefile() as fd: + fd.write(data) + read_http(fd, code=400) + + # XXX: Not sure which one, but one (or more) of these is leading to a + # test timeout on Windows. Figure out what/why and solve. + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_keepalive_ignored(self): + # Trailers after a chunk are ignored. + data1 = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: keep-alive\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0\r\n' # last-chunk + # Normally the final CRLF would go here, but if you put in a + # trailer, it doesn't. + b'trailer1: value1\r\n' + b'trailer2: value2\r\n' + b'\r\n' # Really terminate the chunk. + ) + data2 = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: close\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n bye\r\n' + b'0\r\n' # last-chunk + ) + with self.makefile() as fd: + fd.write(data1) + read_http(fd, body='oh hai') + fd.write(data2) + read_http(fd, body='oh bye') + + self.assertEqual(self.calls, 2) + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_close_ignored(self): + data = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: close\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0\r\n' # last-chunk + # Normally the final CRLF would go here, but if you put in a + # trailer, it doesn't. + # b'\r\n' + b'GETpath2a:123 HTTP/1.1\r\n' + b'Host: a.com\r\n' + b'Connection: close\r\n' + b'\r\n' + ) + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + with self.assertRaises(ConnectionClosed): + read_http(fd) + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_too_long(self): + # Trailers after a chunk are ignored. + data = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: keep-alive\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0\r\n' # last-chunk + # Normally the final CRLF would go here, but if you put in a + # trailer, it doesn't. + b'trailer2: value2' # note lack of \r\n + ) + data += b't' * pywsgi.MAX_REQUEST_LINE + # No termination, because we detect the trailer as being too + # long and abort the connection. + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + with self.assertRaises(ConnectionClosed): + read_http(fd, body='oh bye') + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_request_smuggling_missing_last_chunk_keep_alive(self): + # When something that looks like a request line comes in the trailer + # as the first line, immediately after an invalid last chunk. + # We detect this and abort the connection, because the + # whitespace in the GET line isn't a legal part of a trailer. + # If we didn't abort the connection, then, because we specified + # keep-alive, the server would be hanging around waiting for more input. + data = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: keep-alive\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0' # last-chunk, but missing the \r\n + # Normally the final CRLF would go here, but if you put in a + # trailer, it doesn't. + # b'\r\n' + b'GET /path2?a=:123 HTTP/1.1\r\n' + b'Host: a.com\r\n' + b'Connection: close\r\n' + b'\r\n' + ) + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + with self.assertRaises(ConnectionClosed): + read_http(fd) + + self.assertEqual(self.calls, 1) + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_request_smuggling_header_first(self): + # When something that looks like a header comes in the first line. + data = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: keep-alive\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0\r\n' # last-chunk, but only one CRLF + b'Header: value\r\n' + b'GET /path2?a=:123 HTTP/1.1\r\n' + b'Host: a.com\r\n' + b'Connection: close\r\n' + b'\r\n' + ) + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + with self.assertRaises(ConnectionClosed): + read_http(fd, code=400) + + self.assertEqual(self.calls, 1) + + @greentest.skipOnWindows('Maybe hangs') + def test_trailers_request_smuggling_request_terminates_then_header(self): + data = ( + b'POST /a HTTP/1.1\r\n' + b'Host: localhost\r\n' + b'Connection: keep-alive\r\n' + b'Transfer-Encoding: chunked\r\n' + b'\r\n' + b'2\r\noh\r\n' + b'4\r\n hai\r\n' + b'0\r\n' # last-chunk + b'\r\n' + b'Header: value' + b'GET /path2?a=:123 HTTP/1.1\r\n' + b'Host: a.com\r\n' + b'Connection: close\r\n' + b'\r\n' + ) + with self.makefile() as fd: + fd.write(data) + read_http(fd, body='oh hai') + read_http(fd, code=400) + + self.assertEqual(self.calls, 1) + + +class TestUseWrite(TestCase): + + body = b'abcde' + end = b'end' + content_length = str(len(body + end)) + + def application(self, env, start_response): + if env['PATH_INFO'] == '/explicit-content-length': + write = start_response('200 OK', [('Content-Type', 'text/plain'), + ('Content-Length', self.content_length)]) + write(self.body) + elif env['PATH_INFO'] == '/no-content-length': + write = start_response('200 OK', [('Content-Type', 'text/plain')]) + write(self.body) + elif env['PATH_INFO'] == '/no-content-length-twice': + write = start_response('200 OK', [('Content-Type', 'text/plain')]) + write(self.body) + write(self.body) + else: + # pylint:disable-next=broad-exception-raised + raise Exception('Invalid url') + return [self.end] + + def test_explicit_content_length(self): + with self.makefile() as fd: + fd.write('GET /explicit-content-length HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + response = read_http(fd, body=self.body + self.end) + response.assertHeader('Content-Length', self.content_length) + response.assertHeader('Transfer-Encoding', False) + + def test_no_content_length(self): + with self.makefile() as fd: + fd.write('GET /no-content-length HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + response = read_http(fd, body=self.body + self.end) + + response.assertHeader('Content-Length', False) + response.assertHeader('Transfer-Encoding', 'chunked') + + def test_no_content_length_twice(self): + with self.makefile() as fd: + fd.write('GET /no-content-length-twice HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + response = read_http(fd, body=self.body + self.body + self.end) + + response.assertHeader('Content-Length', False) + response.assertHeader('Transfer-Encoding', 'chunked') + self.assertEqual(response.chunks, [self.body, self.body, self.end]) + + +class HttpsTestCase(TestCase): + + certfile = os.path.join(os.path.dirname(__file__), 'test_server.crt') + keyfile = os.path.join(os.path.dirname(__file__), 'test_server.key') + + def init_server(self, application): + self.server = pywsgi.WSGIServer((self.listen_addr, 0), application, + certfile=self.certfile, keyfile=self.keyfile) + + def urlopen(self, method='GET', post_body=None, **kwargs): # pylint:disable=arguments-differ + import ssl + with self.connect() as raw_sock: + with ssl.wrap_socket(raw_sock) as sock: # pylint:disable=deprecated-method,no-member + with sock.makefile(bufsize=1) as fd: # pylint:disable=unexpected-keyword-arg + fd.write('%s / HTTP/1.1\r\nHost: localhost\r\n' % method) + if post_body is not None: + fd.write('Content-Length: %s\r\n\r\n' % len(post_body)) + fd.write(post_body) + if kwargs.get('body') is None: + kwargs['body'] = post_body + else: + fd.write('\r\n') + fd.flush() + + return read_http(fd, **kwargs) + + def application(self, environ, start_response): + assert environ['wsgi.url_scheme'] == 'https', environ['wsgi.url_scheme'] + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [environ['wsgi.input'].read(10)] + + +import gevent.ssl +HAVE_SSLCONTEXT = getattr(gevent.ssl, 'create_default_context') +if HAVE_SSLCONTEXT: + + class HttpsSslContextTestCase(HttpsTestCase): + def init_server(self, application): + # On 2.7, our certs don't line up with hostname. + # If we just use create_default_context as-is, we get + # `ValueError: check_hostname requires server_hostname`. + # If we set check_hostname to False, we get + # `SSLError: [SSL: PEER_DID_NOT_RETURN_A_CERTIFICATE] peer did not return a certificate` + # (Neither of which happens in Python 3.) But the unverified context + # works both places. See also test___example_servers.py + from gevent.ssl import _create_unverified_context # pylint:disable=no-name-in-module + context = _create_unverified_context() + context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile) + self.server = pywsgi.WSGIServer((self.listen_addr, 0), + application, ssl_context=context) + +class TestHttps(HttpsTestCase): + + if hasattr(socket, 'ssl'): + + def test_012_ssl_server(self): + result = self.urlopen(method="POST", post_body='abc') + self.assertEqual(result.body, 'abc') + + def test_013_empty_return(self): + result = self.urlopen() + self.assertEqual(result.body, '') + +if HAVE_SSLCONTEXT: + class TestHttpsWithContext(HttpsSslContextTestCase, TestHttps): # pylint:disable=too-many-ancestors + pass + +class TestInternational(TestCase): + validator = None # wsgiref.validate.IteratorWrapper([]) does not have __len__ + + def application(self, environ, start_response): + path_bytes = b'/\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' + if PY3: + # Under PY3, the escapes were decoded as latin-1 + path_bytes = path_bytes.decode('latin-1') + + self.assertEqual(environ['PATH_INFO'], path_bytes) + self.assertEqual(environ['QUERY_STRING'], '%D0%B2%D0%BE%D0%BF%D1%80%D0%BE%D1%81=%D0%BE%D1%82%D0%B2%D0%B5%D1%82') + start_response("200 PASSED", [('Content-Type', 'text/plain')]) + return [] + + def test(self): + with self.connect() as sock: + sock.sendall( + b'''GET /%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82?%D0%B2%D0%BE%D0%BF%D1%80%D0%BE%D1%81=%D0%BE%D1%82%D0%B2%D0%B5%D1%82 HTTP/1.1 +Host: localhost +Connection: close + +'''.replace(b'\n', b'\r\n')) + with sock.makefile() as fd: + read_http(fd, reason='PASSED', chunks=False, body='', content_length=0) + + +class TestNonLatin1HeaderFromApplication(TestCase): + error_fatal = False # Allow sending the exception response, don't kill the greenlet + + validator = None # Don't validate the application, it's deliberately bad + header = b'\xe1\xbd\x8a3' # bomb in utf-8 bytes + should_error = PY3 # non-native string under Py3 + + def setUp(self): + super(TestNonLatin1HeaderFromApplication, self).setUp() + self.errors = [] + + def tearDown(self): + self.errors = [] + super(TestNonLatin1HeaderFromApplication, self).tearDown() + + def application(self, environ, start_response): + # We return a header that cannot be encoded in latin-1 + try: + start_response("200 PASSED", + [('Content-Type', 'text/plain'), + ('Custom-Header', self.header)]) + except: + self.errors.append(sys.exc_info()[:2]) + raise + return [] + + def test(self): + with self.connect() as sock: + self.expect_one_error() + sock.sendall(b'''GET / HTTP/1.1\r\n\r\n''') + with sock.makefile() as fd: + if self.should_error: + read_http(fd, code=500, reason='Internal Server Error') + self.assert_error(where_type=pywsgi.SecureEnviron) + self.assertEqual(len(self.errors), 1) + _, v = self.errors[0] + self.assertIsInstance(v, UnicodeError) + else: + read_http(fd, code=200, reason='PASSED') + self.assertEqual(len(self.errors), 0) + + +class TestNonLatin1UnicodeHeaderFromApplication(TestNonLatin1HeaderFromApplication): + # Flip-flop of the superclass: Python 3 native string, Python 2 unicode object + header = u"\u1f4a3" # bomb in unicode + # Error both on py3 and py2. On py2, non-native string. On py3, native string + # that cannot be encoded to latin-1 + should_error = True + + +class TestInputReadline(TestCase): + # this test relies on the fact that readline() returns '' after it reached EOF + # this behaviour is not mandated by WSGI spec, it's just happens that gevent.wsgi behaves like that + # as such, this may change in the future + + validator = None + + def application(self, environ, start_response): + input = environ['wsgi.input'] + lines = [] + while True: + line = input.readline() + if not line: + break + line = line.decode('ascii') if PY3 else line + lines.append(repr(line) + ' ') + start_response('200 hello', []) + return [l.encode('ascii') for l in lines] if PY3 else lines + + def test(self): + with self.makefile() as fd: + content = 'hello\n\nworld\n123' + fd.write('POST / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n' + 'Content-Length: %s\r\n\r\n%s' % (len(content), content)) + fd.flush() + read_http(fd, reason='hello', body="'hello\\n' '\\n' 'world\\n' '123' ") + + +class TestInputIter(TestInputReadline): + + def application(self, environ, start_response): + input = environ['wsgi.input'] + lines = [] + for line in input: + if not line: + break + line = line.decode('ascii') if PY3 else line + lines.append(repr(line) + ' ') + start_response('200 hello', []) + return [l.encode('ascii') for l in lines] if PY3 else lines + + +class TestInputReadlines(TestInputReadline): + + def application(self, environ, start_response): + input = environ['wsgi.input'] + lines = [l.decode('ascii') if PY3 else l for l in input.readlines()] + lines = [repr(line) + ' ' for line in lines] + start_response('200 hello', []) + return [l.encode('ascii') for l in lines] if PY3 else lines + + +class TestInputN(TestCase): + # testing for this: + # File "/home/denis/work/gevent/gevent/pywsgi.py", line 70, in _do_read + # if length and length > self.content_length - self.position: + # TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' + + validator = None + + def application(self, environ, start_response): + environ['wsgi.input'].read(5) + start_response('200 OK', []) + return [] + + def test(self): + self.urlopen() + + +class TestErrorInApplication(TestCase): + + error = object() + error_fatal = False + + def application(self, env, start_response): + self.error = greentest.ExpectedException('TestError.application') + raise self.error + + def test(self): + self.expect_one_error() + self.urlopen(code=500) + self.assert_error(greentest.ExpectedException, self.error) + + +class TestError_after_start_response(TestErrorInApplication): + + def application(self, env, start_response): + self.error = greentest.ExpectedException('TestError_after_start_response.application') + start_response('200 OK', [('Content-Type', 'text/plain')]) + raise self.error + + +class TestEmptyYield(TestCase): + + @staticmethod + def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + yield b"" + yield b"" + + def test_err(self): + chunks = [] + + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + + read_http(fd, body='', chunks=chunks) + + garbage = fd.read() + self.assertEqual(garbage, b"", "got garbage: %r" % garbage) + + +class TestFirstEmptyYield(TestCase): + + @staticmethod + def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + yield b"" + yield b"hello" + + def test_err(self): + chunks = [b'hello'] + + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + + read_http(fd, body='hello', chunks=chunks) + + garbage = fd.read() + self.assertEqual(garbage, b"") + + +class TestEmptyYield304(TestCase): + + @staticmethod + def application(env, start_response): + start_response('304 Not modified', []) + yield b"" + yield b"" + + def test_err(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + read_http(fd, code=304, body='', chunks=False) + garbage = fd.read() + self.assertEqual(garbage, b"") + + +class TestContentLength304(TestCase): + validator = None + + def application(self, env, start_response): + try: + start_response('304 Not modified', [('Content-Length', '100')]) + except AssertionError as ex: + start_response('200 Raised', []) + return ex.args + raise AssertionError('start_response did not fail but it should') + + def test_err(self): + body = "Invalid Content-Length for 304 response: '100' (must be absent or zero)" + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + + read_http(fd, code=200, reason='Raised', body=body, chunks=False) + garbage = fd.read() + self.assertEqual(garbage, b"") + + +class TestBody304(TestCase): + validator = None + + def application(self, env, start_response): + start_response('304 Not modified', []) + return [b'body'] + + def test_err(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + with self.assertRaises(AssertionError) as exc: + read_http(fd) + ex = exc.exception + self.assertEqual(str(ex), 'The 304 response must have no body') + + +class TestWrite304(TestCase): + validator = None + error_raised = None + + def application(self, env, start_response): + write = start_response('304 Not modified', []) + self.error_raised = False + try: + write('body') + except AssertionError as ex: + self.error_raised = True + raise ExpectedAssertionError(*ex.args) + + def test_err(self): + with self.makefile() as fd: + fd.write(b'GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + with self.assertRaises(AssertionError) as exc: + read_http(fd) + ex = exc.exception + + self.assertEqual(str(ex), 'The 304 response must have no body') + self.assertTrue(self.error_raised, 'write() must raise') + + +class TestEmptyWrite(TestEmptyYield): + + @staticmethod + def application(env, start_response): + write = start_response('200 OK', [('Content-Type', 'text/plain')]) + write(b"") + write(b"") + return [] + + +class BadRequestTests(TestCase): + validator = None + # pywsgi checks content-length, but wsgi does not + content_length = None + + assert TestCase.handler_class._print_unexpected_exc + + class handler_class(TestCase.handler_class): + def _print_unexpected_exc(self): + raise AssertionError("Should not print a traceback") + + def application(self, env, start_response): + self.assertEqual(env['CONTENT_LENGTH'], self.content_length) + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [b'hello'] + + def test_negative_content_length(self): + self.content_length = '-100' + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %s\r\n\r\n' % self.content_length) + read_http(fd, code=(200, 400)) + + def test_illegal_content_length(self): + self.content_length = 'abc' + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %s\r\n\r\n' % self.content_length) + read_http(fd, code=(200, 400)) + + def test_bad_request_line_with_percent(self): + # If the request is invalid and contains Python formatting characters (%) + # we don't fail to log the error and we do generate a 400. + # https://github.com/gevent/gevent/issues/1708 + bad_request = 'GET / HTTP %\r\n' + with self.makefile() as fd: + fd.write(bad_request) + read_http(fd, code=400) + + +class ChunkedInputTests(TestCase): + dirt = "" + validator = None + + def application(self, env, start_response): + input = env['wsgi.input'] + response = [] + + pi = env["PATH_INFO"] + + if pi == "/short-read": + d = input.read(10) + response = [d] + elif pi == "/lines": + for x in input: + response.append(x) + elif pi == "/ping": + input.read(1) + response.append(b"pong") + else: + raise RuntimeError("bad path") + + start_response('200 OK', [('Content-Type', 'text/plain')]) + return response + + def chunk_encode(self, chunks, dirt=None): + if dirt is None: + dirt = self.dirt + + return chunk_encode(chunks, dirt=dirt) + + def body(self, dirt=None): + return self.chunk_encode(["this", " is ", "chunked", "\nline", " 2", "\n", "line3", ""], dirt=dirt) + + def ping(self, fd): + fd.write("GET /ping HTTP/1.1\r\n\r\n") + read_http(fd, body="pong") + + def ping_if_possible(self, fd): + self.ping(fd) + + def test_short_read_with_content_length(self): + body = self.body() + req = b"POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\nContent-Length:1000\r\n\r\n" + body + with self.connect() as conn: + with conn.makefile(bufsize=1) as fd: # pylint:disable=unexpected-keyword-arg + fd.write(req) + read_http(fd, body="this is ch") + + self.ping_if_possible(fd) + + def test_short_read_with_zero_content_length(self): + body = self.body() + req = b"POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\nContent-Length:0\r\n\r\n" + body + #print("REQUEST:", repr(req)) + + with self.makefile() as fd: + fd.write(req) + read_http(fd, body="this is ch") + + self.ping_if_possible(fd) + + def test_short_read(self): + body = self.body() + req = b"POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\n\r\n" + body + + with self.makefile() as fd: + fd.write(req) + read_http(fd, body="this is ch") + + self.ping_if_possible(fd) + + def test_dirt(self): + body = self.body(dirt="; here is dirt\0bla") + req = b"POST /ping HTTP/1.1\r\ntransfer-encoding: Chunked\r\n\r\n" + body + + with self.makefile() as fd: + fd.write(req) + read_http(fd, body="pong") + + self.ping_if_possible(fd) + + def test_chunked_readline(self): + body = self.body() + req = "POST /lines HTTP/1.1\r\nContent-Length: %s\r\ntransfer-encoding: Chunked\r\n\r\n" % (len(body)) + req = req.encode('latin-1') + req += body + + with self.makefile() as fd: + fd.write(req) + read_http(fd, body='this is chunked\nline 2\nline3') + + def test_close_before_finished(self): + self.expect_one_error() + body = b'4\r\nthi' + req = b"POST /short-read HTTP/1.1\r\ntransfer-encoding: Chunked\r\n\r\n" + body + with self.connect() as sock: + with sock.makefile(bufsize=1, mode='wb') as fd:# pylint:disable=unexpected-keyword-arg + fd.write(req) + fd.close() + + # Python 3 keeps the socket open even though the only + # makefile is gone; python 2 closed them both (because there were + # no outstanding references to the socket). Closing is essential for the server + # to get the message that the read will fail. It's better to be explicit + # to avoid a ResourceWarning + sock.close() + # Under Py2 it still needs to go away, which was implicit before + del fd + del sock + + gevent.get_hub().loop.update_now() + gevent.sleep(0.01) # timing needed for cpython + + if greentest.PYPY: + # XXX: Something is keeping the socket alive, + # by which I mean, the close event is not propagating to the server + # and waking up its recv() loop...we are stuck with the three bytes of + # 'thi' in the buffer and trying to read the forth. No amount of tinkering + # with the timing changes this...the only thing that does is running a + # GC and letting some object get collected. Might this be a problem in real life? + + import gc + gc.collect() + gevent.sleep(0.01) + gevent.get_hub().loop.update_now() + gc.collect() + gevent.sleep(0.01) + + # XXX2: Sometimes windows and PyPy/Travis fail to get this error, leading to a test failure. + # This would have to be due to the socket being kept around and open, + # not closed at the low levels. I haven't seen this locally. + # In the PyPy case, I've seen the IOError reported on the console, but not + # captured in the variables. + # https://travis-ci.org/gevent/gevent/jobs/329232976#L1374 + self.assert_error(IOError, 'unexpected end of file while parsing chunked data') + + +class Expect100ContinueTests(TestCase): + validator = None + + def application(self, environ, start_response): + content_length = int(environ['CONTENT_LENGTH']) + if content_length > 1024: + start_response('417 Expectation Failed', [('Content-Length', '7'), ('Content-Type', 'text/plain')]) + return [b'failure'] + + # pywsgi did sent a "100 continue" for each read + # see http://code.google.com/p/gevent/issues/detail?id=93 + text = environ['wsgi.input'].read(1) + text += environ['wsgi.input'].read(content_length - 1) + start_response('200 OK', [('Content-Length', str(len(text))), ('Content-Type', 'text/plain')]) + return [text] + + def test_continue(self): + with self.makefile() as fd: + fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 1025\r\nExpect: 100-continue\r\n\r\n') + read_http(fd, code=417, body="failure") + + fd.write('PUT / HTTP/1.1\r\nHost: localhost\r\nContent-length: 7\r\nExpect: 100-continue\r\n\r\ntesting') + read_http(fd, code=100) + read_http(fd, body="testing") + + +class MultipleCookieHeadersTest(TestCase): + + validator = None + + def application(self, environ, start_response): + self.assertEqual(environ['HTTP_COOKIE'], 'name1="value1"; name2="value2"') + self.assertEqual(environ['HTTP_COOKIE2'], 'nameA="valueA"; nameB="valueB"') + start_response('200 OK', []) + return [] + + def test(self): + with self.makefile() as fd: + fd.write('''GET / HTTP/1.1 +Host: localhost +Cookie: name1="value1" +Cookie2: nameA="valueA" +Cookie2: nameB="valueB" +Cookie: name2="value2"\n\n'''.replace('\n', '\r\n')) + read_http(fd) + + +class TestLeakInput(TestCase): + + _leak_wsgi_input = None + _leak_environ = None + + def tearDown(self): + TestCase.tearDown(self) + self._leak_wsgi_input = None + self._leak_environ = None + + def application(self, environ, start_response): + pi = environ["PATH_INFO"] + self._leak_wsgi_input = environ["wsgi.input"] + self._leak_environ = environ + if pi == "/leak-frame": + environ["_leak"] = sys._getframe(0) + + text = b"foobar" + start_response('200 OK', [('Content-Length', str(len(text))), ('Content-Type', 'text/plain')]) + return [text] + + def test_connection_close_leak_simple(self): + with self.makefile() as fd: + fd.write(b"GET / HTTP/1.0\r\nConnection: close\r\n\r\n") + d = fd.read() + self.assertTrue(d.startswith(b"HTTP/1.1 200 OK"), d) + + def test_connection_close_leak_frame(self): + with self.makefile() as fd: + fd.write(b"GET /leak-frame HTTP/1.0\r\nConnection: close\r\n\r\n") + d = fd.read() + self.assertTrue(d.startswith(b"HTTP/1.1 200 OK"), d) + self._leak_environ.pop('_leak') + +class TestHTTPResponseSplitting(TestCase): + # The validator would prevent the app from doing the + # bad things it needs to do + validator = None + + status = '200 OK' + headers = () + start_exc = None + + def setUp(self): + TestCase.setUp(self) + self.start_exc = None + self.status = TestHTTPResponseSplitting.status + self.headers = TestHTTPResponseSplitting.headers + + def tearDown(self): + TestCase.tearDown(self) + self.start_exc = None + + def application(self, environ, start_response): + try: + start_response(self.status, self.headers) + except Exception as e: # pylint: disable=broad-except + self.start_exc = e + else: + self.start_exc = None + return () + + def _assert_failure(self, message): + with self.makefile() as fd: + fd.write('GET / HTTP/1.0\r\nHost: localhost\r\n\r\n') + fd.read() + self.assertIsInstance(self.start_exc, ValueError) + self.assertEqual(self.start_exc.args[0], message) + + def test_newline_in_status(self): + self.status = '200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n' + self._assert_failure('carriage return or newline in status') + + def test_newline_in_header_value(self): + self.headers = [('Test', 'Hi\r\nConnection: close')] + self._assert_failure('carriage return or newline in header value') + + def test_newline_in_header_name(self): + self.headers = [('Test\r\n', 'Hi')] + self._assert_failure('carriage return or newline in header name') + + +class TestInvalidEnviron(TestCase): + validator = None + # check that WSGIServer does not insert any default values for CONTENT_LENGTH + + def application(self, environ, start_response): + for key, value in environ.items(): + if key in ('CONTENT_LENGTH', 'CONTENT_TYPE') or key.startswith('HTTP_'): + if key != 'HTTP_HOST': + raise ExpectedAssertionError('Unexpected environment variable: %s=%r' % ( + key, value)) + start_response('200 OK', []) + return [] + + def test(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.0\r\nHost: localhost\r\n\r\n') + read_http(fd) + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') + read_http(fd) + + +class TestInvalidHeadersDropped(TestCase): + validator = None + # check that invalid headers with a _ are dropped + + def application(self, environ, start_response): + self.assertNotIn('HTTP_X_AUTH_USER', environ) + start_response('200 OK', []) + return [] + + def test(self): + with self.makefile() as fd: + fd.write('GET / HTTP/1.0\r\nx-auth_user: bob\r\n\r\n') + read_http(fd) + + +class TestHandlerSubclass(TestCase): + + validator = None + + class handler_class(TestCase.handler_class): + + def read_requestline(self): + data = self.rfile.read(7) + if data[0] == b'<'[0]: # py3: indexing bytes returns ints. sigh. + # Returning nothing stops handle_one_request() + # Note that closing or even deleting self.socket() here + # can lead to the read side throwing Connection Reset By Peer, + # depending on the Python version and OS + data += self.rfile.read(15) + if data.lower() == b'': + self.socket.sendall(b'HELLO') + else: + self.log_error('Invalid request: %r', data) + return None + return data + self.rfile.readline() + + def application(self, environ, start_response): + start_response('200 OK', []) + return [] + + def test(self): + with self.makefile() as fd: + fd.write(b'\x00') + fd.flush() # flush() is needed on PyPy, apparently it buffers slightly differently + self.assertEqual(fd.read(), b'HELLO') + + with self.makefile() as fd: + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') + fd.flush() + read_http(fd) + + with self.makefile() as fd: + # Trigger an error + fd.write('\x00') + fd.flush() + self.assertEqual(fd.read(), b'') + + +class TestErrorAfterChunk(TestCase): + validator = None + + @staticmethod + def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + yield b"hello" + raise greentest.ExpectedException('TestErrorAfterChunk') + + def test(self): + with self.makefile() as fd: + self.expect_one_error() + fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n') + with self.assertRaises(ValueError): + read_http(fd) + self.assert_error(greentest.ExpectedException) + + +def chunk_encode(chunks, dirt=None): + if dirt is None: + dirt = "" + + b = b"" + for c in chunks: + x = "%x%s\r\n%s\r\n" % (len(c), dirt, c) + b += x.encode('ascii') + return b + + +class TestInputRaw(greentest.BaseTestCase): + def make_input(self, data, content_length=None, chunked_input=False): + if isinstance(data, list): + data = chunk_encode(data) + chunked_input = True + elif isinstance(data, str) and PY3: + data = data.encode("ascii") + return Input(StringIO(data), content_length=content_length, chunked_input=chunked_input) + + if PY3: + def assertEqual(self, first, second, msg=None): + if isinstance(second, str): + second = second.encode('ascii') + super(TestInputRaw, self).assertEqual(first, second, msg) + + def test_short_post(self): + i = self.make_input("1", content_length=2) + self.assertRaises(IOError, i.read) + + def test_short_post_read_with_length(self): + i = self.make_input("1", content_length=2) + self.assertRaises(IOError, i.read, 2) + + def test_short_post_readline(self): + i = self.make_input("1", content_length=2) + self.assertRaises(IOError, i.readline) + + def test_post(self): + i = self.make_input("12", content_length=2) + data = i.read() + self.assertEqual(data, "12") + + def test_post_read_with_length(self): + i = self.make_input("12", content_length=2) + data = i.read(10) + self.assertEqual(data, "12") + + def test_chunked(self): + i = self.make_input(["1", "2", ""]) + data = i.read() + self.assertEqual(data, "12") + + def test_chunked_read_with_length(self): + i = self.make_input(["1", "2", ""]) + data = i.read(10) + self.assertEqual(data, "12") + + def test_chunked_missing_chunk(self): + i = self.make_input(["1", "2"]) + self.assertRaises(IOError, i.read) + + def test_chunked_missing_chunk_read_with_length(self): + i = self.make_input(["1", "2"]) + self.assertRaises(IOError, i.read, 10) + + def test_chunked_missing_chunk_readline(self): + i = self.make_input(["1", "2"]) + self.assertRaises(IOError, i.readline) + + def test_chunked_short_chunk(self): + i = self.make_input("2\r\n1", chunked_input=True) + self.assertRaises(IOError, i.read) + + def test_chunked_short_chunk_read_with_length(self): + i = self.make_input("2\r\n1", chunked_input=True) + self.assertRaises(IOError, i.read, 2) + + def test_chunked_short_chunk_readline(self): + i = self.make_input("2\r\n1", chunked_input=True) + self.assertRaises(IOError, i.readline) + + def test_32bit_overflow(self): + # https://github.com/gevent/gevent/issues/289 + # Should not raise an OverflowError on Python 2 + data = b'asdf\nghij\n' + long_data = b'a' * (pywsgi.MAX_REQUEST_LINE + 10) + long_data += b'\n' + data += long_data + partial_data = b'qjk\n' # Note terminating \n + n = 25 * 1000000000 + if hasattr(n, 'bit_length'): + self.assertEqual(n.bit_length(), 35) + if not PY3 and not PYPY: + # Make sure we have the impl we think we do + self.assertRaises(OverflowError, StringIO(data).readline, n) + + i = self.make_input(data, content_length=n) + # No size hint, but we have too large a content_length to fit + self.assertEqual(i.readline(), b'asdf\n') + # Large size hint + self.assertEqual(i.readline(n), b'ghij\n') + self.assertEqual(i.readline(n), long_data) + + # Now again with the real content length, assuring we can't read past it + i = self.make_input(data + partial_data, content_length=len(data) + 1) + self.assertEqual(i.readline(), b'asdf\n') + self.assertEqual(i.readline(n), b'ghij\n') + self.assertEqual(i.readline(n), long_data) + # Now we've reached content_length so we shouldn't be able to + # read anymore except the one byte remaining + self.assertEqual(i.readline(n), b'q') + + +class Test414(TestCase): + + @staticmethod + def application(env, start_response): + raise AssertionError('should not get there') + + def test(self): + longline = 'x' * 20000 + with self.makefile() as fd: + fd.write(('''GET /%s HTTP/1.0\r\nHello: world\r\n\r\n''' % longline).encode('latin-1')) + read_http(fd, code=414) + + +class TestLogging(TestCase): + + # Something that gets wrapped in a LoggingLogAdapter + class Logger(object): + accessed = None + logged = None + thing = None + + def log(self, level, msg): + self.logged = (level, msg) + + def access(self, msg): + self.accessed = msg + + def get_thing(self): + return self.thing + + def init_logger(self): + return self.Logger() + + @staticmethod + def application(env, start_response): + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [b'hello'] + + # Tests for issue #663 + + def test_proxy_methods_on_log(self): + # An object that looks like a logger gets wrapped + # with a proxy that + self.assertTrue(isinstance(self.server.log, pywsgi.LoggingLogAdapter)) + self.server.log.access("access") + self.server.log.write("write") + self.assertEqual(self.server.log.accessed, "access") + self.assertEqual(self.server.log.logged, (20, "write")) + + def test_set_attributes(self): + # Not defined by the wrapper, it goes to the logger + self.server.log.thing = 42 + self.assertEqual(self.server.log.get_thing(), 42) + + del self.server.log.thing + self.assertEqual(self.server.log.get_thing(), None) + + def test_status_log(self): + # Issue 664: Make sure we format the status line as a string + self.urlopen() + msg = self.server.log.logged[1] + self.assertTrue('"GET / HTTP/1.1" 200 ' in msg, msg) + + # Issue 756: Make sure we don't throw a newline on the end + self.assertTrue('\n' not in msg, msg) + +class TestEnviron(TestCase): + + # The wsgiref validator asserts type(environ) is dict. + # https://mail.python.org/pipermail/web-sig/2016-March/005455.html + validator = None + + def init_server(self, application): + super(TestEnviron, self).init_server(application) + self.server.environ_class = pywsgi.SecureEnviron + + def application(self, env, start_response): + self.assertIsInstance(env, pywsgi.SecureEnviron) + start_response('200 OK', [('Content-Type', 'text/plain')]) + return [] + + def test_environ_is_secure_by_default(self): + self.urlopen() + + def test_default_secure_repr(self): + environ = pywsgi.SecureEnviron() + self.assertIn('"}), str(environ)) + self.assertEqual(repr({'key': ""}), repr(environ)) + + environ.whitelist_keys = ('key',) + self.assertEqual(str({'key': 'value'}), str(environ)) + self.assertEqual(repr({'key': 'value'}), repr(environ)) + + del environ.whitelist_keys + + def test_override_class_defaults(self): + class EnvironClass(pywsgi.SecureEnviron): + __slots__ = () + + environ = EnvironClass() + + self.assertTrue(environ.secure_repr) + EnvironClass.default_secure_repr = False + self.assertFalse(environ.secure_repr) + + self.assertEqual(str({}), str(environ)) + self.assertEqual(repr({}), repr(environ)) + + EnvironClass.default_secure_repr = True + EnvironClass.default_whitelist_keys = ('key',) + + environ['key'] = 1 + self.assertEqual(str({'key': 1}), str(environ)) + self.assertEqual(repr({'key': 1}), repr(environ)) + + # Clean up for leaktests + del environ + del EnvironClass + import gc; gc.collect() + + + def test_copy_still_secure(self): + for cls in (pywsgi.Environ, pywsgi.SecureEnviron): + self.assertIsInstance(cls().copy(), cls) + + def test_pickle_copy_returns_dict(self): + # Anything going through copy.copy/pickle should + # return the same pickle that a dict would. + import pickle + import json + + for cls in (pywsgi.Environ, pywsgi.SecureEnviron): + bltin = {'key': 'value'} + env = cls(bltin) + self.assertIsInstance(env, cls) + self.assertEqual(bltin, env) + self.assertEqual(env, bltin) + + for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1): + # It's impossible to get a subclass of dict to pickle + # identically, but it can restore identically + env_dump = pickle.dumps(env, protocol) + self.assertNotIn(b'Environ', env_dump) + loaded = pickle.loads(env_dump) + self.assertEqual(type(loaded), dict) + + self.assertEqual(json.dumps(bltin), json.dumps(env)) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__queue.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c603079d0cc75a14419945b35fd87cadce75de69 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__queue.py @@ -0,0 +1,470 @@ +import unittest + +import gevent.testing as greentest +from gevent.testing import TestCase +import gevent +from gevent.hub import get_hub, LoopExit +from gevent import util +from gevent import queue +from gevent.queue import Empty, Full +from gevent.event import AsyncResult +from gevent.testing.timing import AbstractGenericGetTestCase + +# pylint:disable=too-many-ancestors + +class TestQueue(TestCase): + + def test_send_first(self): + self.switch_expected = False + q = queue.Queue() + q.put('hi') + self.assertEqual(q.peek(), 'hi') + self.assertEqual(q.get(), 'hi') + + def test_peek_empty(self): + q = queue.Queue() + # No putters waiting, in the main loop: LoopExit + with self.assertRaises(LoopExit): + q.peek() + + def waiter(q): + self.assertRaises(Empty, q.peek, timeout=0.01) + g = gevent.spawn(waiter, q) + gevent.sleep(0.1) + g.join() + + def test_peek_multi_greenlet(self): + q = queue.Queue() + g = gevent.spawn(q.peek) + g.start() + gevent.sleep(0) + q.put(1) + g.join() + self.assertTrue(g.exception is None) + self.assertEqual(q.peek(), 1) + + def test_send_last(self): + q = queue.Queue() + + def waiter(q): + with gevent.Timeout(0.1 if not greentest.RUNNING_ON_APPVEYOR else 0.5): + self.assertEqual(q.get(), 'hi2') + return "OK" + + p = gevent.spawn(waiter, q) + gevent.sleep(0.01) + q.put('hi2') + gevent.sleep(0.01) + assert p.get(timeout=0) == "OK" + + def test_max_size(self): + q = queue.Queue(2) + results = [] + + def putter(q): + q.put('a') + results.append('a') + q.put('b') + results.append('b') + q.put('c') + results.append('c') + return "OK" + + p = gevent.spawn(putter, q) + gevent.sleep(0) + self.assertEqual(results, ['a', 'b']) + self.assertEqual(q.get(), 'a') + gevent.sleep(0) + self.assertEqual(results, ['a', 'b', 'c']) + self.assertEqual(q.get(), 'b') + self.assertEqual(q.get(), 'c') + assert p.get(timeout=0) == "OK" + + def test_zero_max_size(self): + q = queue.Channel() + + def sender(evt, q): + q.put('hi') + evt.set('done') + + def receiver(evt, q): + x = q.get() + evt.set(x) + + e1 = AsyncResult() + e2 = AsyncResult() + + p1 = gevent.spawn(sender, e1, q) + gevent.sleep(0.001) + self.assertTrue(not e1.ready()) + p2 = gevent.spawn(receiver, e2, q) + self.assertEqual(e2.get(), 'hi') + self.assertEqual(e1.get(), 'done') + with gevent.Timeout(0): + gevent.joinall([p1, p2]) + + def test_multiple_waiters(self): + # tests that multiple waiters get their results back + q = queue.Queue() + + def waiter(q, evt): + evt.set(q.get()) + + sendings = ['1', '2', '3', '4'] + evts = [AsyncResult() for x in sendings] + for i, _ in enumerate(sendings): + gevent.spawn(waiter, q, evts[i]) # XXX use waitall for them + + gevent.sleep(0.01) # get 'em all waiting + + results = set() + + def collect_pending_results(): + for e in evts: + with gevent.Timeout(0.001, False): + x = e.get() + results.add(x) + return len(results) + + q.put(sendings[0]) + self.assertEqual(collect_pending_results(), 1) + q.put(sendings[1]) + self.assertEqual(collect_pending_results(), 2) + q.put(sendings[2]) + q.put(sendings[3]) + self.assertEqual(collect_pending_results(), 4) + + def test_waiters_that_cancel(self): + q = queue.Queue() + + def do_receive(q, evt): + with gevent.Timeout(0, RuntimeError()): + try: + result = q.get() + evt.set(result) # pragma: no cover (should have raised) + except RuntimeError: + evt.set('timed out') + + evt = AsyncResult() + gevent.spawn(do_receive, q, evt) + self.assertEqual(evt.get(), 'timed out') + + q.put('hi') + self.assertEqual(q.get(), 'hi') + + def test_senders_that_die(self): + q = queue.Queue() + + def do_send(q): + q.put('sent') + + gevent.spawn(do_send, q) + self.assertEqual(q.get(), 'sent') + + def test_two_waiters_one_dies(self): + + def waiter(q, evt): + evt.set(q.get()) + + def do_receive(q, evt): + with gevent.Timeout(0, RuntimeError()): + try: + result = q.get() + evt.set(result) # pragma: no cover (should have raised) + except RuntimeError: + evt.set('timed out') + + q = queue.Queue() + dying_evt = AsyncResult() + waiting_evt = AsyncResult() + gevent.spawn(do_receive, q, dying_evt) + gevent.spawn(waiter, q, waiting_evt) + gevent.sleep(0.1) + q.put('hi') + self.assertEqual(dying_evt.get(), 'timed out') + self.assertEqual(waiting_evt.get(), 'hi') + + def test_two_bogus_waiters(self): + def do_receive(q, evt): + with gevent.Timeout(0, RuntimeError()): + try: + result = q.get() + evt.set(result) # pragma: no cover (should have raised) + except RuntimeError: + evt.set('timed out') + + q = queue.Queue() + e1 = AsyncResult() + e2 = AsyncResult() + gevent.spawn(do_receive, q, e1) + gevent.spawn(do_receive, q, e2) + gevent.sleep(0.1) + q.put('sent') + self.assertEqual(e1.get(), 'timed out') + self.assertEqual(e2.get(), 'timed out') + self.assertEqual(q.get(), 'sent') + + +class TestChannel(TestCase): + + def test_send(self): + channel = queue.Channel() + + events = [] + + def another_greenlet(): + events.append(channel.get()) + events.append(channel.get()) + + g = gevent.spawn(another_greenlet) + + events.append('sending') + channel.put('hello') + events.append('sent hello') + channel.put('world') + events.append('sent world') + + self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events) + g.get() + + def test_wait(self): + channel = queue.Channel() + events = [] + + def another_greenlet(): + events.append('sending hello') + channel.put('hello') + events.append('sending world') + channel.put('world') + events.append('sent world') + + g = gevent.spawn(another_greenlet) + + events.append('waiting') + events.append(channel.get()) + events.append(channel.get()) + + self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events) + gevent.sleep(0) + self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events) + g.get() + + def test_iterable(self): + channel = queue.Channel() + gevent.spawn(channel.put, StopIteration) + r = list(channel) + self.assertEqual(r, []) + +class TestJoinableQueue(TestCase): + + def test_task_done(self): + channel = queue.JoinableQueue() + X = object() + gevent.spawn(channel.put, X) + result = channel.get() + self.assertIs(result, X) + self.assertEqual(1, channel.unfinished_tasks) + channel.task_done() + self.assertEqual(0, channel.unfinished_tasks) + + +class TestNoWait(TestCase): + + def test_put_nowait_simple(self): + result = [] + q = queue.Queue(1) + + def store_result(func, *args): + result.append(func(*args)) + + run_callback = get_hub().loop.run_callback + + run_callback(store_result, util.wrap_errors(Full, q.put_nowait), 2) + run_callback(store_result, util.wrap_errors(Full, q.put_nowait), 3) + gevent.sleep(0) + assert len(result) == 2, result + assert result[0] is None, result + assert isinstance(result[1], queue.Full), result + + def test_get_nowait_simple(self): + result = [] + q = queue.Queue(1) + q.put(4) + + def store_result(func, *args): + result.append(func(*args)) + + run_callback = get_hub().loop.run_callback + + run_callback(store_result, util.wrap_errors(Empty, q.get_nowait)) + run_callback(store_result, util.wrap_errors(Empty, q.get_nowait)) + gevent.sleep(0) + assert len(result) == 2, result + assert result[0] == 4, result + assert isinstance(result[1], queue.Empty), result + + # get_nowait must work from the mainloop + def test_get_nowait_unlock(self): + result = [] + q = queue.Queue(1) + p = gevent.spawn(q.put, 5) + + def store_result(func, *args): + result.append(func(*args)) + + assert q.empty(), q + gevent.sleep(0) + assert q.full(), q + get_hub().loop.run_callback(store_result, q.get_nowait) + gevent.sleep(0) + assert q.empty(), q + assert result == [5], result + assert p.ready(), p + assert p.dead, p + assert q.empty(), q + + def test_get_nowait_unlock_channel(self): + # get_nowait runs fine in the hub, and + # it switches to a waiting putter if needed. + result = [] + q = queue.Channel() + p = gevent.spawn(q.put, 5) + + def store_result(func, *args): + result.append(func(*args)) + + self.assertTrue(q.empty()) + self.assertTrue(q.full()) + + gevent.sleep(0.001) + self.assertTrue(q.empty()) + self.assertTrue(q.full()) + + get_hub().loop.run_callback(store_result, q.get_nowait) + gevent.sleep(0.001) + self.assertTrue(q.empty()) + self.assertTrue(q.full()) + self.assertEqual(result, [5]) + self.assertTrue(p.ready()) + self.assertTrue(p.dead) + self.assertTrue(q.empty()) + + # put_nowait must work from the mainloop + def test_put_nowait_unlock(self): + result = [] + q = queue.Queue() + p = gevent.spawn(q.get) + + def store_result(func, *args): + result.append(func(*args)) + + self.assertTrue(q.empty(), q) + self.assertFalse(q.full(), q) + gevent.sleep(0.001) + + self.assertTrue(q.empty(), q) + self.assertFalse(q.full(), q) + + get_hub().loop.run_callback(store_result, q.put_nowait, 10) + + self.assertFalse(p.ready(), p) + gevent.sleep(0.001) + + self.assertEqual(result, [None]) + self.assertTrue(p.ready(), p) + self.assertFalse(q.full(), q) + self.assertTrue(q.empty(), q) + + +class TestJoinEmpty(TestCase): + + def test_issue_45(self): + """Test that join() exits immediately if not jobs were put into the queue""" + self.switch_expected = False + q = queue.JoinableQueue() + q.join() + +class AbstractTestWeakRefMixin(object): + + def test_weak_reference(self): + import weakref + one = self._makeOne() + ref = weakref.ref(one) + self.assertIs(one, ref()) + + +class TestGetInterrupt(AbstractTestWeakRefMixin, AbstractGenericGetTestCase): + + Timeout = Empty + + kind = queue.Queue + + def wait(self, timeout): + return self._makeOne().get(timeout=timeout) + + def _makeOne(self): + return self.kind() + +class TestGetInterruptJoinableQueue(TestGetInterrupt): + kind = queue.JoinableQueue + +class TestGetInterruptLifoQueue(TestGetInterrupt): + kind = queue.LifoQueue + +class TestGetInterruptPriorityQueue(TestGetInterrupt): + kind = queue.PriorityQueue + +class TestGetInterruptChannel(TestGetInterrupt): + kind = queue.Channel + + +class TestPutInterrupt(AbstractGenericGetTestCase): + kind = queue.Queue + Timeout = Full + + def setUp(self): + super(TestPutInterrupt, self).setUp() + self.queue = self._makeOne() + + def wait(self, timeout): + while not self.queue.full(): + self.queue.put(1) + return self.queue.put(2, timeout=timeout) + + def _makeOne(self): + return self.kind(1) + + +class TestPutInterruptJoinableQueue(TestPutInterrupt): + kind = queue.JoinableQueue + +class TestPutInterruptLifoQueue(TestPutInterrupt): + kind = queue.LifoQueue + +class TestPutInterruptPriorityQueue(TestPutInterrupt): + kind = queue.PriorityQueue + +class TestPutInterruptChannel(TestPutInterrupt): + kind = queue.Channel + + def _makeOne(self): + return self.kind() + + +if hasattr(queue, 'SimpleQueue'): + + class TestGetInterruptSimpleQueue(TestGetInterrupt): + kind = queue.SimpleQueue + + def test_raises_timeout_Timeout(self): + raise unittest.SkipTest("Not supported") + + test_raises_timeout_Timeout_exc_customized = test_raises_timeout_Timeout + test_outer_timeout_is_not_lost = test_raises_timeout_Timeout + + +del AbstractGenericGetTestCase + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__real_greenlet.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__real_greenlet.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e572ae6079fbde59b286364e67f5dcc47cabd1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__real_greenlet.py @@ -0,0 +1,34 @@ +"""Testing that greenlet restores sys.exc_info. + +Passes with CPython + greenlet 0.4.0 + +Fails with PyPy 2.2.1 +""" +from __future__ import print_function +import sys + +from gevent import testing as greentest + +class Test(greentest.TestCase): + + def test(self): + import greenlet + + print('Your greenlet version: %s' % (getattr(greenlet, '__version__', None), )) + + result = [] + + def func(): + result.append(repr(sys.exc_info())) + + g = greenlet.greenlet(func) + try: + 1 / 0 + except ZeroDivisionError: + g.switch() + + + self.assertEqual(result, ['(None, None, None)']) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount.py new file mode 100644 index 0000000000000000000000000000000000000000..b95558f63003ba7fc73abcf5660986a17edf18c4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount.py @@ -0,0 +1,189 @@ +# Copyright (c) 2008 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +"""This test checks that underlying socket instances (gevent.socket.socket._sock) +are not leaked by the hub. +""" +from __future__ import print_function + +from _socket import socket as c_socket +import sys +if sys.version_info[0] >= 3: + # Python3 enforces that __weakref__ appears only once, + # and not when a slotted class inherits from an unslotted class. + # We mess around with the class MRO below and violate that rule + # (because socket.socket defines __slots__ with __weakref__), + # so import socket.socket before that can happen. + __import__('socket') + Socket = c_socket +else: + class Socket(c_socket): + "Something we can have a weakref to" + +import _socket +_socket.socket = Socket + + +from gevent import monkey; monkey.patch_all() + +import gevent.testing as greentest +from gevent.testing import support +from gevent.testing import params + + +try: + from thread import start_new_thread +except ImportError: + from _thread import start_new_thread +from time import sleep +import weakref +import gc + +import socket +socket._realsocket = Socket + +SOCKET_TIMEOUT = 0.1 +if greentest.RESOLVER_DNSPYTHON: + # Takes a bit longer to resolve the client + # address initially. + SOCKET_TIMEOUT *= 2 + +if greentest.RUNNING_ON_CI: + SOCKET_TIMEOUT *= 2 + + +class Server(object): + + listening = False + client_data = None + server_port = None + + def __init__(self, raise_on_timeout): + self.raise_on_timeout = raise_on_timeout + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + self.server_port = support.bind_port(self.socket, params.DEFAULT_BIND_ADDR) + except: + self.close() + raise + + def close(self): + self.socket.close() + self.socket = None + + def handle_request(self): + try: + self.socket.settimeout(SOCKET_TIMEOUT) + + self.socket.listen(5) + + self.listening = True + + try: + conn, _ = self.socket.accept() # pylint:disable=no-member + except socket.timeout: + if self.raise_on_timeout: + raise + return + + try: + self.client_data = conn.recv(100) + conn.send(b'bye') + finally: + conn.close() + finally: + self.close() + + +class Client(object): + + server_data = None + + def __init__(self, server_port): + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.server_port = server_port + + + def close(self): + self.socket.close() + self.socket = None + + def make_request(self): + try: + self.socket.connect((params.DEFAULT_CONNECT, self.server_port)) + self.socket.send(b'hello') + self.server_data = self.socket.recv(100) + finally: + self.close() + + +class Test(greentest.TestCase): + __timeout__ = greentest.LARGE_TIMEOUT + + def run_interaction(self, run_client): + server = Server(raise_on_timeout=run_client) + wref_to_hidden_server_socket = weakref.ref(server.socket._sock) + client = None + start_new_thread(server.handle_request) + if run_client: + client = Client(server.server_port) + start_new_thread(client.make_request) + + # Wait until we do our business; we will always close + # the server; We may also close the client. + # On PyPy, we may not actually see the changes they write to + # their dicts immediately. + for obj in server, client: + if obj is None: + continue + while obj.socket is not None: + sleep(0.01) + + # If we have a client, then we should have data + if run_client: + self.assertEqual(server.client_data, b'hello') + self.assertEqual(client.server_data, b'bye') + + return wref_to_hidden_server_socket + + def run_and_check(self, run_client): + wref_to_hidden_server_socket = self.run_interaction(run_client=run_client) + greentest.gc_collect_if_needed() + if wref_to_hidden_server_socket(): + from pprint import pformat + print(pformat(gc.get_referrers(wref_to_hidden_server_socket()))) + for x in gc.get_referrers(wref_to_hidden_server_socket()): + print(pformat(x)) + for y in gc.get_referrers(x): + print('-', pformat(y)) + self.fail('server socket should be dead by now') + + def test_clean_exit(self): + self.run_and_check(True) + self.run_and_check(True) + + def test_timeout_exit(self): + self.run_and_check(False) + self.run_and_check(False) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount_core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount_core.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eb9f4f51dd1d1dd27caf9ebb823b01867d479a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__refcount_core.py @@ -0,0 +1,25 @@ +import sys +import weakref + +from gevent import testing as greentest + + +class Dummy(object): + def __init__(self): + __import__('gevent.core') + +@greentest.skipIf(weakref.ref(Dummy())() is not None, + "Relies on refcounting for fast weakref cleanup") +class Test(greentest.TestCase): + def test(self): + from gevent import socket + s = socket.socket() + r = weakref.ref(s) + s.close() + del s + self.assertIsNone(r()) + +assert weakref.ref(Dummy())() is None or hasattr(sys, 'pypy_version_info') + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__resolver_dnspython.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__resolver_dnspython.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0ec9eebe5cf52fe28a84776d77cef7e7a23380 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__resolver_dnspython.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +""" +Tests explicitly using the DNS python resolver. + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import unittest +import subprocess +import os + +from gevent import testing as greentest + +@unittest.skipUnless(greentest.resolver_dnspython_available(), + "dnspython not available") +class TestDnsPython(unittest.TestCase): + + def _run_one(self, mod_name): + cmd = [ + sys.executable, + '-m', + 'gevent.tests.monkey_package.' + mod_name + ] + + env = dict(os.environ) + env['GEVENT_RESOLVER'] = 'dnspython' + + output = subprocess.check_output(cmd, env=env) + self.assertIn(b'_g_patched_module_dns', output) + self.assertNotIn(b'_g_patched_module_dns.rdtypes', output) + return output + + def test_import_dns_no_monkey_patch(self): + self._run_one('issue1526_no_monkey') + + def test_import_dns_with_monkey_patch(self): + self._run_one('issue1526_with_monkey') + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__select.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__select.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e850b06088fac57a9381710a4dd6509a833770 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__select.py @@ -0,0 +1,126 @@ +from gevent.testing import six +import sys +import os +import errno +from gevent import select, socket +import gevent.core +import gevent.testing as greentest +import gevent.testing.timing +import unittest + + +class TestSelect(gevent.testing.timing.AbstractGenericWaitTestCase): + + def wait(self, timeout): + select.select([], [], [], timeout) + + + +@greentest.skipOnWindows("Cant select on files") +class TestSelectRead(gevent.testing.timing.AbstractGenericWaitTestCase): + + def wait(self, timeout): + r, w = os.pipe() + try: + select.select([r], [], [], timeout) + finally: + os.close(r) + os.close(w) + + # Issue #12367: http://www.freebsd.org/cgi/query-pr.cgi?pr=kern/155606 + @unittest.skipIf(sys.platform.startswith('freebsd'), + 'skip because of a FreeBSD bug: kern/155606') + def test_errno(self): + # Backported from test_select.py in 3.4 + with open(__file__, 'rb') as fp: + fd = fp.fileno() + fp.close() + try: + select.select([fd], [], [], 0) + except OSError as err: + # Python 3 + self.assertEqual(err.errno, errno.EBADF) + except select.error as err: # pylint:disable=duplicate-except + # Python 2 (select.error is OSError on py3) + self.assertEqual(err.args[0], errno.EBADF) + else: + self.fail("exception not raised") + + +@unittest.skipUnless(hasattr(select, 'poll'), "Needs poll") +@greentest.skipOnWindows("Cant poll on files") +class TestPollRead(gevent.testing.timing.AbstractGenericWaitTestCase): + def wait(self, timeout): + # On darwin, the read pipe is reported as writable + # immediately, for some reason. So we carefully register + # it only for read events (the default is read and write) + r, w = os.pipe() + try: + poll = select.poll() + poll.register(r, select.POLLIN) + poll.poll(timeout * 1000) + finally: + poll.unregister(r) + os.close(r) + os.close(w) + + def test_unregister_never_registered(self): + # "Attempting to remove a file descriptor that was + # never registered causes a KeyError exception to be + # raised." + poll = select.poll() + self.assertRaises(KeyError, poll.unregister, 5) + + def test_poll_invalid(self): + self.skipTest( + "libev >= 4.27 aborts the process if built with EV_VERIFY >= 2. " + "For libuv, depending on whether the fileno is reused or not " + "this either crashes or does nothing.") + with open(__file__, 'rb') as fp: + fd = fp.fileno() + + poll = select.poll() + poll.register(fd, select.POLLIN) + # Close after registering; libuv refuses to even + # create a watcher if it would get EBADF (so this turns into + # a test of whether or not we successfully initted the watcher). + fp.close() + result = poll.poll(0) + self.assertEqual(result, [(fd, select.POLLNVAL)]) # pylint:disable=no-member + +class TestSelectTypes(greentest.TestCase): + + def test_int(self): + sock = socket.socket() + try: + select.select([int(sock.fileno())], [], [], 0.001) + finally: + sock.close() + + if hasattr(six.builtins, 'long'): + def test_long(self): + sock = socket.socket() + try: + select.select( + [six.builtins.long(sock.fileno())], [], [], 0.001) + finally: + sock.close() + + def test_iterable(self): + sock = socket.socket() + + def fileno_iter(): + yield int(sock.fileno()) + + try: + select.select(fileno_iter(), [], [], 0.001) + finally: + sock.close() + + def test_string(self): + self.switch_expected = False + self.assertRaises(TypeError, select.select, ['hello'], [], [], 0.001) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__selectors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__selectors.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a52aca03511836fe9efaa88589aed4d7b99cf0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__selectors.py @@ -0,0 +1,111 @@ +# Tests for gevent.selectors in its native form, without +# monkey-patching. + +import gevent +from gevent import socket +from gevent import selectors + +import gevent.testing as greentest + +class SelectorTestMixin(object): + + @staticmethod + def run_selector_once(sel, timeout=3): + # Run in a background greenlet, leaving the main + # greenlet free to send data. + events = sel.select(timeout=timeout) + for key, mask in events: + key.data(sel, key.fileobj, mask) + gevent.sleep() + + unregister_after_send = True + + def read_from_ready_socket_and_reply(self, selector, conn, _events): + data = conn.recv(100) # Should be ready + if data: + conn.send(data) # Hope it won't block + + # Must unregister before we close. + if self.unregister_after_send: + selector.unregister(conn) + conn.close() + + def _check_selector(self, sel): + server, client = socket.socketpair() + glet = None + try: + sel.register(server, selectors.EVENT_READ, self.read_from_ready_socket_and_reply) + glet = gevent.spawn(self.run_selector_once, sel) + DATA = b'abcdef' + client.send(DATA) + data = client.recv(50) # here is probably where we yield to the event loop + self.assertEqual(data, DATA) + finally: + sel.close() + server.close() + client.close() + if glet is not None: + glet.join(10) + self.assertTrue(glet is not None and glet.ready()) + + +class GeventSelectorTest(SelectorTestMixin, + greentest.TestCase): + + def test_select_using_socketpair(self): + # Basic test. + with selectors.GeventSelector() as sel: + self._check_selector(sel) + + def test_select_many_sockets(self): + try: + AF_UNIX = socket.AF_UNIX + except AttributeError: + AF_UNIX = None + + pairs = [socket.socketpair() for _ in range(10)] + + try: + server_sel = selectors.GeventSelector() + client_sel = selectors.GeventSelector() + for i, pair in enumerate(pairs): + server, client = pair + server_sel.register(server, selectors.EVENT_READ, + self.read_from_ready_socket_and_reply) + client_sel.register(client, selectors.EVENT_READ, i) + # Prime them all to be ready at once. + data = str(i).encode('ascii') + client.send(data) + + # Read and reply to all the clients.. + # Everyone should be ready, so we ask not to block. + # The call to gevent.idle() is there to make sure that + # all event loop implementations (looking at you, libuv) + # get a chance to poll for IO. Without it, libuv + # doesn't find any results here. + # Not blocking only works for AF_UNIX sockets, though. + # If we got AF_INET (Windows) the data may need some time to + # traverse through the layers. + gevent.idle() + self.run_selector_once( + server_sel, + timeout=-1 if pairs[0][0].family == AF_UNIX else 3) + + found = 0 + for key, _ in client_sel.select(timeout=3): + expected = str(key.data).encode('ascii') + data = key.fileobj.recv(50) + self.assertEqual(data, expected) + found += 1 + self.assertEqual(found, len(pairs)) + finally: + server_sel.close() + client_sel.close() + for pair in pairs: + for s in pair: + s.close() + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__semaphore.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__semaphore.py new file mode 100644 index 0000000000000000000000000000000000000000..6036b612ca09a01539a0c2911b9cbe5f24d137f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__semaphore.py @@ -0,0 +1,425 @@ +### +# This file is test__semaphore.py only for organization purposes. +# The public API, +# and the *only* correct place to import Semaphore --- even in tests --- +# is ``gevent.lock``, never ``gevent._semaphore``. +## +from __future__ import print_function +from __future__ import absolute_import + +import weakref + +import gevent +import gevent.exceptions +from gevent.lock import Semaphore +from gevent.lock import BoundedSemaphore + +import gevent.testing as greentest +from gevent.testing import timing + +class TestSemaphore(greentest.TestCase): + + # issue 39 + def test_acquire_returns_false_after_timeout(self): + s = Semaphore(value=0) + result = s.acquire(timeout=0.01) + assert result is False, repr(result) + + def test_release_twice(self): + s = Semaphore() + result = [] + s.rawlink(lambda s: result.append('a')) + s.release() + s.rawlink(lambda s: result.append('b')) + s.release() + gevent.sleep(0.001) + # The order, though, is not guaranteed. + self.assertEqual(sorted(result), ['a', 'b']) + + def test_semaphore_weakref(self): + s = Semaphore() + r = weakref.ref(s) + self.assertEqual(s, r()) + + @greentest.ignores_leakcheck + def test_semaphore_in_class_with_del(self): + # Issue #704. This used to crash the process + # under PyPy through at least 4.0.1 if the Semaphore + # was implemented with Cython. + class X(object): + def __init__(self): + self.s = Semaphore() + + def __del__(self): + self.s.acquire() + + X() + import gc + gc.collect() + gc.collect() + + + def test_rawlink_on_unacquired_runs_notifiers(self): + # https://github.com/gevent/gevent/issues/1287 + + # Rawlinking a ready semaphore should fire immediately, + # not raise LoopExit + s = Semaphore() + gevent.wait([s]) + + +class TestSemaphoreMultiThread(greentest.TestCase): + # Tests that the object can be acquired correctly across + # multiple threads. + # Used as a base class. + + # See https://github.com/gevent/gevent/issues/1437 + + def _getTargetClass(self): + return Semaphore + + def _makeOne(self): + # Create an object that is associated with the current hub. If + # we don't do this now, it gets initialized lazily the first + # time it would have to block, which, in the event of threads, + # would be from an arbitrary thread. + return self._getTargetClass()(1) + + def _makeThreadMain(self, thread_running, thread_acquired, sem, + acquired, exc_info, + **thread_acquire_kwargs): + from gevent._hub_local import get_hub_if_exists + import sys + + def thread_main(): + thread_running.set() + try: + acquired.append( + sem.acquire(**thread_acquire_kwargs) + ) + except: + exc_info[:] = sys.exc_info() + raise # Print + finally: + hub = get_hub_if_exists() + if hub is not None: + hub.join() + hub.destroy(destroy_loop=True) + thread_acquired.set() + return thread_main + + IDLE_ITERATIONS = 5 + + def _do_test_acquire_in_one_then_another(self, + release=True, + require_thread_acquired_to_finish=False, + **thread_acquire_kwargs): + from gevent import monkey + self.assertFalse(monkey.is_module_patched('threading')) + + import threading + thread_running = threading.Event() + thread_acquired = threading.Event() + + sem = self._makeOne() + # Make future acquires block + sem.acquire() + + exc_info = [] + acquired = [] + + t = threading.Thread(target=self._makeThreadMain( + thread_running, thread_acquired, sem, + acquired, exc_info, + **thread_acquire_kwargs + )) + t.daemon = True + t.start() + thread_running.wait(10) # implausibly large time + if release: + sem.release() + # Spin the loop to be sure the release gets through. + # (Release schedules the notifier to run, and when the + # notifier run it sends the async notification to the + # other thread. Depending on exactly where we are in the + # event loop, and the limit to the number of callbacks + # that get run (including time-based) the notifier may or + # may not be immediately ready to run, so this can take up + # to two iterations.) + for _ in range(self.IDLE_ITERATIONS): + gevent.idle() + if thread_acquired.wait(timing.LARGE_TICK): + break + + self.assertEqual(acquired, [True]) + + if not release and thread_acquire_kwargs.get("timeout"): + # Spin the loop to be sure that the timeout has a chance to + # process. Interleave this with something that drops the GIL + # so the background thread has a chance to notice that. + for _ in range(self.IDLE_ITERATIONS): + gevent.idle() + if thread_acquired.wait(timing.LARGE_TICK): + break + thread_acquired.wait(timing.LARGE_TICK * 5) + + if require_thread_acquired_to_finish: + self.assertTrue(thread_acquired.is_set()) + try: + self.assertEqual(exc_info, []) + finally: + exc_info = None + + return sem, acquired + + def test_acquire_in_one_then_another(self): + self._do_test_acquire_in_one_then_another(release=True) + + def test_acquire_in_one_then_another_timed(self): + sem, acquired_in_thread = self._do_test_acquire_in_one_then_another( + release=False, + require_thread_acquired_to_finish=True, + timeout=timing.SMALLEST_RELIABLE_DELAY) + self.assertEqual([False], acquired_in_thread) + # This doesn't, of course, notify anything, because + # the waiter has given up. + sem.release() + notifier = getattr(sem, '_notifier', None) + self.assertIsNone(notifier) + + def test_acquire_in_one_wait_greenlet_wait_thread_gives_up(self): + # The waiter in the thread both arrives and gives up while + # the notifier is already running...or at least, that's what + # we'd like to arrange, but the _notify_links function doesn't + # drop the GIL/object lock, so the other thread is stuck and doesn't + # actually get to call into the acquire method. + + from gevent import monkey + self.assertFalse(monkey.is_module_patched('threading')) + + import threading + + sem = self._makeOne() + # Make future acquires block + sem.acquire() + + def greenlet_one(): + ack = sem.acquire() + # We're running in the notifier function right now. It switched to + # us. + thread.start() + gevent.sleep(timing.LARGE_TICK) + return ack + + exc_info = [] + acquired = [] + + glet = gevent.spawn(greenlet_one) + thread = threading.Thread(target=self._makeThreadMain( + threading.Event(), threading.Event(), + sem, + acquired, exc_info, + timeout=timing.LARGE_TICK + )) + thread.daemon = True + gevent.idle() + sem.release() + glet.join() + for _ in range(3): + gevent.idle() + thread.join(timing.LARGE_TICK) + + self.assertEqual(glet.value, True) + self.assertEqual([], exc_info) + self.assertEqual([False], acquired) + self.assertTrue(glet.dead, glet) + glet = None + + def assertOneHasNoHub(self, sem): + self.assertIsNone(sem.hub, sem) + + @greentest.skipOnPyPyOnWindows("Flaky there; can't reproduce elsewhere") + def test_dueling_threads(self, acquire_args=(), create_hub=None): + # pylint:disable=too-many-locals,too-many-statements + + # Threads doing nothing but acquiring and releasing locks, without + # having any other greenlets to switch to. + # https://github.com/gevent/gevent/issues/1698 + from gevent import monkey + from gevent._hub_local import get_hub_if_exists + + self.assertFalse(monkey.is_module_patched('threading')) + + import threading + from time import sleep as native_sleep + + sem = self._makeOne() + self.assertOneHasNoHub(sem) + count = 10000 + results = [-1, -1] + run = True + def do_it(ix): + if create_hub: + gevent.get_hub() + + try: + for i in range(count): + if not run: + break + + acquired = sem.acquire(*acquire_args) + assert acquire_args or acquired + if acquired: + sem.release() + results[ix] = i + if not create_hub: + # We don't artificially create the hub. + self.assertIsNone( + get_hub_if_exists(), + (get_hub_if_exists(), ix, i) + ) + if create_hub and i % 10 == 0: + gevent.sleep(timing.SMALLEST_RELIABLE_DELAY) + elif i % 100 == 0: + native_sleep(timing.SMALLEST_RELIABLE_DELAY) + except Exception as ex: # pylint:disable=broad-except + import traceback; traceback.print_exc() + results[ix] = str(ex) + ex = None + finally: + hub = get_hub_if_exists() + if hub is not None: + hub.join() + hub.destroy(destroy_loop=True) + + t1 = threading.Thread(target=do_it, args=(0,)) + t1.daemon = True + t2 = threading.Thread(target=do_it, args=(1,)) + t2.daemon = True + t1.start() + t2.start() + + t1.join(1) + t2.join(1) + + while t1.is_alive() or t2.is_alive(): + cur = list(results) + t1.join(7) + t2.join(7) + if cur == results: + # Hmm, after two seconds, no progress + run = False + break + + self.assertEqual(results, [count - 1, count - 1]) + + def test_dueling_threads_timeout(self): + self.test_dueling_threads((True, 4)) + + def test_dueling_threads_with_hub(self): + self.test_dueling_threads(create_hub=True) + + + # XXX: Need a test with multiple greenlets in a non-primary + # thread. Things should work, just very slowly; instead of moving through + # greenlet.switch(), they'll be moving with async watchers. + +class TestBoundedSemaphoreMultiThread(TestSemaphoreMultiThread): + + def _getTargetClass(self): + return BoundedSemaphore + +@greentest.skipOnPurePython("Needs C extension") +class TestCExt(greentest.TestCase): + + def test_c_extension(self): + self.assertEqual(Semaphore.__module__, + 'gevent._gevent_c_semaphore') + + +class SwitchWithFixedHash(object): + # Replaces greenlet.switch with a callable object + # with a hash code we control. This only matters if + # we're hashing this somewhere (which we used to), but + # that doesn't preserve order, so we don't do + # that anymore. + + def __init__(self, greenlet, hashcode): + self.switch = greenlet.switch + self.hashcode = hashcode + + def __hash__(self): + raise AssertionError + + def __eq__(self, other): + raise AssertionError + + def __call__(self, *args, **kwargs): + return self.switch(*args, **kwargs) + + def __repr__(self): + return repr(self.switch) + +class FirstG(gevent.Greenlet): + # A greenlet whose switch method will have a low hashcode. + + hashcode = 10 + + def __init__(self, *args, **kwargs): + gevent.Greenlet.__init__(self, *args, **kwargs) + self.switch = SwitchWithFixedHash(self, self.hashcode) + + +class LastG(FirstG): + # A greenlet whose switch method will have a high hashcode. + hashcode = 12 + + +def acquire_then_exit(sem, should_quit): + sem.acquire() + should_quit.append(True) + + +def acquire_then_spawn(sem, should_quit): + if should_quit: + return + sem.acquire() + g = FirstG.spawn(release_then_spawn, sem, should_quit) + g.join() + +def release_then_spawn(sem, should_quit): + sem.release() + if should_quit: # pragma: no cover + return + g = FirstG.spawn(acquire_then_spawn, sem, should_quit) + g.join() + +class TestSemaphoreFair(greentest.TestCase): + + def test_fair_or_hangs(self): + # If the lock isn't fair, this hangs, spinning between + # the last two greenlets. + # See https://github.com/gevent/gevent/issues/1487 + sem = Semaphore() + should_quit = [] + + keep_going1 = FirstG.spawn(acquire_then_spawn, sem, should_quit) + keep_going2 = FirstG.spawn(acquire_then_spawn, sem, should_quit) + exiting = LastG.spawn(acquire_then_exit, sem, should_quit) + + with self.assertRaises(gevent.exceptions.LoopExit): + gevent.joinall([keep_going1, keep_going2, exiting]) + + self.assertTrue(exiting.dead, exiting) + self.assertTrue(keep_going2.dead, keep_going2) + self.assertFalse(keep_going1.dead, keep_going1) + + sem.release() + keep_going1.kill() + keep_going2.kill() + exiting.kill() + + gevent.idle() + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__server.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__server.py new file mode 100644 index 0000000000000000000000000000000000000000..0f57d2f8c9d093029d833d3e7b49c947fcd0bfd8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__server.py @@ -0,0 +1,564 @@ +from __future__ import print_function, division +from contextlib import contextmanager +import unittest +import errno +import os + + +import gevent.testing as greentest +from gevent.testing import PY3 +from gevent.testing import sysinfo +from gevent.testing import DEFAULT_SOCKET_TIMEOUT as _DEFAULT_SOCKET_TIMEOUT +from gevent.testing.timing import SMALLEST_RELIABLE_DELAY +from gevent.testing.sockets import tcp_listener +from gevent.testing import WIN + +from gevent import socket +import gevent +from gevent.server import StreamServer +from gevent.exceptions import LoopExit + + +class SimpleStreamServer(StreamServer): + + def handle(self, client_socket, _address): # pylint:disable=method-hidden + fd = client_socket.makefile() + try: + request_line = fd.readline() + if not request_line: + return + try: + _method, path, _rest = request_line.split(' ', 3) + except Exception: + print('Failed to parse request line: %r' % (request_line, )) + raise + if path == '/ping': + client_socket.sendall(b'HTTP/1.0 200 OK\r\n\r\nPONG') + elif path in ['/long', '/short']: + client_socket.sendall(b'hello') + while True: + data = client_socket.recv(1) + if not data: + break + else: + client_socket.sendall(b'HTTP/1.0 404 WTF?\r\n\r\n') + finally: + fd.close() + +def sleep_to_clear_old_sockets(*_args): + try: + # Allow any queued callbacks needed to close sockets + # to run. On Windows, this needs to spin the event loop to + # allow proper FD cleanup. Otherwise we risk getting an + # old FD that's being closed and then get spurious connection + # errors. + gevent.sleep(0 if not WIN else SMALLEST_RELIABLE_DELAY) + except Exception: # pylint:disable=broad-except + pass + + +class Settings(object): + ServerClass = StreamServer + ServerSubClass = SimpleStreamServer + restartable = True + close_socket_detected = True + + @staticmethod + def assertAcceptedConnectionError(inst): + with inst.makefile() as conn: + try: + result = conn.read() + except socket.timeout: + result = None + inst.assertFalse(result) + + assert500 = assertAcceptedConnectionError + + @staticmethod + def assert503(inst): + # regular reads timeout + inst.assert500() + # attempt to send anything reset the connection + try: + inst.send_request() + except socket.error as ex: + if ex.args[0] not in greentest.CONN_ABORTED_ERRORS: + raise + + @staticmethod + def assertPoolFull(inst): + with inst.assertRaises(socket.timeout): + inst.assertRequestSucceeded(timeout=0.01) + + @staticmethod + def fill_default_server_args(inst, kwargs): + kwargs.setdefault('spawn', inst.get_spawn()) + return kwargs + +class TestCase(greentest.TestCase): + # pylint: disable=too-many-public-methods + __timeout__ = greentest.LARGE_TIMEOUT + Settings = Settings + server = None + + def cleanup(self): + if getattr(self, 'server', None) is not None: + self.server.stop() + self.server = None + sleep_to_clear_old_sockets() + + def get_listener(self): + return self._close_on_teardown(tcp_listener(backlog=5)) + + def get_server_host_port_family(self): + server_host = self.server.server_host + if not server_host: + server_host = greentest.DEFAULT_LOCAL_HOST_ADDR + elif server_host == '::': + server_host = greentest.DEFAULT_LOCAL_HOST_ADDR6 + + try: + family = self.server.socket.family + except AttributeError: + # server deletes socket when closed + family = socket.AF_INET + + return server_host, self.server.server_port, family + + @contextmanager + def makefile(self, timeout=_DEFAULT_SOCKET_TIMEOUT, bufsize=1, include_raw_socket=False): + server_host, server_port, family = self.get_server_host_port_family() + bufarg = 'buffering' if PY3 else 'bufsize' + makefile_kwargs = {bufarg: bufsize} + if PY3: + # Under Python3, you can't read and write to the same + # makefile() opened in r, and r+ is not allowed + makefile_kwargs['mode'] = 'rwb' + + with socket.socket(family=family) as sock: + rconn = None + # We want the socket to be accessible from the fileobject + # we return. On Python 2, natively this is available as + # _sock, but Python 3 doesn't have that. + sock.connect((server_host, server_port)) + sock.settimeout(timeout) + with sock.makefile(**makefile_kwargs) as rconn: + result = rconn if not include_raw_socket else (rconn, sock) + yield result + + def send_request(self, url='/', timeout=_DEFAULT_SOCKET_TIMEOUT, bufsize=1): + with self.makefile(timeout=timeout, bufsize=bufsize) as conn: + self.send_request_to_fd(conn, url) + + def send_request_to_fd(self, fd, url='/'): + fd.write(('GET %s HTTP/1.0\r\n\r\n' % url).encode('latin-1')) + fd.flush() + + LOCAL_CONN_REFUSED_ERRORS = () + if greentest.OSX: + # A kernel bug in OS X sometimes results in this + LOCAL_CONN_REFUSED_ERRORS = (errno.EPROTOTYPE,) + elif greentest.WIN and greentest.PYPY3: + # We see WinError 10049: The requested address is not valid + # which is not one of the errors we get anywhere else. + # Not sure which errno constant this is? + LOCAL_CONN_REFUSED_ERRORS = (10049,) + + def assertConnectionRefused(self, in_proc_server=True): + try: + with self.assertRaises(socket.error) as exc: + with self.makefile() as conn: + conn.close() + except LoopExit: + if not in_proc_server: + raise + # A LoopExit is fine. If we've killed the server + # and don't have any other greenlets to run, then + # blocking to open the connection might raise this. + # This became likely on Windows once we stopped + # passing IP addresses through an extra call to + # ``getaddrinfo``, which changed the number of switches + return + + ex = exc.exception + self.assertIn(ex.args[0], + (errno.ECONNREFUSED, errno.EADDRNOTAVAIL, + errno.ECONNRESET, errno.ECONNABORTED) + self.LOCAL_CONN_REFUSED_ERRORS, + (ex, ex.args)) + + def assert500(self): + self.Settings.assert500(self) + + def assert503(self): + self.Settings.assert503(self) + + def assertAcceptedConnectionError(self): + self.Settings.assertAcceptedConnectionError(self) + + def assertPoolFull(self): + self.Settings.assertPoolFull(self) + + def assertNotAccepted(self): + try: + with self.makefile(include_raw_socket=True) as (conn, sock): + conn.write(b'GET / HTTP/1.0\r\n\r\n') + conn.flush() + result = b'' + try: + while True: + data = sock.recv(1) + if not data: + break + result += data + except socket.timeout: + self.assertFalse(result) + return + except LoopExit: + # See assertConnectionRefused + return + + self.assertTrue(result.startswith(b'HTTP/1.0 500 Internal Server Error'), repr(result)) + + + def assertRequestSucceeded(self, timeout=_DEFAULT_SOCKET_TIMEOUT): + with self.makefile(timeout=timeout) as conn: + conn.write(b'GET /ping HTTP/1.0\r\n\r\n') + result = conn.read() + + self.assertTrue(result.endswith(b'\r\n\r\nPONG'), repr(result)) + + def start_server(self): + self.server.start() + self.assertRequestSucceeded() + self.assertRequestSucceeded() + + def stop_server(self): + self.server.stop() + self.assertConnectionRefused() + + def report_netstat(self, _msg): + # At one point this would call 'sudo netstat -anp | grep PID' + # with os.system. We can probably do better with psutil. + return + + def _create_server(self, *args, **kwargs): + kind = kwargs.pop('server_kind', self.ServerSubClass) + addr = kwargs.pop('server_listen_addr', (greentest.DEFAULT_BIND_ADDR, 0)) + return kind(addr, *args, **kwargs) + + def init_server(self, *args, **kwargs): + self.server = self._create_server(*args, **kwargs) + self.server.start() + sleep_to_clear_old_sockets() + + @property + def socket(self): + return self.server.socket + + def _test_invalid_callback(self): + if sysinfo.RUNNING_ON_APPVEYOR: + self.skipTest("Sometimes misses the error") # XXX: Why? + + try: + # Can't use a kwarg here, WSGIServer and StreamServer + # take different things (application and handle) + self.init_server(lambda: None) + self.expect_one_error() + + self.assert500() + self.assert_error(TypeError) + finally: + self.server.stop() + # XXX: There's something unreachable (with a traceback?) + # We need to clear it to make the leak checks work on Travis; + # so far I can't reproduce it locally on OS X. + import gc; gc.collect() + + def fill_default_server_args(self, kwargs): + return self.Settings.fill_default_server_args(self, kwargs) + + def ServerClass(self, *args, **kwargs): + return self.Settings.ServerClass(*args, + **self.fill_default_server_args(kwargs)) + + def ServerSubClass(self, *args, **kwargs): + return self.Settings.ServerSubClass(*args, + **self.fill_default_server_args(kwargs)) + + def get_spawn(self): + return None + +class TestDefaultSpawn(TestCase): + + def get_spawn(self): + return gevent.spawn + + def _test_server_start_stop(self, restartable): + self.report_netstat('before start') + self.start_server() + self.report_netstat('after start') + if restartable and self.Settings.restartable: + self.server.stop_accepting() + self.report_netstat('after stop_accepting') + self.assertNotAccepted() + self.server.start_accepting() + self.report_netstat('after start_accepting') + sleep_to_clear_old_sockets() + self.assertRequestSucceeded() + self.stop_server() + self.report_netstat('after stop') + + def test_backlog_is_not_accepted_for_socket(self): + self.switch_expected = False + with self.assertRaises(TypeError): + self.ServerClass(self.get_listener(), backlog=25) + + @greentest.skipOnLibuvOnCIOnPyPy("Sometimes times out") + @greentest.skipOnAppVeyor("Sometimes times out.") + def test_backlog_is_accepted_for_address(self): + self.server = self.ServerSubClass((greentest.DEFAULT_BIND_ADDR, 0), backlog=25) + self.assertConnectionRefused() + self._test_server_start_stop(restartable=False) + + def test_subclass_just_create(self): + self.server = self.ServerSubClass(self.get_listener()) + self.assertNotAccepted() + + @greentest.skipOnAppVeyor("Sometimes times out.") + def test_subclass_with_socket(self): + self.server = self.ServerSubClass(self.get_listener()) + # the connection won't be refused, because there exists a + # listening socket, but it won't be handled also + self.assertNotAccepted() + self._test_server_start_stop(restartable=True) + + def test_subclass_with_address(self): + self.server = self.ServerSubClass((greentest.DEFAULT_BIND_ADDR, 0)) + self.assertConnectionRefused() + self._test_server_start_stop(restartable=True) + + def test_invalid_callback(self): + self._test_invalid_callback() + + @greentest.reraises_flaky_timeout(socket.timeout) + def _test_serve_forever(self): + g = gevent.spawn(self.server.serve_forever) + try: + sleep_to_clear_old_sockets() + self.assertRequestSucceeded() + self.server.stop() + self.assertFalse(self.server.started) + self.assertConnectionRefused() + finally: + g.kill() + g.get() + self.server.stop() + + def test_serve_forever(self): + self.server = self.ServerSubClass((greentest.DEFAULT_BIND_ADDR, 0)) + self.assertFalse(self.server.started) + self.assertConnectionRefused() + self._test_serve_forever() + + def test_serve_forever_after_start(self): + self.server = self.ServerSubClass((greentest.DEFAULT_BIND_ADDR, 0)) + self.assertConnectionRefused() + self.assertFalse(self.server.started) + self.server.start() + self.assertTrue(self.server.started) + self._test_serve_forever() + + @greentest.skipIf(greentest.EXPECT_POOR_TIMER_RESOLUTION, "Sometimes spuriously fails") + def test_server_closes_client_sockets(self): + self.server = self.ServerClass((greentest.DEFAULT_BIND_ADDR, 0), lambda *args: []) + self.server.start() + sleep_to_clear_old_sockets() + with self.makefile() as conn: + self.send_request_to_fd(conn) + # use assert500 below? + with gevent.Timeout._start_new_or_dummy(1): + try: + result = conn.read() + if result: + assert result.startswith('HTTP/1.0 500 Internal Server Error'), repr(result) + except socket.timeout: + pass + except socket.error as ex: + if ex.args[0] == 10053: + pass # "established connection was aborted by the software in your host machine" + elif ex.args[0] == errno.ECONNRESET: + pass + else: + raise + + self.stop_server() + + @property + def socket(self): + return self.server.socket + + def test_error_in_spawn(self): + self.init_server() + self.assertTrue(self.server.started) + error = ExpectedError('test_error_in_spawn') + def _spawn(*_args): + gevent.getcurrent().throw(error) + self.server._spawn = _spawn + self.expect_one_error() + self.assertAcceptedConnectionError() + self.assert_error(ExpectedError, error) + + def test_server_repr_when_handle_is_instancemethod(self): + # PR 501 + self.init_server() + assert self.server.started + self.assertIn('Server', repr(self.server)) + + self.server.set_handle(self.server.handle) + self.assertIn('handle=', repr(self.server)) + + self.server.set_handle(self.test_server_repr_when_handle_is_instancemethod) + self.assertIn('test_server_repr_when_handle_is_instancemethod', repr(self.server)) + + def handle(): + pass + self.server.set_handle(handle) + self.assertIn('handle= returned a result with an error set + + # It's not safe to continue after a SystemError, so we just skip the test there. + + # As of Jan 2018 with CFFI 1.11.2 this happens reliably on macOS 3.6 and 3.7 + # as well. + + # See https://bitbucket.org/cffi/cffi/issues/352/systemerror-returned-a-result-with-an + + # This is fixed in 1.11.3 + + import gevent.signal # make sure it's in sys.modules pylint:disable=redefined-outer-name + assert gevent.signal + import site + if greentest.PY3: + from importlib import reload as reload_module + else: + # builtin on py2 + reload_module = reload # pylint:disable=undefined-variable + + try: + reload_module(site) + except TypeError: + # Non-CFFI on Travis triggers this, for some reason, + # but only on 3.6, not 3.4 or 3.5, and not yet on 3.7. + + # The only module seen to trigger this is __main__, i.e., this module. + + # This is hard to trigger in a virtualenv since it appears they + # install their own site.py, different from the one that ships with + # Python 3.6., and at least the version I have doesn't mess with + # __cached__ + assert greentest.PY36 + import sys + for m in set(sys.modules.values()): + try: + if m.__cached__ is None: + print("Module has None __cached__", m, file=sys.stderr) + except AttributeError: + continue + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__sleep0.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__sleep0.py new file mode 100644 index 0000000000000000000000000000000000000000..d95d677604634772e94b4de581f6066e01ecc72d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__sleep0.py @@ -0,0 +1,10 @@ +import gevent +from gevent.testing.util import alarm + + +alarm(3) + + +with gevent.Timeout(0.01, False): + while True: + gevent.sleep(0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket.py new file mode 100644 index 0000000000000000000000000000000000000000..e049c81fb4a18579c8605e9351d1ca5e0b2d5fd5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket.py @@ -0,0 +1,661 @@ +from __future__ import print_function +from __future__ import absolute_import + +from gevent import monkey +# This line can be commented out so that most tests run with the +# system socket for comparison. +monkey.patch_all() + +import sys +import array +import socket +import time +import unittest +from functools import wraps + +import gevent +from gevent._compat import reraise + +import gevent.testing as greentest + +from gevent.testing import six +from gevent.testing import LARGE_TIMEOUT +from gevent.testing import support +from gevent.testing import params +from gevent.testing.sockets import tcp_listener +from gevent.testing.skipping import skipWithoutExternalNetwork +from gevent.testing.skipping import skipOnMacOnCI + +# we use threading on purpose so that we can test both regular and +# gevent sockets with the same code +from threading import Thread as _Thread +from threading import Event + +errno_types = int + +# socket.accept/unwrap/makefile aren't found for some reason +# pylint:disable=no-member + +class BaseThread(object): + terminal_exc = None + + def __init__(self, target): + @wraps(target) + def errors_are_fatal(*args, **kwargs): + try: + return target(*args, **kwargs) + except: # pylint:disable=bare-except + self.terminal_exc = sys.exc_info() + raise + self.target = errors_are_fatal + +class GreenletThread(BaseThread): + + def __init__(self, target=None, args=()): + BaseThread.__init__(self, target) + self.glet = gevent.spawn(self.target, *args) + + def join(self, *args, **kwargs): + return self.glet.join(*args, **kwargs) + + def is_alive(self): + return not self.glet.ready() + +if not monkey.is_module_patched('threading'): + class ThreadThread(BaseThread, _Thread): + def __init__(self, **kwargs): + target = kwargs.pop('target') + BaseThread.__init__(self, target) + _Thread.__init__(self, target=self.target, **kwargs) + self.start() + Thread = ThreadThread +else: + Thread = GreenletThread + +class TestTCP(greentest.TestCase): + __timeout__ = None + TIMEOUT_ERROR = socket.timeout + long_data = ", ".join([str(x) for x in range(20000)]) + if not isinstance(long_data, bytes): + long_data = long_data.encode('ascii') + + def setUp(self): + super(TestTCP, self).setUp() + if '-v' in sys.argv: + printed = [] + try: + from time import perf_counter as now + except ImportError: + from time import time as now + def log(*args): + if not printed: + print() + printed.append(1) + print("\t -> %0.6f" % now(), *args) + + orig_cot = self._close_on_teardown + def cot(o): + log("Registering for teardown", o) + def c(o=o): + log("Closing on teardown", o) + o.close() + o = None + orig_cot(c) + return o + self._close_on_teardown = cot + + else: + def log(*_args): + "Does nothing" + self.log = log + + + self.listener = self._close_on_teardown(self._setup_listener()) + # It is important to watch the lifetimes of socket objects and + # ensure that: + # (1) they are closed; and + # (2) *before* the next test begins. + # + # For example, it's a bad bad thing to leave a greenlet running past the + # scope of the individual test method if that greenlet will close + # a socket object --- especially if that socket object might also have been + # closed explicitly. + # + # On Windows, we've seen issue with filenos getting reused while something + # still thinks they have the original fileno around. When they later + # close that fileno, a completely unrelated object is closed. + self.port = self.listener.getsockname()[1] + + def _setup_listener(self): + return tcp_listener() + + def create_connection(self, host=None, port=None, timeout=None, + blocking=None): + sock = self._close_on_teardown(socket.socket()) + sock.connect((host or params.DEFAULT_CONNECT, port or self.port)) + if timeout is not None: + sock.settimeout(timeout) + if blocking is not None: + sock.setblocking(blocking) + return sock + + def _test_sendall(self, data, match_data=None, client_method='sendall', + **client_args): + # pylint:disable=too-many-locals,too-many-branches,too-many-statements + log = self.log + log("test_sendall using method", client_method) + + read_data = [] + accepted_event = Event() + + def accept_and_read(): + log("\taccepting", self.listener) + conn, _ = self.listener.accept() + try: + with conn.makefile(mode='rb') as r: + log("\taccepted on server; client conn is", conn, "file is", r) + accepted_event.set() + log("\treading") + read_data.append(r.read()) + log("\tdone reading", r, "got bytes", len(read_data[0])) + del r + finally: + conn.close() + del conn + + + server = Thread(target=accept_and_read) + try: + log("creating client connection") + client = self.create_connection(**client_args) + + # It's important to wait for the server to fully accept before + # we shutdown and close the socket. In SSL mode, the number + # and timing of data exchanges to complete the handshake and + # thus exactly when greenlet switches occur, varies by TLS version. + # + # It turns out that on < TLS1.3, we were getting lucky and the + # server was the greenlet that raced ahead and blocked in r.read() + # before the client returned from create_connection(). + # + # But when TLS 1.3 was deployed (OpenSSL 1.1), the *client* was the + # one that raced ahead while the server had yet to return from + # self.listener.accept(). So the client sent the data to the socket, + # and closed, before the server could do anything, and the server, + # when it got switched to by server.join(), found its new socket + # dead. + accepted_event.wait() + log("Client got accepted event from server", client, "; sending data", len(data)) + try: + x = getattr(client, client_method)(data) + log("Client sent data: result from method", x) + finally: + log("Client will unwrap and shutdown") + if hasattr(client, 'unwrap'): + # Are we dealing with an SSLSocket? If so, unwrap it + # before attempting to shut down the socket. This does the + # SSL shutdown handshake and (hopefully) stops ``accept_and_read`` + # from generating ``ConnectionResetError`` on AppVeyor. + try: + client = client.unwrap() + except (ValueError, OSError): + # PyPy raises _cffi_ssl._stdssl.error.SSLSyscallError, + # which is an IOError in 2.7 and OSError in 3.7 + pass + + try: + # The implicit reference-based nastiness of Python 2 + # sockets interferes, especially when using SSL sockets. + # The best way to get a decent FIN to the server is to shutdown + # the output. Doing that on Python 3, OTOH, is contraindicated + # except on PyPy, so this used to read ``PY2 or PYPY``. But + # it seems that a shutdown is generally good practice, and I didn't + # document what errors we saw without it. Per issue #1637 + # lets do a shutdown everywhere, but only after removing any + # SSL wrapping. + client.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + log("Client will close") + client.close() + finally: + server.join(10) + assert not server.is_alive() + + if server.terminal_exc: + reraise(*server.terminal_exc) + + if match_data is None: + match_data = self.long_data + read_data = read_data[0].split(b',') + match_data = match_data.split(b',') + self.assertEqual(read_data[0], match_data[0]) + self.assertEqual(len(read_data), len(match_data)) + self.assertEqual(read_data, match_data) + + def test_sendall_str(self): + self._test_sendall(self.long_data) + + if six.PY2: + def test_sendall_unicode(self): + self._test_sendall(six.text_type(self.long_data)) + + @skipOnMacOnCI("Sometimes fails for no apparent reason (buffering?)") + def test_sendall_array(self): + data = array.array("B", self.long_data) + self._test_sendall(data) + + def test_sendall_empty(self): + data = b'' + self._test_sendall(data, data) + + def test_sendall_empty_with_timeout(self): + # Issue 719 + data = b'' + self._test_sendall(data, data, timeout=10) + + def test_sendall_nonblocking(self): + # https://github.com/benoitc/gunicorn/issues/1282 + # Even if the socket is non-blocking, we make at least + # one attempt to send data. Under Py2 before this fix, we + # would incorrectly immediately raise a timeout error + data = b'hi\n' + self._test_sendall(data, data, blocking=False) + + def test_empty_send(self): + # Issue 719 + data = b'' + self._test_sendall(data, data, client_method='send') + + def test_fullduplex(self): + N = 100000 + + def server(): + remote_client, _ = self.listener.accept() + self._close_on_teardown(remote_client) + # start reading, then, while reading, start writing. the reader should not hang forever + + sender = Thread(target=remote_client.sendall, + args=((b't' * N),)) + try: + result = remote_client.recv(1000) + self.assertEqual(result, b'hello world') + finally: + sender.join() + + server_thread = Thread(target=server) + client = self.create_connection() + client_file = self._close_on_teardown(client.makefile()) + client_reader = Thread(target=client_file.read, args=(N, )) + time.sleep(0.1) + client.sendall(b'hello world') + time.sleep(0.1) + + # close() used to hang + client_file.close() + client.close() + + # this tests "full duplex" bug; + server_thread.join() + + client_reader.join() + + def test_recv_timeout(self): + def accept(): + # make sure the conn object stays alive until the end; + # premature closing triggers a ResourceWarning and + # EOF on the client. + conn, _ = self.listener.accept() + self._close_on_teardown(conn) + + acceptor = Thread(target=accept) + client = self.create_connection() + try: + client.settimeout(1) + start = time.time() + with self.assertRaises(self.TIMEOUT_ERROR): + client.recv(1024) + took = time.time() - start + self.assertTimeWithinRange(took, 1 - 0.1, 1 + 0.1) + finally: + acceptor.join() + + # Subclasses can disable this + _test_sendall_timeout_check_time = True + + # Travis-CI container infrastructure is configured with + # large socket buffers, at least 2MB, as-of Jun 3, 2015, + # so we must be sure to send more data than that. + # In 2018, this needs to be increased *again* as a smaller value was + # still often being sent. + _test_sendall_data = b'hello' * 100000000 + + # This doesn't make much sense...why are we really skipping this? + @greentest.skipOnWindows("On Windows send() accepts whatever is thrown at it") + def test_sendall_timeout(self): + client_sock = [] + acceptor = Thread(target=lambda: client_sock.append(self.listener.accept())) + client = self.create_connection() + time.sleep(0.1) + assert client_sock + client.settimeout(0.1) + start = time.time() + try: + with self.assertRaises(self.TIMEOUT_ERROR): + client.sendall(self._test_sendall_data) + if self._test_sendall_timeout_check_time: + took = time.time() - start + self.assertTimeWithinRange(took, 0.09, 0.21) + finally: + acceptor.join() + client.close() + client_sock[0][0].close() + + def test_makefile(self): + def accept_once(): + conn, _ = self.listener.accept() + fd = conn.makefile(mode='wb') + fd.write(b'hello\n') + fd.flush() + fd.close() + conn.close() # for pypy + + acceptor = Thread(target=accept_once) + try: + client = self.create_connection() + # Closing the socket doesn't close the file + client_file = client.makefile(mode='rb') + client.close() + line = client_file.readline() + self.assertEqual(line, b'hello\n') + self.assertEqual(client_file.read(), b'') + client_file.close() + finally: + acceptor.join() + + def test_makefile_timeout(self): + + def accept_once(): + conn, _ = self.listener.accept() + try: + time.sleep(0.3) + finally: + conn.close() # for pypy + + acceptor = Thread(target=accept_once) + try: + client = self.create_connection() + client.settimeout(0.1) + fd = client.makefile(mode='rb') + self.assertRaises(self.TIMEOUT_ERROR, fd.readline) + client.close() + fd.close() + finally: + acceptor.join() + + def test_attributes(self): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) + self.assertIs(s.family, socket.AF_INET) + self.assertEqual(s.type, socket.SOCK_DGRAM) + self.assertEqual(0, s.proto) + + if hasattr(socket, 'SOCK_NONBLOCK'): + s.settimeout(1) + self.assertIs(s.family, socket.AF_INET) + + s.setblocking(0) + std_socket = monkey.get_original('socket', 'socket')(socket.AF_INET, socket.SOCK_DGRAM, 0) + try: + std_socket.setblocking(0) + self.assertEqual(std_socket.type, s.type) + finally: + std_socket.close() + + s.close() + + def test_connect_ex_nonblocking_bad_connection(self): + # Issue 841 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.setblocking(False) + ret = s.connect_ex((greentest.DEFAULT_LOCAL_HOST_ADDR, support.find_unused_port())) + self.assertIsInstance(ret, errno_types) + finally: + s.close() + + @skipWithoutExternalNetwork("Tries to resolve hostname") + def test_connect_ex_gaierror(self): + # Issue 841 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + with self.assertRaises(socket.gaierror): + s.connect_ex(('foo.bar.fizzbuzz', support.find_unused_port())) + finally: + s.close() + + @skipWithoutExternalNetwork("Tries to resolve hostname") + def test_connect_ex_not_call_connect(self): + # Issue 1931 + + def do_it(sock): + try: + with self.assertRaises(socket.gaierror): + sock.connect_ex(('foo.bar.fizzbuzz', support.find_unused_port())) + finally: + sock.close() + + # An instance attribute doesn't matter because we can't set it + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with self.assertRaises(AttributeError): + s.connect = None + s.close() + + # A subclass + class S(socket.socket): + def connect(self, *args): + raise AssertionError('Should not be called') + + s = S(socket.AF_INET, socket.SOCK_STREAM) + do_it(s) + + def test_connect_ex_nonblocking_overflow(self): + # Issue 841 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.setblocking(False) + with self.assertRaises(OverflowError): + s.connect_ex((greentest.DEFAULT_LOCAL_HOST_ADDR, 65539)) + finally: + s.close() + + @unittest.skipUnless(hasattr(socket, 'SOCK_CLOEXEC'), + "Requires SOCK_CLOEXEC") + def test_connect_with_type_flags_ignored(self): + # Issue 944 + # If we have SOCK_CLOEXEC or similar, we shouldn't be passing + # them through to the getaddrinfo call that connect() makes + SOCK_CLOEXEC = socket.SOCK_CLOEXEC # pylint:disable=no-member + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM | SOCK_CLOEXEC) + + def accept_once(): + conn, _ = self.listener.accept() + fd = conn.makefile(mode='wb') + fd.write(b'hello\n') + fd.close() + conn.close() + + acceptor = Thread(target=accept_once) + try: + s.connect((params.DEFAULT_CONNECT, self.port)) + fd = s.makefile(mode='rb') + self.assertEqual(fd.readline(), b'hello\n') + + fd.close() + s.close() + finally: + acceptor.join() + + +class TestCreateConnection(greentest.TestCase): + + __timeout__ = LARGE_TIMEOUT + + def test_refuses(self, **conn_args): + connect_port = support.find_unused_port() + + with self.assertRaisesRegex( + socket.error, + # We really expect "connection refused". It's unclear + # where/why we would get '[errno -2] name or service + # not known' but it seems some systems generate that. + # https://github.com/gevent/gevent/issues/1389 Somehow + # extremly rarely we've also seen 'address already in + # use', which makes even less sense. The manylinux + # 2010 environment produces 'errno 99 Cannot assign + # requested address', which, I guess? + # Meanwhile, the musllinux_1 environment produces + # '[Errno 99] Address not available' + 'refused|not known|already in use|assign|not available' + ): + socket.create_connection( + (greentest.DEFAULT_BIND_ADDR, connect_port), + timeout=30, + **conn_args + ) + + def test_refuses_from_port(self): + source_port = support.find_unused_port() + # Usually we don't want to bind/connect to '', but + # using it as the source is required if we don't want to hang, + # at least on some systems (OS X) + self.test_refuses(source_address=('', source_port)) + + + @greentest.ignores_leakcheck + @skipWithoutExternalNetwork("Tries to resolve hostname") + def test_base_exception(self): + # such as a GreenletExit or a gevent.timeout.Timeout + + class E(BaseException): + pass + + class MockSocket(object): + + created = () + closed = False + + def __init__(self, *_): + MockSocket.created += (self,) + + def connect(self, _): + raise E(_) + + def close(self): + self.closed = True + + def mockgetaddrinfo(*_): + return [(1, 2, 3, 3, 5),] + + import gevent.socket as gsocket + # Make sure we're monkey patched + self.assertEqual(gsocket.create_connection, socket.create_connection) + orig_socket = gsocket.socket + orig_getaddrinfo = gsocket.getaddrinfo + + try: + gsocket.socket = MockSocket + gsocket.getaddrinfo = mockgetaddrinfo + + with self.assertRaises(E): + socket.create_connection(('host', 'port')) + + self.assertEqual(1, len(MockSocket.created)) + self.assertTrue(MockSocket.created[0].closed) + + finally: + MockSocket.created = () + gsocket.socket = orig_socket + gsocket.getaddrinfo = orig_getaddrinfo + +class TestFunctions(greentest.TestCase): + + @greentest.ignores_leakcheck + # Creating new types in the function takes a cycle to cleanup. + def test_wait_timeout(self): + # Issue #635 + from gevent import socket as gsocket + class io(object): + callback = None + + def start(self, *_args): + gevent.sleep(10) + + with self.assertRaises(gsocket.timeout): + gsocket.wait(io(), timeout=0.01) # pylint:disable=no-member + + + def test_signatures(self): + # https://github.com/gevent/gevent/issues/960 + exclude = [] + if greentest.PYPY: + # Up through at least PyPy 5.7.1, they define these as + # gethostbyname(host), whereas the official CPython argument name + # is hostname. But cpython doesn't allow calling with keyword args. + # Likewise for gethostbyaddr: PyPy uses host, cpython uses ip_address + exclude.append('gethostbyname') + exclude.append('gethostbyname_ex') + exclude.append('gethostbyaddr') + if sys.version_info[:2] < (3, 11): + # 3.11+ add ``*, all_errors=False``. We allow that on all versions, + # forcing it to a false value if the user sends a true value before + # exception groups exist. + exclude.append('create_connection') + self.assertMonkeyPatchedFuncSignatures('socket', exclude=exclude) + + def test_resolve_ipv6_scope_id(self): + from gevent import _socketcommon as SC + if not SC.__socket__.has_ipv6: + self.skipTest("Needs IPv6") # pragma: no cover + if not hasattr(SC.__socket__, 'inet_pton'): + self.skipTest("Needs inet_pton") # pragma: no cover + + # A valid IPv6 address, with a scope. + addr = ('2607:f8b0:4000:80e::200e', 80, 0, 9) + # Mock socket + class sock(object): + family = SC.AF_INET6 # pylint:disable=no-member + self.assertIs(addr, SC._resolve_addr(sock, addr)) + +class TestSocket(greentest.TestCase): + + def test_shutdown_when_closed(self): + # https://github.com/gevent/gevent/issues/1089 + # we once raised an AttributeError. + s = socket.socket() + s.close() + with self.assertRaises(socket.error): + s.shutdown(socket.SHUT_RDWR) + + def test_can_be_weak_ref(self): + # stdlib socket can be weak reffed. + import weakref + s = socket.socket() + try: + w = weakref.ref(s) + self.assertIsNotNone(w) + finally: + s.close() + + def test_has_no_dict(self): + # stdlib socket has no dict + s = socket.socket() + try: + with self.assertRaises(AttributeError): + getattr(s, '__dict__') + finally: + s.close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_close.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_close.py new file mode 100644 index 0000000000000000000000000000000000000000..b67adae08b4c874c7167cfce1343d8b089fbd1bc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_close.py @@ -0,0 +1,58 @@ +import gevent +from gevent import socket +from gevent import server +import gevent.testing as greentest + +# XXX also test: send, sendall, recvfrom, recvfrom_into, sendto + + +def readall(sock, _): + while sock.recv(1024): + pass # pragma: no cover we never actually send the data + sock.close() + + +class Test(greentest.TestCase): + + error_fatal = False + + def setUp(self): + self.server = server.StreamServer(greentest.DEFAULT_BIND_ADDR_TUPLE, readall) + self.server.start() + + def tearDown(self): + self.server.stop() + + def test_recv_closed(self): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((greentest.DEFAULT_CONNECT_HOST, self.server.server_port)) + receiver = gevent.spawn(sock.recv, 25) + try: + gevent.sleep(0.001) + sock.close() + receiver.join(timeout=0.1) + self.assertTrue(receiver.ready(), receiver) + self.assertEqual(receiver.value, None) + self.assertIsInstance(receiver.exception, socket.error) + self.assertEqual(receiver.exception.errno, socket.EBADF) + finally: + receiver.kill() + + # XXX: This is possibly due to the bad behaviour of small sleeps? + # The timeout is the global test timeout, 10s + @greentest.skipOnLibuvOnCI("Sometimes randomly times out") + def test_recv_twice(self): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((greentest.DEFAULT_CONNECT_HOST, self.server.server_port)) + receiver = gevent.spawn(sock.recv, 25) + try: + gevent.sleep(0.001) + self.assertRaises(AssertionError, sock.recv, 25) + self.assertRaises(AssertionError, sock.recv, 25) + finally: + receiver.kill() + sock.close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns.py new file mode 100644 index 0000000000000000000000000000000000000000..630a9c00132b8abecb98b0958bfa82fb08647d03 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns.py @@ -0,0 +1,960 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division +import gevent +from gevent import monkey + +import os +import re + +import unittest +import socket +from time import time +import traceback + +import gevent.socket as gevent_socket +import gevent.testing as greentest + +from gevent.testing import util +from gevent.testing.six import xrange +from gevent.testing import flaky +from gevent.testing.skipping import skipWithoutExternalNetwork + + +resolver = gevent.get_hub().resolver +util.debug('Resolver: %s', resolver) + +if getattr(resolver, 'pool', None) is not None: + resolver.pool.size = 1 + +from gevent.testing.sysinfo import RESOLVER_NOT_SYSTEM +from gevent.testing.sysinfo import RESOLVER_DNSPYTHON +from gevent.testing.sysinfo import RESOLVER_ARES +from gevent.testing.sysinfo import PY2 +from gevent.testing.sysinfo import PYPY + +import gevent.testing.timing + + +assert gevent_socket.gaierror is socket.gaierror +assert gevent_socket.error is socket.error + + +RUN_ALL_HOST_TESTS = os.getenv('GEVENTTEST_RUN_ALL_ETC_HOST_TESTS', '') + + +def add(klass, hostname, name=None, + skip=None, skip_reason=None, + require_equal_errors=True): + + call = callable(hostname) + + def _setattr(k, n, func): + if skip: + func = greentest.skipIf(skip, skip_reason,)(func) + if not hasattr(k, n): + setattr(k, n, func) + + if name is None: + if call: + name = hostname.__name__ + else: + name = re.sub(r'[^\w]+', '_', repr(hostname)) + assert name, repr(hostname) + + def test_getaddrinfo_http(self): + x = hostname() if call else hostname + self._test('getaddrinfo', x, 'http', + require_equal_errors=require_equal_errors) + test_getaddrinfo_http.__name__ = 'test_%s_getaddrinfo_http' % name + _setattr(klass, test_getaddrinfo_http.__name__, test_getaddrinfo_http) + + def test_gethostbyname(self): + x = hostname() if call else hostname + ipaddr = self._test('gethostbyname', x, + require_equal_errors=require_equal_errors) + if not isinstance(ipaddr, Exception): + self._test('gethostbyaddr', ipaddr, + require_equal_errors=require_equal_errors) + test_gethostbyname.__name__ = 'test_%s_gethostbyname' % name + _setattr(klass, test_gethostbyname.__name__, test_gethostbyname) + + def test_gethostbyname_ex(self): + x = hostname() if call else hostname + self._test('gethostbyname_ex', x, + require_equal_errors=require_equal_errors) + test_gethostbyname_ex.__name__ = 'test_%s_gethostbyname_ex' % name + _setattr(klass, test_gethostbyname_ex.__name__, test_gethostbyname_ex) + + def test4(self): + x = hostname() if call else hostname + self._test('gethostbyaddr', x, + require_equal_errors=require_equal_errors) + test4.__name__ = 'test_%s_gethostbyaddr' % name + _setattr(klass, test4.__name__, test4) + + def test5(self): + x = hostname() if call else hostname + self._test('getnameinfo', (x, 80), 0, + require_equal_errors=require_equal_errors) + test5.__name__ = 'test_%s_getnameinfo' % name + _setattr(klass, test5.__name__, test5) + +@skipWithoutExternalNetwork("Tries to resolve and compare hostnames/addrinfo") +class TestCase(greentest.TestCase): + maxDiff = None + __timeout__ = 30 + switch_expected = None + + TRACE = not util.QUIET and os.getenv('GEVENT_DEBUG', '') == 'trace' + verbose_dns = TRACE + + def trace(self, message, *args, **kwargs): + if self.TRACE: + util.debug(message, *args, **kwargs) + + # Things that the stdlib should never raise and neither should we; + # these indicate bugs in our code and we want to raise them. + REAL_ERRORS = (AttributeError, ValueError, NameError) + + def __run_resolver(self, function, args): + try: + result = function(*args) + assert not isinstance(result, BaseException), repr(result) + return result + except self.REAL_ERRORS: + raise + except Exception as ex: # pylint:disable=broad-except + if self.TRACE: + traceback.print_exc() + return ex + + def __trace_call(self, result, runtime, function, *args): + util.debug(self.__format_call(function, args)) + self.__trace_fresult(result, runtime) + + def __format_call(self, function, args): + args = repr(args) + if args.endswith(',)'): + args = args[:-2] + ')' + try: + module = function.__module__.replace('gevent._socketcommon', 'gevent') + name = function.__name__ + return '%s:%s%s' % (module, name, args) + except AttributeError: + return function + args + + def __trace_fresult(self, result, seconds): + if isinstance(result, Exception): + msg = ' -=> raised %r' % (result, ) + else: + msg = ' -=> returned %r' % (result, ) + time_ms = ' %.2fms' % (seconds * 1000.0, ) + space = 80 - len(msg) - len(time_ms) + if space > 0: + space = ' ' * space + else: + space = '' + util.debug(msg + space + time_ms) + + if not TRACE: + def run_resolver(self, function, func_args): + now = time() + return self.__run_resolver(function, func_args), time() - now + else: + def run_resolver(self, function, func_args): + self.trace(self.__format_call(function, func_args)) + delta = time() + result = self.__run_resolver(function, func_args) + delta = time() - delta + self.__trace_fresult(result, delta) + return result, delta + + def setUp(self): + super(TestCase, self).setUp() + if not self.verbose_dns: + # Silence the default reporting of errors from the ThreadPool, + # we handle those here. + gevent.get_hub().exception_stream = None + + def tearDown(self): + if not self.verbose_dns: + try: + del gevent.get_hub().exception_stream + except AttributeError: + pass # Happens under leak tests + super(TestCase, self).tearDown() + + def should_log_results(self, result1, result2): + if not self.verbose_dns: + return False + + if isinstance(result1, BaseException) and isinstance(result2, BaseException): + return type(result1) is not type(result2) + return repr(result1) != repr(result2) + + def _test(self, func_name, *args, **kwargs): + """ + Runs the function *func_name* with *args* and compares gevent and the system. + + Keyword arguments are passed to the function itself; variable args are + used for the socket function. + + Returns the gevent result. + """ + gevent_func = getattr(gevent_socket, func_name) + real_func = monkey.get_original('socket', func_name) + + tester = getattr(self, '_run_test_' + func_name, self._run_test_generic) + result = tester(func_name, real_func, gevent_func, args, **kwargs) + _real_result, time_real, gevent_result, time_gevent = result + + if self.verbose_dns and time_gevent > time_real + 0.02 and time_gevent > 0.03: + msg = 'gevent:%s%s took %dms versus %dms stdlib' % ( + func_name, args, time_gevent * 1000.0, time_real * 1000.0) + + if time_gevent > time_real + 1: + word = 'VERY' + else: + word = 'quite' + + util.log('\nWARNING: %s slow: %s', word, msg, color='warning') + + return gevent_result + + def _run_test_generic(self, func_name, real_func, gevent_func, func_args, + require_equal_errors=True): + real_result, time_real = self.run_resolver(real_func, func_args) + gevent_result, time_gevent = self.run_resolver(gevent_func, func_args) + if util.QUIET and self.should_log_results(real_result, gevent_result): + util.log('') + self.__trace_call(real_result, time_real, real_func, func_args) + self.__trace_call(gevent_result, time_gevent, gevent_func, func_args) + + self.assertEqualResults(real_result, gevent_result, func_name, + require_equal_errors=require_equal_errors) + return real_result, time_real, gevent_result, time_gevent + + def _normalize_result(self, result, func_name): + norm_name = '_normalize_result_' + func_name + if hasattr(self, norm_name): + return getattr(self, norm_name)(result) + return result + + NORMALIZE_GAI_IGNORE_CANONICAL_NAME = RESOLVER_ARES # It tends to return them even when not asked for + if not RESOLVER_NOT_SYSTEM: + def _normalize_result_getaddrinfo(self, result): + return result + def _normalize_result_gethostbyname_ex(self, result): + return result + else: + def _normalize_result_gethostbyname_ex(self, result): + # Often the second and third part of the tuple (hostname, aliaslist, ipaddrlist) + # can be in different orders if we're hitting different servers, + # or using the native and ares resolvers due to load-balancing techniques. + # We sort them. + if isinstance(result, BaseException): + return result + # result[1].sort() # we wind up discarding this + + # On Py2 in test_russion_gethostbyname_ex, this + # is actually an integer, for some reason. In TestLocalhost.tets__ip6_localhost, + # the result isn't this long (maybe an error?). + try: + result[2].sort() + except AttributeError: + pass + except IndexError: + return result + # On some systems, a random alias is found in the aliaslist + # by the system resolver, but not by cares, and vice versa. We deem the aliaslist + # unimportant and discard it. + # On some systems (Travis CI), the ipaddrlist for 'localhost' can come back + # with two entries 127.0.0.1 (presumably two interfaces?) for c-ares + ips = result[2] + if ips == ['127.0.0.1', '127.0.0.1']: + ips = ['127.0.0.1'] + # On some systems, the hostname can get caps + return (result[0].lower(), [], ips) + + def _normalize_result_getaddrinfo(self, result): + # Result is a list + # (family, socktype, proto, canonname, sockaddr) + # e.g., + # (AF_INET, SOCK_STREAM, IPPROTO_TCP, 'readthedocs.io', (127.0.0.1, 80)) + if isinstance(result, BaseException): + return result + + # On Python 3, the builtin resolver can return SOCK_RAW results, but + # c-ares doesn't do that. So we remove those if we find them. + # Likewise, on certain Linux systems, even on Python 2, IPPROTO_SCTP (132) + # results may be returned --- but that may not even have a constant in the + # socket module! So to be safe, we strip out anything that's not + # SOCK_STREAM or SOCK_DGRAM + if isinstance(result, list): + result = [ + x + for x in result + if x[1] in (socket.SOCK_STREAM, socket.SOCK_DGRAM) + and x[2] in (socket.IPPROTO_TCP, socket.IPPROTO_UDP) + ] + + if self.NORMALIZE_GAI_IGNORE_CANONICAL_NAME: + result = [ + (family, kind, proto, '', addr) + for family, kind, proto, _, addr + in result + ] + + if isinstance(result, list): + result.sort() + return result + + def _normalize_result_getnameinfo(self, result): + return result + + NORMALIZE_GHBA_IGNORE_ALIAS = False + def _normalize_result_gethostbyaddr(self, result): + if not RESOLVER_NOT_SYSTEM: + return result + + if self.NORMALIZE_GHBA_IGNORE_ALIAS and isinstance(result, tuple): + # On some systems, a random alias is found in the aliaslist + # by the system resolver, but not by cares and vice versa. This is *probably* only the + # case for localhost or things otherwise in /etc/hosts. We deem the aliaslist + # unimportant and discard it. + return (result[0], [], result[2]) + return result + + def _compare_exceptions_strict(self, real_result, gevent_result, func_name): + if repr(real_result) == repr(gevent_result): + # Catch things like `OverflowError('port must be 0-65535.',)``` + return + + msg = (func_name, 'system:', repr(real_result), 'gevent:', repr(gevent_result)) + self.assertIs(type(gevent_result), type(real_result), msg) + + if isinstance(real_result, TypeError): + return + + if PYPY and isinstance(real_result, socket.herror): + # PyPy doesn't do errno or multiple arguments in herror; + # it just puts a string like 'host lookup failed: '; + # it must be doing that manually. + return + + self.assertEqual(real_result.args, gevent_result.args, msg) + if hasattr(real_result, 'errno'): + self.assertEqual(real_result.errno, gevent_result.errno) + + def _compare_exceptions_lenient(self, real_result, gevent_result, func_name): + try: + self._compare_exceptions_strict(real_result, gevent_result, func_name) + except AssertionError: + # Allow raising different things in a few rare cases. + if ( + func_name not in ( + 'getaddrinfo', + 'gethostbyaddr', + 'gethostbyname', + 'gethostbyname_ex', + 'getnameinfo', + ) + or type(real_result) not in (socket.herror, socket.gaierror) + or type(gevent_result) not in (socket.herror, socket.gaierror, socket.error) + ): + raise + util.log('WARNING: error type mismatch for %s: %r (gevent) != %r (stdlib)', + func_name, + gevent_result, real_result, + color='warning') + + _compare_exceptions = _compare_exceptions_lenient if RESOLVER_NOT_SYSTEM else _compare_exceptions_strict + + def _compare_results(self, real_result, gevent_result, func_name): + if real_result == gevent_result: + return True + + compare_func = getattr(self, '_compare_results_' + func_name, + self._generic_compare_results) + return compare_func(real_result, gevent_result, func_name) + + def _generic_compare_results(self, real_result, gevent_result, func_name): + try: + if len(real_result) != len(gevent_result): + return False + except TypeError: + return False + + return all(self._compare_results(x, y, func_name) + for (x, y) + in zip(real_result, gevent_result)) + + def _compare_results_getaddrinfo(self, real_result, gevent_result, func_name): + # On some systems, we find more results with + # one resolver than we do with the other resolver. + # So as long as they have some subset in common, + # we'll take it. + errors = isinstance(real_result, Exception) + isinstance(gevent_result, Exception) + if errors == 2: + return True + if errors == 1: + return False + + if not set(real_result).isdisjoint(set(gevent_result)): + return True + return self._generic_compare_results(real_result, gevent_result, func_name) + + def _compare_address_strings(self, a, b): + # IPv6 address from different requests might be different + a_segments = a.count(':') + b_segments = b.count(':') + if a_segments and b_segments: + if a_segments == b_segments and a_segments in (4, 5, 6, 7): + return True + if a.rstrip(':').startswith(b.rstrip(':')) or b.rstrip(':').startswith(a.rstrip(':')): + return True + if a_segments >= 2 and b_segments >= 2 and a.split(':')[:2] == b.split(':')[:2]: + return True + + return a.split('.', 1)[-1] == b.split('.', 1)[-1] + + def _compare_results_gethostbyname(self, real_result, gevent_result, _func_name): + # Both strings. + return self._compare_address_strings(real_result, gevent_result) + + def _compare_results_gethostbyname_ex(self, real_result, gevent_result, _func_name): + # Results are IPv4 only: + # (hostname, [aliaslist], [ipaddrlist]) + # As for getaddrinfo, we'll just check the ipaddrlist has something in common. + return not set(real_result[2]).isdisjoint(set(gevent_result[2])) + + def assertEqualResults(self, real_result, gevent_result, func_name, + require_equal_errors=True): + errors = ( + OverflowError, + TypeError, + UnicodeError, + socket.error, + socket.gaierror, + socket.herror, + ) + if isinstance(real_result, errors) and isinstance(gevent_result, errors): + if require_equal_errors: + self._compare_exceptions(real_result, gevent_result, func_name) + return + + real_result = self._normalize_result(real_result, func_name) + gevent_result = self._normalize_result(gevent_result, func_name) + + if self._compare_results(real_result, gevent_result, func_name): + return + + # If we're using a different resolver, allow the real resolver to generate an + # error that the gevent resolver actually gets an answer to. + if ( + RESOLVER_NOT_SYSTEM + and isinstance(real_result, errors) + and not isinstance(gevent_result, errors) + ): + return + + # On PyPy, socket.getnameinfo() can produce results even when the hostname resolves to + # multiple addresses, like www.gevent.org does. DNSPython (and c-ares?) don't do that, + # they refuse to pick a name and raise ``socket.error`` + if ( + RESOLVER_NOT_SYSTEM + and PYPY + and func_name == 'getnameinfo' + and isinstance(gevent_result, socket.error) + and not isinstance(real_result, socket.error) + ): + return + + + # From 2.7 on, assertEqual does a better job highlighting the results than we would + # because it calls assertSequenceEqual, which highlights the exact + # difference in the tuple + self.assertEqual(real_result, gevent_result) + + +class TestTypeError(TestCase): + pass + +add(TestTypeError, None) +add(TestTypeError, 25) + + +class TestHostname(TestCase): + NORMALIZE_GHBA_IGNORE_ALIAS = True + + def __normalize_name(self, result): + if (RESOLVER_ARES or RESOLVER_DNSPYTHON) and isinstance(result, tuple): + # The system resolver can return the FQDN, in the first result, + # when given certain configurations. But c-ares and dnspython + # do not. + name = result[0] + name = name.split('.', 1)[0] + result = (name,) + result[1:] + return result + + def _normalize_result_gethostbyaddr(self, result): + result = TestCase._normalize_result_gethostbyaddr(self, result) + return self.__normalize_name(result) + + def _normalize_result_getnameinfo(self, result): + result = TestCase._normalize_result_getnameinfo(self, result) + if PY2: + # Not sure why we only saw this on Python 2 + result = self.__normalize_name(result) + return result + +add( + TestHostname, + socket.gethostname, + skip=greentest.RUNNING_ON_TRAVIS and greentest.RESOLVER_NOT_SYSTEM, + skip_reason=("Sometimes get a different result for getaddrinfo " + "with dnspython; c-ares produces different results for " + "localhost on Travis beginning Sept 2019") +) + + +class TestLocalhost(TestCase): + # certain tests in test_patched_socket.py only work if getaddrinfo('localhost') does not switch + # (e.g. NetworkConnectionAttributesTest.testSourceAddress) + #switch_expected = False + # XXX: The above has been commented out for some time. Apparently this isn't the case + # anymore. + + def _normalize_result_getaddrinfo(self, result): + if RESOLVER_NOT_SYSTEM: + # We see that some impls (OS X) return extra results + # like DGRAM that ares does not. + return () + return super(TestLocalhost, self)._normalize_result_getaddrinfo(result) + + NORMALIZE_GHBA_IGNORE_ALIAS = True + if greentest.RUNNING_ON_TRAVIS and greentest.PY2 and RESOLVER_NOT_SYSTEM: + def _normalize_result_gethostbyaddr(self, result): + # Beginning in November 2017 after an upgrade to Travis, + # we started seeing ares return ::1 for localhost, but + # the system resolver is still returning 127.0.0.1 under Python 2 + result = super(TestLocalhost, self)._normalize_result_gethostbyaddr(result) + if isinstance(result, tuple): + result = (result[0], result[1], ['127.0.0.1']) + return result + + +add( + TestLocalhost, 'ip6-localhost', + skip=RESOLVER_DNSPYTHON, # XXX: Fix these. + skip_reason="Can return gaierror(-2)" +) +add( + TestLocalhost, 'localhost', + skip=greentest.RUNNING_ON_TRAVIS, + skip_reason="Can return gaierror(-2)" +) + + + + +class TestNonexistent(TestCase): + pass + +add(TestNonexistent, 'nonexistentxxxyyy') + + +class Test1234(TestCase): + pass + +add(Test1234, '1.2.3.4') + + +class Test127001(TestCase): + NORMALIZE_GHBA_IGNORE_ALIAS = True + +add( + Test127001, '127.0.0.1', + # skip=RESOLVER_DNSPYTHON, + # skip_reason="Beginning Dec 1 2017, ares started returning ip6-localhost " + # "instead of localhost" +) + + + +class TestBroadcast(TestCase): + switch_expected = False + + if RESOLVER_DNSPYTHON: + # dnspython raises errors for broadcasthost/255.255.255.255, but the system + # can resolve it. + + @unittest.skip('ares raises errors for broadcasthost/255.255.255.255') + def test__broadcast__gethostbyaddr(self): + return + + test__broadcast__gethostbyname = test__broadcast__gethostbyaddr + +add(TestBroadcast, '') + + +from gevent.resolver._hostsfile import HostsFile +class SanitizedHostsFile(HostsFile): + def iter_all_host_addr_pairs(self): + for name, addr in super(SanitizedHostsFile, self).iter_all_host_addr_pairs(): + if (RESOLVER_NOT_SYSTEM + and (name.endswith('local') # ignore bonjour, ares can't find them + # ignore common aliases that ares can't find + or addr == '255.255.255.255' + or name == 'broadcasthost' + # We get extra results from some impls, like OS X + # it returns DGRAM results + or name == 'localhost')): + continue # pragma: no cover + if name.endswith('local'): + # These can only be found if bonjour is running, + # and are very slow to do so with the system resolver on OS X + continue + yield name, addr + + +@greentest.skipIf(greentest.RUNNING_ON_CI, + "This sometimes randomly fails on Travis with ares and on appveyor, beginning Feb 13, 2018") +# Probably due to round-robin DNS, +# since this is not actually the system's etc hosts file. +# TODO: Rethink this. We need something reliable. Go back to using +# the system's etc hosts? +class TestEtcHosts(TestCase): + + MAX_HOSTS = int(os.getenv('GEVENTTEST_MAX_ETC_HOSTS', '10')) + + @classmethod + def populate_tests(cls): + hf = SanitizedHostsFile(os.path.join(os.path.dirname(__file__), + 'hosts_file.txt')) + all_etc_hosts = sorted(hf.iter_all_host_addr_pairs()) + if len(all_etc_hosts) > cls.MAX_HOSTS and not RUN_ALL_HOST_TESTS: + all_etc_hosts = all_etc_hosts[:cls.MAX_HOSTS] + + for host, ip in all_etc_hosts: + add(cls, host) + add(cls, ip) + + + +TestEtcHosts.populate_tests() + + + +class TestGeventOrg(TestCase): + # For this test to work correctly, it needs to resolve to + # an address with a single A record; round-robin DNS and multiple A records + # may mess it up (subsequent requests---and we always make two---may return + # unequal results). We used to use gevent.org, but that now has multiple A records; + # trying www.gevent.org which is a CNAME to readthedocs.org then worked, but it became + # an alias for python-gevent.readthedocs.org, which is an alias for readthedocs.io, + # and which also has multiple addresses. So we run the resolver twice to try to get + # the different answers, if needed. Even then it's not enough, so + # we normalize the two addresses we get to a single one. + HOSTNAME = 'www.gevent.org' + + + + def _normalize_result_gethostbyname(self, result): + if result == '104.17.33.82': + result = '104.17.32.82' + if result == '104.16.254.120': + result = '104.16.253.120' + return result + + def _normalize_result_gethostbyname_ex(self, result): + result = super(TestGeventOrg, self)._normalize_result_gethostbyname_ex(result) + if result[0] == 'python-gevent.readthedocs.org': + result = ('readthedocs.io', ) + result[1:] + return result + + def test_AI_CANONNAME(self): + # Not all systems support AI_CANONNAME; notably tha manylinux + # resolvers *sometimes* do not. Specifically, sometimes they + # provide the canonical name *only* on the first result. + + args = ( + # host + TestGeventOrg.HOSTNAME, + # port + None, + # family + socket.AF_INET, + # type + 0, + # proto + 0, + # flags + socket.AI_CANONNAME + ) + gevent_result = gevent_socket.getaddrinfo(*args) + self.assertEqual(gevent_result[0][3], 'readthedocs.io') + real_result = socket.getaddrinfo(*args) + + self.NORMALIZE_GAI_IGNORE_CANONICAL_NAME = not all(r[3] for r in real_result) + try: + self.assertEqualResults(real_result, gevent_result, 'getaddrinfo') + finally: + del self.NORMALIZE_GAI_IGNORE_CANONICAL_NAME + +add(TestGeventOrg, TestGeventOrg.HOSTNAME) + + +class TestFamily(TestCase): + def test_inet(self): + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, socket.AF_INET) + + def test_unspec(self): + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, socket.AF_UNSPEC) + + def test_badvalue(self): + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, 255) + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, 255000) + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, -1) + + @unittest.skipIf(RESOLVER_DNSPYTHON, "Raises the wrong errno") + def test_badtype(self): + self._test('getaddrinfo', TestGeventOrg.HOSTNAME, 'x') + + +class Test_getaddrinfo(TestCase): + + def _test_getaddrinfo(self, *args): + self._test('getaddrinfo', *args) + + def test_80(self): + self._test_getaddrinfo(TestGeventOrg.HOSTNAME, 80) + + def test_int_string(self): + self._test_getaddrinfo(TestGeventOrg.HOSTNAME, '80') + + def test_0(self): + self._test_getaddrinfo(TestGeventOrg.HOSTNAME, 0) + + def test_http(self): + self._test_getaddrinfo(TestGeventOrg.HOSTNAME, 'http') + + def test_notexistent_tld(self): + self._test_getaddrinfo('myhost.mytld', 53) + + def test_notexistent_dot_com(self): + self._test_getaddrinfo('sdfsdfgu5e66098032453245wfdggd.com', 80) + + def test1(self): + return self._test_getaddrinfo(TestGeventOrg.HOSTNAME, 52, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 0) + + def test2(self): + return self._test_getaddrinfo(TestGeventOrg.HOSTNAME, 53, socket.AF_INET, socket.SOCK_DGRAM, 17) + + @unittest.skipIf(RESOLVER_DNSPYTHON, + "dnspython only returns some of the possibilities") + def test3(self): + return self._test_getaddrinfo('google.com', 'http', socket.AF_INET6) + + + @greentest.skipIf(PY2, "Enums only on Python 3.4+") + def test_enums(self): + # https://github.com/gevent/gevent/issues/1310 + + # On Python 3, getaddrinfo does special things to make sure that + # the fancy enums are returned. + + gai = gevent_socket.getaddrinfo('example.com', 80, + socket.AF_INET, + socket.SOCK_STREAM, socket.IPPROTO_TCP) + af, socktype, _proto, _canonname, _sa = gai[0] + self.assertIs(socktype, socket.SOCK_STREAM) + self.assertIs(af, socket.AF_INET) + +class TestInternational(TestCase): + if PY2: + # We expect these to raise UnicodeEncodeError, which is a + # subclass of ValueError + REAL_ERRORS = set(TestCase.REAL_ERRORS) - {ValueError,} + + if RESOLVER_ARES: + + def test_russian_getaddrinfo_http(self): + # And somehow, test_russion_getaddrinfo_http (``getaddrinfo(name, 'http')``) + # manages to work with recent versions of Python 2, but our preemptive encoding + # to ASCII causes it to fail with the c-ares resolver; but only that one test out of + # all of them. + self.skipTest("ares fails to encode.") + + +# dns python can actually resolve these: it uses +# the 2008 version of idna encoding, whereas on Python 2, +# with the default resolver, it tries to encode to ascii and +# raises a UnicodeEncodeError. So we get different results. + +# Starting 20221027, on GitHub Actions and *some* versions of Python, +# we started getting a different error result from our own resolver +# compared to the system. This is very weird because our own resolver +# calls the system. I can't reproduce locally. Perhaps the two +# different answers are because of caching? One from the real DNS +# server, one from the local resolver library? Hence +# require_equal_errors=False +# ('system:', "herror(2, 'Host name lookup failure')", +# 'gevent:', "herror(1, 'Unknown host')") +add(TestInternational, u'президент.рф', 'russian', + skip=(PY2 and RESOLVER_DNSPYTHON), + skip_reason="dnspython can actually resolve these", + require_equal_errors=False) +add(TestInternational, u'президент.рф'.encode('idna'), 'idna', + require_equal_errors=False) + +@skipWithoutExternalNetwork("Tries to resolve and compare hostnames/addrinfo") +class TestInterrupted_gethostbyname(gevent.testing.timing.AbstractGenericWaitTestCase): + + # There are refs to a Waiter in the C code that don't go + # away yet; one gc may or may not do it. + @greentest.ignores_leakcheck + def test_returns_none_after_timeout(self): + super(TestInterrupted_gethostbyname, self).test_returns_none_after_timeout() + + def wait(self, timeout): + with gevent.Timeout(timeout, False): + for index in xrange(1000000): + try: + gevent_socket.gethostbyname('www.x%s.com' % index) + except socket.error: + pass + raise AssertionError('Timeout was not raised') + + def cleanup(self): + # Depending on timing, this can raise: + # (This suddenly started happening on Apr 6 2016; www.x1000000.com + # is apparently no longer around) + + # File "test__socket_dns.py", line 538, in cleanup + # gevent.get_hub().threadpool.join() + # File "/home/travis/build/gevent/gevent/src/gevent/threadpool.py", line 108, in join + # sleep(delay) + # File "/home/travis/build/gevent/gevent/src/gevent/hub.py", line 169, in sleep + # hub.wait(loop.timer(seconds, ref=ref)) + # File "/home/travis/build/gevent/gevent/src/gevent/hub.py", line 651, in wait + # result = waiter.get() + # File "/home/travis/build/gevent/gevent/src/gevent/hub.py", line 899, in get + # return self.hub.switch() + # File "/home/travis/build/gevent/gevent/src/greentest/greentest.py", line 520, in switch + # return _original_Hub.switch(self, *args) + # File "/home/travis/build/gevent/gevent/src/gevent/hub.py", line 630, in switch + # return RawGreenlet.switch(self) + # gaierror: [Errno -2] Name or service not known + try: + gevent.get_hub().threadpool.join() + except Exception: # pragma: no cover pylint:disable=broad-except + traceback.print_exc() + + +# class TestInterrupted_getaddrinfo(greentest.GenericWaitTestCase): +# +# def wait(self, timeout): +# with gevent.Timeout(timeout, False): +# for index in range(1000): +# try: +# gevent_socket.getaddrinfo('www.a%s.com' % index, 'http') +# except socket.gaierror: +# pass + + +class TestBadName(TestCase): + pass + +add(TestBadName, 'xxxxxxxxxxxx') + +class TestBadIP(TestCase): + pass + +add(TestBadIP, '1.2.3.400') + + +@greentest.skipIf(greentest.RUNNING_ON_TRAVIS, "Travis began returning ip6-localhost") +class Test_getnameinfo_127001(TestCase): + + def test(self): + self._test('getnameinfo', ('127.0.0.1', 80), 0) + + def test_DGRAM(self): + self._test('getnameinfo', ('127.0.0.1', 779), 0) + self._test('getnameinfo', ('127.0.0.1', 779), socket.NI_DGRAM) + + def test_NOFQDN(self): + # I get ('localhost', 'www') with _socket but ('localhost.localdomain', 'www') with gevent.socket + self._test('getnameinfo', ('127.0.0.1', 80), socket.NI_NOFQDN) + + def test_NAMEREQD(self): + self._test('getnameinfo', ('127.0.0.1', 80), socket.NI_NAMEREQD) + + +class Test_getnameinfo_geventorg(TestCase): + + @unittest.skipIf(RESOLVER_DNSPYTHON, + "dnspython raises an error when multiple results are returned") + def test_NUMERICHOST(self): + self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), 0) + self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), socket.NI_NUMERICHOST) + + @unittest.skipIf(RESOLVER_DNSPYTHON, + "dnspython raises an error when multiple results are returned") + def test_NUMERICSERV(self): + self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), socket.NI_NUMERICSERV) + + def test_domain1(self): + self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), 0) + + def test_domain2(self): + self._test('getnameinfo', ('www.gevent.org', 80), 0) + + def test_port_zero(self): + self._test('getnameinfo', ('www.gevent.org', 0), 0) + + +class Test_getnameinfo_fail(TestCase): + + def test_port_string(self): + self._test('getnameinfo', ('www.gevent.org', 'http'), 0) + + def test_bad_flags(self): + self._test('getnameinfo', ('localhost', 80), 55555555) + + +class TestInvalidPort(TestCase): + + @flaky.reraises_flaky_race_condition() + def test_overflow_neg_one(self): + # An Appveyor beginning 2019-03-21, the system resolver + # sometimes returns ('23.100.69.251', '65535') instead of + # raising an error. That IP address belongs to + # readthedocs[.io?] which is where www.gevent.org is a CNAME + # to...but it doesn't actually *reverse* to readthedocs.io. + # Can't reproduce locally, not sure what's happening + self._test('getnameinfo', ('www.gevent.org', -1), 0) + + # Beginning with PyPy 2.7 7.1 on Appveyor, we sometimes see this + # return an OverflowError instead of the TypeError about None + @greentest.skipOnLibuvOnPyPyOnWin("Errors dont match") + def test_typeerror_none(self): + self._test('getnameinfo', ('www.gevent.org', None), 0) + + # Beginning with PyPy 2.7 7.1 on Appveyor, we sometimes see this + # return an TypeError instead of the OverflowError. + # XXX: But see Test_getnameinfo_fail.test_port_string where this does work. + @greentest.skipOnLibuvOnPyPyOnWin("Errors don't match") + def test_typeerror_str(self): + self._test('getnameinfo', ('www.gevent.org', 'x'), 0) + + def test_overflow_port_too_large(self): + self._test('getnameinfo', ('www.gevent.org', 65536), 0) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns6.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns6.py new file mode 100644 index 0000000000000000000000000000000000000000..6452211b763b4c8a9f059cbc3113269af23d2d10 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_dns6.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +from __future__ import print_function, absolute_import, division + +import socket +import unittest + +import gevent.testing as greentest +from gevent.tests.test__socket_dns import TestCase, add + +from gevent.testing.sysinfo import OSX +from gevent.testing.sysinfo import RESOLVER_DNSPYTHON +from gevent.testing.sysinfo import RESOLVER_ARES +from gevent.testing.sysinfo import PYPY +from gevent.testing.sysinfo import PY2 + +# We can't control the DNS servers on CI (or in general...) +# for the system. This works best with the google DNS servers +# The getnameinfo test can fail on CI. + +# Previously only Test6_ds failed, but as of Jan 2018, Test6 +# and Test6_google begin to fail: + +# First differing element 0: +# 'vm2.test-ipv6.com' +# 'ip119.gigo.com' + +# - ('vm2.test-ipv6.com', [], ['2001:470:1:18::125']) +# ? --------- ^^ ^^ + +# + ('ip119.gigo.com', [], ['2001:470:1:18::119']) +# ? ^^^^^^^^ ^^ + +# These are known to work on jamadden's OS X machine using the google +# resolvers (but not with DNSPython; things don't *quite* match)...so +# by default we skip the tests everywhere else. + +class Test6(TestCase): + NORMALIZE_GHBA_IGNORE_ALIAS = True + # host that only has AAAA record + host = 'aaaa.test-ipv6.com' + + def _normalize_result_gethostbyaddr(self, result): + # This part of the test is effectively disabled. There are multiple address + # that resolve and which ones you get depend on the settings + # of the system and ares. They don't match exactly. + return () + + if RESOLVER_ARES and PY2: + def _normalize_result_getnameinfo(self, result): + # Beginning 2020-07-23, + # c-ares returns a scope id on the result: + # ('2001:470:1:18::115%0', 'http') + # The standard library does not (on linux or os x). + # I've only seen '%0', so only remove that + ipaddr, service = result + if ipaddr.endswith('%0'): + ipaddr = ipaddr[:-2] + return (ipaddr, service) + + if not OSX and RESOLVER_DNSPYTHON: + # It raises gaierror instead of socket.error, + # which is not great and leads to failures. + def _run_test_getnameinfo(self, *_args, **_kwargs): + return (), 0, (), 0 + + def _run_test_gethostbyname(self, *_args, **_kwargs): + raise unittest.SkipTest("gethostbyname[_ex] does not support IPV6") + + _run_test_gethostbyname_ex = _run_test_gethostbyname + + def test_empty(self): + self._test('getaddrinfo', self.host, 'http') + + def test_inet(self): + self._test('getaddrinfo', self.host, None, socket.AF_INET) + + def test_inet6(self): + self._test('getaddrinfo', self.host, None, socket.AF_INET6) + + def test_unspec(self): + self._test('getaddrinfo', self.host, None, socket.AF_UNSPEC) + + +class Test6_google(Test6): + host = 'ipv6.google.com' + + if greentest.RUNNING_ON_CI: + # Disabled, there are multiple possibilities + # and we can get different ones. Even the system resolvers + # can go round-robin and provide different answers. + def _normalize_result_getnameinfo(self, result): + return () + + if PYPY: + # PyPy tends to be especially problematic in that area. + _normalize_result_getaddrinfo = _normalize_result_getnameinfo + +add(Test6, Test6.host) +add(Test6_google, Test6_google.host) + + + +class Test6_ds(Test6): + # host that has both A and AAAA records + host = 'ds.test-ipv6.com' + + _normalize_result_gethostbyname = Test6._normalize_result_gethostbyaddr + +add(Test6_ds, Test6_ds.host) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_errors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..1b9b30cc19cdad2240180d6491ec863523b97a5e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_errors.py @@ -0,0 +1,48 @@ +# Copyright (c) 2008-2009 AG Projects +# Author: Denis Bilenko +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import gevent.testing as greentest +from gevent.testing import support +from gevent.testing import sysinfo + +from gevent.socket import socket, error +from gevent.exceptions import LoopExit + + +class TestSocketErrors(greentest.TestCase): + + __timeout__ = 5 + + def test_connection_refused(self): + port = support.find_unused_port() + with socket() as s: + try: + with self.assertRaises(error) as exc: + s.connect((greentest.DEFAULT_CONNECT_HOST, port)) + except LoopExit: + return + ex = exc.exception + self.assertIn(ex.args[0], sysinfo.CONN_REFUSED_ERRORS, ex) + self.assertIn('refused', str(ex).lower()) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ex.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ex.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce77a97c3f8715812b00971d5983e1871c66a1a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ex.py @@ -0,0 +1,44 @@ +import gevent.testing as greentest +from gevent import socket +import errno +import sys + + +class TestClosedSocket(greentest.TestCase): + + switch_expected = False + + def test(self): + sock = socket.socket() + sock.close() + try: + sock.send(b'a', timeout=1) + self.fail("Should raise socket error") + except OSError as ex: + if ex.args[0] != errno.EBADF: + if sys.platform.startswith('win'): + # Windows/Py3 raises "OSError: [WinError 10038] " + # which is not standard and not what it does + # on Py2. + pass + else: + raise + + +class TestRef(greentest.TestCase): + + switch_expected = False + + def test(self): + # pylint:disable=no-member + sock = socket.socket() + self.assertTrue(sock.ref) + sock.ref = False + self.assertFalse(sock.ref) + self.assertFalse(sock._read_event.ref) + self.assertFalse(sock._write_event.ref) + sock.close() + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_send_memoryview.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_send_memoryview.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5036cd004abad191b6620216de1e23cd576cab --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_send_memoryview.py @@ -0,0 +1,40 @@ +# See issue #466 +import unittest +import ctypes + +import gevent.testing as greentest + +class AnStructure(ctypes.Structure): + _fields_ = [("x", ctypes.c_int)] + + +def _send(socket): + for meth in ('sendall', 'send'): + anStructure = AnStructure() + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.connect((greentest.DEFAULT_CONNECT_HOST, 12345)) + getattr(sock, meth)(anStructure) + sock.close() + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.connect((greentest.DEFAULT_CONNECT_HOST, 12345)) + sock.settimeout(1.0) + getattr(sock, meth)(anStructure) + sock.close() + +class TestSendBuiltinSocket(unittest.TestCase): + + def test_send(self): + import socket + _send(socket) + + +class TestSendGeventSocket(unittest.TestCase): + + def test_send(self): + import gevent.socket + _send(gevent.socket) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ssl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..07ec9363818fb1e0b11ccfbfe0fd965367f22bf4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_ssl.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +from gevent import monkey +monkey.patch_all() + + +try: + import httplib +except ImportError: + from http import client as httplib +import socket + + +import gevent.testing as greentest + + +@greentest.skipUnless( + hasattr(socket, 'ssl'), + "Needs socket.ssl (Python 2)" +) +@greentest.skipWithoutExternalNetwork("Tries to access amazon.com") +class AmazonHTTPSTests(greentest.TestCase): + + __timeout__ = 30 + + def test_amazon_response(self): + conn = httplib.HTTPSConnection('sdb.amazonaws.com') + conn.request('GET', '/') + conn.getresponse() + + def test_str_and_repr(self): + conn = socket.socket() + conn.connect(('sdb.amazonaws.com', 443)) + ssl_conn = socket.ssl(conn) # pylint:disable=no-member + assert str(ssl_conn) + assert repr(ssl_conn) + + +if __name__ == "__main__": + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_timeout.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d4d8fa90096dd2fdf62699efa3554a2359ff63 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socket_timeout.py @@ -0,0 +1,51 @@ +import gevent +from gevent import socket +import gevent.testing as greentest + + +class Test(greentest.TestCase): + + server = None + acceptor = None + server_port = None + + def _accept(self): + try: + conn, _ = self.server.accept() + self._close_on_teardown(conn) + except socket.error: + pass + + def setUp(self): + super(Test, self).setUp() + self.server = self._close_on_teardown(greentest.tcp_listener(backlog=1)) + self.server_port = self.server.getsockname()[1] + self.acceptor = gevent.spawn(self._accept) + gevent.sleep(0) + + def tearDown(self): + if self.acceptor is not None: + self.acceptor.kill() + self.acceptor = None + if self.server is not None: + self.server.close() + self.server = None + super(Test, self).tearDown() + + def test_timeout(self): + gevent.sleep(0) + sock = socket.socket() + self._close_on_teardown(sock) + sock.connect((greentest.DEFAULT_CONNECT_HOST, self.server_port)) + + sock.settimeout(0.1) + with self.assertRaises(socket.error) as cm: + sock.recv(1024) + + ex = cm.exception + self.assertEqual(ex.args, ('timed out',)) + self.assertEqual(str(ex), 'timed out') + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socketpair.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socketpair.py new file mode 100644 index 0000000000000000000000000000000000000000..f17ad9ff9245d06f5813a7214eee27064b663177 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__socketpair.py @@ -0,0 +1,37 @@ +from gevent import monkey; monkey.patch_all() +import socket +import unittest + + +class TestSocketpair(unittest.TestCase): + + def test_makefile(self): + msg = b'hello world' + x, y = socket.socketpair() + x.sendall(msg) + x.close() + with y.makefile('rb') as f: + read = f.read() + self.assertEqual(msg, read) + y.close() + + @unittest.skipUnless(hasattr(socket, 'fromfd'), + 'Needs socket.fromfd') + def test_fromfd(self): + msg = b'hello world' + x, y = socket.socketpair() + xx = socket.fromfd(x.fileno(), x.family, socket.SOCK_STREAM) + x.close() + yy = socket.fromfd(y.fileno(), y.family, socket.SOCK_STREAM) + y.close() + + xx.sendall(msg) + xx.close() + with yy.makefile('rb') as f: + read = f.read() + self.assertEqual(msg, read) + yy.close() + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ssl.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..b80bca0fdd7e9190d61cee80d5aa393e0e3feae4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__ssl.py @@ -0,0 +1,138 @@ +from __future__ import print_function, division, absolute_import +from gevent import monkey +monkey.patch_all() +import os + +import socket +import gevent.testing as greentest +# Be careful not to have TestTCP as a bare attribute in this module, +# even aliased, to avoid running duplicate tests +from gevent.tests import test__socket +import ssl + + +def ssl_listener(private_key, certificate): + raw_listener = socket.socket() + greentest.bind_and_listen(raw_listener) + # pylint:disable=deprecated-method + sock = wrap_socket(raw_listener, keyfile=private_key, certfile=certificate, + server_side=True) + return sock, raw_listener + +def wrap_socket(sock, *, keyfile=None, certfile=None, server_side=False): + context = ssl.SSLContext( + protocol=ssl.PROTOCOL_TLS + ) + context.verify_mode = ssl.CERT_NONE + context.check_hostname = False + context.load_default_certs() + if keyfile is not None or certfile is not None: + context.load_cert_chain(certfile=certfile, keyfile=keyfile) + return context.wrap_socket(sock, server_side=server_side) + +class TestSSL(test__socket.TestTCP): + + # To generate: + # openssl req -x509 -newkey rsa:4096 -keyout test_server.key -out test_server.crt -days 36500 -nodes -subj '/CN=localhost' + certfile = os.path.join(os.path.dirname(__file__), 'test_server.crt') + privfile = os.path.join(os.path.dirname(__file__), 'test_server.key') + # Python 2.x has socket.sslerror (which is an alias for + # ssl.SSLError); That's gone in Py3 though. In Python 2, most timeouts are raised + # as SSLError, but Python 3 raises the normal socket.timeout instead. So this has + # the effect of making TIMEOUT_ERROR be SSLError on Py2 and socket.timeout on Py3 + # See https://bugs.python.org/issue10272. + # PyPy3 7.2 has a bug, though: it shares much of the SSL implementation with Python 2, + # and it unconditionally does `socket.sslerror = SSLError` when ssl is imported. + # So we can't rely on getattr/hasattr tests, we must be explicit. + TIMEOUT_ERROR = socket.timeout # pylint:disable=no-member + + def _setup_listener(self): + listener, raw_listener = ssl_listener(self.privfile, self.certfile) + self._close_on_teardown(raw_listener) + return listener + + def create_connection(self, *args, **kwargs): # pylint:disable=signature-differs + return self._close_on_teardown( + # pylint:disable=deprecated-method + wrap_socket(super(TestSSL, self).create_connection(*args, **kwargs))) + + # The SSL library can take a long time to buffer the large amount of data we're trying + # to send, so we can't compare to the timeout values + _test_sendall_timeout_check_time = False + + # The SSL layer has extra buffering, so test_sendall needs + # to send a very large amount to make it timeout + _test_sendall_data = data_sent = b'hello' * 100000000 + + test_sendall_array = greentest.skipOnMacOnCI("Sometimes misses data")( + greentest.skipOnManylinux("Sometimes misses data")( + test__socket.TestTCP.test_sendall_array + ) + ) + + test_sendall_str = greentest.skipOnMacOnCI("Sometimes misses data")( + greentest.skipOnManylinux("Sometimes misses data")( + test__socket.TestTCP.test_sendall_str + ) + ) + + @greentest.skipOnWindows("Not clear why we're skipping") + def test_ssl_sendall_timeout0(self): + # Issue #317: SSL_WRITE_PENDING in some corner cases + + server_sock = [] + acceptor = test__socket.Thread(target=lambda: server_sock.append( + # pylint:disable=no-member + self.listener.accept())) + client = self.create_connection() + client.setblocking(False) + try: + # Python 3 raises ssl.SSLWantWriteError; Python 2 simply *hangs* + # on non-blocking sockets because it's a simple loop around + # send(). Python 2.6 doesn't have SSLWantWriteError + expected = getattr(ssl, 'SSLWantWriteError', ssl.SSLError) + with self.assertRaises(expected): + client.sendall(self._test_sendall_data) + finally: + acceptor.join() + client.close() + server_sock[0][0].close() + + # def test_fullduplex(self): + # try: + # super(TestSSL, self).test_fullduplex() + # except LoopExit: + # if greentest.LIBUV and greentest.WIN: + # # XXX: Unable to duplicate locally + # raise greentest.SkipTest("libuv on Windows sometimes raises LoopExit") + # raise + + @greentest.ignores_leakcheck + @greentest.skipOnPy310("No longer raises SSLError") + def test_empty_send(self): + # Issue 719 + # Sending empty bytes with the 'send' method raises + # ssl.SSLEOFError in the stdlib. PyPy 4.0 and CPython 2.6 + # both just raise the superclass, ssl.SSLError. + + # Ignored during leakchecks because the third or fourth iteration of the + # test hangs on CPython 2/posix for some reason, likely due to + # the use of _close_on_teardown keeping something alive longer than intended. + # cf test__makefile_ref + with self.assertRaises(ssl.SSLError): + super(TestSSL, self).test_empty_send() + + @greentest.ignores_leakcheck + def test_sendall_nonblocking(self): + # Override; doesn't work with SSL sockets. + pass + + @greentest.ignores_leakcheck + def test_connect_with_type_flags_ignored(self): + # Override; doesn't work with SSL sockets. + pass + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..f239e816863f9b60e0de8613f92701d39b749ee8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess.py @@ -0,0 +1,517 @@ +import sys +import os +import errno +import unittest + +import time +import tempfile + +import gevent.testing as greentest +import gevent +from gevent.testing import mock +from gevent import subprocess + +if not hasattr(subprocess, 'mswindows'): + # PyPy3, native python subprocess + subprocess.mswindows = False + + +PYPY = hasattr(sys, 'pypy_version_info') +PY3 = sys.version_info[0] >= 3 + + +if subprocess.mswindows: + SETBINARY = 'import msvcrt; msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY);' +else: + SETBINARY = '' + + +python_universal_newlines = hasattr(sys.stdout, 'newlines') +# The stdlib of Python 3 on Windows doesn't properly handle universal newlines +# (it produces broken results compared to Python 2) +# See gevent.subprocess for more details. +python_universal_newlines_broken = PY3 and subprocess.mswindows + +@greentest.skipWithoutResource('subprocess') +class TestPopen(greentest.TestCase): + + # Use the normal error handling. Make sure that any background greenlets + # subprocess spawns propagate errors as expected. + error_fatal = False + + def test_exit(self): + popen = subprocess.Popen([sys.executable, '-c', 'import sys; sys.exit(10)']) + self.assertEqual(popen.wait(), 10) + + def test_wait(self): + popen = subprocess.Popen([sys.executable, '-c', 'import sys; sys.exit(11)']) + gevent.wait([popen]) + self.assertEqual(popen.poll(), 11) + + def test_child_exception(self): + with self.assertRaises(OSError) as exc: + subprocess.Popen(['*']).wait() + + self.assertEqual(exc.exception.errno, 2) + + def test_leak(self): + num_before = greentest.get_number_open_files() + p = subprocess.Popen([sys.executable, "-c", "print()"], + stdout=subprocess.PIPE) + p.wait() + p.stdout.close() + del p + + num_after = greentest.get_number_open_files() + self.assertEqual(num_before, num_after) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_communicate(self): + p = subprocess.Popen([sys.executable, "-W", "ignore", + "-c", + 'import sys,os;' + 'sys.stderr.write("pineapple");' + 'sys.stdout.write(sys.stdin.read())'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + (stdout, stderr) = p.communicate(b"banana") + self.assertEqual(stdout, b"banana") + if sys.executable.endswith('-dbg'): + assert stderr.startswith(b'pineapple') + else: + self.assertEqual(stderr, b"pineapple") + + @greentest.skipIf(subprocess.mswindows, + "Windows does weird things here") + @greentest.skipOnLibuvOnCIOnPyPy("Sometimes segfaults") + def test_communicate_universal(self): + # Native string all the things. See https://github.com/gevent/gevent/issues/1039 + p = subprocess.Popen( + [ + sys.executable, + "-W", "ignore", + "-c", + 'import sys,os;' + 'sys.stderr.write("pineapple\\r\\n\\xff\\xff\\xf2\\xf9\\r\\n");' + 'sys.stdout.write(sys.stdin.read())' + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True + ) + (stdout, stderr) = p.communicate('banana\r\n\xff\xff\xf2\xf9\r\n') + self.assertIsInstance(stdout, str) + self.assertIsInstance(stderr, str) + self.assertEqual(stdout, + 'banana\n\xff\xff\xf2\xf9\n') + + self.assertEqual(stderr, + 'pineapple\n\xff\xff\xf2\xf9\n') + + @greentest.skipOnWindows("Windows IO is weird; this doesn't raise") + def test_communicate_undecodable(self): + # If the subprocess writes non-decodable data, `communicate` raises the + # same UnicodeDecodeError that the stdlib does, instead of + # printing it to the hub. This only applies to Python 3, because only it + # will actually use text mode. + # See https://github.com/gevent/gevent/issues/1510 + with subprocess.Popen( + [ + sys.executable, + '-W', 'ignore', + '-c', + "import os, sys; " + r'os.write(sys.stdout.fileno(), b"\xff")' + ], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, universal_newlines=True + ) as p: + with self.assertRaises(UnicodeDecodeError): + p.communicate() + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_universal1(self): + with subprocess.Popen( + [ + sys.executable, "-c", + 'import sys,os;' + SETBINARY + + 'sys.stdout.write("line1\\n");' + 'sys.stdout.flush();' + 'sys.stdout.write("line2\\r");' + 'sys.stdout.flush();' + 'sys.stdout.write("line3\\r\\n");' + 'sys.stdout.flush();' + 'sys.stdout.write("line4\\r");' + 'sys.stdout.flush();' + 'sys.stdout.write("\\nline5");' + 'sys.stdout.flush();' + 'sys.stdout.write("\\nline6");' + ], + stdout=subprocess.PIPE, + universal_newlines=1, + bufsize=1 + ) as p: + stdout = p.stdout.read() + if python_universal_newlines: + # Interpreter with universal newline support + if not python_universal_newlines_broken: + self.assertEqual(stdout, + "line1\nline2\nline3\nline4\nline5\nline6") + else: + # Note the extra newline after line 3 + self.assertEqual(stdout, + 'line1\nline2\nline3\n\nline4\n\nline5\nline6') + else: + # Interpreter without universal newline support + self.assertEqual(stdout, + "line1\nline2\rline3\r\nline4\r\nline5\nline6") + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_universal2(self): + with subprocess.Popen( + [ + sys.executable, "-c", + 'import sys,os;' + SETBINARY + + 'sys.stdout.write("line1\\n");' + 'sys.stdout.flush();' + 'sys.stdout.write("line2\\r");' + 'sys.stdout.flush();' + 'sys.stdout.write("line3\\r\\n");' + 'sys.stdout.flush();' + 'sys.stdout.write("line4\\r\\nline5");' + 'sys.stdout.flush();' + 'sys.stdout.write("\\nline6");' + ], + stdout=subprocess.PIPE, + universal_newlines=1, + bufsize=1 + ) as p: + stdout = p.stdout.read() + if python_universal_newlines: + # Interpreter with universal newline support + if not python_universal_newlines_broken: + self.assertEqual(stdout, + "line1\nline2\nline3\nline4\nline5\nline6") + else: + # Note the extra newline after line 3 + self.assertEqual(stdout, + 'line1\nline2\nline3\n\nline4\n\nline5\nline6') + else: + # Interpreter without universal newline support + self.assertEqual(stdout, + "line1\nline2\rline3\r\nline4\r\nline5\nline6") + + @greentest.skipOnWindows("Uses 'grep' command") + def test_nonblock_removed(self): + # see issue #134 + r, w = os.pipe() + stdin = subprocess.FileObject(r) + with subprocess.Popen(['grep', 'text'], stdin=stdin) as p: + try: + # Closing one half of the pipe causes Python 3 on OS X to terminate the + # child process; it exits with code 1 and the assert that p.poll is None + # fails. Removing the close lets it pass under both Python 3 and 2.7. + # If subprocess.Popen._remove_nonblock_flag is changed to a noop, then + # the test fails (as expected) even with the close removed + #os.close(w) + time.sleep(0.1) + self.assertEqual(p.poll(), None) + finally: + if p.poll() is None: + p.kill() + stdin.close() + os.close(w) + + def test_issue148(self): + for _ in range(7): + with self.assertRaises(OSError) as exc: + with subprocess.Popen('this_name_must_not_exist'): + pass + + self.assertEqual(exc.exception.errno, errno.ENOENT) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_check_output_keyword_error(self): + with self.assertRaises(subprocess.CalledProcessError) as exc: # pylint:disable=no-member + subprocess.check_output([sys.executable, '-c', 'import sys; sys.exit(44)']) + + self.assertEqual(exc.exception.returncode, 44) + + @greentest.skipOnPy3("The default buffer changed in Py3") + def test_popen_bufsize(self): + # Test that subprocess has unbuffered output by default + # (as the vanilla subprocess module) + with subprocess.Popen( + [sys.executable, '-u', '-c', + 'import sys; sys.stdout.write(sys.stdin.readline())'], + stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) as p: + p.stdin.write(b'foobar\n') + r = p.stdout.readline() + self.assertEqual(r, b'foobar\n') + + @greentest.ignores_leakcheck + @greentest.skipOnWindows("Not sure why?") + def test_subprocess_in_native_thread(self): + # gevent.subprocess doesn't work from a background + # native thread. See #688 + from gevent import monkey + + # must be a native thread; defend against monkey-patching + ex = [] + Thread = monkey.get_original('threading', 'Thread') + + def fn(): + with self.assertRaises(TypeError) as exc: + gevent.subprocess.Popen('echo 123', shell=True) + ex.append(exc.exception) + + thread = Thread(target=fn) + thread.start() + thread.join() + + self.assertEqual(len(ex), 1) + self.assertTrue(isinstance(ex[0], TypeError), ex) + self.assertEqual(ex[0].args[0], 'child watchers are only available on the default loop') + + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def __test_no_output(self, kwargs, kind): + with subprocess.Popen( + [sys.executable, '-c', 'pass'], + stdout=subprocess.PIPE, + **kwargs + ) as proc: + stdout, stderr = proc.communicate() + + self.assertIsInstance(stdout, kind) + self.assertIsNone(stderr) + + @greentest.skipOnLibuvOnCIOnPyPy("Sometimes segfaults; " + "https://travis-ci.org/gevent/gevent/jobs/327357682") + def test_universal_newlines_text_mode_no_output_is_always_str(self): + # If the file is in universal_newlines mode, we should always get a str when + # there is no output. + # https://github.com/gevent/gevent/pull/939 + self.__test_no_output({'universal_newlines': True}, str) + + @greentest.skipIf(sys.version_info[:2] < (3, 6), "Need encoding argument") + def test_encoded_text_mode_no_output_is_str(self): + # If the file is in universal_newlines mode, we should always get a str when + # there is no output. + # https://github.com/gevent/gevent/pull/939 + self.__test_no_output({'encoding': 'utf-8'}, str) + + def test_default_mode_no_output_is_always_str(self): + # If the file is in default mode, we should always get a str when + # there is no output. + # https://github.com/gevent/gevent/pull/939 + self.__test_no_output({}, bytes) + +@greentest.skipOnWindows("Testing POSIX fd closing") +class TestFDs(unittest.TestCase): + + @mock.patch('os.closerange') + @mock.patch('gevent.subprocess._set_inheritable') + @mock.patch('os.close') + def test_close_fds_brute_force(self, close, set_inheritable, closerange): + keep = ( + 4, 5, + # Leave a hole + # 6, + 7, + ) + subprocess.Popen._close_fds_brute_force(keep, None) + + closerange.assert_has_calls([ + mock.call(3, 4), + mock.call(8, subprocess.MAXFD), + ]) + + set_inheritable.assert_has_calls([ + mock.call(4, True), + mock.call(5, True), + ]) + + close.assert_called_once_with(6) + + @mock.patch('gevent.subprocess.Popen._close_fds_brute_force') + @mock.patch('os.listdir') + def test_close_fds_from_path_bad_values(self, listdir, brute_force): + listdir.return_value = 'Not an Integer' + + subprocess.Popen._close_fds_from_path('path', [], 42) + brute_force.assert_called_once_with([], 42) + + @mock.patch('os.listdir') + @mock.patch('os.closerange') + @mock.patch('gevent.subprocess._set_inheritable') + @mock.patch('os.close') + def test_close_fds_from_path(self, close, set_inheritable, closerange, listdir): + keep = ( + 4, 5, + # Leave a hole + # 6, + 7, + ) + listdir.return_value = ['1', '6', '37'] + + subprocess.Popen._close_fds_from_path('path', keep, 5) + + self.assertEqual([], closerange.mock_calls) + + set_inheritable.assert_has_calls([ + mock.call(4, True), + mock.call(7, True), + ]) + + close.assert_has_calls([ + mock.call(6), + mock.call(37), + ]) + + @mock.patch('gevent.subprocess.Popen._close_fds_brute_force') + @mock.patch('os.path.isdir') + def test_close_fds_no_dir(self, isdir, brute_force): + isdir.return_value = False + + subprocess.Popen._close_fds([], 42) + brute_force.assert_called_once_with([], 42) + isdir.assert_has_calls([ + mock.call('/proc/self/fd'), + mock.call('/dev/fd'), + ]) + + @mock.patch('gevent.subprocess.Popen._close_fds_from_path') + @mock.patch('gevent.subprocess.Popen._close_fds_brute_force') + @mock.patch('os.path.isdir') + def test_close_fds_with_dir(self, isdir, brute_force, from_path): + isdir.return_value = True + + subprocess.Popen._close_fds([7], 42) + + self.assertEqual([], brute_force.mock_calls) + from_path.assert_called_once_with('/proc/self/fd', [7], 42) + +class RunFuncTestCase(greentest.TestCase): + # Based on code from python 3.6+ + + __timeout__ = greentest.LARGE_TIMEOUT + + @greentest.skipWithoutResource('subprocess') + def run_python(self, code, **kwargs): + """Run Python code in a subprocess using subprocess.run""" + argv = [sys.executable, "-c", code] + return subprocess.run(argv, **kwargs) + + def test_returncode(self): + # call() function with sequence argument + cp = self.run_python("import sys; sys.exit(47)") + self.assertEqual(cp.returncode, 47) + with self.assertRaises(subprocess.CalledProcessError): # pylint:disable=no-member + cp.check_returncode() + + def test_check(self): + with self.assertRaises(subprocess.CalledProcessError) as c: # pylint:disable=no-member + self.run_python("import sys; sys.exit(47)", check=True) + self.assertEqual(c.exception.returncode, 47) + + def test_check_zero(self): + # check_returncode shouldn't raise when returncode is zero + cp = self.run_python("import sys; sys.exit(0)", check=True) + self.assertEqual(cp.returncode, 0) + + def test_timeout(self): + # run() function with timeout argument; we want to test that the child + # process gets killed when the timeout expires. If the child isn't + # killed, this call will deadlock since subprocess.run waits for the + # child. + with self.assertRaises(subprocess.TimeoutExpired): + self.run_python("while True: pass", timeout=0.0001) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_capture_stdout(self): + # capture stdout with zero return code + cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE) + self.assertIn(b'BDFL', cp.stdout) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_capture_stderr(self): + cp = self.run_python("import sys; sys.stderr.write('BDFL')", + stderr=subprocess.PIPE) + self.assertIn(b'BDFL', cp.stderr) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_check_output_stdin_arg(self): + # run() can be called with stdin set to a file + with tempfile.TemporaryFile() as tf: + tf.write(b'pear') + tf.seek(0) + cp = self.run_python( + "import sys; sys.stdout.write(sys.stdin.read().upper())", + stdin=tf, stdout=subprocess.PIPE) + self.assertIn(b'PEAR', cp.stdout) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_check_output_input_arg(self): + # check_output() can be called with input set to a string + cp = self.run_python( + "import sys; sys.stdout.write(sys.stdin.read().upper())", + input=b'pear', stdout=subprocess.PIPE) + self.assertIn(b'PEAR', cp.stdout) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_check_output_stdin_with_input_arg(self): + # run() refuses to accept 'stdin' with 'input' + with tempfile.TemporaryFile() as tf: + tf.write(b'pear') + tf.seek(0) + with self.assertRaises(ValueError, + msg="Expected ValueError when stdin and input args supplied.") as c: + self.run_python("print('will not be run')", + stdin=tf, input=b'hare') + self.assertIn('stdin', c.exception.args[0]) + self.assertIn('input', c.exception.args[0]) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_check_output_timeout(self): + with self.assertRaises(subprocess.TimeoutExpired) as c: + self.run_python( + ( + "import sys, time\n" + "sys.stdout.write('BDFL')\n" + "sys.stdout.flush()\n" + "time.sleep(3600)" + ), + # Some heavily loaded buildbots (sparc Debian 3.x) require + # this much time to start and print. + timeout=3, stdout=subprocess.PIPE) + self.assertEqual(c.exception.output, b'BDFL') + # output is aliased to stdout + self.assertEqual(c.exception.stdout, b'BDFL') + + def test_run_kwargs(self): + newenv = os.environ.copy() + newenv["FRUIT"] = "banana" + cp = self.run_python(('import sys, os;' + 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'), + env=newenv) + self.assertEqual(cp.returncode, 33) + + # This test _might_ wind up a bit fragile on loaded build+test machines + # as it depends on the timing with wide enough margins for normal situations + # but does assert that it happened "soon enough" to believe the right thing + # happened. + @greentest.skipOnWindows("requires posix like 'sleep' shell command") + def test_run_with_shell_timeout_and_capture_output(self): + #Output capturing after a timeout mustn't hang forever on open filehandles + with self.runs_in_given_time(0.1): + with self.assertRaises(subprocess.TimeoutExpired): + subprocess.run('sleep 3', shell=True, timeout=0.1, + capture_output=True) # New session unspecified. + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_interrupted.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_interrupted.py new file mode 100644 index 0000000000000000000000000000000000000000..96842222faabc8796d6a98ed34404af12870d353 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_interrupted.py @@ -0,0 +1,42 @@ +import sys + +if 'runtestcase' in sys.argv[1:]: # pragma: no cover + import gevent + import gevent.subprocess + gevent.spawn(sys.exit, 'bye') + # Look closely, this doesn't actually do anything, that's a string + # not a division + gevent.subprocess.Popen([sys.executable, '-c', '"1/0"']) + gevent.sleep(1) +else: + # XXX: Handle this more automatically. See comments in the testrunner. + from gevent.testing.resources import exit_without_resource + exit_without_resource('subprocess') + + import subprocess + for _ in range(5): + # not on Py2 pylint:disable=consider-using-with + out, err = subprocess.Popen([sys.executable, '-W', 'ignore', + __file__, 'runtestcase'], + stderr=subprocess.PIPE).communicate() + # We've seen a few unexpected forms of output. + # + # The first involves 'refs'; I don't remember what that was + # about, but I think it had to do with debug builds of Python. + # + # The second is the classic "Unhandled exception in thread + # started by \nsys.excepthook is missing\nlost sys.stderr". + # This is a race condition between closing sys.stderr and + # writing buffered data to a pipe that hasn't been read. We + # only see this using GEVENT_FILE=thread (which makes sense); + # likewise, on Python 2 with thread, we can sometimes get + # `super() argument 1 must be type, not None`; this happens on module + # cleanup. + # + # The third is similar to the second: "AssertionError: + # ...\nIOError: close() called during concurrent operation on + # the same file object.\n" + if b'refs' in err or b'sys.excepthook' in err or b'concurrent' in err: + assert err.startswith(b'bye'), repr(err) # pragma: no cover + else: + assert err.strip() == b'bye', repr(err) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_poll.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..1a569d5d6dacd85a04cbbfd3b6aab798b02b1a74 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__subprocess_poll.py @@ -0,0 +1,13 @@ +import sys +# XXX: Handle this more automatically. See comments in the testrunner. +from gevent.testing.resources import exit_without_resource +exit_without_resource('subprocess') + +from gevent.subprocess import Popen +from gevent.testing.util import alarm + +alarm(3) + +popen = Popen([sys.executable, '-c', 'pass']) +while popen.poll() is None: + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__systemerror.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__systemerror.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcc7e7f125dc42dd8ad7311a49ed664a766aeac --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__systemerror.py @@ -0,0 +1,110 @@ +import sys +import gevent.testing as greentest +import gevent +from gevent.hub import get_hub + +def raise_(ex): + raise ex + + +MSG = 'should be re-raised and caught' + + +class Test(greentest.TestCase): + x = None + error_fatal = False + + def start(self, *args): + raise NotImplementedError + + def setUp(self): + self.x = None + + def test_sys_exit(self): + self.start(sys.exit, MSG) + + try: + gevent.sleep(0.001) + except SystemExit as ex: + assert str(ex) == MSG, repr(str(ex)) + else: + raise AssertionError('must raise SystemExit') + + def test_keyboard_interrupt(self): + self.start(raise_, KeyboardInterrupt) + + try: + gevent.sleep(0.001) + except KeyboardInterrupt: + pass + else: + raise AssertionError('must raise KeyboardInterrupt') + + def test_keyboard_interrupt_stderr_patched(self): + # XXX: This one non-top-level call prevents us from being + # run in a process with other tests. + from gevent import monkey + monkey.patch_sys(stdin=False, stdout=False, stderr=True) + try: + try: + self.start(raise_, KeyboardInterrupt) + while True: + gevent.sleep(0.1) + except KeyboardInterrupt: + pass # expected + finally: + sys.stderr = monkey.get_original('sys', 'stderr') + + def test_system_error(self): + self.start(raise_, SystemError(MSG)) + + with self.assertRaisesRegex(SystemError, + MSG): + gevent.sleep(0.002) + + def test_exception(self): + self.start(raise_, Exception('regular exception must not kill the program')) + gevent.sleep(0.001) + + +class TestCallback(Test): + + def tearDown(self): + if self.x is not None: + # libuv: See the notes in libuv/loop.py:loop._start_callback_timer + # If that's broken, test_exception can fail sporadically. + # If the issue is the same, then adding `gevent.sleep(0)` here + # will solve it. There's also a race condition for the first loop, + # so we sleep twice. + assert not self.x.pending, self.x + + def start(self, *args): + self.x = get_hub().loop.run_callback(*args) + + if greentest.LIBUV: + def test_exception(self): + # This call will enter the loop for the very first time (if we're running + # standalone). On libuv, where timers run first, that means that depending on the + # amount of time that elapses between the call to uv_timer_start and uv_run, + # this timer might fire before our check or prepare watchers, and hence callbacks, + # run. + # We make this call now so that the call in the super class is guaranteed to be + # somewhere in the loop and not subject to that race condition. + gevent.sleep(0.001) + super(TestCallback, self).test_exception() + +class TestSpawn(Test): + + def tearDown(self): + gevent.sleep(0.0001) + if self.x is not None: + assert self.x.dead, self.x + + def start(self, *args): + self.x = gevent.spawn(*args) + + +del Test + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__thread.py new file mode 100644 index 0000000000000000000000000000000000000000..01d0036a8cbe23227d97dc568ce58c1228c5a9fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__thread.py @@ -0,0 +1,31 @@ +from __future__ import print_function +from __future__ import absolute_import + +from gevent.thread import allocate_lock + +import gevent.testing as greentest + +try: + from _thread import allocate_lock as std_allocate_lock +except ImportError: # Py2 + from thread import allocate_lock as std_allocate_lock + + +class TestLock(greentest.TestCase): + + def test_release_unheld_lock(self): + std_lock = std_allocate_lock() + g_lock = allocate_lock() + with self.assertRaises(Exception) as exc: + std_lock.release() + std_exc = exc.exception + + with self.assertRaises(Exception) as exc: + g_lock.release() + g_exc = exc.exception + + self.assertIsInstance(g_exc, type(std_exc)) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading.py new file mode 100644 index 0000000000000000000000000000000000000000..25a377d0535fe849a09807e42eaef7a88fd0ba85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading.py @@ -0,0 +1,92 @@ +""" +Tests specifically for the monkey-patched threading module. +""" +from gevent import monkey; monkey.patch_all() # pragma: testrunner-no-monkey-combine +import gevent.hub + +# check that the locks initialized by 'threading' did not init the hub +assert gevent.hub._get_hub() is None, 'monkey.patch_all() should not init hub' + +import gevent +import gevent.testing as greentest +import threading + + +def helper(): + threading.current_thread() + gevent.sleep(0.2) + +class TestCleanup(greentest.TestCase): + + def _do_test(self, spawn): + before = len(threading._active) + + g = spawn(helper) + gevent.sleep(0.1) + self.assertEqual(len(threading._active), before + 1) + + try: + g.join() + except AttributeError: + while not g.dead: + gevent.sleep() + # Raw greenlet has no join(), uses a weakref to cleanup. + # so the greenlet has to die. On CPython, it's enough to + # simply delete our reference. + del g + # On PyPy, it might take a GC, but for some reason, even + # running several GC's doesn't clean it up under 5.6.0. + # So we skip the test. + #import gc + #gc.collect() + + self.assertEqual(len(threading._active), before) + + + def test_cleanup_gevent(self): + self._do_test(gevent.spawn) + + @greentest.skipOnPyPy("weakref is not cleaned up in a timely fashion") + def test_cleanup_raw(self): + self._do_test(gevent.spawn_raw) + + +class TestLockThread(greentest.TestCase): + + def _spawn(self, func): + t = threading.Thread(target=func) + t.start() + return t + + def test_spin_lock_switches(self): + # https://github.com/gevent/gevent/issues/1464 + # pylint:disable=consider-using-with + lock = threading.Lock() + lock.acquire() + spawned = [] + + def background(): + spawned.append(True) + while not lock.acquire(False): + pass + + thread = threading.Thread(target=background) + # If lock.acquire(False) doesn't yield when it fails, + # then this never returns. + thread.start() + # Verify it tried to run + self.assertEqual(spawned, [True]) + # We can attempt to join it, which won't work. + thread.join(0) + # We can release the lock and then it will acquire. + lock.release() + thread.join() + + +class TestLockGreenlet(TestLockThread): + + def _spawn(self, func): + return gevent.spawn(func) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_2.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7c12f9e7fbdb23c6c15a5c93452feaf320d330 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_2.py @@ -0,0 +1,636 @@ +# testing gevent's Event, Lock, RLock, Semaphore, BoundedSemaphore with standard test_threading + +from gevent.testing.six import xrange +import gevent.testing as greentest + +setup_ = """from gevent import monkey; monkey.patch_all() +from gevent.event import Event +from gevent.lock import RLock, Semaphore, BoundedSemaphore +from gevent.thread import allocate_lock as Lock +import threading +threading.Event = Event +threading.Lock = Lock +# NOTE: We're completely patching around the allocate_lock +# patch we try to do with RLock; our monkey patch doesn't +# behave this way, but we do it in tests to make sure that +# our RLock implementation behaves correctly by itself. +# However, we must test the patched version too, so make it +# available. +threading.NativeRLock = threading.RLock +threading.RLock = RLock +threading.Semaphore = Semaphore +threading.BoundedSemaphore = BoundedSemaphore +""" + +exec(setup_) + +setup_3 = '\n'.join(' %s' % line for line in setup_.split('\n')) +setup_4 = '\n'.join(' %s' % line for line in setup_.split('\n')) + +from gevent.testing import support +verbose = support.verbose + +import random +import re +import sys +import threading +import _thread as thread +import time +import unittest +import weakref + + +from gevent.tests import lock_tests +verbose = False +# pylint:disable=consider-using-with + +from unittest.mock import patch as Patch + + + +def skipDueToHang(cls): + return unittest.skipIf( + greentest.PYPY3 and greentest.RUNNING_ON_CI, + "SKIPPED: Timeout on PyPy3 on Travis" + )(cls) + +class Counter(object): + # A trivial mutable counter. + def __init__(self): + self.value = 0 + + def inc(self): + self.value += 1 + + def dec(self): + self.value -= 1 + + def get(self): + return self.value + + +class TestThread(threading.Thread): + def __init__(self, name, testcase, sema, mutex, nrunning): + threading.Thread.__init__(self, name=name) + + self.testcase = testcase + self.sema = sema + self.mutex = mutex + self.nrunning = nrunning + + def run(self): + delay = random.random() / 10000.0 + if verbose: + print('task %s will run for %.1f usec' % ( + self.name, delay * 1e6)) + + with self.sema: + with self.mutex: + self.nrunning.inc() + if verbose: + print(self.nrunning.get(), 'tasks are running') + self.testcase.assertLessEqual(self.nrunning.get(), 3) + + time.sleep(delay) + if verbose: + print('task', self.name, 'done') + + with self.mutex: + self.nrunning.dec() + self.testcase.assertGreaterEqual(self.nrunning.get(), 0) + if verbose: + print('%s is finished. %d tasks are running' % ( + self.name, self.nrunning.get())) + +@skipDueToHang +class ThreadTests(unittest.TestCase): + maxDiff = None + + # Create a bunch of threads, let each do some work, wait until all are + # done. + def test_various_ops(self): + # This takes about n/3 seconds to run (about n/3 clumps of tasks, + # times about 1 second per clump). + NUMTASKS = 10 + + # no more than 3 of the 10 can run at once + sema = threading.BoundedSemaphore(value=3) + mutex = threading.RLock() + numrunning = Counter() + + threads = [] + + initial_regex = r'' + if sys.version_info[:2] < (3, 13): + # prior to 3.13, they distinguished the initial state from + # the stopped state. + initial_regex = r'' + + for i in range(NUMTASKS): + t = TestThread("" % i, self, sema, mutex, numrunning) + threads.append(t) + # pylint:disable-next=attribute-defined-outside-init + t.daemon = False # Under PYPY we get daemon by default? + self.assertIsNone(t.ident) + self.assertFalse(t.daemon) + self.assertTrue(re.match(initial_regex, repr(t)), + repr(t)) + t.start() + + if verbose: + print('waiting for all tasks to complete') + for t in threads: + t.join(NUMTASKS) + self.assertFalse(t.is_alive(), t.__dict__) + if hasattr(t, 'ident'): + self.assertNotEqual(t.ident, 0) + self.assertFalse(t.ident is None) + self.assertTrue(re.match(r'', repr(t))) + if verbose: + print('all tasks done') + self.assertEqual(numrunning.get(), 0) + + def test_ident_of_no_threading_threads(self): + # The ident still must work for the main thread and dummy threads, + # as must the repr and str. + + t = threading.current_thread() + self.assertFalse(t.ident is None) + str(t) + repr(t) + + def f(): + t = threading.current_thread() + ident.append(t.ident) + str(t) + repr(t) + done.set() + + done = threading.Event() + ident = [] + thread.start_new_thread(f, ()) + done.wait() + self.assertFalse(ident[0] is None) + # Kill the "immortal" _DummyThread + del threading._active[ident[0]] + + # run with a small(ish) thread stack size (256kB) + def test_various_ops_small_stack(self): + if verbose: + print('with 256kB thread stack size...') + try: + threading.stack_size(262144) + except thread.error: + if verbose: + print('platform does not support changing thread stack size') + return + self.test_various_ops() + threading.stack_size(0) + + # run with a large thread stack size (1MB) + def test_various_ops_large_stack(self): + if verbose: + print('with 1MB thread stack size...') + try: + threading.stack_size(0x100000) + except thread.error: + if verbose: + print('platform does not support changing thread stack size') + return + self.test_various_ops() + threading.stack_size(0) + + def test_foreign_thread(self): + # Check that a "foreign" thread can use the threading module. + def f(mutex): + # Calling current_thread() forces an entry for the foreign + # thread to get made in the threading._active map. + threading.current_thread() + mutex.release() + + mutex = threading.Lock() + mutex.acquire() + tid = thread.start_new_thread(f, (mutex,)) + # Wait for the thread to finish. + mutex.acquire() + self.assertIn(tid, threading._active) + self.assertIsInstance(threading._active[tid], + threading._DummyThread) + del threading._active[tid] + # in gevent, we actually clean up threading._active, but it's not happended there yet + + # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) + # exposed at the Python level. This test relies on ctypes to get at it. + def SKIP_test_PyThreadState_SetAsyncExc(self): + try: + import ctypes + except ImportError: + if verbose: + print("test_PyThreadState_SetAsyncExc can't import ctypes") + return # can't do anything + + set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc + + class AsyncExc(Exception): + pass + + exception = ctypes.py_object(AsyncExc) + + # `worker_started` is set by the thread when it's inside a try/except + # block waiting to catch the asynchronously set AsyncExc exception. + # `worker_saw_exception` is set by the thread upon catching that + # exception. + worker_started = threading.Event() + worker_saw_exception = threading.Event() + + class Worker(threading.Thread): + id = None + finished = False + + def run(self): + self.id = thread.get_ident() + self.finished = False + + try: + while True: + worker_started.set() + time.sleep(0.1) + except AsyncExc: + self.finished = True + worker_saw_exception.set() + + t = Worker() + # pylint:disable-next=attribute-defined-outside-init + t.daemon = True # so if this fails, we don't hang Python at shutdown + t.start() + if verbose: + print(" started worker thread") + + # Try a thread id that doesn't make sense. + if verbose: + print(" trying nonsensical thread id") + result = set_async_exc(ctypes.c_long(-1), exception) + self.assertEqual(result, 0) # no thread states modified + + # Now raise an exception in the worker thread. + if verbose: + print(" waiting for worker thread to get started") + worker_started.wait() + if verbose: + print(" verifying worker hasn't exited") + self.assertFalse(t.finished) + if verbose: + print(" attempting to raise asynch exception in worker") + result = set_async_exc(ctypes.c_long(t.id), exception) + self.assertEqual(result, 1) # one thread state modified + if verbose: + print(" waiting for worker to say it caught the exception") + worker_saw_exception.wait(timeout=10) + self.assertTrue(t.finished) + if verbose: + print(" all OK -- joining worker") + if t.finished: + t.join() + # else the thread is still running, and we have no way to kill it + + def test_limbo_cleanup(self): + # Issue 7481: Failure to start thread should cleanup the limbo map. + def fail_new_thread(*_args, **_kw): + raise thread.error() + if hasattr(threading, '_start_new_thread'): + patcher = Patch.object(threading, '_start_new_thread', new=fail_new_thread) + else: + # 3.13 or later + patcher = Patch.object(threading, '_start_joinable_thread', new=fail_new_thread) + + self.addCleanup(patcher.stop) + patcher.start() + + t = threading.Thread(target=lambda: None) + self.assertRaises(thread.error, t.start) + self.assertFalse( + t in threading._limbo, + "Failed to cleanup _limbo map on failure of Thread.start().") + + def test_finalize_runnning_thread(self): + # Issue 1402: the PyGILState_Ensure / _Release functions may be called + # very late on python exit: on deallocation of a running thread for + # example. + try: + import ctypes + getattr(ctypes, 'pythonapi') # not available on PyPy + getattr(ctypes.pythonapi, 'PyGILState_Ensure') # not available on PyPy3 + except (ImportError, AttributeError): + if verbose: + print("test_finalize_with_runnning_thread can't import ctypes") + return # can't do anything + + del ctypes # pyflakes fix + + import subprocess + rc = subprocess.call([sys.executable, "-W", "ignore", "-c", """if 1: +%s + import ctypes, sys, time + try: + import thread + except ImportError: + import _thread as thread # Py3 + + # This lock is used as a simple event variable. + ready = thread.allocate_lock() + ready.acquire() + + # Module globals are cleared before __del__ is run + # So we save the functions in class dict + class C: + ensure = ctypes.pythonapi.PyGILState_Ensure + release = ctypes.pythonapi.PyGILState_Release + def __del__(self): + state = self.ensure() + self.release(state) + + def waitingThread(): + x = C() + ready.release() + time.sleep(100) + + thread.start_new_thread(waitingThread, ()) + ready.acquire() # Be sure the other thread is waiting. + sys.exit(42) + """ % setup_3]) + self.assertEqual(rc, 42) + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_join_nondaemon_on_shutdown(self): + # Issue 1722344 + # Raising SystemExit skipped threading._shutdown + import subprocess + script = """if 1: +%s + import threading + from time import sleep + + def child(): + sleep(0.3) + # As a non-daemon thread we SHOULD wake up and nothing + # should be torn down yet + print("Woke up, sleep function is: %%s.%%s" %% (sleep.__module__, sleep.__name__)) + + threading.Thread(target=child).start() + raise SystemExit + """ % setup_4 + p = subprocess.Popen([sys.executable, "-W", "ignore", "-c", script], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + stdout = stdout.strip() + stdout = stdout.decode('utf-8') + stderr = stderr.decode('utf-8') + + + self.assertEqual( + 'Woke up, sleep function is: gevent.hub.sleep', + stdout) + + # On Python 2, importing pkg_resources tends to result in some 'ImportWarning' + # being printed to stderr about packages missing __init__.py; the -W ignore is... + # ignored. + # self.assertEqual(stderr, "") + + @greentest.skipIf( + not(hasattr(sys, 'getcheckinterval')), + "Needs sys.getcheckinterval" + ) + def test_enumerate_after_join(self): + # Try hard to trigger #1703448: a thread is still returned in + # threading.enumerate() after it has been join()ed. + enum = threading.enumerate + import warnings + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + # get/set checkinterval are deprecated in Python 3, + # and removed in Python 3.9 + old_interval = sys.getcheckinterval() # pylint:disable=no-member + try: + for i in xrange(1, 100): + # Try a couple times at each thread-switching interval + # to get more interleavings. + sys.setcheckinterval(i // 5) # pylint:disable=no-member + t = threading.Thread(target=lambda: None) + t.start() + t.join() + l = enum() + self.assertFalse(t in l, + "#1703448 triggered after %d trials: %s" % (i, l)) + finally: + sys.setcheckinterval(old_interval) # pylint:disable=no-member + + if not hasattr(sys, 'pypy_version_info'): + def test_no_refcycle_through_target(self): + class RunSelfFunction(object): + def __init__(self, should_raise): + # The links in this refcycle from Thread back to self + # should be cleaned up when the thread completes. + self.should_raise = should_raise + self.thread = threading.Thread(target=self._run, + args=(self,), + kwargs={'_yet_another': self}) + self.thread.start() + + def _run(self, _other_ref, _yet_another): + if self.should_raise: + raise SystemExit + + cyclic_object = RunSelfFunction(should_raise=False) + weak_cyclic_object = weakref.ref(cyclic_object) + cyclic_object.thread.join() + del cyclic_object + self.assertIsNone(weak_cyclic_object(), + msg=('%d references still around' % + sys.getrefcount(weak_cyclic_object()))) + + raising_cyclic_object = RunSelfFunction(should_raise=True) + weak_raising_cyclic_object = weakref.ref(raising_cyclic_object) + raising_cyclic_object.thread.join() + del raising_cyclic_object + self.assertIsNone(weak_raising_cyclic_object(), + msg=('%d references still around' % + sys.getrefcount(weak_raising_cyclic_object()))) + +@skipDueToHang +class ThreadJoinOnShutdown(unittest.TestCase): + + maxDiff = None + + def _run_and_join(self, script): + script = """if 1: +%s + import sys, os, time, threading + # a thread, which waits for the main program to terminate + def joiningfunc(mainthread): + mainthread.join() + print('end of thread') + \n""" % setup_3 + script + + import subprocess + p = subprocess.Popen([sys.executable, "-W", "ignore", "-c", script], stdout=subprocess.PIPE) + rc = p.wait() + data = p.stdout.read().replace(b'\r', b'') + p.stdout.close() + data = data.decode('utf-8') + self.assertEqual(data, "end of main\nend of thread\n") + self.assertNotEqual(rc, 2, "interpreter was blocked") + self.assertEqual(rc, 0, "Unexpected error") + + @greentest.skipOnLibuvOnPyPyOnWin("hangs") + def test_1_join_on_shutdown(self): + # The usual case: on exit, wait for a non-daemon thread + script = """if 1: + import os + t = threading.Thread(target=joiningfunc, + args=(threading.current_thread(),)) + t.start() + time.sleep(0.2) + print('end of main') + """ + self._run_and_join(script) + + @greentest.skipOnPyPy3OnCI("Sometimes randomly times out") + def test_2_join_in_forked_process(self): + # Like the test above, but from a forked interpreter + import os + if not hasattr(os, 'fork'): + return + script = """if 1: + childpid = os.fork() + if childpid != 0: + os.waitpid(childpid, 0) + sys.exit(0) + + t = threading.Thread(target=joiningfunc, + args=(threading.current_thread(),)) + t.start() + print('end of main') + """ + self._run_and_join(script) + + def test_3_join_in_forked_from_thread(self): + # Like the test above, but fork() was called from a worker thread + # In the forked process, the main Thread object must be marked as stopped. + import os + if not hasattr(os, 'fork'): + return + # Skip platforms with known problems forking from a worker thread. + # See http://bugs.python.org/issue3863. + # skip disable because I think the bug shouldn't apply to gevent -- denis + #if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): + # print(('Skipping test_3_join_in_forked_from_thread' + # ' due to known OS bugs on'), sys.platform, file=sys.stderr) + # return + + # A note on CFFI: Under Python 3, using CFFI tends to initialize the GIL, + # whether or not we spawn any actual threads. Now, os.fork() calls + # PyEval_ReInitThreads, which only does any work of the GIL has been taken. + # One of the things it does is call threading._after_fork to reset + # some thread state, which causes the main thread (threading._main_thread) + # to be reset to the current thread---which for Python >= 3.4 happens + # to be our version of thread, gevent.threading.Thread, which doesn't + # initialize the _tstate_lock ivar. This causes threading._shutdown to crash + # with an AssertionError and this test to fail. We hack around this by + # making sure _after_fork is not called in the child process. + # XXX: Figure out how to really fix that. + + script = """if 1: + main_thread = threading.current_thread() + def worker(): + childpid = os.fork() + if childpid != 0: + os.waitpid(childpid, 0) + sys.exit(0) + + t = threading.Thread(target=joiningfunc, + args=(main_thread,)) + print('end of main') + t.start() + t.join() # Should not block: main_thread is already stopped + + w = threading.Thread(target=worker) + w.start() + import sys + if sys.version_info[:2] >= (3, 7) or (sys.version_info[:2] >= (3, 5) and hasattr(sys, 'pypy_version_info') and sys.platform != 'darwin'): + w.join() + """ + # In PyPy3 5.8.0, if we don't wait on this top-level "thread", 'w', + # we never see "end of thread". It's not clear why, since that's being + # done in a child of this process. Yet in normal CPython 3, waiting on this + # causes the whole process to lock up (possibly because of some loop within + # the interpreter waiting on thread locks, like the issue described in threading.py + # for Python 3.4? in any case, it doesn't hang in Python 2.) This changed in + # 3.7a1 and waiting on it is again necessary and doesn't hang. + # PyPy3 5.10.1 is back to the "old" cpython behaviour, and waiting on it + # causes the whole process to hang, but apparently only on OS X---linux was fine without it + self._run_and_join(script) + + +@skipDueToHang +class ThreadingExceptionTests(unittest.TestCase): + # A RuntimeError should be raised if Thread.start() is called + # multiple times. + # pylint:disable=bad-thread-instantiation + def test_start_thread_again(self): + thread_ = threading.Thread() + thread_.start() + self.assertRaises(RuntimeError, thread_.start) + + def test_joining_current_thread(self): + current_thread = threading.current_thread() + self.assertRaises(RuntimeError, current_thread.join) + + def test_joining_inactive_thread(self): + thread_ = threading.Thread() + self.assertRaises(RuntimeError, thread_.join) + + def test_daemonize_active_thread(self): + thread_ = threading.Thread() + thread_.start() + self.assertRaises(RuntimeError, setattr, thread_, "daemon", True) + + +@skipDueToHang +class LockTests(lock_tests.LockTests): + locktype = staticmethod(threading.Lock) + +@skipDueToHang +class RLockTests(lock_tests.RLockTests): + locktype = staticmethod(threading.RLock) + +@skipDueToHang +class NativeRLockTests(lock_tests.RLockTests): + # See comments at the top of the file for the difference + # between this and RLockTests, and why they both matter + locktype = staticmethod(threading.NativeRLock) + +@skipDueToHang +class EventTests(lock_tests.EventTests): + eventtype = staticmethod(threading.Event) + +@skipDueToHang +class ConditionAsRLockTests(lock_tests.RLockTests): + # An Condition uses an RLock by default and exports its API. + locktype = staticmethod(threading.Condition) + +@skipDueToHang +class ConditionTests(lock_tests.ConditionTests): + condtype = staticmethod(threading.Condition) + +@skipDueToHang +class SemaphoreTests(lock_tests.SemaphoreTests): + semtype = staticmethod(threading.Semaphore) + +@skipDueToHang +class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests): + semtype = staticmethod(threading.BoundedSemaphore) + + +if __name__ == "__main__": + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_before_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_before_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..b84ececaec820420640871da10775fb1a24c85bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_before_monkey.py @@ -0,0 +1,23 @@ +# If stdlib threading is imported *BEFORE* monkey patching, +# we can still get the current (main) thread, and it's not a DummyThread. + +import threading +from gevent import monkey +monkey.patch_all() # pragma: testrunner-no-monkey-combine + +import gevent.testing as greentest + + +class Test(greentest.TestCase): + + def test_main_thread(self): + current = threading.current_thread() + self.assertFalse(isinstance(current, threading._DummyThread)) + self.assertTrue(isinstance(current, monkey.get_original('threading', 'Thread'))) + # in 3.4, if the patch is incorrectly done, getting the repr + # of the thread fails + repr(current) + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_fork_from_dummy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_fork_from_dummy.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8df88bb826feda8510026a85733e3983eaba44 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_fork_from_dummy.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +""" +Tests for `issue 2020 `_: +3.11.8 and 3.12.2 try to swizzle ``__class__`` of the dummy thread +found when forking from inside a greenlet. + +""" +from gevent import monkey; monkey.patch_all() # pragma: testrunner-no-monkey-combine + +import unittest +import gevent.testing as greentest + +import tempfile + +@greentest.skipOnWindows("Uses os.fork") +class Test(greentest.TestCase): + + + def test_fork_from_dummy_thread(self): + import os + import threading + import contextlib + + import gevent + from gevent.threading import _DummyThread + if not _DummyThread._NEEDS_CLASS_FORK_FIXUP: + self.skipTest('No patch need be applied') + + def do_it(out): + # Be sure we've put the DummyThread in the threading + # maps + assert isinstance(threading.current_thread(), threading._DummyThread) + with open(out, 'wt', encoding='utf-8') as f: + with contextlib.redirect_stderr(f): + r = os.fork() + if r == 0: + # In the child. + # Our stderr redirect above will capture the + # "Exception ignored in _after_fork()" that the interpreter + # prints; actually printing the main_thread will result in + # raising an exception if our patch doesn't work. + main = threading.main_thread() + print(main, file=f) + print(type(main), file=f) + return r + + with tempfile.NamedTemporaryFile('w+t', suffix='.gevent_threading.txt') as tf: + glet = gevent.spawn(do_it, tf.name) + glet.join() + pid = glet.get() + if pid == 0: + # Dump the child process quickly + os._exit(0) + + os.waitpid(pid, 0) + tf.seek(0, 0) + contents = tf.read() + + + self.assertIn("", contents) + self.assertNotIn("_DummyThread", contents) + + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_holding_lock_while_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_holding_lock_while_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..b12da765559fdc36b57fe9067582714a8e42867e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_holding_lock_while_monkey.py @@ -0,0 +1,9 @@ +from gevent import monkey +import threading +# Make sure that we can patch gevent while holding +# a threading lock. Under Python2, where RLock is implemented +# in python code, this used to throw RuntimeErro("Cannot release un-acquired lock") +# See https://github.com/gevent/gevent/issues/615 +# pylint:disable=useless-with-lock +with threading.RLock(): + monkey.patch_all() # pragma: testrunner-no-monkey-combine diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_monkey_in_thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_monkey_in_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..6e2bb9456ae7c989d1f045dbc232f8d8840047b8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_monkey_in_thread.py @@ -0,0 +1,68 @@ +# We can monkey-patch in a thread, but things don't work as expected. +from __future__ import print_function + +import threading +from gevent import monkey +import gevent.testing as greentest + + +class Test(greentest.TestCase): + + @greentest.ignores_leakcheck # can't be run multiple times + def test_patch_in_thread(self): + all_warnings = [] + try: + get_ident = threading.get_ident + except AttributeError: + get_ident = threading._get_ident + + def process_warnings(warnings): + all_warnings.extend(warnings) + monkey._process_warnings = process_warnings + + current = threading.current_thread() + current_id = get_ident() + + def target(): + tcurrent = threading.current_thread() + monkey.patch_all() # pragma: testrunner-no-monkey-combine + tcurrent2 = threading.current_thread() + self.assertIsNot(tcurrent, current) + # We get a dummy thread now + self.assertIsNot(tcurrent, tcurrent2) + + thread = threading.Thread(target=target) + thread.start() + try: + thread.join() + except: # pylint:disable=bare-except + # XXX: This can raise LoopExit in some cases. + greentest.reraiseFlakyTestRaceCondition() + + self.assertNotIsInstance(current, threading._DummyThread) + self.assertIsInstance(current, monkey.get_original('threading', 'Thread')) + + + # We generated some warnings + if greentest.PY3: + self.assertEqual( + all_warnings, + ['Monkey-patching outside the main native thread. Some APIs will not be ' + 'available. Expect a KeyError to be printed at shutdown.', + 'Monkey-patching not on the main thread; threading.main_thread().join() ' + 'will hang from a greenlet']) + else: + self.assertEqual( + all_warnings, + ['Monkey-patching outside the main native thread. Some APIs will not be ' + 'available. Expect a KeyError to be printed at shutdown.']) + + + # Manual clean up so we don't get a KeyError + del threading._active[current_id] + threading._active[(getattr(threading, 'get_ident', None) or threading._get_ident)()] = current + + + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_native_before_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_native_before_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..e015370babb126b56f774e11ff4513c049e8b9af --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_native_before_monkey.py @@ -0,0 +1,70 @@ +# If stdlib threading is imported *BEFORE* monkey patching, *and* +# there is a native thread created, we can still get the current +# (main) thread, and it's not a DummyThread. +# Joining the native thread also does not fail + +import threading +from time import sleep as time_sleep + +import gevent.testing as greentest + +class NativeThread(threading.Thread): + do_run = True + + def run(self): + while self.do_run: + time_sleep(0.1) + + def stop(self, timeout=None): + self.do_run = False + self.join(timeout=timeout) + +native_thread = None +monkey = None + +class Test(greentest.TestCase): + + @classmethod + def tearDownClass(cls): + global native_thread + if native_thread is not None: + native_thread.stop(1) + native_thread = None + + def test_main_thread(self): + current = threading.current_thread() + self.assertNotIsInstance(current, threading._DummyThread) + # pylint:disable-next=used-before-assignment + self.assertIsInstance(current, monkey.get_original('threading', 'Thread')) + # in 3.4, if the patch is incorrectly done, getting the repr + # of the thread fails + repr(current) + + if hasattr(threading, 'main_thread'): # py 3.4 + self.assertEqual(threading.current_thread(), threading.main_thread()) + + @greentest.ignores_leakcheck # because it can't be run multiple times + def test_join_native_thread(self): + if native_thread is None or not native_thread.do_run: # pragma: no cover + self.skipTest("native_thread already closed") + + self.assertTrue(native_thread.is_alive()) + + native_thread.stop(timeout=1) + self.assertFalse(native_thread.is_alive()) + + # again, idempotent + native_thread.stop() + self.assertFalse(native_thread.is_alive()) + + +if __name__ == '__main__': + native_thread = NativeThread() + native_thread.daemon = True # pylint:disable=attribute-defined-outside-init + native_thread.start() + + # Only patch after we're running + from gevent import monkey + monkey.patch_all() # pragma: testrunner-no-monkey-combine + + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_no_monkey.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_no_monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..44b70ba56ad8e183a5f292093d5fc9e9a33d7341 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_no_monkey.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +""" +Tests for ``gevent.threading`` that DO NOT monkey patch. This +allows easy comparison with the standard module. + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import threading + +from gevent import threading as gthreading +from gevent import testing + +class TestDummyThread(testing.TestCase): + + def test_name(self): + # Matches the stdlib. + # https://github.com/gevent/gevent/issues/1659 + std_dummy = threading._DummyThread() + gvt_dummy = gthreading._DummyThread() + self.assertIsNot(type(std_dummy), type(gvt_dummy)) + + self.assertStartsWith(std_dummy.name, 'Dummy-') + self.assertStartsWith(gvt_dummy.name, 'Dummy-') + + +if __name__ == '__main__': + testing.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_patched_local.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_patched_local.py new file mode 100644 index 0000000000000000000000000000000000000000..6b78d323165cb8c7ffabae4c3523701ff506ffff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_patched_local.py @@ -0,0 +1,27 @@ +from gevent import monkey; monkey.patch_all() +import threading + + +localdata = threading.local() +localdata.x = "hello" +assert localdata.x == 'hello' +success = [] + + +def func(): + try: + getattr(localdata, 'x') + raise AssertionError('localdata.x must raise AttributeError') + except AttributeError: + pass + # We really want to check this is exactly an empty dict, + # not just anything falsey + # pylint:disable=use-implicit-booleaness-not-comparison + assert localdata.__dict__ == {}, localdata.__dict__ + success.append(1) + +t = threading.Thread(None, func) +t.start() +t.join() +assert success == [1], 'test failed' +assert localdata.x == 'hello' diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_vs_settrace.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_vs_settrace.py new file mode 100644 index 0000000000000000000000000000000000000000..7cca26babcd36c7a4f524644ef1543338726aa4d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threading_vs_settrace.py @@ -0,0 +1,162 @@ +from __future__ import print_function +import sys +import subprocess +import unittest +from gevent.thread import allocate_lock +import gevent.testing as greentest + +script = """ +from gevent import monkey +monkey.patch_all() # pragma: testrunner-no-monkey-combine +import sys, os, threading, time + + +# A deadlock-killer, to prevent the +# testsuite to hang forever +def killer(): + time.sleep(0.2) + sys.stdout.write('..program blocked; aborting!') + sys.stdout.flush() + os._exit(2) +t = threading.Thread(target=killer) +t.daemon = True +t.start() + + +def trace(frame, event, arg): + if threading is not None: + threading.current_thread() + return trace + + +def doit(): + sys.stdout.write("..thread started..") + + +def test1(): + t = threading.Thread(target=doit) + t.start() + t.join() + sys.settrace(None) + +sys.settrace(trace) +if len(sys.argv) > 1: + test1() + +sys.stdout.write("..finishing..") +""" + + +class TestTrace(unittest.TestCase): + @greentest.skipOnPurePython("Locks can be traced in Pure Python") + def test_untraceable_lock(self): + # Untraceable locks were part of the solution to https://bugs.python.org/issue1733757 + # which details a deadlock that could happen if a trace function invoked + # threading.currentThread at shutdown time---the cleanup lock would be held + # by the VM, and calling currentThread would try to acquire it again. The interpreter + # changed in 2.6 to use the `with` statement (https://hg.python.org/cpython/rev/76f577a9ec03/), + # which apparently doesn't trace in quite the same way. + if hasattr(sys, 'gettrace'): + old = sys.gettrace() + else: + old = None + + lst = [] + try: + def trace(frame, ev, _arg): + lst.append((frame.f_code.co_filename, frame.f_lineno, ev)) + print("TRACE: %s:%s %s" % lst[-1]) + return trace + + with allocate_lock(): + sys.settrace(trace) + finally: + sys.settrace(old) + + self.assertEqual(lst, [], "trace not empty") + + @greentest.skipOnPurePython("Locks can be traced in Pure Python") + def test_untraceable_lock_uses_different_lock(self): + if hasattr(sys, 'gettrace'): + old = sys.gettrace() + else: + old = None + + lst = [] + # we should be able to use unrelated locks from within the trace function + l = allocate_lock() + try: + def trace(frame, ev, _arg): + with l: + lst.append((frame.f_code.co_filename, frame.f_lineno, ev)) + # print("TRACE: %s:%s %s" % lst[-1]) + return trace + + l2 = allocate_lock() + sys.settrace(trace) + # Separate functions, not the C-implemented `with` so the trace + # function gets a crack at them + l2.acquire() + l2.release() + finally: + sys.settrace(old) + + # Have an assert so that we know if we miscompile + self.assertTrue(lst, "should not compile on pypy") + + @greentest.skipOnPurePython("Locks can be traced in Pure Python") + def test_untraceable_lock_uses_same_lock(self): + from gevent.hub import LoopExit + if hasattr(sys, 'gettrace'): + old = sys.gettrace() + else: + old = None + + lst = [] + e = None + # we should not be able to use the same lock from within the trace function + # because it's over acquired but instead of deadlocking it raises an exception + l = allocate_lock() + try: + def trace(frame, ev, _arg): + with l: + lst.append((frame.f_code.co_filename, frame.f_lineno, ev)) + return trace + + sys.settrace(trace) + # Separate functions, not the C-implemented `with` so the trace + # function gets a crack at them + l.acquire() + except LoopExit as ex: + e = ex + finally: + sys.settrace(old) + + # Have an assert so that we know if we miscompile + self.assertTrue(lst, "should not compile on pypy") + self.assertTrue(isinstance(e, LoopExit)) + + def run_script(self, more_args=()): + if ( + greentest.PYPY3 + and greentest.RUNNING_ON_APPVEYOR + and sys.version_info[:2] == (3, 7) + ): + # Somehow launching the subprocess fails with exit code 1, and + # produces no output. It's not clear why. + self.skipTest("Known to hang on AppVeyor") + args = [sys.executable, "-u", "-c", script] + args.extend(more_args) + rc = subprocess.call(args) + self.assertNotEqual(rc, 2, "interpreter was blocked") + self.assertEqual(rc, 0, "Unexpected error") + + def test_finalize_with_trace(self): + self.run_script() + + def test_bootstrap_inner_with_trace(self): + self.run_script(["1"]) + + +if __name__ == "__main__": + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threadpool.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threadpool.py new file mode 100644 index 0000000000000000000000000000000000000000..9616faba62a7b18291cccdb26c749605f11e0498 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test__threadpool.py @@ -0,0 +1,825 @@ +from __future__ import print_function + +from time import time, sleep +import contextlib +import random +import weakref +import gc + + +import gevent.threadpool +from gevent.threadpool import ThreadPool +import gevent +from gevent.exceptions import InvalidThreadUseError + +import gevent.testing as greentest +from gevent.testing import ExpectedException +from gevent.testing import PYPY + + + +# pylint:disable=too-many-ancestors + + +@contextlib.contextmanager +def disabled_gc(): + was_enabled = gc.isenabled() + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() + + +class TestCase(greentest.TestCase): + # These generally need more time + __timeout__ = greentest.LARGE_TIMEOUT + pool = None + _all_pools = () + + ClassUnderTest = ThreadPool + def _FUT(self): + return self.ClassUnderTest + + def _makeOne(self, maxsize, create_all_worker_threads=greentest.RUN_LEAKCHECKS): + self.pool = pool = self._FUT()(maxsize) + self._all_pools += (pool,) + if create_all_worker_threads: + # Max size to help eliminate false positives + self.pool.size = maxsize + return pool + + def cleanup(self): + self.pool = None + all_pools, self._all_pools = self._all_pools, () + for pool in all_pools: + kill = getattr(pool, 'kill', None) or getattr(pool, 'shutdown') + kill() + del kill + + if greentest.RUN_LEAKCHECKS: + # Each worker thread created a greenlet object and switched to it. + # It's a custom subclass, but even if it's not, it appears that + # the root greenlet for the new thread sticks around until there's a + # gc. Simply calling 'getcurrent()' is enough to "leak" a greenlet.greenlet + # and a weakref. + for _ in range(3): + gc.collect() + + +class PoolBasicTests(TestCase): + + def test_execute_async(self): + pool = self._makeOne(2) + r = [] + first = pool.spawn(r.append, 1) + first.get() + self.assertEqual(r, [1]) + gevent.sleep(0) + + pool.apply_async(r.append, (2, )) + self.assertEqual(r, [1]) + + pool.apply_async(r.append, (3, )) + self.assertEqual(r, [1]) + + pool.apply_async(r.append, (4, )) + self.assertEqual(r, [1]) + gevent.sleep(0.01) + self.assertEqualFlakyRaceCondition(sorted(r), [1, 2, 3, 4]) + + def test_apply(self): + pool = self._makeOne(1) + result = pool.apply(lambda a: ('foo', a), (1, )) + self.assertEqual(result, ('foo', 1)) + + def test_apply_raises(self): + pool = self._makeOne(1) + + def raiser(): + raise ExpectedException() + + with self.assertRaises(ExpectedException): + pool.apply(raiser) + # Don't let the metaclass automatically force any error + # that reaches the hub from a spawned greenlet to become + # fatal; that defeats the point of the test. + test_apply_raises.error_fatal = False + + def test_init_valueerror(self): + self.switch_expected = False + with self.assertRaises(ValueError): + self._makeOne(-1) + +# +# tests from standard library test/test_multiprocessing.py + + +class TimingWrapper(object): + + def __init__(self, the_func): + self.func = the_func + self.elapsed = None + + def __call__(self, *args, **kwds): + t = time() + try: + return self.func(*args, **kwds) + finally: + self.elapsed = time() - t + + +def sqr(x, wait=0.0): + sleep(wait) + return x * x + + +def sqr_random_sleep(x): + sleep(random.random() * 0.1) + return x * x + + +TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.082, 0.035, 0.14 + +class _AbstractPoolTest(TestCase): + + size = 1 + + MAP_IS_GEN = False + + def setUp(self): + greentest.TestCase.setUp(self) + self._makeOne(self.size) + + @greentest.ignores_leakcheck + def test_map(self): + pmap = self.pool.map + if self.MAP_IS_GEN: + pmap = lambda f, i: list(self.pool.map(f, i)) + self.assertEqual(pmap(sqr, range(10)), list(map(sqr, range(10)))) + self.assertEqual(pmap(sqr, range(100)), list(map(sqr, range(100)))) + + self.pool.kill() + del self.pool + del pmap + +SMALL_RANGE = 10 +LARGE_RANGE = 1000 + +if (greentest.PYPY and (greentest.WIN or greentest.RUN_COVERAGE)) or greentest.RUN_LEAKCHECKS: + # PyPy 5.10 is *really* slow at spawning or switching between + # threads (especially on Windows or when coverage is enabled) Tests that happen + # instantaneously on other platforms time out due to the overhead. + + # Leakchecks also take much longer due to all the calls into the GC, + # most especially on Python 3 + LARGE_RANGE = 50 + +class TestPool(_AbstractPoolTest): + + def test_greenlet_class(self): + from greenlet import getcurrent + from gevent.threadpool import _WorkerGreenlet + worker_greenlet = self.pool.apply(getcurrent) + + self.assertIsInstance(worker_greenlet, _WorkerGreenlet) + r = repr(worker_greenlet) + self.assertIn('ThreadPoolWorker', r) + self.assertIn('thread_ident', r) + self.assertIn('hub=', r) + + from gevent.util import format_run_info + + info = '\n'.join(format_run_info()) + self.assertIn("") + + value = hexobj.sub('X', value) + value = value.replace('epoll', 'select') + value = value.replace('select', 'default') + value = value.replace('test__util', '__main__') + value = re.compile(' fileno=.').sub('', value) + value = value.replace('ref=-1', 'ref=0') + value = value.replace("type.current_tree", 'GreenletTree.current_tree') + value = value.replace('gevent.tests.__main__.MyLocal', '__main__.MyLocal') + # The repr in CPython greenlet 1.0a1 added extra info + value = value.replace('(otid=X) ', '') + value = value.replace(' dead>', '>') + value = value.replace(' current active started main>', '>') + return value + + @greentest.ignores_leakcheck + def test_tree(self): + with gevent.get_hub().ignoring_expected_test_error(): + tree, str_tree, tree_format = self._build_tree() + + self.assertTrue(tree.root) + + self.assertNotIn('Parent', str_tree) # Simple output + value = self._normalize_tree_format(tree_format) + + expected = """\ + + : Parent: None + : Greenlet Locals: + : Local at X + : {'foo': 42} + +--- + : Parent: + +--- ; finished with value + | +--- ; finished with exception ExpectedException() + : Parent: + +--- ; finished with value + | +--- ; finished with exception ExpectedException() + : Parent: + +--- ; finished with value + : Spawn Tree Locals + : {'stl': 'STL'} + | +--- ; finished with value + | +--- ; finished with exception ExpectedException() + : Parent: + +--- >>; finished with value + """.strip() + self.assertEqual(expected, value) + + @greentest.ignores_leakcheck + def test_tree_no_track(self): + gevent.config.track_greenlet_tree = False + with gevent.get_hub().ignoring_expected_test_error(): + self._build_tree() + + @greentest.ignores_leakcheck + def test_forest_fake_parent(self): + from greenlet import greenlet as RawGreenlet + + def t4(): + # Ignore this one, make the child the parent, + # and don't be a child of the hub. + c = RawGreenlet(util.GreenletTree.current_tree) + c.parent.greenlet_tree_is_ignored = True + c.greenlet_tree_is_root = True + return c.switch() + + + g = RawGreenlet(t4) + tree = g.switch() + + tree_format = tree.format(details={'running_stacks': False, + 'spawning_stacks': False}) + value = self._normalize_tree_format(tree_format) + + expected = """\ +; not running + : Parent: + """.strip() + + self.assertEqual(expected, value) + + +class TestAssertSwitches(unittest.TestCase): + + def test_time_sleep(self): + # A real blocking function + from time import sleep + + # No time given, we detect the failure to switch immediately + with self.assertRaises(util._FailedToSwitch) as exc: + with util.assert_switches(): + sleep(0.001) + + message = str(exc.exception) + self.assertIn('To any greenlet in', message) + + # Supply a max blocking allowed and exceed it + with self.assertRaises(util._FailedToSwitch): + with util.assert_switches(0.001): + sleep(0.1) + + + # Supply a max blocking allowed, and exit before that happens, + # but don't switch to the hub as requested + with self.assertRaises(util._FailedToSwitch) as exc: + with util.assert_switches(0.001, hub_only=True): + sleep(0) + + message = str(exc.exception) + self.assertIn('To the hub in', message) + self.assertIn('(max allowed 0.0010 seconds)', message) + + # Supply a max blocking allowed, and exit before that happens, + # and allow any switch (or no switch). + # Note that we need to use a relatively long duration; + # sleep(0) on Windows can actually take a substantial amount of time + # sometimes (more than 0.001s) + with util.assert_switches(1.0, hub_only=False): + sleep(0) + + + def test_no_switches_no_function(self): + # No blocking time given, no switch performed: exception + with self.assertRaises(util._FailedToSwitch): + with util.assert_switches(): + pass + + # blocking time given, for all greenlets, no switch performed: nothing + with util.assert_switches(max_blocking_time=1, hub_only=False): + pass + + def test_exception_not_supressed(self): + + with self.assertRaises(NameError): + with util.assert_switches(): + raise NameError() + + def test_nested(self): + from greenlet import gettrace + with util.assert_switches() as outer: + self.assertEqual(gettrace(), outer.tracer) + self.assertIsNotNone(outer.tracer.active_greenlet) + + with util.assert_switches() as inner: + self.assertEqual(gettrace(), inner.tracer) + self.assertEqual(inner.tracer.previous_trace_function, outer.tracer) + + inner.tracer('switch', (self, self)) + + self.assertIs(self, inner.tracer.active_greenlet) + self.assertIs(self, outer.tracer.active_greenlet) + + self.assertEqual(gettrace(), outer.tracer) + + +class TestFuncs(greentest.TestCase): + + def test_clear_stack_frames(self): + import inspect + import threading + completed = [] + def do_it(): + util.clear_stack_frames(inspect.currentframe()) + completed.append(1) + t = threading.Thread(target=do_it) + t.start() + t.join(10) + self.assertEqual(completed, [1]) + +if __name__ == '__main__': + greentest.main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.crt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.crt new file mode 100644 index 0000000000000000000000000000000000000000..9fde198dc797954fa893dcbce264b79b2f4ed46a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.crt @@ -0,0 +1,29 @@ +-----BEGIN CERTIFICATE----- +MIIFCzCCAvOgAwIBAgIUFL7iwYYAfAarNFw2C0Q1zEjC4yUwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIxMDcwODExMzAwN1oYDzIxMjEw +NjE0MTEzMDA3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQC2v+TV2yx9DK78LWCLhBKl1g0AcdWi4H9LIbc30RbO +5LOnhL+FxPE9vRU1nD5Z01o7zgqJr8boNqU1oOxhOAyUZkSZwd6SeJHQvLRZQDRI +ov3QCL4nYb53T3usSlXw5MuxUql/OwvLcvPO/8FBXKmIBpfOHHxfAwA7+BU8f8ZF +aDB02sNnLlAXZc9xB1FkDNAZnM9fjWAAJbtfRcJO0l7zq8AQ/EdO6YVK6vhScf/I +ovKcMbDV3GPt8YUSlqLAuIv3rFPclDvpDdp+c96OXA3wK6YhsFBvYmzgRnoVfX8V +FQdp4vlcXsqEh9tPhvDmWvfU2xldbX50I1S9/TIucIxrksY7W9787p4lGEjJTfkF +mfo/jdNcY7GE/sHj7aVbbK753ZEWV3j7ZbO1llweI5m6Qk4nPwd/H2CHIKqRbitZ +Qg7ymGAAoCmbbXnrKI4UUrMysQgtuFYUMKstIMYO8bLAF5npVoVuMg10XxNKgBYC +o0+D/RUaTM2rQRtfcwXeIFXNxDuhvblwTTrW2xG+Z2xVENeFVFAjgqEa4YPdjtxO +A3mlldtrM5lLClvCLvcusw79RMYShC3NwMNmVTN9wdX1Vgmcf401dlXN4LCqIj51 +yIfhB7LD6ll3eAM/qK5gwPPvhz330zfWax8f0lzLRQ1r7l9IY/Y91n7KFRLDy9cD +IQIDAQABo1MwUTAdBgNVHQ4EFgQUGSmTQfHLd9mwvtfNtCJykD8F5jkwHwYDVR0j +BBgwFoAUGSmTQfHLd9mwvtfNtCJykD8F5jkwDwYDVR0TAQH/BAUwAwEB/zANBgkq +hkiG9w0BAQsFAAOCAgEAmeKcbwDzSnZhL9H4oPEzOslTEazn1vRGNTkDabGzHlO1 +b56Mw36fOKW9cPSS9By1HiB3iQipUZ6AQ9pIIBv75Z0yNPxsIqhTpDACWEx8jk/k +rhzCIMIoxURfBAKQ3Oml7U++EagyBZgQAHjGEROuRE++kUDeEy0SwIWiXmEX1OZ4 +tBbaW+Q7Gc+CPHVouOZUq8Ogt9zI98rIiT5VFPm2hBZrcguoqmqSN533HJTJVimi +vCBtkRK3YfsMsZYO0jmj8TWsTAZly3wwgMkjV4g5hLtrYOHU6sm8H32QjDcbahLG +7JCgQR5WCgfs/u2RHFysNwURf/Hq+9ieCEtSQrk4u19YvkwpZxVD9xUONaGNZvPR +ottciZKo4pGShJADtUTnkKJEOYLTgg3jSUJPQ55AzVwAJTudLEyUGPwJL1lJ4nFu +WDSSiZXqoAaD1j2CNGhkzWBT1mJEcvPTuKxDNwYzhF44B0KQSeS3vJtMibELCOZ8 +a4WuR4xFe6fleL4fqHYpjI5IWYUDfFRC8lqvWdJl4oCSMH+s0B/m/FWme3lt+7/K +Z0vOk3uvi09OLQZTTuGgcSVPoO+zzJOuhLzTdO+FzlbBHlZax/iNZQ1GYZ0gk6wY +9+gxqdVZQXy4UIhjHV2TbW8OlhVyRC1O+YN5pjyD884aYLD+JrxZXQtSlNlurcw= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.key b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.key new file mode 100644 index 0000000000000000000000000000000000000000..e6c979b398a117b99282f700dcaf42c7969877fa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/test_server.key @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC2v+TV2yx9DK78 +LWCLhBKl1g0AcdWi4H9LIbc30RbO5LOnhL+FxPE9vRU1nD5Z01o7zgqJr8boNqU1 +oOxhOAyUZkSZwd6SeJHQvLRZQDRIov3QCL4nYb53T3usSlXw5MuxUql/OwvLcvPO +/8FBXKmIBpfOHHxfAwA7+BU8f8ZFaDB02sNnLlAXZc9xB1FkDNAZnM9fjWAAJbtf +RcJO0l7zq8AQ/EdO6YVK6vhScf/IovKcMbDV3GPt8YUSlqLAuIv3rFPclDvpDdp+ +c96OXA3wK6YhsFBvYmzgRnoVfX8VFQdp4vlcXsqEh9tPhvDmWvfU2xldbX50I1S9 +/TIucIxrksY7W9787p4lGEjJTfkFmfo/jdNcY7GE/sHj7aVbbK753ZEWV3j7ZbO1 +llweI5m6Qk4nPwd/H2CHIKqRbitZQg7ymGAAoCmbbXnrKI4UUrMysQgtuFYUMKst +IMYO8bLAF5npVoVuMg10XxNKgBYCo0+D/RUaTM2rQRtfcwXeIFXNxDuhvblwTTrW +2xG+Z2xVENeFVFAjgqEa4YPdjtxOA3mlldtrM5lLClvCLvcusw79RMYShC3NwMNm +VTN9wdX1Vgmcf401dlXN4LCqIj51yIfhB7LD6ll3eAM/qK5gwPPvhz330zfWax8f +0lzLRQ1r7l9IY/Y91n7KFRLDy9cDIQIDAQABAoICAAml7+rqe1rOxJ5Dtwkmm+Vt +e5o+aE0FFTNeQFIOE+owYNvDQmlJkIL17Jy79v6/DdCCfEPwp8uytt4x9MjdMKzV +CWIkvh91hh1DGTJtFVWQZV4KWB+0JV4fMCRUeF0Tdz2RY6l38JN5Ki4PiqBsx/aK +gpE7J8XMXsLLwjNDe7BGY+iHdDGKXGgf0+ffvwhNNN9lS/17dUoMs+u/vxZyPNkY +hDdhWlJsOcFOznVr11k8YRql9PQVgqEZUzE8CrOqCpm022iV2uPe+14Zt/JEIehA +JbE5ocV/qMfecKuZyI/QYGfSt9+MkZyVn5p/QVCoFNWEC77G/Rock2jEaVXSU1dz +uxiU65WrqMdvcetZ6xzhUB/Bz3N5aevjwmFmPjMHzF4npw2xn2dejPkQ31YeIdOF +a9Z1tWq8q/UHA2RoooM2hCMJjaIwcABSemCbuFw7ZXm3YUzUFMycav9RGcQ8Q/0h +ZPZWo52eVWhQdvI7Xy+gsssBS2/bk+nPgdDDSdprt+IiB1WuL762xB5upcim+cUJ +vrx7CiDo5Fh8kJhgvSHjBCON5A/l6eg8XPX56+MBA3t0frTTub3o0tubJlYSlClF +nqoNHlXczd0vdtoMpSSaBj7N2GL3FtaWi0jbyagK0IndaouMQM8njBQoI0bTmvHg +COfd4uDg4h23jgseqmbBAoIBAQDepq2qASQpQ38qeq586a/YoD4PtZOeapjRNfGj +gnvQaSSouaLoq3dRSlKmZwE4nKnSnCKI4Ixje9Likfbdt4/I+hXODTzEy+WpmqlJ +1x4svF6MsB/YZ6r76koGK8/vgPO/w7xLGp5Xi2E5gTaH04o/PuUo/k7yx0FkSHoA +EU7WDoriH/6sgkolUL6xsmq8ljq4kHidP2UfYwzsIwngTL+jFYznzTsr6CXsTdH9 +I7ppvpS3xhFsdDp0YQyMGHdtvAdEeGz/m6cxxsnwAz0EhwN2qYJD9oNCP+uxk0zD +d1QD/XUUcMUrUxyQ1EBn2wAmcj9yYNeMNmhZYz47CowHym0tAoIBAQDSHzwCpk/M +3h5dk0yMgyRMq+flwj1P+eDOrGpmk9VmdCcvIQs1ArbW0/VMQ+lQNXgTZ74o/ccT +ABogeD1WOq3fh5PcU6wHAVD1GL1sZ6ZCP9jQXalxt0/1vooDu+LRDLNhcsFY0AJR +QfPu37beaCFjlwFf5P0lEPcTTpXBfEaqSvjA2kCys2IMeiKce36GQTy2HJBIe0py +Pj+cgxZ3/lg0vGV6SrnMXh5wPbWtsVnhQBilG7niQ15txSrgV5rUYUQPNEfIuDdS +MVjH1USbjoNAMlwYJF5Kcel9fn6neHfWqvW3bregw598iCg0Y67KbJl4iFzOqumh +lZUy1gD2P65FAoIBADA8P+dSs/jUjJoxVdft8JCntopEtiRdx5mbbCwWOqid/rkm +7molq4XK6jjum88d8ZSVCs5Ih2GOE9PN94N1HwtVUp//MikYWzrxLLe4iOr8LCei +iGOjoeFNkpffqf6jGytyRjqnG6KvqXKB0cR/SbYF9DN7VLM4A6ysHvIgzcmGAQSY +Fd5do56N7aIlmwYcLcCKW/cFIu030jbeKGeVePbl1k7poWYTtxOIkHOc5+e8yA9A +M8ohLADGfadkLYtybsigpkyB9ijMfjcnHHL8pP1yH6yFnU4e9vrThI/cLDFpGZJC +FBUcvlWKBiH5ygCKQ8CNxmSz7Mtguryjvk55xkkCggEAQuwRx+JCXkSMNU95vPLz +t7u0oxfHQVabhBej18HT4MqzxC3pDNwtcaSWZtDmWVZ+ROfwx8t0ARgyOg8xseoE +gMIElNLNYnnH2BgmFIW6jTUaj9qU4hP5UpJ6EJBhwCUkaLAM5oVxh4HS+EymSJWv +tLFejbU37vtFRg/sYHB9bTVtnrakjoXVf5XSujYW6RmUBYh5Z6xk3Jf42Jdjq5oF +a95pD5cHMBD17teoqoZm0vgAIW4AOREt3RZD/qnINUY5UAJdro8Fh5cR6KuDK2wr +X2HqtQG4SkuXixGjsyEKQgO3ONH5iCll/Vq8O1tYSz5lbt83d9c1i/JBT6ybJ9LG +ZQKCAQALlAI1Cd8swU1g5a9newXRHfkOYYlJ/CpKbvblBlc0oejEI6oJAD9ykZrE +v3/6JMojI0J7ILjGj5a1eyGtleqY1JyrO5dy/djueaHHgLQNNYBkGWbdFN99XV9s +iE1iuYthyVKXqMkbhxKcW8L1kyer/Z+o4I3LP4NfMzC9ibhPkjyg6JD2zBT1N49t +26SUApm2Icz54+HVVKHbimfVI6R9NqcVjO7TmQae5UjKeiI8xOiBcjDrtU9K5rj3 +O2IOx7mAEc08Mz8ApLo9dnY0+dmPhprJPcpZl1haAvY3CF50iYTcABbAlk1nVfoo +0OV9kUaHy/EaY8/cPeMERFc/SVZi +-----END PRIVATE KEY----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_do_leakchecks.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_do_leakchecks.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2c3623a7723cafb7a2c92f77736733c31f71a3e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_do_leakchecks.txt @@ -0,0 +1,10 @@ +test___monkey_patching.py +test__monkey_ssl_warning.py +test___monitor.py +test__monkey_scope.py +test__ares_timeout.py +test__close_backend_fd.py +test__hub_join.py +test__hub_join_timeout.py +test__issue112.py +test__issue1864.py diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_monkeypatch.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_monkeypatch.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e68c5d38f0ca7aa0df5245dfe627eb9c7116eb9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_monkeypatch.txt @@ -0,0 +1,29 @@ +test___config.py +test___ident.py +test___monitor.py +test__ares_timeout.py +test__backdoor.py +test__close_backend_fd.py +test__events.py +test__example_echoserver.py +test__example_portforwarder.py +test__example_udp_client.py +test__example_wsgiserver.py +test__example_wsgiserver_ssl.py +test__example_webproxy.py +test__examples.py +test__getaddrinfo_import.py +test__hub_join.py +test__hub_join_timeout.py +test__issue1864.py +test__issue330.py +test__iwait.py +test__monkey_scope.py +test__pywsgi.py +test__server.py +test__server_pywsgi.py +test__socket_close.py +test__socket_dns6.py +test__socket_errors.py +test__socket_send_memoryview.py +test__socket_timeout.py diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_use_resolver.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_use_resolver.txt new file mode 100644 index 0000000000000000000000000000000000000000..79a91270fd433dee6693ebc7b8d2546b4b28a480 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/tests_that_dont_use_resolver.txt @@ -0,0 +1,137 @@ +test__all__.py +#uses socket test__api.py +test__api_timeout.py +test__ares_host_result.py +test__ares_timeout.py # explicitly uses ares resolver +# uses socket test__backdoor.py +test__close_backend_fd.py +test__core_async.py +test__core_callback.py +test__core_loop_run.py +test__core.py +test__core_stat.py +test__core_timer.py +test__core_watcher.py +test__destroy.py +# uses socket test__doctests.py +test__environ.py +test__event.py +# uses socket test__example_echoserver.py +# uses socket test__example_portforwarder.py +# uses socket test__example_w*.py +# uses bunch of things test__examples.py +# uses socket test__example_udp_client.py +# uses socket test__example_udp_server.py +test__exc_info.py +#test__execmodules.py +test__fileobject.py +# uses socket test__greenio.py +test__GreenletExit.py +test__greenlet.py +test__greenletset.py +# uses socket test__greenness.py +test__hub_join.py +test__hub_join_timeout.py +# uses socket test__hub.py +test__issue112.py +test__issue1864.py +test__joinall.py +test__local.py +test__loop_callback.py +test__memleak.py +# uses lots of things test___monkey_patching.py +test__monkey.py +test__order.py +test__os.py +test__pool.py +# uses socket test__pywsgi.py +test__queue.py +test__monkey_queue.py +# uses socket test__refcount.py +test__select.py +test__semaphore.py +# uses socket test__server.py +# test__server_pywsgi.py +test__signal.py +# uses socket test__socket_close.py +# test__socket_dns6.py +# test__socket_dns.py +# test__socket_errors.py +# test__socket.py +# test__socket_ssl.py +# test__socket_timeout.py +test__subprocess_interrupted.py +test__subprocess.py +test__systemerror.py +test__threading_2.py +test__threading_patched_local.py +test__threading_vs_settrace.py +test__threadpool.py +test__timeout.py + +test__compat.py +test__core_fork.py +test__doctests.py +test__core_loop_run_sig_mod.py +test__execmodules.py +test__greenio.py +test__greenness.py +test__hub.py +test__import_blocking_in_greenlet.py +test__import_wait.py +test__issue230.py +test__issue330.py +test__issue467.py +test__issue6.py +test__issue600.py +test__issue607.py +test__issue461_471.py +test__monkey_builtins_future.py +test__monkey_hub_in_thread.py +test__monkey_logging.py +test__monkey_multiple_imports.py +test__monkey_scope.py +test__monkey_selectors.py +test__monkey_sigchld.py +test__monkey_sigchld_2.py +test__nondefaultloop.py +test__monkey_sigchld_3.py +test__real_greenlet.py +test__refcount.py +test__sleep0.py +test__subprocess_poll.py +test__threading.py +test__threading_before_monkey.py +test__threading_holding_lock_while_monkey.py +test__threading_monkey_in_thread.py +test__threading_native_before_monkey.py +test__threadpool_executor_patched.py + + +# monkey patched standard tests: +test_queue.py +test_select.py +test_signal.py +test_subprocess.py +test_threading_local.py +test_threading.py +test_thread.py +test_selectors.py +test_timeout.py + +# test_asyncore probably does use the resolver, but only +# implicitly for localhost, which is covered well enough +# elsewhere that we don't need to spend the 20s (*2) +test_asyncore.py + +test___config.py +test__destroy_default_loop.py +test__util.py +test___ident.py +test__issue639.py +test__issue_728.py +test__refcount_core.py +test__api.py +test__monitor.py +test__events.py +test__iwait.py diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/wrongcert.pem b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/wrongcert.pem new file mode 100644 index 0000000000000000000000000000000000000000..5f92f9bce765eff03e06349acd007d06da03d001 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/tests/wrongcert.pem @@ -0,0 +1,32 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQC89ZNxjTgWgq7Z1g0tJ65w+k7lNAj5IgjLb155UkUrz0XsHDnH +FlbsVUg2Xtk6+bo2UEYIzN7cIm5ImpmyW/2z0J1IDVDlvR2xJ659xrE0v5c2cB6T +f9lnNTwpSoeK24Nd7Jwq4j9vk95fLrdqsBq0/KVlsCXeixS/CaqqduXfvwIDAQAB +AoGAQFko4uyCgzfxr4Ezb4Mp5pN3Npqny5+Jey3r8EjSAX9Ogn+CNYgoBcdtFgbq +1yif/0sK7ohGBJU9FUCAwrqNBI9ZHB6rcy7dx+gULOmRBGckln1o5S1+smVdmOsW +7zUVLBVByKuNWqTYFlzfVd6s4iiXtAE2iHn3GCyYdlICwrECQQDhMQVxHd3EFbzg +SFmJBTARlZ2GKA3c1g/h9/XbkEPQ9/RwI3vnjJ2RaSnjlfoLl8TOcf0uOGbOEyFe +19RvCLXjAkEA1s+UE5ziF+YVkW3WolDCQ2kQ5WG9+ccfNebfh6b67B7Ln5iG0Sbg +ky9cjsO3jbMJQtlzAQnH1850oRD5Gi51dQJAIbHCDLDZU9Ok1TI+I2BhVuA6F666 +lEZ7TeZaJSYq34OaUYUdrwG9OdqwZ9sy9LUav4ESzu2lhEQchCJrKMn23QJAReqs +ZLHUeTjfXkVk7dHhWPWSlUZ6AhmIlA/AQ7Payg2/8wM/JkZEJEPvGVykms9iPUrv +frADRr+hAGe43IewnQJBAJWKZllPgKuEBPwoEldHNS8nRu61D7HzxEzQ2xnfj+Nk +2fgf1MAzzTRsikfGENhVsVWeqOcijWb6g5gsyCmlRpc= +-----END RSA PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIICsDCCAhmgAwIBAgIJAOqYOYFJfEEoMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMDgwNjI2MTgxNTUyWhcNMDkwNjI2MTgxNTUyWjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB +gQC89ZNxjTgWgq7Z1g0tJ65w+k7lNAj5IgjLb155UkUrz0XsHDnHFlbsVUg2Xtk6 ++bo2UEYIzN7cIm5ImpmyW/2z0J1IDVDlvR2xJ659xrE0v5c2cB6Tf9lnNTwpSoeK +24Nd7Jwq4j9vk95fLrdqsBq0/KVlsCXeixS/CaqqduXfvwIDAQABo4GnMIGkMB0G +A1UdDgQWBBTctMtI3EO9OjLI0x9Zo2ifkwIiNjB1BgNVHSMEbjBsgBTctMtI3EO9 +OjLI0x9Zo2ifkwIiNqFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUt +U3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAOqYOYFJ +fEEoMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAQwa7jya/DfhaDn7E +usPkpgIX8WCL2B1SqnRTXEZfBPPVq/cUmFGyEVRVATySRuMwi8PXbVcOhXXuocA+ +43W+iIsD9pXapCZhhOerCq18TC1dWK98vLUsoK8PMjB6e5H/O8bqojv0EeC+fyCw +eSHj5jpC8iZKjCHBn+mAi4cQ514= +-----END CERTIFICATE----- diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/thread.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..5942387dc3ed6803fb5613a7d3cfcea0b46cca18 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/thread.py @@ -0,0 +1,331 @@ +""" +Implementation of the standard :mod:`thread` module that spawns greenlets. + +.. note:: + + This module is a helper for :mod:`gevent.monkey` and is not + intended to be used directly. For spawning greenlets in your + applications, prefer higher level constructs like + :class:`gevent.Greenlet` class or :func:`gevent.spawn`. +""" +import sys + +__implements__ = [ + 'allocate_lock', + 'get_ident', + 'exit', + 'LockType', + 'stack_size', + 'start_new_thread', + '_local', +] + ([ + 'start_joinable_thread', + 'lock', + '_ThreadHandle', + '_make_thread_handle', +] if sys.version_info[:2] >= (3, 13) else [ + +]) + + +__imports__ = ['error'] + +import _thread as __thread__ # pylint:disable=import-error + +__target__ = '_thread' +__imports__ += [ + 'TIMEOUT_MAX', + 'allocate', + 'exit_thread', + 'interrupt_main', + 'start_new' +] + +# We can't actually produce a value that "may be used +# to identify this particular thread system-wide", right? +# Even if we could, I imagine people will want to pass this to +# non-Python (native) APIs, so we shouldn't mess with it. +__imports__.append('get_native_id') + +# Added to 3.12 +if hasattr(__thread__, 'daemon_threads_allowed'): + __imports__.append('daemon_threads_allowed') + +error = __thread__.error + +from gevent._compat import PYPY +from gevent._util import copy_globals +from gevent.hub import getcurrent +from gevent.hub import GreenletExit +from gevent.hub import sleep +from gevent._hub_local import get_hub_if_exists +from gevent.greenlet import Greenlet +from gevent.lock import BoundedSemaphore +from gevent.local import local as _local +from gevent.exceptions import LoopExit + + +if hasattr(__thread__, 'RLock'): + # Added in Python 3.4, backported to PyPy 2.7-7.0 + __imports__.append("RLock") + + + +def get_ident(gr=None): + if gr is None: + gr = getcurrent() + return id(gr) + + +def _start_new_greenlet(function, args=(), kwargs=None): + if kwargs is not None: + greenlet = Greenlet.spawn(function, *args, **kwargs) # pylint:disable=not-a-mapping + else: + greenlet = Greenlet.spawn(function, *args) + return greenlet + +def start_new_thread(function, args=(), kwargs=None): + return get_ident(_start_new_greenlet(function, args, kwargs)) + +def start_joinable_thread(function, handle=None, daemon=True): # pylint:disable=unused-argument + """ + *For internal use only*: start a new thread. + + Like start_new_thread(), this starts a new thread calling the given function. + Unlike start_new_thread(), this returns a handle object with methods to join + or detach the given thread. + This function is not for third-party code, please use the + `threading` module instead. During finalization the runtime will not wait for + the thread to exit if daemon is True. If handle is provided it must be a + newly created thread._ThreadHandle instance. + """ + # The above docstring is from python 3.13. + # + # _thread._ThreadHandle has: + # - readonly property `ident` + # - method is_done + # - method join + # - method _set_done - threading._shutdown calls this + # + # I have no idea what it means if you pass a provided handle, + # because you can't change the ident once created, and + # the constructor of ThreadHande takes arbitrary positional + # and keyword arguments, and throws them away. (The ident is set + # by C code directly accessing internal structure members). + greenlet = _start_new_greenlet(function) # XXX: Daemon is ignored + + if handle is not None: + assert isinstance(handle, _ThreadHandle) + handle._set_greenlet(greenlet) + + return handle + +class _ThreadHandle: + # The constructor must accept and ignore all arguments + # to match the stdlib. + def __init__(self, *_args, **_kwargs): + """Does nothing; ignores args""" + + # Must keep a weak reference to the greenlet + # to avoid problems managing the _active list of + # threads, which can sometimes rely on garbage collection. + # Also, this breaks a cycle. + _greenlet_ref = None + + def _set_greenlet(self, glet): + from weakref import ref + assert glet is not None + self._greenlet_ref = ref(glet) + + def _get_greenlet(self): + return ( + self._greenlet_ref() + if self._greenlet_ref is not None + else None + ) + + def join(self, timeout): + # TODO: This is what we patch Thread.join to do on all versions, + # so there's another implementation in gevent.monkey._patch_thread_common. + # UNIFY THEM. + glet = self._get_greenlet() + if glet is not None: + if glet is getcurrent(): + raise RuntimeError('Cannot joint current thread') + if hasattr(glet, 'join'): + return glet.join(timeout) + # working with a raw greenlet. That + # means it's probably the MainThread, because the main + # greenlet is always raw. But it could also be a dummy + from time import time + + end = None + if timeout: + end = time() + timeout + + while not self.is_done(): + if end is not None and time() > end: + return + sleep(0.001) + return None + + @property + def ident(self): + glet = self._get_greenlet() + if glet is not None: + return get_ident(glet) + return None + + def is_done(self): + glet = self._get_greenlet() + if glet is None: + return True + + return glet.dead + + def _set_done(self, enter_hub=True): + """ + Mark the thread as complete. + + This releases our reference (if any) to our greenlet. + + By default, this will bounce back to the hub so that waiters + in ``join`` can get notified. Set *enter_hub* to false not to + do this. + """ + self._greenlet_ref = None + # Let the loop go around so that anyone waiting in + # join() gets to know about it. This is particularly + # important during threading/interpreter shutdown. + if enter_hub: + sleep(0.001) + + + def __repr__(self): + return '<%s.%s at 0x%x greenlet=%r>' % ( + self.__class__.__module__, + self.__class__.__name__, + id(self), + self._get_greenlet() + ) + +def _make_thread_handle(*_args): + """ + Called on 3.13 after forking in the child. + Takes ``(module, ident)``, returns a handle object + with that ident. + """ + # The argument _should_ be a thread identifier int + handle = _ThreadHandle() + handle._set_greenlet(getcurrent()) + return handle + +class LockType(BoundedSemaphore): + """ + The basic lock type. + + .. versionchanged:: 24.10.1 + Subclassing this object is no longer allowed. This matches the + Python 3 API. + """ + # Change the ValueError into the appropriate thread error + # and any other API changes we need to make to match behaviour + _OVER_RELEASE_ERROR = __thread__.error + + if PYPY: + _OVER_RELEASE_ERROR = RuntimeError + + + _TIMEOUT_MAX = __thread__.TIMEOUT_MAX # pylint:disable=no-member + + def __init__(self): + """ + .. versionchanged:: 24.10.1 + No longer accepts arguments to pass to the super class. If you + want a semaphore with a different count, use a semaphore class directly. + This matches the Lock API of Python 3 + """ + super().__init__() + + @classmethod + def __init_subclass__(cls): + raise TypeError + + def acquire(self, blocking=True, timeout=-1): + # This is the Python 3 signature. + # On Python 2, Lock.acquire has the signature `Lock.acquire([wait])` + # where `wait` is a boolean that cannot be passed by name, only position. + # so we're fine to use the Python 3 signature. + + # Transform the default -1 argument into the None that our + # semaphore implementation expects, and raise the same error + # the stdlib implementation does. + if timeout == -1: + timeout = None + if not blocking and timeout is not None: + raise ValueError("can't specify a timeout for a non-blocking call") + if timeout is not None: + if timeout < 0: + # in C: if(timeout < 0 && timeout != -1) + raise ValueError("timeout value must be strictly positive") + if timeout > self._TIMEOUT_MAX: + raise OverflowError('timeout value is too large') + + + try: + acquired = BoundedSemaphore.acquire(self, blocking, timeout) + except LoopExit: + # Raised when the semaphore was not trivially ours, and we needed + # to block. Some other thread presumably owns the semaphore, and there are no greenlets + # running in this thread to switch to. So the best we can do is + # release the GIL and try again later. + if blocking: # pragma: no cover + raise + acquired = False + + if not acquired and not blocking and getcurrent() is not get_hub_if_exists(): + # Run other callbacks. This makes spin locks works. + # We can't do this if we're in the hub, which we could easily be: + # printing the repr of a thread checks its tstate_lock, and sometimes we + # print reprs in the hub. + # See https://github.com/gevent/gevent/issues/1464 + + # By using sleep() instead of self.wait(0), we don't force a trip + # around the event loop *unless* we've been running callbacks for + # longer than our switch interval. + sleep() + return acquired + + # Should we implement _is_owned, at least for Python 2? See notes in + # monkey.py's patch_existing_locks. + +allocate_lock = lock = LockType + + +def exit(): + raise GreenletExit + + +if hasattr(__thread__, 'stack_size'): + _original_stack_size = __thread__.stack_size + + def stack_size(size=None): + if size is None: + return _original_stack_size() + if size > _original_stack_size(): + return _original_stack_size(size) + # not going to decrease stack_size, because otherwise other + # greenlets in this thread will suffer +else: + __implements__.remove('stack_size') + +__imports__ = copy_globals(__thread__, globals(), + only_names=__imports__, + ignore_missing_names=True) + +__all__ = __implements__ + __imports__ +__all__.remove('_local') + + +# XXX interrupt_main +# XXX _count() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threading.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threading.py new file mode 100644 index 0000000000000000000000000000000000000000..7749fba2f3bf694b7ff196f44b232af356f71d85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threading.py @@ -0,0 +1,421 @@ +""" +Implementation of the standard :mod:`threading` using greenlets. + +.. note:: + + This module is a helper for :mod:`gevent.monkey` and is not + intended to be used directly. For spawning greenlets in your + applications, prefer higher level constructs like + :class:`gevent.Greenlet` class or :func:`gevent.spawn`. Attributes + in this module like ``__threading__`` are implementation artifacts subject + to change at any time. + +.. versionchanged:: 1.2.3 + + Defer adjusting the stdlib's list of active threads until we are + monkey patched. Previously this was done at import time. We are + documented to only be used as a helper for monkey patching, so this should + functionally be the same, but some applications ignore the documentation and + directly import this module anyway. + + A positive consequence is that ``import gevent.threading, + threading; threading.current_thread()`` will no longer return a DummyThread + before monkey-patching. +""" + + +import os +import sys + +__implements__ = [ + 'local', + '_allocate_lock', + 'Lock', + '_get_ident', + '_sleep', + '_DummyThread', + # RLock cannot go here, even though we need to import it. + # If it goes here, it replaces the RLock from the native + # threading module, but we really just need it here when some + # things import this module. + #'RLock', +] + ([ + '_start_new_thread', +] if sys.version_info[:2] < (3, 13) else [ + '_start_joinable_thread', + '_ThreadHandle', + '_make_thread_handle', +]) + + +__extensions__ = [ +] + + +import threading as __threading__ # imports os, sys, _thread, functools, time, itertools +_DummyThread_ = __threading__._DummyThread +_MainThread_ = __threading__._MainThread + + +from gevent.local import local +from gevent.thread import start_new_thread as _start_new_thread +from gevent.thread import start_joinable_thread +from gevent.thread import _ThreadHandle +from gevent.thread import _make_thread_handle +from gevent.thread import allocate_lock as _allocate_lock +from gevent.thread import get_ident as _get_ident +from gevent.hub import sleep as _sleep, getcurrent +from gevent.lock import RLock + + +from gevent._util import LazyOnClass + +# Exports, prevent unused import warnings. +# XXX: Why don't we use __all__? +local = local +start_new_thread = _start_new_thread +_start_joinable_thread = start_joinable_thread +_make_thread_handle = _make_thread_handle +_ThreadHandle = _ThreadHandle +allocate_lock = _allocate_lock +_get_ident = _get_ident +_sleep = _sleep +getcurrent = getcurrent + +Lock = _allocate_lock +RLock = RLock + + +def _cleanup(g): + __threading__._active.pop(_get_ident(g), None) + +def _make_cleanup_id(gid): + def _(_r): + __threading__._active.pop(gid, None) + return _ + +_weakref = None + + +class _DummyThread(_DummyThread_): + # We avoid calling the superclass constructor. This makes us about + # twice as fast: + # + # - 1.16 vs 0.68usec on PyPy (unknown version, older Intel mac) + # - 29.3 vs 17.7usec on CPython 2.7 (older intel Mac) + # - 0.98 vs 2.95usec on CPython 3.12.2 (newer M2 mac) + # + # It als has the important effect of avoiding allocation and then + # immediate deletion of _Thread__block, a lock. This is especially + # important on PyPy where locks go through the cpyext API and + # Cython, which is known to be slow and potentially buggy (e.g., + # https://bitbucket.org/pypy/pypy/issues/2149/memory-leak-for-python-subclass-of-cpyext#comment-22347393) + + # These objects are constructed quite frequently in some cases, so + # the optimization matters: for example, in gunicorn, which uses + # pywsgi.WSGIServer, most every request is handled in a new greenlet, + # and every request uses a logging.Logger to write the access log, + # and every call to a log method captures the current thread (by + # default). + # + # (Obviously we have to duplicate the effects of the constructor, + # at least for external state purposes, which is potentially + # slightly fragile.) + + # For the same reason, instances of this class will cleanup their own entry + # in ``threading._active`` + + # This class also solves a problem forking process with subprocess: after forking, + # Thread.__stop is called, which throws an exception when __block doesn't + # exist. + + # Capture the static things as class vars to save on memory/ + # construction time. + # In Py2, they're all private; in Py3, they become protected + _Thread__stopped = _is_stopped = _stopped = False + _Thread__initialized = _initialized = True + _Thread__daemonic = _daemonic = True + _Thread__args = _args = () + _Thread__kwargs = _kwargs = None + _Thread__target = _target = None + _Thread_ident = _ident = None + _Thread__started = _started = __threading__.Event() + _Thread__started.set() + _tstate_lock = None + _handle = None # 3.13 + + def __init__(self): # pylint:disable=super-init-not-called + #_DummyThread_.__init__(self) + + # It'd be nice to use a pattern like "greenlet-%d", but there are definitely + # third-party libraries checking thread names to detect DummyThread objects. + self._name = self._Thread__name = __threading__._newname("Dummy-%d") + # All dummy threads in the same native thread share the same ident + # (that of the native thread), unless we're monkey-patched. + self._set_ident() + # _handle is only needed for 3.13; keeps a weak reference + # to the greenlet. + self._handle = _make_thread_handle(self._ident) + # ``_native_id`` backs the ``native_id`` property. + self._native_id = __threading__.get_native_id() + + g = getcurrent() + gid = _get_ident(g) + __threading__._active[gid] = self + rawlink = getattr(g, 'rawlink', None) + if rawlink is not None: + # raw greenlet.greenlet greenlets don't + # have rawlink... + rawlink(_cleanup) + else: + # ... so for them we use weakrefs. + # See https://github.com/gevent/gevent/issues/918 + ref = self.__weakref_ref + ref = ref(g, _make_cleanup_id(gid)) # pylint:disable=too-many-function-args + self.__raw_ref = ref + assert self.__raw_ref is ref # prevent pylint thinking its unused + + def _Thread__stop(self): + pass + + _stop = _Thread__stop # py3 + + def _wait_for_tstate_lock(self, *args, **kwargs): # pylint:disable=signature-differs + pass + + @LazyOnClass + def __weakref_ref(self): + return __import__('weakref').ref + + # In Python 3.11.8+ and 3.12.2+ (yes, minor patch releases), + # CPython's ``threading._after_fork`` hook began swizzling the + # type of the _DummyThread into _MainThread if such a dummy thread + # was the current thread when ``os.fork()`` gets called. + # From CPython's perspective, that's a more-or-less fine thing to do. + # While _DummyThread isn't a subclass of _MainThread, they are both + # subclasses of Thread, and _MainThread doesn't add any new instance + # variables. + # + # From gevent's perspective, that's NOT good. Our _DummyThread + # doesn't have all the instance variables that Thread does, and so + # attempting to do anything with this now-fake _MainThread doesn't work. + # You in fact immediately get assertion errors from inside ``_after_fork``. + # Now, these are basically harmless --- they're printed, and they prevent the cleanup + # of some globals in _threading, but that probably doesn't matter --- but + # people complained, and it could break some test scenarios (due to unexpected + # output on stderr, for example) + # + # We thought of a few options to patch around this: + # + # - Live with the performance penalty. Newer CPythons are making it + # harder and harder to perform well, so if we can possibly avoid + # adding our own performance regressions, that would be good. + # + # - ``after_fork`` uses ``isinstance(current, _DummyThread)`` + # before swizzling, so we could use a metaclass to make that + # check return false. That's a fairly large compatibility risk, + # both because of the use of a metaclass (what if some other + # subclass of _DummyTHread is using an incompatible metaclass?) + # and the change in ``isinstance`` behaviour. We could limit the latter + # to a window around the fork, using ``os.register_at_fork(before, after_in_parent=)``, + # but that's a lot of moving pieces requiring the use of a global or class + # variable to track state. + # + # - We could copy the ivars of the current main thread into the + # _DummyThread in ``register_at_fork(before=)``. That appears to + # work, but also requires the use of + # ``register_at_fork(after_in_parent=)`` to reverse it. + # + # - We could simply prevent swizzling the class in the first + # place. In combination with + # ``register_at_fork(after_in_child=)`` to establish a *real* + # new _MainThread, that's a clean solution. Establishing a real + # new _MainThread is something that CPython itself is prepared + # to do if it can't figure out what the current thread is. The + # compatibility risk of this is relatively low: swizzling + # classes is frowned upon and uncommon, and we can limit it to + # just preventing this specific case. And if somebody was + # attempting this already with some other thread subclass, it + # would (probably?) have the exact same issues, so we can be pretty + # sure nobody is doing that. + # + # We're initially going with the last fix; the __class__ part is here, + # the ``after_in_child`` fixup we only apply if we're monkey-patching. + # + # Now, all of this is moot in 3.13, which takes a very different + # approach to handling this, and also changes some names. See + # https://github.com/python/cpython/commit/0e9c364f4ac18a2237bdbac702b96bcf8ef9cb09 + + # Tests pass just fine in 3.8 (and presumably 3.9 and 3.10) with these fixes + # applied, but just in case, we only do it where we know it's necessary. + _NEEDS_CLASS_FORK_FIXUP = ( + (sys.version_info[:2] == (3, 11) and sys.version_info[:3] >= (3, 11, 8)) + or sys.version_info[:3] >= (3, 12, 2) + ) + + if _NEEDS_CLASS_FORK_FIXUP: + # Override with a property, as opposed to using __setattr__, + # to avoid adding overhead on any other attribute setting. + @property + def __class__(self): + return type(self) + + @__class__.setter + def __class__(self, new_class): + # Even if we wanted to allow setting this, I'm not sure + # exactly how to do so when we have a property object handling it. + # Getting the descriptor from ``object.__dict__['__class__']`` + # and using its ``__set__`` method raises a TypeError (as does + # the simpler ``super().__class__``). + # + # Better allow the TypeError for now as opposed to silently ignoring + # the assignment. + if new_class is not _MainThread_: + object.__dict__['__class__'].__set__(self, new_class) + + + + + + +def main_native_thread(): + return __threading__.main_thread() # pylint:disable=no-member + + +# XXX: Issue 18808 breaks us on Python 3.4+. +# Thread objects now expect a callback from the interpreter itself +# (threadmodule.c:release_sentinel) when the C-level PyThreadState +# object is being deallocated. Because this never happens +# when a greenlet exits, join() and friends will block forever. +# Fortunately this is easy to fix: just ensure that the allocation of the +# lock, _set_sentinel, creates a *gevent* lock, and release it when +# we're done. The main _shutdown code is in Python and deals with +# this gracefully. + +class Thread(__threading__.Thread): + + # Only happens in < 3.13 + def _set_tstate_lock(self): + super(Thread, self)._set_tstate_lock() + greenlet = getcurrent() + greenlet.rawlink(self.__greenlet_finished) + + def __greenlet_finished(self, _): + if self._tstate_lock: + self._tstate_lock.release() + self._stop() + +__implements__.append('Thread') + +class Timer(Thread, __threading__.Timer): # pylint:disable=abstract-method,inherit-non-class + pass + +__implements__.append('Timer') + +_set_sentinel = allocate_lock +if sys.version_info[:2] < (3, 13): + __implements__.append('_set_sentinel') +else: + __extensions__.append('_set_sentinel') +# The main thread is patched up with more care +# in _gevent_will_monkey_patch + +__implements__.remove('_get_ident') +__implements__.append('get_ident') +get_ident = _get_ident +__implements__.remove('_sleep') + +if hasattr(__threading__, '_CRLock'): + # Python 3 changed the implementation of threading.RLock + # Previously it was a factory function around threading._RLock + # which in turn used _allocate_lock. Now, it wants to use + # threading._CRLock, which is imported from _thread.RLock and as such + # is implemented in C. So it bypasses our _allocate_lock function. + # Fortunately they left the Python fallback in place and use it + # if the imported _CRLock is None; this arranges for that to be the case. + + # This was also backported to PyPy 2.7-7.0 + _CRLock = None + __implements__.append('_CRLock') + + +class _ForkHooks: + + _before_fork_current_thread = None + _before_fork_active = None + + + def before_fork_in_parent(self): + self._before_fork_active = dict(__threading__._active) + self._before_fork_current_thread = __threading__.current_thread() + + def after_fork_in_child(self): + # We've already imported threading, which installed its "after" hook, + # so we're going to be called after that hook. + # Note that this is only installed when monkey-patching. + # TODO: Is there any point to checking to see if the current thread is + # our dummy thread before doing this? + active = __threading__._active + assert len(active) == 1 + + # We cannot actually kill the greenlets via throw(): + # - If it was the main greenlet, the process will exit + # - In any case, that would unwind the stack and execute + # code that, before 2024-10-03, would never have executed. + # + # But we can take them out of the map and make them appear + # stopped; if they truly are no longer referenced, GC will + # kick in a nd delete the greenlet. If gevent is still waiting + # to switch to them, that will still happen... + # + # This happens automatically on <= 3.12 which hardcodes the call to + # ``Thread._stop``; for 3.13, we need to go through the handle. + current_ident = get_ident() + for green_ident, thread in self._before_fork_active.items(): + if green_ident != current_ident: + try: + handle = thread._handle + except AttributeError: + assert sys.version_info[:2] < (3, 13) + assert not thread.is_alive() + else: + # We DO NOT want to bounce to the hub. We're running + # at a very sensitive time and it's best to keep tight control + # over what gets to run. + handle._set_done(enter_hub=False) + + + main = __threading__._MainThread() + main._ident = get_ident() # 3.13: reset to the greenlet version. + __threading__._active[__threading__.get_ident()] = main + __threading__._main_thread = main + + main = __threading__.main_thread() + # XXX: Not the case. Maybe don't save main. + assert main.ident == __threading__.get_ident() + + +_fork_hooks = _ForkHooks() + +def _gevent_will_monkey_patch(native_module, items, warn): # pylint:disable=unused-argument + # Make sure the MainThread can be found by our current greenlet ID, + # otherwise we get a new DummyThread, which cannot be joined. + # Fixes tests in test_threading_2 under PyPy. + main_thread = main_native_thread() + if __threading__.current_thread() != main_thread: + warn("Monkey-patching outside the main native thread. Some APIs " + "will not be available. Expect a KeyError to be printed at shutdown.") + return + + if _get_ident() not in __threading__._active: + main_id = main_thread.ident + del __threading__._active[main_id] + main_thread._ident = main_thread._Thread__ident = _get_ident() + __threading__._active[_get_ident()] = main_thread + + register_at_fork = getattr(os, 'register_at_fork', None) + if register_at_fork: + #if _DummyThread._NEEDS_CLASS_FORK_FIXUP: + register_at_fork( + before=_fork_hooks.before_fork_in_parent, + after_in_child=_fork_hooks.after_fork_in_child) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threadpool.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threadpool.py new file mode 100644 index 0000000000000000000000000000000000000000..afbc8680f6a5c17788e408336989bce9c5edb375 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/threadpool.py @@ -0,0 +1,819 @@ +# Copyright (c) 2012 Denis Bilenko. See LICENSE for details. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys + + +from greenlet import greenlet as RawGreenlet + +from gevent import monkey +from gevent._compat import integer_types +from gevent.event import AsyncResult +from gevent.exceptions import InvalidThreadUseError +from gevent.greenlet import Greenlet + +from gevent._hub_local import get_hub_if_exists +from gevent.hub import _get_hub_noargs as get_hub +from gevent.hub import getcurrent +from gevent.hub import sleep +from gevent.lock import Semaphore +from gevent.pool import GroupMappingMixin +from gevent.util import clear_stack_frames + +from gevent._threading import Queue +from gevent._threading import EmptyTimeout +from gevent._threading import start_new_thread +from gevent._threading import get_thread_ident + + +__all__ = [ + 'ThreadPool', + 'ThreadResult', +] + +def _format_hub(hub): + if hub is None: + return '' + return '<%s at 0x%x thread_ident=0x%x>' % ( + hub.__class__.__name__, id(hub), hub.thread_ident + ) + + +def _get_thread_profile(_sys=sys): + if 'threading' in _sys.modules: + return _sys.modules['threading']._profile_hook + + +def _get_thread_trace(_sys=sys): + if 'threading' in _sys.modules: + return _sys.modules['threading']._trace_hook + + +class _WorkerGreenlet(RawGreenlet): + # Exists to produce a more useful repr for worker pool + # threads/greenlets, and manage the communication of the worker + # thread with the threadpool. + + # Inform the gevent.util.GreenletTree that this should be + # considered the root (for printing purposes) + greenlet_tree_is_root = True + + _thread_ident = 0 + _exc_info = sys.exc_info + _get_hub_if_exists = staticmethod(get_hub_if_exists) + # We capture the hub each time through the loop in case its created + # so we can destroy it after a fork. + _hub_of_worker = None + # The hub of the threadpool we're working for. Just for info. + _hub = None + + # A cookie passed to task_queue.get() + _task_queue_cookie = None + + # If not -1, how long to block waiting for a task before we + # exit. + _idle_task_timeout = -1 + + def __init__(self, threadpool): + # Construct in the main thread (owner of the threadpool) + # The parent greenlet and thread identifier will be set once the + # new thread begins running. + RawGreenlet.__init__(self) + + self._hub = threadpool.hub + # Avoid doing any imports in the background thread if it's not + # necessary (monkey.get_original imports if not patched). + # Background imports can hang Python 2 (gevent's thread resolver runs in the BG, + # and resolving may have to import the idna module, which needs an import lock, so + # resolving at module scope) + if monkey.is_module_patched('sys'): + stderr = monkey.get_original('sys', 'stderr') + else: + stderr = sys.stderr + self._stderr = stderr + # We can capture the task_queue; even though it can change if the threadpool + # is re-innitted, we won't be running in that case + self._task_queue = threadpool.task_queue # type:gevent._threading.Queue + self._task_queue_cookie = self._task_queue.allocate_cookie() + self._unregister_worker = threadpool._unregister_worker + self._idle_task_timeout = threadpool._idle_task_timeout + + threadpool._register_worker(self) + try: + start_new_thread(self._begin, ()) + except: + self._unregister_worker(self) + raise + + def _begin(self, _get_c=getcurrent, _get_ti=get_thread_ident): + # Pass arguments to avoid accessing globals during module shutdown. + + # we're in the new thread (but its root greenlet). Establish invariants and get going + # by making this the current greenlet. + self.parent = _get_c() # pylint:disable=attribute-defined-outside-init + self._thread_ident = _get_ti() + # ignore the parent attribute. (We can't set parent to None.) + self.parent.greenlet_tree_is_ignored = True + try: + self.switch() # goto run() + except: # pylint:disable=bare-except + # run() will attempt to print any exceptions, but that might + # not work during shutdown. sys.excepthook and such may be gone, + # so things might not get printed at all except for a cryptic + # message. This is especially true on Python 2 (doesn't seem to be + # an issue on Python 3). + pass + + def __fixup_hub_before_block(self): + hub = self._get_hub_if_exists() # Don't create one; only set if a worker function did it + if hub is not None: + hub.name = 'ThreadPool Worker Hub' + # While we block, don't let the monitoring thread, if any, + # report us as blocked. Indeed, so long as we never + # try to switch greenlets, don't report us as blocked--- + # the threadpool is *meant* to run blocking tasks + if hub is not None and hub.periodic_monitoring_thread is not None: + hub.periodic_monitoring_thread.ignore_current_greenlet_blocking() + self._hub_of_worker = hub + + @staticmethod + def __print_tb(tb, stderr): + # Extracted from traceback to avoid accessing any module + # globals (these sometimes happen during interpreter shutdown; + # see test__subprocess_interrupted) + while tb is not None: + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + print(' File "%s", line %d, in %s' % (filename, lineno, name), + file=stderr) + tb = tb.tb_next + + def _before_run_task(self, func, args, kwargs, thread_result, + _sys=sys, + _get_thread_profile=_get_thread_profile, + _get_thread_trace=_get_thread_trace): + # pylint:disable=unused-argument + _sys.setprofile(_get_thread_profile()) + _sys.settrace(_get_thread_trace()) + + def _after_run_task(self, func, args, kwargs, thread_result, _sys=sys): + # pylint:disable=unused-argument + _sys.setprofile(None) + _sys.settrace(None) + + def __run_task(self, func, args, kwargs, thread_result): + self._before_run_task(func, args, kwargs, thread_result) + try: + thread_result.set(func(*args, **kwargs)) + except: # pylint:disable=bare-except + thread_result.handle_error((self, func), self._exc_info()) + finally: + self._after_run_task(func, args, kwargs, thread_result) + del func, args, kwargs, thread_result + + def run(self): + # pylint:disable=too-many-branches + task = None + exc_info = sys.exc_info + fixup_hub_before_block = self.__fixup_hub_before_block + task_queue_get = self._task_queue.get + task_queue_cookie = self._task_queue_cookie + run_task = self.__run_task + task_queue_done = self._task_queue.task_done + idle_task_timeout = self._idle_task_timeout + try: # pylint:disable=too-many-nested-blocks + while 1: # tiny bit faster than True on Py2 + fixup_hub_before_block() + + try: + task = task_queue_get(task_queue_cookie, idle_task_timeout) + except EmptyTimeout: + # Nothing to do, exit the thread. Do not + # go into the next block where we would call + # queue.task_done(), because we didn't actually + # take a task. + return + try: + if task is None: + return + + run_task(*task) + except: + task = repr(task) + raise + finally: + task = None if not isinstance(task, str) else task + task_queue_done() + except Exception as e: # pylint:disable=broad-except + print( + "Failed to run worker thread. Task=%r Exception=%r" % ( + task, e + ), + file=self._stderr) + self.__print_tb(exc_info()[-1], self._stderr) + finally: + # Re-check for the hub in case the task created it but then + # failed. + self.cleanup(self._get_hub_if_exists()) + + def cleanup(self, hub_of_worker): + if self._hub is not None: + self._hub = None + self._unregister_worker(self) + self._unregister_worker = lambda _: None + self._task_queue = None + self._task_queue_cookie = None + + if hub_of_worker is not None: + hub_of_worker.destroy(True) + + def __repr__(self, _format_hub=_format_hub): + return "" % ( + id(self), + self._thread_ident, + _format_hub(self._hub) + ) + + +class ThreadPool(GroupMappingMixin): + """ + A pool of native worker threads. + + This can be useful for CPU intensive functions, or those that + otherwise will not cooperate with gevent. The best functions to execute + in a thread pool are small functions with a single purpose; ideally they release + the CPython GIL. Such functions are extension functions implemented in C. + + It implements the same operations as a :class:`gevent.pool.Pool`, + but using threads instead of greenlets. + + .. note:: The method :meth:`apply_async` will always return a new + greenlet, bypassing the threadpool entirely. + + Most users will not need to create instances of this class. Instead, + use the threadpool already associated with gevent's hub:: + + pool = gevent.get_hub().threadpool + result = pool.spawn(lambda: "Some func").get() + + .. important:: It is only possible to use instances of this class from + the thread running their hub. Typically that means from the thread that + created them. Using the pattern shown above takes care of this. + + There is no gevent-provided way to have a single process-wide limit on the + number of threads in various pools when doing that, however. The suggested + way to use gevent and threadpools is to have a single gevent hub + and its one threadpool (which is the default without doing any extra work). + Only dispatch minimal blocking functions to the threadpool, functions that + do not use the gevent hub. + + The `len` of instances of this class is the number of enqueued + (unfinished) tasks. + + Just before a task starts running in a worker thread, + the values of :func:`threading.setprofile` and :func:`threading.settrace` + are consulted. Any values there are installed in that thread for the duration + of the task (using :func:`sys.setprofile` and :func:`sys.settrace`, respectively). + (Because worker threads are long-lived and outlast any given task, this arrangement + lets the hook functions change between tasks, but does not let them see the + bookkeeping done by the worker thread itself.) + + .. caution:: Instances of this class are only true if they have + unfinished tasks. + + .. versionchanged:: 1.5a3 + The undocumented ``apply_e`` function, deprecated since 1.1, + was removed. + .. versionchanged:: 20.12.0 + Install the profile and trace functions in the worker thread while + the worker thread is running the supplied task. + .. versionchanged:: 22.08.0 + Add the option to let idle threads expire and be removed + from the pool after *idle_task_timeout* seconds (-1 for no + timeout) + """ + + __slots__ = ( + 'hub', + '_maxsize', + # A Greenlet that runs to adjust the number of worker + # threads. + 'manager', + # The PID of the process we were created in. + # Used to help detect a fork and then re-create + # internal state. + 'pid', + 'fork_watcher', + # A semaphore initialized with ``maxsize`` counting the + # number of available worker threads we have. As a + # gevent.lock.Semaphore, this is only safe to use from a single + # native thread. + '_available_worker_threads_greenlet_sem', + # A set of running or pending _WorkerGreenlet objects; + # we rely on the GIL for thread safety. + '_worker_greenlets', + # The task queue is itself safe to use from multiple + # native threads. + 'task_queue', + '_idle_task_timeout', + ) + + _WorkerGreenlet = _WorkerGreenlet + + def __init__(self, maxsize, hub=None, idle_task_timeout=-1): + if hub is None: + hub = get_hub() + self.hub = hub + self.pid = os.getpid() + self.manager = None + self.task_queue = Queue() + self.fork_watcher = None + self._idle_task_timeout = idle_task_timeout + + self._worker_greenlets = set() + self._maxsize = 0 + # Note that by starting with 1, we actually allow + # maxsize + 1 tasks in the queue. + self._available_worker_threads_greenlet_sem = Semaphore(1, hub) + self._set_maxsize(maxsize) + self.fork_watcher = hub.loop.fork(ref=False) + + def _register_worker(self, worker): + self._worker_greenlets.add(worker) + + def _unregister_worker(self, worker): + self._worker_greenlets.discard(worker) + + def _set_maxsize(self, maxsize): + if not isinstance(maxsize, integer_types): + raise TypeError('maxsize must be integer: %r' % (maxsize, )) + if maxsize < 0: + raise ValueError('maxsize must not be negative: %r' % (maxsize, )) + difference = maxsize - self._maxsize + self._available_worker_threads_greenlet_sem.counter += difference + self._maxsize = maxsize + self.adjust() + # make sure all currently blocking spawn() start unlocking if maxsize increased + self._available_worker_threads_greenlet_sem._start_notify() + + def _get_maxsize(self): + return self._maxsize + + maxsize = property(_get_maxsize, _set_maxsize, doc="""\ + The maximum allowed number of worker threads. + + This is also (approximately) a limit on the number of tasks that + can be queued without blocking the waiting greenlet. If this many + tasks are already running, then the next greenlet that submits a task + will block waiting for a task to finish. + """) + + def __repr__(self, _format_hub=_format_hub): + return '<%s at 0x%x tasks=%s size=%s maxsize=%s hub=%s>' % ( + self.__class__.__name__, + id(self), + len(self), self.size, self.maxsize, + _format_hub(self.hub), + ) + + def __len__(self): + # XXX just do unfinished_tasks property + # Note that this becomes the boolean value of this class, + # that's probably not what we want! + return self.task_queue.unfinished_tasks + + def _get_size(self): + return len(self._worker_greenlets) + + def _set_size(self, size): + if size < 0: + raise ValueError('Size of the pool cannot be negative: %r' % (size, )) + if size > self._maxsize: + raise ValueError('Size of the pool cannot be bigger than maxsize: %r > %r' % (size, self._maxsize)) + if self.manager: + self.manager.kill() + while len(self._worker_greenlets) < size: + self._add_thread() + delay = self.hub.loop.approx_timer_resolution + while len(self._worker_greenlets) > size: + while len(self._worker_greenlets) - size > self.task_queue.unfinished_tasks: + self.task_queue.put(None) + if getcurrent() is self.hub: + break + sleep(delay) + delay = min(delay * 2, .05) + if self._worker_greenlets: + self.fork_watcher.start(self._on_fork) + else: + self.fork_watcher.stop() + + size = property(_get_size, _set_size, doc="""\ + The number of running pooled worker threads. + + Setting this attribute will add or remove running + worker threads, up to `maxsize`. + + Initially there are no pooled running worker threads, and + threads are created on demand to satisfy concurrent + requests up to `maxsize` threads. + """) + + + def _on_fork(self): + # fork() only leaves one thread; also screws up locks; + # let's re-create locks and threads, and do our best to + # clean up any worker threads left behind. + # NOTE: See comment in gevent.hub.reinit. + pid = os.getpid() + if pid != self.pid: + # The OS threads have been destroyed, but the Python + # objects may live on, creating refcount "leaks". Python 2 + # leaves dead frames (those that are for dead OS threads) + # around; Python 3.8 does not. + thread_ident_to_frame = dict(sys._current_frames()) + for worker in list(self._worker_greenlets): + frame = thread_ident_to_frame.get(worker._thread_ident) + clear_stack_frames(frame) + worker.cleanup(worker._hub_of_worker) + # We can't throw anything to the greenlet, nor can we + # switch to it or set a parent. Those would all be cross-thread + # operations, which aren't allowed. + worker.__dict__.clear() + + # We've cleared f_locals and on Python 3.4, possibly the actual + # array locals of the stack frame, but the task queue may still be + # referenced if we didn't actually get all the locals. Shut it down + # and clear it before we throw away our reference. + self.task_queue.kill() + self.__init__(self._maxsize) + + + def join(self): + """Waits until all outstanding tasks have been completed.""" + delay = max(0.0005, self.hub.loop.approx_timer_resolution) + while self.task_queue.unfinished_tasks > 0: + sleep(delay) + delay = min(delay * 2, .05) + + def kill(self): + self.size = 0 + self.fork_watcher.close() + + def _adjust_step(self): + # if there is a possibility & necessity for adding a thread, do it + while (len(self._worker_greenlets) < self._maxsize + and self.task_queue.unfinished_tasks > len(self._worker_greenlets)): + self._add_thread() + # while the number of threads is more than maxsize, kill one + # we do not check what's already in task_queue - it could be all Nones + while len(self._worker_greenlets) - self._maxsize > self.task_queue.unfinished_tasks: + self.task_queue.put(None) + if self._worker_greenlets: + self.fork_watcher.start(self._on_fork) + elif self.fork_watcher is not None: + self.fork_watcher.stop() + + def _adjust_wait(self): + delay = self.hub.loop.approx_timer_resolution + while True: + self._adjust_step() + if len(self._worker_greenlets) <= self._maxsize: + return + sleep(delay) + delay = min(delay * 2, .05) + + def adjust(self): + self._adjust_step() + if not self.manager and len(self._worker_greenlets) > self._maxsize: + # might need to feed more Nones into the pool to shutdown + # threads. + self.manager = Greenlet.spawn(self._adjust_wait) + + def _add_thread(self): + self._WorkerGreenlet(self) + + def spawn(self, func, *args, **kwargs): + """ + Add a new task to the threadpool that will run ``func(*args, + **kwargs)``. + + Waits until a slot is available. Creates a new native thread + if necessary. + + This must only be called from the native thread that owns this + object's hub. This is because creating the necessary data + structures to communicate back to this thread isn't thread + safe, so the hub must not be running something else. Also, + ensuring the pool size stays correct only works within a + single thread. + + :return: A :class:`gevent.event.AsyncResult`. + :raises InvalidThreadUseError: If called from a different thread. + + .. versionchanged:: 1.5 + Document the thread-safety requirements. + """ + if self.hub != get_hub(): + raise InvalidThreadUseError + + while 1: + semaphore = self._available_worker_threads_greenlet_sem + semaphore.acquire() + if semaphore is self._available_worker_threads_greenlet_sem: + # If we were asked to change size or re-init we could have changed + # semaphore objects. + break + + # Returned; lets a greenlet in this thread wait + # for the pool thread. Signaled when the async watcher + # is fired from the pool thread back into this thread. + result = AsyncResult() + task_queue = self.task_queue + # Encapsulates the async watcher the worker thread uses to + # call back into this thread. Immediately allocates and starts the + # async watcher in this thread, because it uses this hub/loop, + # which is not thread safe. + thread_result = None + try: + thread_result = ThreadResult(result, self.hub, semaphore.release) + task_queue.put((func, args, kwargs, thread_result)) + self.adjust() + except: + if thread_result is not None: + thread_result.destroy_in_main_thread() + semaphore.release() + raise + return result + + def _apply_immediately(self): + # If we're being called from a different thread than the one that + # created us, e.g., because a worker task is trying to use apply() + # recursively, we have no choice but to run the task immediately; + # if we try to AsyncResult.get() in the worker thread, it's likely to have + # nothing to switch to and lead to a LoopExit. + return get_hub() is not self.hub + + def _apply_async_cb_spawn(self, callback, result): + callback(result) + + def _apply_async_use_greenlet(self): + # Always go to Greenlet because our self.spawn uses threads + return True + +class _FakeAsync(object): + + def send(self): + pass + close = stop = send + + def __call__(self, result): + "fake out for 'receiver'" + + def __bool__(self): + return False + + __nonzero__ = __bool__ + +_FakeAsync = _FakeAsync() + +class ThreadResult(object): + """ + A one-time event for cross-thread communication. + + Uses a hub's "async" watcher capability; it must be constructed and + destroyed in the thread running the hub (because creating, starting, and + destroying async watchers isn't guaranteed to be thread safe). + """ + + # Using slots here helps to debug reference cycles/leaks + __slots__ = ('exc_info', 'async_watcher', '_call_when_ready', 'value', + 'context', 'hub', 'receiver') + + def __init__(self, receiver, hub, call_when_ready): + self.receiver = receiver + self.hub = hub + self.context = None + self.value = None + self.exc_info = () + self.async_watcher = hub.loop.async_() + self._call_when_ready = call_when_ready + self.async_watcher.start(self._on_async) + + @property + def exception(self): + return self.exc_info[1] if self.exc_info else None + + def _on_async(self): + # Called in the hub thread. + + aw = self.async_watcher + self.async_watcher = _FakeAsync + + aw.stop() + aw.close() + + # Typically this is pool.semaphore.release and we have to + # call this in the Hub; if we don't we get the dreaded + # LoopExit (XXX: Why?) + try: + self._call_when_ready() + if self.exc_info: + self.hub.handle_error(self.context, *self.exc_info) + self.context = None + self.async_watcher = _FakeAsync + self.hub = None + self._call_when_ready = _FakeAsync + + self.receiver(self) + finally: + self.receiver = _FakeAsync + self.value = None + if self.exc_info: + self.exc_info = (self.exc_info[0], self.exc_info[1], None) + + def destroy_in_main_thread(self): + """ + This must only be called from the thread running the hub. + """ + self.async_watcher.stop() + self.async_watcher.close() + self.async_watcher = _FakeAsync + + self.context = None + self.hub = None + self._call_when_ready = _FakeAsync + self.receiver = _FakeAsync + + def set(self, value): + self.value = value + self.async_watcher.send() + + def handle_error(self, context, exc_info): + self.context = context + self.exc_info = exc_info + self.async_watcher.send() + + # link protocol: + def successful(self): + return self.exception is None + + +try: + import concurrent.futures +except ImportError: + pass +else: + __all__.append("ThreadPoolExecutor") + + from gevent.timeout import Timeout as GTimeout + from gevent._util import Lazy + from concurrent.futures import _base as cfb + + def _ignore_error(future_proxy, fn): + def cbwrap(_): + del _ + # We're called with the async result (from the threadpool), but + # be sure to pass in the user-visible _FutureProxy object.. + try: + fn(future_proxy) + except Exception: # pylint: disable=broad-except + # Just print, don't raise to the hub's parent. + future_proxy.hub.print_exception((fn, future_proxy), None, None, None) + return cbwrap + + def _wrap(future_proxy, fn): + def f(_): + fn(future_proxy) + return f + + class _FutureProxy(object): + def __init__(self, asyncresult): + self.asyncresult = asyncresult + + # Internal implementation details of a c.f.Future + + @Lazy + def _condition(self): + if monkey.is_module_patched('threading') or self.done(): + import threading + return threading.Condition() + # We can only properly work with conditions + # when we've been monkey-patched. This is necessary + # for the wait/as_completed module functions. + raise AttributeError("_condition") + + @Lazy + def _waiters(self): + self.asyncresult.rawlink(self.__when_done) + return [] + + def __when_done(self, _): + # We should only be called when _waiters has + # already been accessed. + waiters = getattr(self, '_waiters') + for w in waiters: # pylint:disable=not-an-iterable + if self.successful(): + w.add_result(self) + else: + w.add_exception(self) + + @property + def _state(self): + if self.done(): + return cfb.FINISHED + return cfb.RUNNING + + def set_running_or_notify_cancel(self): + # Does nothing, not even any consistency checks. It's + # meant to be internal to the executor and we don't use it. + return + + def result(self, timeout=None): + try: + return self.asyncresult.result(timeout=timeout) + except GTimeout: + # XXX: Theoretically this could be a completely + # unrelated timeout instance. Do we care about that? + raise concurrent.futures.TimeoutError() + + def exception(self, timeout=None): + try: + self.asyncresult.get(timeout=timeout) + return self.asyncresult.exception + except GTimeout: + raise concurrent.futures.TimeoutError() + + def add_done_callback(self, fn): + """Exceptions raised by *fn* are ignored.""" + if self.done(): + fn(self) + else: + self.asyncresult.rawlink(_ignore_error(self, fn)) + + def rawlink(self, fn): + self.asyncresult.rawlink(_wrap(self, fn)) + + def __str__(self): + return str(self.asyncresult) + + def __getattr__(self, name): + return getattr(self.asyncresult, name) + + class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor): + """ + A version of :class:`concurrent.futures.ThreadPoolExecutor` that + always uses native threads, even when threading is monkey-patched. + + The ``Future`` objects returned from this object can be used + with gevent waiting primitives like :func:`gevent.wait`. + + .. caution:: If threading is *not* monkey-patched, then the ``Future`` + objects returned by this object are not guaranteed to work with + :func:`~concurrent.futures.as_completed` and :func:`~concurrent.futures.wait`. + The individual blocking methods like :meth:`~concurrent.futures.Future.result` + and :meth:`~concurrent.futures.Future.exception` will always work. + + .. versionadded:: 1.2a1 + This is a provisional API. + """ + + def __init__(self, *args, **kwargs): + """ + Takes the same arguments as ``concurrent.futures.ThreadPoolExecuter``, which + vary between Python versions. + + The first argument is always *max_workers*, the maximum number of + threads to use. Most other arguments, while accepted, are ignored. + """ + super(ThreadPoolExecutor, self).__init__(*args, **kwargs) + self._threadpool = ThreadPool(self._max_workers) + + def submit(self, fn, *args, **kwargs): # pylint:disable=arguments-differ + with self._shutdown_lock: # pylint:disable=not-context-manager + if self._shutdown: + raise RuntimeError('cannot schedule new futures after shutdown') + + future = self._threadpool.spawn(fn, *args, **kwargs) + return _FutureProxy(future) + + def shutdown(self, wait=True, **kwargs): # pylint:disable=arguments-differ + # In 3.9, this added ``cancel_futures=False`` + super(ThreadPoolExecutor, self).shutdown(wait, **kwargs) + # XXX: We don't implement wait properly + kill = getattr(self._threadpool, 'kill', None) + if kill: # pylint:disable=using-constant-test + self._threadpool.kill() + self._threadpool = None + + kill = shutdown # greentest compat + + def _adjust_thread_count(self): + # Does nothing. We don't want to spawn any "threads", + # let the threadpool handle that. + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/time.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/time.py new file mode 100644 index 0000000000000000000000000000000000000000..34abf85e28ce5f6193d827173e2cd089bb472973 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/time.py @@ -0,0 +1,27 @@ +# Copyright (c) 2018 gevent. See LICENSE for details. +""" +The standard library :mod:`time` module, but :func:`sleep` is +gevent-aware. + +.. versionadded:: 1.3a2 +""" + +from __future__ import absolute_import + +__implements__ = [ + 'sleep', +] + +__all__ = __implements__ + +import time as __time__ + +from gevent._util import copy_globals + +__imports__ = copy_globals(__time__, globals(), + names_to_ignore=__implements__) + + + +from gevent.hub import sleep +sleep = sleep # pylint diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/timeout.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..bf60ed12bef842cc5f92b213c79e2ef34647e263 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/timeout.py @@ -0,0 +1,401 @@ +# Copyright (c) 2009-2010 Denis Bilenko. See LICENSE for details. +""" +Timeouts. + +Many functions in :mod:`gevent` have a *timeout* argument that allows +limiting the time the function will block. When that is not available, +the :class:`Timeout` class and :func:`with_timeout` function in this +module add timeouts to arbitrary code. + +.. warning:: + + Timeouts can only work when the greenlet switches to the hub. + If a blocking function is called or an intense calculation is ongoing during + which no switches occur, :class:`Timeout` is powerless. +""" +from __future__ import absolute_import, print_function, division + +from gevent._compat import string_types +from gevent._util import _NONE + +from greenlet import getcurrent +from gevent._hub_local import get_hub_noargs as get_hub + +__all__ = [ + 'Timeout', + 'with_timeout', +] + + +class _FakeTimer(object): + # An object that mimics the API of get_hub().loop.timer, but + # without allocating any native resources. This is useful for timeouts + # that will never expire. + # Also partially mimics the API of Timeout itself for use in _start_new_or_dummy + + # This object is used as a singleton, so it should be + # immutable. + __slots__ = () + + @property + def pending(self): + return False + + active = pending + + @property + def seconds(self): + "Always returns None" + + timer = exception = seconds + + def start(self, *args, **kwargs): + # pylint:disable=unused-argument + raise AssertionError("non-expiring timer cannot be started") + + def stop(self): + return + + cancel = stop + + stop = close = cancel + + def __enter__(self): + return self + + def __exit__(self, _t, _v, _tb): + return + +_FakeTimer = _FakeTimer() + + +class Timeout(BaseException): + """ + Timeout(seconds=None, exception=None, ref=True, priority=-1) + + Raise *exception* in the current greenlet after *seconds* + have elapsed:: + + timeout = Timeout(seconds, exception) + timeout.start() + try: + ... # exception will be raised here, after *seconds* passed since start() call + finally: + timeout.close() + + .. warning:: + + You must **always** call `close` on a ``Timeout`` object you have created, + whether or not the code that the timeout was protecting finishes + executing before the timeout elapses (whether or not the + ``Timeout`` exception is raised) This ``try/finally`` + construct or a ``with`` statement is a good pattern. (If + the timeout object will be started again, use `cancel` instead + of `close`; this is rare. You must still `close` it when you are + done.) + + When *exception* is omitted or ``None``, the ``Timeout`` instance + itself is raised:: + + >>> import gevent + >>> gevent.Timeout(0.1).start() + >>> gevent.sleep(0.2) #doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + Timeout: 0.1 seconds + + If the *seconds* argument is not given or is ``None`` (e.g., + ``Timeout()``), then the timeout will never expire and never raise + *exception*. This is convenient for creating functions which take + an optional timeout parameter of their own. (Note that this is **not** + the same thing as a *seconds* value of ``0``.) + + :: + + def function(args, timeout=None): + "A function with an optional timeout." + timer = Timeout(timeout) + with timer: + ... + + .. caution:: + + A *seconds* value less than ``0.0`` (e.g., ``-1``) is poorly defined. In the future, + support for negative values is likely to do the same thing as a value + of ``None`` or ``0`` + + A *seconds* value of ``0`` requests that the event loop spin and poll for I/O; + it will immediately expire as soon as control returns to the event loop. + + .. rubric:: Use As A Context Manager + + To simplify starting and canceling timeouts, the ``with`` + statement can be used:: + + with gevent.Timeout(seconds, exception) as timeout: + pass # ... code block ... + + This is equivalent to the try/finally block above with one + additional feature: if *exception* is the literal ``False``, the + timeout is still raised, but the context manager suppresses it, so + the code outside the with-block won't see it. + + This is handy for adding a timeout to the functions that don't + support a *timeout* parameter themselves:: + + data = None + with gevent.Timeout(5, False): + data = mysock.makefile().readline() + if data is None: + ... # 5 seconds passed without reading a line + else: + ... # a line was read within 5 seconds + + .. caution:: + + If ``readline()`` above catches and doesn't re-raise + :exc:`BaseException` (for example, with a bare ``except:``), then + your timeout will fail to function and control won't be returned + to you when you expect. + + .. rubric:: Catching Timeouts + + When catching timeouts, keep in mind that the one you catch may + not be the one you have set (a calling function may have set its + own timeout); if you going to silence a timeout, always check that + it's the instance you need:: + + timeout = Timeout(1) + timeout.start() + try: + ... + except Timeout as t: + if t is not timeout: + raise # not my timeout + finally: + timeout.close() + + + .. versionchanged:: 1.1b2 + + If *seconds* is not given or is ``None``, no longer allocate a + native timer object that will never be started. + + .. versionchanged:: 1.1 + + Add warning about negative *seconds* values. + + .. versionchanged:: 1.3a1 + + Timeout objects now have a :meth:`close` + method that *must* be called when the timeout will no longer be + used to properly clean up native resources. + The ``with`` statement does this automatically. + + .. versionchanged:: 24.10.1 + + Timeout values can be compared to be less than an integer value, + or to be less than other timeouts, e.g., ``Timeout(0) < 1`` is true. + Timeouts are not absolutely ordered and support no other comparisons; this + is purely for convenience and may be removed or altered in the future. + + """ + + # We inherit a __dict__ from BaseException, so __slots__ actually + # makes us larger. + + def __init__(self, seconds=None, exception=None, ref=True, priority=-1, + _one_shot=False): + BaseException.__init__(self) + self.seconds = seconds + self.exception = exception + self._one_shot = _one_shot + if seconds is None: + # Avoid going through the timer codepath if no timeout is + # desired; this avoids some CFFI interactions on PyPy that can lead to a + # RuntimeError if this implementation is used during an `import` statement. See + # https://bitbucket.org/pypy/pypy/issues/2089/crash-in-pypy-260-linux64-with-gevent-11b1 + # and https://github.com/gevent/gevent/issues/618. + # Plus, in general, it should be more efficient + + self.timer = _FakeTimer + else: + # XXX: A timer <= 0 could cause libuv to block the loop; we catch + # that case in libuv/loop.py + self.timer = get_hub().loop.timer(seconds or 0.0, ref=ref, priority=priority) + + def start(self): + """Schedule the timeout.""" + if self.pending: + raise AssertionError('%r is already started; to restart it, cancel it first' % self) + + if self.seconds is None: + # "fake" timeout (never expires) + return + + if self.exception is None or self.exception is False or isinstance(self.exception, string_types): + # timeout that raises self + throws = self + else: + # regular timeout with user-provided exception + throws = self.exception + + # Make sure the timer updates the current time so that we don't + # expire prematurely. + self.timer.start(self._on_expiration, getcurrent(), throws, update=True) + + def _on_expiration(self, prev_greenlet, ex): + # Hook for subclasses. + prev_greenlet.throw(ex) + + @classmethod + def start_new(cls, timeout=None, exception=None, ref=True, _one_shot=False): + """Create a started :class:`Timeout`. + + This is a shortcut, the exact action depends on *timeout*'s type: + + * If *timeout* is a :class:`Timeout`, then call its :meth:`start` method + if it's not already begun. + * Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as + arguments, then call its :meth:`start` method. + + Returns the :class:`Timeout` instance. + """ + if isinstance(timeout, Timeout): + if not timeout.pending: + timeout.start() + return timeout + timeout = cls(timeout, exception, ref=ref, _one_shot=_one_shot) + timeout.start() + return timeout + + @staticmethod + def _start_new_or_dummy(timeout, exception=None, ref=True): + # Internal use only in 1.1 + # Return an object with a 'cancel' method; if timeout is None, + # this will be a shared instance object that does nothing. Otherwise, + # return an actual Timeout. A 0 value is allowed and creates a real Timeout. + + # Because negative values are hard to reason about, + # and are often used as sentinels in Python APIs, in the future it's likely + # that a negative timeout will also return the shared instance. + # This saves the previously common idiom of + # 'timer = Timeout.start_new(t) if t is not None else None' + # followed by 'if timer is not None: timer.cancel()'. + # That idiom was used to avoid any object allocations. + + # A staticmethod is slightly faster under CPython, compared to a classmethod; + # under PyPy in synthetic benchmarks it makes no difference. + if timeout is None: + return _FakeTimer + return Timeout.start_new(timeout, exception, ref, _one_shot=True) + + @property + def pending(self): + """True if the timeout is scheduled to be raised.""" + return self.timer.pending or self.timer.active + + def cancel(self): + """ + If the timeout is pending, cancel it. Otherwise, do nothing. + + The timeout object can be :meth:`started ` again. If + you will not start the timeout again, you should use + :meth:`close` instead. + """ + self.timer.stop() + if self._one_shot: + self.close() + + def close(self): + """ + Close the timeout and free resources. The timer cannot be started again + after this method has been used. + """ + self.timer.stop() + self.timer.close() + self.timer = _FakeTimer + + def __repr__(self): + classname = type(self).__name__ + if self.pending: + pending = ' pending' + else: + pending = '' + if self.exception is None: + exception = '' + else: + exception = ' exception=%r' % self.exception + return '<%s at %s seconds=%s%s%s>' % (classname, hex(id(self)), self.seconds, exception, pending) + + def __str__(self): + """ + >>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + Timeout + """ + if self.seconds is None: + return '' + + suffix = '' if self.seconds == 1 else 's' + + if self.exception is None: + return '%s second%s' % (self.seconds, suffix) + if self.exception is False: + return '%s second%s (silent)' % (self.seconds, suffix) + return '%s second%s: %s' % (self.seconds, suffix, self.exception) + + def __enter__(self): + """ + Start and return the timer. If the timer is already started, just return it. + """ + if not self.pending: + self.start() + return self + + def __exit__(self, typ, value, tb): + """ + Stop the timer. + + .. versionchanged:: 1.3a1 + The underlying native timer is also stopped. This object cannot be + used again. + """ + self.close() + if value is self and self.exception is False: + return True # Suppress the exception + + def __lt__(self, other): + """ + For convenience, timeouts can be compared to integers (numbers) + based on their seconds value. + """ + try: + return self.seconds < other.seconds + except AttributeError: + try: + return self.seconds < other + except TypeError: + return NotImplemented + +def with_timeout(seconds, function, *args, **kwds): + """Wrap a call to *function* with a timeout; if the called + function fails to return before the timeout, cancel it and return a + flag value, provided by *timeout_value* keyword argument. + + If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`. + + Keyword argument *timeout_value* is not passed to *function*. + """ + timeout_value = kwds.pop("timeout_value", _NONE) + timeout = Timeout.start_new(seconds, _one_shot=True) + try: + try: + return function(*args, **kwds) + except Timeout as ex: + if ex is timeout and timeout_value is not _NONE: + return timeout_value + raise + finally: + timeout.cancel() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/util.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/util.py new file mode 100644 index 0000000000000000000000000000000000000000..8744846a22063714f358df9ea8bf035c15785a4b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/util.py @@ -0,0 +1,667 @@ +# Copyright (c) 2009 Denis Bilenko. See LICENSE for details. +""" +Low-level utilities. +""" + +from __future__ import absolute_import, print_function, division + +import functools +import pprint +import sys +import traceback + +from greenlet import getcurrent + +from gevent._compat import perf_counter +from gevent._compat import PYPY +from gevent._compat import thread_mod_name +from gevent._util import _NONE + +__all__ = [ + 'format_run_info', + 'print_run_info', + 'GreenletTree', + 'wrap_errors', + 'assert_switches', +] + +# PyPy is very slow at formatting stacks +# for some reason. +_STACK_LIMIT = 20 if PYPY else None + + +def _noop(): + return None + +def _ready(): + return False + +class wrap_errors(object): + """ + Helper to make function return an exception, rather than raise it. + + Because every exception that is unhandled by greenlet will be logged, + it is desirable to prevent non-error exceptions from leaving a greenlet. + This can done with a simple ``try/except`` construct:: + + def wrapped_func(*args, **kwargs): + try: + return func(*args, **kwargs) + except (TypeError, ValueError, AttributeError) as ex: + return ex + + This class provides a shortcut to write that in one line:: + + wrapped_func = wrap_errors((TypeError, ValueError, AttributeError), func) + + It also preserves ``__str__`` and ``__repr__`` of the original function. + """ + # QQQ could also support using wrap_errors as a decorator + + def __init__(self, errors, func): + """ + Calling this makes a new function from *func*, such that it catches *errors* (an + :exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and + return it as a value. + """ + self.__errors = errors + self.__func = func + # Set __doc__, __wrapped__, etc, especially useful on Python 3. + functools.update_wrapper(self, func) + + def __call__(self, *args, **kwargs): + func = self.__func + try: + return func(*args, **kwargs) + except self.__errors as ex: + return ex + + def __str__(self): + return str(self.__func) + + def __repr__(self): + return repr(self.__func) + + def __getattr__(self, name): + return getattr(self.__func, name) + + +def print_run_info(thread_stacks=True, greenlet_stacks=True, limit=_NONE, file=None): + """ + Call `format_run_info` and print the results to *file*. + + If *file* is not given, `sys.stderr` will be used. + + .. versionadded:: 1.3b1 + """ + lines = format_run_info(thread_stacks=thread_stacks, + greenlet_stacks=greenlet_stacks, + limit=limit) + file = sys.stderr if file is None else file + for l in lines: + print(l, file=file) + + +def format_run_info(thread_stacks=True, + greenlet_stacks=True, + limit=_NONE, + current_thread_ident=None): + """ + format_run_info(thread_stacks=True, greenlet_stacks=True, limit=None) -> [str] + + Request information about the running threads of the current process. + + This is a debugging utility. Its output has no guarantees other than being + intended for human consumption. + + :keyword bool thread_stacks: If true, then include the stacks for + running threads. + :keyword bool greenlet_stacks: If true, then include the stacks for + running greenlets. (Spawning stacks will always be printed.) + Setting this to False can reduce the output volume considerably + without reducing the overall information if *thread_stacks* is true + and you can associate a greenlet to a thread (using ``thread_ident`` + printed values). + :keyword int limit: If given, passed directly to `traceback.format_stack`. + If not given, this defaults to the whole stack under CPython, and a + smaller stack under PyPy. + + :return: A sequence of text lines detailing the stacks of running + threads and greenlets. (One greenlet will duplicate one thread, + the current thread and greenlet. If there are multiple running threads, + the stack for the current greenlet may be incorrectly duplicated in multiple + greenlets.) + Extra information about + :class:`gevent.Greenlet` object will also be returned. + + .. versionadded:: 1.3a1 + .. versionchanged:: 1.3a2 + Renamed from ``dump_stacks`` to reflect the fact that this + prints additional information about greenlets, including their + spawning stack, parent, locals, and any spawn tree locals. + .. versionchanged:: 1.3b1 + Added the *thread_stacks*, *greenlet_stacks*, and *limit* params. + """ + if current_thread_ident is None: + from gevent import monkey + current_thread_ident = monkey.get_original(thread_mod_name, 'get_ident')() + + lines = [] + + limit = _STACK_LIMIT if limit is _NONE else limit + _format_thread_info(lines, thread_stacks, limit, current_thread_ident) + _format_greenlet_info(lines, greenlet_stacks, limit) + return lines + + +def is_idle_threadpool_worker(frame): + return frame.f_locals and frame.f_locals.get('gevent_threadpool_worker_idle') + + +def _format_thread_info(lines, thread_stacks, limit, current_thread_ident): + import threading + + threads = {th.ident: th for th in threading.enumerate()} + lines.append('*' * 80) + lines.append('* Threads') + + thread = None + frame = None + for thread_ident, frame in sys._current_frames().items(): + do_stacks = thread_stacks + lines.append("*" * 80) + thread = threads.get(thread_ident) + name = None + if not thread: + # Is it an idle threadpool thread? thread pool threads + # don't have a Thread object, they're low-level + if is_idle_threadpool_worker(frame): + name = 'idle threadpool worker' + do_stacks = False + else: + name = thread.name + if getattr(thread, 'gevent_monitoring_thread', None): + name = repr(thread.gevent_monitoring_thread()) + if current_thread_ident == thread_ident: + name = '%s) (CURRENT' % (name,) + lines.append('Thread 0x%x (%s)\n' % (thread_ident, name)) + if do_stacks: + lines.append(''.join(traceback.format_stack(frame, limit))) + elif not thread_stacks: + lines.append('\t...stack elided...') + + # We may have captured our own frame, creating a reference + # cycle, so clear it out. + del thread + del frame + del lines + del threads + +def _format_greenlet_info(lines, greenlet_stacks, limit): + # Use the gc module to inspect all objects to find the greenlets + # since there isn't a global registry + lines.append('*' * 80) + lines.append('* Greenlets') + lines.append('*' * 80) + for tree in sorted(GreenletTree.forest(), + key=lambda t: '' if t.is_current_tree else repr(t.greenlet)): + lines.append("---- Thread boundary") + lines.extend(tree.format_lines(details={ + # greenlets from other threads tend to have their current + # frame just match our current frame, which is not helpful, + # so don't render their stack. + 'running_stacks': greenlet_stacks if tree.is_current_tree else False, + 'running_stack_limit': limit, + })) + + del lines + +dump_stacks = format_run_info + +def _line(f): + @functools.wraps(f) + def w(self, *args, **kwargs): + r = f(self, *args, **kwargs) + self.lines.append(r) + + return w + +class _TreeFormatter(object): + UP_AND_RIGHT = '+' + HORIZONTAL = '-' + VERTICAL = '|' + VERTICAL_AND_RIGHT = '+' + DATA = ':' + + label_space = 1 + horiz_width = 3 + indent = 1 + + def __init__(self, details, depth=0): + self.lines = [] + self.depth = depth + self.details = details + if not details: + self.child_data = lambda *args, **kwargs: None + + def deeper(self): + return type(self)(self.details, self.depth + 1) + + @_line + def node_label(self, text): + return text + + @_line + def child_head(self, label, right=VERTICAL_AND_RIGHT): + return ( + ' ' * self.indent + + right + + self.HORIZONTAL * self.horiz_width + + ' ' * self.label_space + + label + ) + + def last_child_head(self, label): + return self.child_head(label, self.UP_AND_RIGHT) + + @_line + def child_tail(self, line, vertical=VERTICAL): + return ( + ' ' * self.indent + + vertical + + ' ' * self.horiz_width + + line + ) + + def last_child_tail(self, line): + return self.child_tail(line, vertical=' ' * len(self.VERTICAL)) + + @_line + def child_data(self, data, data_marker=DATA): # pylint:disable=method-hidden + return (( + ' ' * self.indent + + (data_marker if not self.depth else ' ') + + ' ' * self.horiz_width + + ' ' * self.label_space + + data + ),) + + def last_child_data(self, data): + return self.child_data(data, ' ') + + def child_multidata(self, data): + # Remove embedded newlines + for l in data.splitlines(): + self.child_data(l) + + +class GreenletTree(object): + """ + Represents a tree of greenlets. + + In gevent, the *parent* of a greenlet is usually the hub, so this + tree is primarily arganized along the *spawning_greenlet* dimension. + + This object has a small str form showing this hierarchy. The `format` + method can output more details. The exact output is unspecified but is + intended to be human readable. + + Use the `forest` method to get the root greenlet trees for + all threads, and the `current_tree` to get the root greenlet tree for + the current thread. + """ + + #: The greenlet this tree represents. + greenlet = None + + #: Is this tree the root for the current thread? + is_current_tree = False + + def __init__(self, greenlet): + self.greenlet = greenlet + self.child_trees = [] + + def add_child(self, tree): + if tree is self: + return + self.child_trees.append(tree) + + @property + def root(self): + return self.greenlet.parent is None + + def __getattr__(self, name): + return getattr(self.greenlet, name) + + DEFAULT_DETAILS = { + 'running_stacks': True, + 'running_stack_limit': _STACK_LIMIT, + 'spawning_stacks': True, + 'locals': True, + } + + def format_lines(self, details=True): + """ + Return a sequence of lines for the greenlet tree. + + :keyword bool details: If true (the default), + then include more informative details in the output. + """ + if not isinstance(details, dict): + if not details: + details = {} + else: + details = self.DEFAULT_DETAILS.copy() + else: + params = details + details = self.DEFAULT_DETAILS.copy() + details.update(params) + tree = _TreeFormatter(details, depth=0) + lines = [l[0] if isinstance(l, tuple) else l + for l in self._render(tree)] + return lines + + def format(self, details=True): + """ + Like `format_lines` but returns a string. + """ + lines = self.format_lines(details) + return '\n'.join(lines) + + def __str__(self): + return self.format(False) + + # Prior to greenlet 3.0rc1, getting tracebacks of inactive + # greenlets could crash on Python 3.12. So we added a + # version-based setting here to disable it. That's fixed in the + # 3.0 final releases, but appears to be back with Python 3.12.1; + # this is likely related to https://github.com/python-greenlet/greenlet/issues/388 + #_SUPPORTS_TRACEBACK = sys.version_info[:3] < (3, 12, 1) + _SUPPORTS_TRACEBACK = True + + @classmethod + def __render_tb(cls, tree, label, frame, limit): + tree.child_data(label) + + if cls._SUPPORTS_TRACEBACK: + tb = ''.join(traceback.format_stack(frame, limit)) + else: + tb = '' + tree.child_multidata(tb) + + @staticmethod + def __spawning_parent(greenlet): + return (getattr(greenlet, 'spawning_greenlet', None) or _noop)() + + def __render_locals(self, tree): + # Defer the import to avoid cycles + from gevent.local import all_local_dicts_for_greenlet + + gr_locals = all_local_dicts_for_greenlet(self.greenlet) + if gr_locals: + tree.child_data("Greenlet Locals:") + for (kind, idl), vals in gr_locals: + if not vals: + continue # not set in this greenlet; ignore it. + tree.child_data(" Local %s at %s" % (kind, hex(idl))) + tree.child_multidata(" " + pprint.pformat(vals)) + + def _render(self, tree): + label = repr(self.greenlet) + if not self.greenlet: # Not running or dead + # raw greenlets do not have ready + if getattr(self.greenlet, 'ready', _ready)(): + label += '; finished' + if self.greenlet.value is not None: + label += ' with value ' + repr(self.greenlet.value)[:30] + elif getattr(self.greenlet, 'exception', None) is not None: + label += ' with exception ' + repr(self.greenlet.exception) + else: + label += '; not running' + tree.node_label(label) + + tree.child_data('Parent: ' + repr(self.greenlet.parent)) + + if getattr(self.greenlet, 'gevent_monitoring_thread', None) is not None: + tree.child_data('Monitoring Thread:' + repr(self.greenlet.gevent_monitoring_thread())) + + if self.greenlet and tree.details and tree.details['running_stacks']: + self.__render_tb(tree, 'Running:', self.greenlet.gr_frame, + tree.details['running_stack_limit']) + + + spawning_stack = getattr(self.greenlet, 'spawning_stack', None) + if spawning_stack and tree.details and tree.details['spawning_stacks']: + # We already placed a limit on the spawning stack when we captured it. + self.__render_tb(tree, 'Spawned at:', spawning_stack, None) + + spawning_parent = self.__spawning_parent(self.greenlet) + tree_locals = getattr(self.greenlet, 'spawn_tree_locals', None) + if tree_locals and tree_locals is not getattr(spawning_parent, 'spawn_tree_locals', None): + tree.child_data('Spawn Tree Locals') + tree.child_multidata(pprint.pformat(tree_locals)) + + self.__render_locals(tree) + try: + self.__render_children(tree) + except RuntimeError: # pragma: no cover + # If the tree is exceptionally deep, we can hit the recursion error. + # Usually it's several levels down so we can make a print call. + # This came up in test__semaphore before TestSemaphoreFair + # was fixed. + print("When rendering children", *sys.exc_info()) + return tree.lines + + def __render_children(self, tree): + children = sorted(self.child_trees, + key=lambda c: ( + # raw greenlets first. Note that we could be accessing + # minimal_ident for a hub from a different thread, which isn't + # technically thread safe. + getattr(c, 'minimal_ident', -1), + # running greenlets next + getattr(c, 'ready', _ready)(), + id(c.parent))) + for n, child in enumerate(children): + child_tree = child._render(tree.deeper()) + + head = tree.child_head + tail = tree.child_tail + data = tree.child_data + + if n == len(children) - 1: + # last child does not get the line drawn + head = tree.last_child_head + tail = tree.last_child_tail + data = tree.last_child_data + + head(child_tree.pop(0)) + for child_data in child_tree: + if isinstance(child_data, tuple): + data(child_data[0]) + else: + tail(child_data) + + return tree.lines + + + @staticmethod + def _root_greenlet(greenlet): + while greenlet.parent is not None and not getattr(greenlet, 'greenlet_tree_is_root', False): + greenlet = greenlet.parent + return greenlet + + @classmethod + def _forest(cls): + from gevent._greenlet_primitives import get_reachable_greenlets + main_greenlet = cls._root_greenlet(getcurrent()) + + trees = {} # greenlet -> GreenletTree + roots = {} # root greenlet -> GreenletTree + current_tree = roots[main_greenlet] = trees[main_greenlet] = cls(main_greenlet) + current_tree.is_current_tree = True + + root_greenlet = cls._root_greenlet + glets = get_reachable_greenlets() + + for ob in glets: + spawn_parent = cls.__spawning_parent(ob) + + if spawn_parent is None: + # spawn parent is dead, or raw greenlet. + # reparent under the root. + spawn_parent = root_greenlet(ob) + + if spawn_parent is root_greenlet(spawn_parent) and spawn_parent not in roots: + assert spawn_parent not in trees + trees[spawn_parent] = roots[spawn_parent] = cls(spawn_parent) + + + try: + parent_tree = trees[spawn_parent] + except KeyError: # pragma: no cover + parent_tree = trees[spawn_parent] = cls(spawn_parent) + + try: + # If the child also happened to be a spawning parent, + # we could have seen it before; the reachable greenlets + # are in no particular order. + child_tree = trees[ob] + except KeyError: + trees[ob] = child_tree = cls(ob) + parent_tree.add_child(child_tree) + + return roots, current_tree + + @classmethod + def forest(cls): + """ + forest() -> sequence + + Return a sequence of `GreenletTree`, one for each running + native thread. + """ + + return list(cls._forest()[0].values()) + + @classmethod + def current_tree(cls): + """ + current_tree() -> GreenletTree + + Returns the `GreenletTree` for the current thread. + """ + return cls._forest()[1] + +class _FailedToSwitch(AssertionError): + pass + +class assert_switches(object): + """ + A context manager for ensuring a block of code switches greenlets. + + This performs a similar function as the :doc:`monitoring thread + `, but the scope is limited to the body of the with + statement. If the code within the body doesn't yield to the hub + (and doesn't raise an exception), then upon exiting the + context manager an :exc:`AssertionError` will be raised. + + This is useful in unit tests and for debugging purposes. + + :keyword float max_blocking_time: If given, the body is allowed + to block for up to this many fractional seconds before + an error is raised. + :keyword bool hub_only: If True, then *max_blocking_time* only + refers to the amount of time spent between switches into the + hub. If False, then it refers to the maximum time between + *any* switches. If *max_blocking_time* is not given, has no + effect. + + Example:: + + # This will always raise an exception: nothing switched + with assert_switches(): + pass + + # This will never raise an exception; nothing switched, + # but it happened very fast + with assert_switches(max_blocking_time=1.0): + pass + + .. versionadded:: 1.3 + + .. versionchanged:: 1.4 + If an exception is raised, it now includes information about + the duration of blocking and the parameters of this object. + """ + + hub = None + tracer = None + _entered = None + + + def __init__(self, max_blocking_time=None, hub_only=False): + self.max_blocking_time = max_blocking_time + self.hub_only = hub_only + + def __enter__(self): + from gevent import get_hub + from gevent import _tracer + + self.hub = hub = get_hub() + + # TODO: We could optimize this to use the GreenletTracer + # installed by the monitoring thread, if there is one. + # As it is, we will chain trace calls back to it. + if not self.max_blocking_time: + self.tracer = _tracer.GreenletTracer() + elif self.hub_only: + self.tracer = _tracer.HubSwitchTracer(hub, self.max_blocking_time) + else: + self.tracer = _tracer.MaxSwitchTracer(hub, self.max_blocking_time) + + self._entered = perf_counter() + self.tracer.monitor_current_greenlet_blocking() + return self + + def __exit__(self, t, v, tb): + self.tracer.kill() + hub = self.hub; self.hub = None + tracer = self.tracer; self.tracer = None + + # Only check if there was no exception raised, we + # don't want to hide anything + if t is not None: + return + + + did_block = tracer.did_block_hub(hub) + if did_block: + execution_time_s = perf_counter() - self._entered + active_greenlet = did_block[1] + report_lines = tracer.did_block_hub_report(hub, active_greenlet, {}) + + message = 'To the hub' if self.hub_only else 'To any greenlet' + message += ' in %.4f seconds' % (execution_time_s,) + max_block = self.max_blocking_time + message += ' (max allowed %.4f seconds)' % (max_block,) if max_block else '' + message += '\n' + message += '\n'.join(report_lines) + raise _FailedToSwitch(message) + + +def clear_stack_frames(frame): + """Do our best to clear local variables in all frames in a stack.""" + # On Python 3, frames have a .clear() method that can raise a RuntimeError. + while frame is not None: + try: + frame.clear() + except (RuntimeError, AttributeError): + pass + try: + frame.f_locals.clear() + except AttributeError: + # Python 3.13 removed clear(); + # f_locals is now a FrameLocalsProxy. + pass + frame = frame.f_back diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/win32util.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/win32util.py new file mode 100644 index 0000000000000000000000000000000000000000..7158d693e719eda1cb2478c3c0a8453d6cc6e6e8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/win32util.py @@ -0,0 +1,98 @@ +# Copyright (c) 2001-2007 Twisted Matrix Laboratories. +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +"""Error formatting function for Windows. + +The code is taken from twisted.python.win32 module. +""" + +from __future__ import absolute_import +import os + + +__all__ = ['formatError'] + + +class _ErrorFormatter(object): + """ + Formatter for Windows error messages. + + @ivar winError: A callable which takes one integer error number argument + and returns an L{exceptions.WindowsError} instance for that error (like + L{ctypes.WinError}). + + @ivar formatMessage: A callable which takes one integer error number + argument and returns a C{str} giving the message for that error (like + L{win32api.FormatMessage}). + + @ivar errorTab: A mapping from integer error numbers to C{str} messages + which correspond to those errors (like L{socket.errorTab}). + """ + def __init__(self, WinError, FormatMessage, errorTab): + self.winError = WinError + self.formatMessage = FormatMessage + self.errorTab = errorTab + + @classmethod + def fromEnvironment(cls): + """ + Get as many of the platform-specific error translation objects as + possible and return an instance of C{cls} created with them. + """ + try: + from ctypes import WinError + except ImportError: + WinError = None + try: + from win32api import FormatMessage + except ImportError: + FormatMessage = None + try: + from socket import errorTab + except ImportError: + errorTab = None + return cls(WinError, FormatMessage, errorTab) + + def formatError(self, errorcode): + """ + Returns the string associated with a Windows error message, such as the + ones found in socket.error. + + Attempts direct lookup against the win32 API via ctypes and then + pywin32 if available), then in the error table in the socket module, + then finally defaulting to C{os.strerror}. + + @param errorcode: the Windows error code + @type errorcode: C{int} + + @return: The error message string + @rtype: C{str} + """ + if self.winError is not None: + return str(self.winError(errorcode)) + if self.formatMessage is not None: + return self.formatMessage(errorcode) + if self.errorTab is not None: + result = self.errorTab.get(errorcode) + if result is not None: + return result + return os.strerror(errorcode) + +formatError = _ErrorFormatter.fromEnvironment().formatError diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/git/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..486010e17af37a8eefe18551cf88fb2ea51d72ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/__init__.py @@ -0,0 +1,300 @@ +# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors +# +# This module is part of GitPython and is released under the +# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ + +# @PydevCodeAnalysisIgnore + +__all__ = [ + "Actor", + "AmbiguousObjectName", + "BadName", + "BadObject", + "BadObjectType", + "BaseIndexEntry", + "Blob", + "BlobFilter", + "BlockingLockFile", + "CacheError", + "CheckoutError", + "CommandError", + "Commit", + "Diff", + "DiffConstants", + "DiffIndex", + "Diffable", + "FetchInfo", + "Git", + "GitCmdObjectDB", + "GitCommandError", + "GitCommandNotFound", + "GitConfigParser", + "GitDB", + "GitError", + "HEAD", + "Head", + "HookExecutionError", + "INDEX", + "IndexEntry", + "IndexFile", + "IndexObject", + "InvalidDBRoot", + "InvalidGitRepositoryError", + "List", # Deprecated - import this from `typing` instead. + "LockFile", + "NULL_TREE", + "NoSuchPathError", + "ODBError", + "Object", + "Optional", # Deprecated - import this from `typing` instead. + "ParseError", + "PathLike", + "PushInfo", + "RefLog", + "RefLogEntry", + "Reference", + "Remote", + "RemoteProgress", + "RemoteReference", + "Repo", + "RepositoryDirtyError", + "RootModule", + "RootUpdateProgress", + "Sequence", # Deprecated - import from `typing`, or `collections.abc` in 3.9+. + "StageType", + "Stats", + "Submodule", + "SymbolicReference", + "TYPE_CHECKING", # Deprecated - import this from `typing` instead. + "Tag", + "TagObject", + "TagReference", + "Tree", + "TreeModifier", + "Tuple", # Deprecated - import this from `typing` instead. + "Union", # Deprecated - import this from `typing` instead. + "UnmergedEntriesError", + "UnsafeOptionError", + "UnsafeProtocolError", + "UnsupportedOperation", + "UpdateProgress", + "WorkTreeRepositoryUnsupported", + "refresh", + "remove_password_if_present", + "rmtree", + "safe_decode", + "to_hex_sha", +] + +__version__ = '3.1.46' + +from typing import Any, List, Optional, Sequence, TYPE_CHECKING, Tuple, Union + +if TYPE_CHECKING: + from types import ModuleType + +import warnings + +from gitdb.util import to_hex_sha + +from git.exc import ( + AmbiguousObjectName, + BadName, + BadObject, + BadObjectType, + CacheError, + CheckoutError, + CommandError, + GitCommandError, + GitCommandNotFound, + GitError, + HookExecutionError, + InvalidDBRoot, + InvalidGitRepositoryError, + NoSuchPathError, + ODBError, + ParseError, + RepositoryDirtyError, + UnmergedEntriesError, + UnsafeOptionError, + UnsafeProtocolError, + UnsupportedOperation, + WorkTreeRepositoryUnsupported, +) +from git.types import PathLike + +try: + from git.compat import safe_decode # @NoMove + from git.config import GitConfigParser # @NoMove + from git.objects import ( # @NoMove + Blob, + Commit, + IndexObject, + Object, + RootModule, + RootUpdateProgress, + Submodule, + TagObject, + Tree, + TreeModifier, + UpdateProgress, + ) + from git.refs import ( # @NoMove + HEAD, + Head, + RefLog, + RefLogEntry, + Reference, + RemoteReference, + SymbolicReference, + Tag, + TagReference, + ) + from git.diff import ( # @NoMove + INDEX, + NULL_TREE, + Diff, + DiffConstants, + DiffIndex, + Diffable, + ) + from git.db import GitCmdObjectDB, GitDB # @NoMove + from git.cmd import Git # @NoMove + from git.repo import Repo # @NoMove + from git.remote import FetchInfo, PushInfo, Remote, RemoteProgress # @NoMove + from git.index import ( # @NoMove + BaseIndexEntry, + BlobFilter, + CheckoutError, + IndexEntry, + IndexFile, + StageType, + # NOTE: This tells type checkers what util resolves to. We delete it, and it is + # really resolved by __getattr__, which warns. See below on what to use instead. + util, + ) + from git.util import ( # @NoMove + Actor, + BlockingLockFile, + LockFile, + Stats, + remove_password_if_present, + rmtree, + ) +except GitError as _exc: + raise ImportError("%s: %s" % (_exc.__class__.__name__, _exc)) from _exc + + +def _warned_import(message: str, fullname: str) -> "ModuleType": + import importlib + + warnings.warn(message, DeprecationWarning, stacklevel=3) + return importlib.import_module(fullname) + + +def _getattr(name: str) -> Any: + # TODO: If __version__ is made dynamic and lazily fetched, put that case right here. + + if name == "util": + return _warned_import( + "The expression `git.util` and the import `from git import util` actually " + "reference git.index.util, and not the git.util module accessed in " + '`from git.util import XYZ` or `sys.modules["git.util"]`. This potentially ' + "confusing behavior is currently preserved for compatibility, but may be " + "changed in the future and should not be relied on.", + fullname="git.index.util", + ) + + for names, prefix in ( + ({"head", "log", "reference", "symbolic", "tag"}, "git.refs"), + ({"base", "fun", "typ"}, "git.index"), + ): + if name not in names: + continue + + fullname = f"{prefix}.{name}" + + return _warned_import( + f"{__name__}.{name} is a private alias of {fullname} and subject to " + f"immediate removal. Use {fullname} instead.", + fullname=fullname, + ) + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +if not TYPE_CHECKING: + # NOTE: The expression `git.util` gives git.index.util and `from git import util` + # imports git.index.util, NOT git.util. It may not be feasible to change this until + # the next major version, to avoid breaking code inadvertently relying on it. + # + # - If git.index.util *is* what you want, use (or import from) that, to avoid + # confusion. + # + # - To use the "real" git.util module, write `from git.util import ...`, or if + # necessary access it as `sys.modules["git.util"]`. + # + # Note also that `import git.util` technically imports the "real" git.util... but + # the *expression* `git.util` after doing so is still git.index.util! + # + # (This situation differs from that of other indirect-submodule imports that are + # unambiguously non-public and subject to immediate removal. Here, the public + # git.util module, though different, makes less discoverable that the expression + # `git.util` refers to a non-public attribute of the git module.) + # + # This had originally come about by a wildcard import. Now that all intended imports + # are explicit, the intuitive but potentially incompatible binding occurs due to the + # usual rules for Python submodule bindings. So for now we replace that binding with + # git.index.util, delete that, and let __getattr__ handle it and issue a warning. + # + # For the same runtime behavior, it would be enough to forgo importing util, and + # delete util as created naturally; __getattr__ would behave the same. But type + # checkers would not know what util refers to when accessed as an attribute of git. + del util + + # This is "hidden" to preserve static checking for undefined/misspelled attributes. + __getattr__ = _getattr + +# { Initialize git executable path + +GIT_OK = None + + +def refresh(path: Optional[PathLike] = None) -> None: + """Convenience method for setting the git executable path. + + :param path: + Optional path to the Git executable. If not absolute, it is resolved + immediately, relative to the current directory. + + :note: + The `path` parameter is usually omitted and cannot be used to specify a custom + command whose location is looked up in a path search on each call. See + :meth:`Git.refresh ` for details on how to achieve this. + + :note: + This calls :meth:`Git.refresh ` and sets other global + configuration according to the effect of doing so. As such, this function should + usually be used instead of using :meth:`Git.refresh ` or + :meth:`FetchInfo.refresh ` directly. + + :note: + This function is called automatically, with no arguments, at import time. + """ + global GIT_OK + GIT_OK = False + + if not Git.refresh(path=path): + return + if not FetchInfo.refresh(): # noqa: F405 + return # type: ignore[unreachable] + + GIT_OK = True + + +try: + refresh() +except Exception as _exc: + raise ImportError("Failed to initialize: {0}".format(_exc)) from _exc + +# } END initialize git executable path diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/git/cmd.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..15d7820df5dbbc0b4693b7367883ebb9eb7af23e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/cmd.py @@ -0,0 +1,1741 @@ +# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors +# +# This module is part of GitPython and is released under the +# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ + +from __future__ import annotations + +__all__ = ["GitMeta", "Git"] + +import contextlib +import io +import itertools +import logging +import os +import re +import signal +import subprocess +from subprocess import DEVNULL, PIPE, Popen +import sys +from textwrap import dedent +import threading +import warnings + +from git.compat import defenc, force_bytes, safe_decode +from git.exc import ( + CommandError, + GitCommandError, + GitCommandNotFound, + UnsafeOptionError, + UnsafeProtocolError, +) +from git.util import ( + cygpath, + expand_path, + is_cygwin_git, + patch_env, + remove_password_if_present, + stream_copy, +) + +# typing --------------------------------------------------------------------------- + +from typing import ( + Any, + AnyStr, + BinaryIO, + Callable, + Dict, + IO, + Iterator, + List, + Mapping, + Optional, + Sequence, + TYPE_CHECKING, + TextIO, + Tuple, + Union, + cast, + overload, +) + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +from git.types import Literal, PathLike, TBD + +if TYPE_CHECKING: + from git.diff import DiffIndex + from git.repo.base import Repo + +# --------------------------------------------------------------------------------- + +execute_kwargs = { + "istream", + "with_extended_output", + "with_exceptions", + "as_process", + "output_stream", + "stdout_as_string", + "kill_after_timeout", + "with_stdout", + "universal_newlines", + "shell", + "env", + "max_chunk_size", + "strip_newline_in_stdout", +} + +_logger = logging.getLogger(__name__) + + +# ============================================================================== +## @name Utilities +# ------------------------------------------------------------------------------ +# Documentation +## @{ + + +def handle_process_output( + process: "Git.AutoInterrupt" | Popen, + stdout_handler: Union[ + None, + Callable[[AnyStr], None], + Callable[[List[AnyStr]], None], + Callable[[bytes, "Repo", "DiffIndex"], None], + ], + stderr_handler: Union[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None]], + finalizer: Union[None, Callable[[Union[Popen, "Git.AutoInterrupt"]], None]] = None, + decode_streams: bool = True, + kill_after_timeout: Union[None, float] = None, +) -> None: + R"""Register for notifications to learn that process output is ready to read, and + dispatch lines to the respective line handlers. + + This function returns once the finalizer returns. + + :param process: + :class:`subprocess.Popen` instance. + + :param stdout_handler: + f(stdout_line_string), or ``None``. + + :param stderr_handler: + f(stderr_line_string), or ``None``. + + :param finalizer: + f(proc) - wait for proc to finish. + + :param decode_streams: + Assume stdout/stderr streams are binary and decode them before pushing their + contents to handlers. + + This defaults to ``True``. Set it to ``False`` if: + + - ``universal_newlines == True``, as then streams are in text mode, or + - decoding must happen later, such as for :class:`~git.diff.Diff`\s. + + :param kill_after_timeout: + :class:`float` or ``None``, Default = ``None`` + + To specify a timeout in seconds for the git command, after which the process + should be killed. + """ + + # Use 2 "pump" threads and wait for both to finish. + def pump_stream( + cmdline: List[str], + name: str, + stream: Union[BinaryIO, TextIO], + is_decode: bool, + handler: Union[None, Callable[[Union[bytes, str]], None]], + ) -> None: + try: + for line in stream: + if handler: + if is_decode: + assert isinstance(line, bytes) + line_str = line.decode(defenc) + handler(line_str) + else: + handler(line) + + except Exception as ex: + _logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}") + if "I/O operation on closed file" not in str(ex): + # Only reraise if the error was not due to the stream closing. + raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex + finally: + stream.close() + + if hasattr(process, "proc"): + process = cast("Git.AutoInterrupt", process) + cmdline: str | Tuple[str, ...] | List[str] = getattr(process.proc, "args", "") + p_stdout = process.proc.stdout if process.proc else None + p_stderr = process.proc.stderr if process.proc else None + else: + process = cast(Popen, process) # type: ignore[redundant-cast] + cmdline = getattr(process, "args", "") + p_stdout = process.stdout + p_stderr = process.stderr + + if not isinstance(cmdline, (tuple, list)): + cmdline = cmdline.split() + + pumps: List[Tuple[str, IO, Callable[..., None] | None]] = [] + if p_stdout: + pumps.append(("stdout", p_stdout, stdout_handler)) + if p_stderr: + pumps.append(("stderr", p_stderr, stderr_handler)) + + threads: List[threading.Thread] = [] + + for name, stream, handler in pumps: + t = threading.Thread(target=pump_stream, args=(cmdline, name, stream, decode_streams, handler)) + t.daemon = True + t.start() + threads.append(t) + + # FIXME: Why join? Will block if stdin needs feeding... + for t in threads: + t.join(timeout=kill_after_timeout) + if t.is_alive(): + if isinstance(process, Git.AutoInterrupt): + process._terminate() + else: # Don't want to deal with the other case. + raise RuntimeError( + "Thread join() timed out in cmd.handle_process_output()." + f" kill_after_timeout={kill_after_timeout} seconds" + ) + if stderr_handler: + error_str: Union[str, bytes] = ( + f"error: process killed because it timed out. kill_after_timeout={kill_after_timeout} seconds" + ) + if not decode_streams and isinstance(p_stderr, BinaryIO): + # Assume stderr_handler needs binary input. + error_str = cast(str, error_str) + error_str = error_str.encode() + # We ignore typing on the next line because mypy does not like the way + # we inferred that stderr takes str or bytes. + stderr_handler(error_str) # type: ignore[arg-type] + + if finalizer: + finalizer(process) + + +safer_popen: Callable[..., Popen] + +if sys.platform == "win32": + + def _safer_popen_windows( + command: Union[str, Sequence[Any]], + *, + shell: bool = False, + env: Optional[Mapping[str, str]] = None, + **kwargs: Any, + ) -> Popen: + """Call :class:`subprocess.Popen` on Windows but don't include a CWD in the + search. + + This avoids an untrusted search path condition where a file like ``git.exe`` in + a malicious repository would be run when GitPython operates on the repository. + The process using GitPython may have an untrusted repository's working tree as + its current working directory. Some operations may temporarily change to that + directory before running a subprocess. In addition, while by default GitPython + does not run external commands with a shell, it can be made to do so, in which + case the CWD of the subprocess, which GitPython usually sets to a repository + working tree, can itself be searched automatically by the shell. This wrapper + covers all those cases. + + :note: + This currently works by setting the + :envvar:`NoDefaultCurrentDirectoryInExePath` environment variable during + subprocess creation. It also takes care of passing Windows-specific process + creation flags, but that is unrelated to path search. + + :note: + The current implementation contains a race condition on :attr:`os.environ`. + GitPython isn't thread-safe, but a program using it on one thread should + ideally be able to mutate :attr:`os.environ` on another, without + unpredictable results. See comments in: + https://github.com/gitpython-developers/GitPython/pull/1650 + """ + # CREATE_NEW_PROCESS_GROUP is needed for some ways of killing it afterwards. + # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal + # https://docs.python.org/3/library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP + creationflags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP + + # When using a shell, the shell is the direct subprocess, so the variable must + # be set in its environment, to affect its search behavior. + if shell: + # The original may be immutable, or the caller may reuse it. Mutate a copy. + env = {} if env is None else dict(env) + env["NoDefaultCurrentDirectoryInExePath"] = "1" # The "1" can be any value. + + # When not using a shell, the current process does the search in a + # CreateProcessW API call, so the variable must be set in our environment. With + # a shell, that's unnecessary if https://github.com/python/cpython/issues/101283 + # is patched. In Python versions where it is unpatched, in the rare case the + # ComSpec environment variable is unset, the search for the shell itself is + # unsafe. Setting NoDefaultCurrentDirectoryInExePath in all cases, as done here, + # is simpler and protects against that. (As above, the "1" can be any value.) + with patch_env("NoDefaultCurrentDirectoryInExePath", "1"): + return Popen( + command, + shell=shell, + env=env, + creationflags=creationflags, + **kwargs, + ) + + safer_popen = _safer_popen_windows +else: + safer_popen = Popen + + +def dashify(string: str) -> str: + return string.replace("_", "-") + + +def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]: + return {s: getattr(self, s) for s in self.__slots__ if s not in exclude} + + +def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None: + for k, v in d.items(): + setattr(self, k, v) + for k in excluded: + setattr(self, k, None) + + +## -- End Utilities -- @} + + +class _AutoInterrupt: + """Process wrapper that terminates the wrapped process on finalization. + + This kills/interrupts the stored process instance once this instance goes out of + scope. It is used to prevent processes piling up in case iterators stop reading. + + All attributes are wired through to the contained process object. + + The wait method is overridden to perform automatic status code checking and possibly + raise. + """ + + __slots__ = ("proc", "args", "status") + + # If this is non-zero it will override any status code during _terminate, used + # to prevent race conditions in testing. + _status_code_if_terminate: int = 0 + + def __init__(self, proc: Union[None, subprocess.Popen], args: Any) -> None: + self.proc = proc + self.args = args + self.status: Union[int, None] = None + + def _terminate(self) -> None: + """Terminate the underlying process.""" + if self.proc is None: + return + + proc = self.proc + self.proc = None + if proc.stdin: + proc.stdin.close() + if proc.stdout: + proc.stdout.close() + if proc.stderr: + proc.stderr.close() + # Did the process finish already so we have a return code? + try: + if proc.poll() is not None: + self.status = self._status_code_if_terminate or proc.poll() + return + except OSError as ex: + _logger.info("Ignored error after process had died: %r", ex) + + # It can be that nothing really exists anymore... + if os is None or getattr(os, "kill", None) is None: + return + + # Try to kill it. + try: + proc.terminate() + status = proc.wait() # Ensure the process goes away. + + self.status = self._status_code_if_terminate or status + except OSError as ex: + _logger.info("Ignored error after process had died: %r", ex) + # END exception handling + + def __del__(self) -> None: + self._terminate() + + def __getattr__(self, attr: str) -> Any: + return getattr(self.proc, attr) + + # TODO: Bad choice to mimic `proc.wait()` but with different args. + def wait(self, stderr: Union[None, str, bytes] = b"") -> int: + """Wait for the process and return its status code. + + :param stderr: + Previously read value of stderr, in case stderr is already closed. + + :warn: + May deadlock if output or error pipes are used and not handled separately. + + :raise git.exc.GitCommandError: + If the return status is not 0. + """ + if stderr is None: + stderr_b = b"" + stderr_b = force_bytes(data=stderr, encoding="utf-8") + status: Union[int, None] + if self.proc is not None: + status = self.proc.wait() + p_stderr = self.proc.stderr + else: # Assume the underlying proc was killed earlier or never existed. + status = self.status + p_stderr = None + + def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> bytes: + if stream: + try: + return stderr_b + force_bytes(stream.read()) + except (OSError, ValueError): + return stderr_b or b"" + else: + return stderr_b or b"" + + # END status handling + + if status != 0: + errstr = read_all_from_possibly_closed_stream(p_stderr) + _logger.debug("AutoInterrupt wait stderr: %r" % (errstr,)) + raise GitCommandError(remove_password_if_present(self.args), status, errstr) + return status + + +_AutoInterrupt.__name__ = "AutoInterrupt" +_AutoInterrupt.__qualname__ = "Git.AutoInterrupt" + + +class _CatFileContentStream: + """Object representing a sized read-only stream returning the contents of + an object. + + This behaves like a stream, but counts the data read and simulates an empty stream + once our sized content region is empty. + + If not all data are read to the end of the object's lifetime, we read the rest to + ensure the underlying stream continues to work. + """ + + __slots__ = ("_stream", "_nbr", "_size") + + def __init__(self, size: int, stream: IO[bytes]) -> None: + self._stream = stream + self._size = size + self._nbr = 0 # Number of bytes read. + + # Special case: If the object is empty, has null bytes, get the final + # newline right away. + if size == 0: + stream.read(1) + # END handle empty streams + + def read(self, size: int = -1) -> bytes: + bytes_left = self._size - self._nbr + if bytes_left == 0: + return b"" + if size > -1: + # Ensure we don't try to read past our limit. + size = min(bytes_left, size) + else: + # They try to read all, make sure it's not more than what remains. + size = bytes_left + # END check early depletion + data = self._stream.read(size) + self._nbr += len(data) + + # Check for depletion, read our final byte to make the stream usable by + # others. + if self._size - self._nbr == 0: + self._stream.read(1) # final newline + # END finish reading + return data + + def readline(self, size: int = -1) -> bytes: + if self._nbr == self._size: + return b"" + + # Clamp size to lowest allowed value. + bytes_left = self._size - self._nbr + if size > -1: + size = min(bytes_left, size) + else: + size = bytes_left + # END handle size + + data = self._stream.readline(size) + self._nbr += len(data) + + # Handle final byte. + if self._size - self._nbr == 0: + self._stream.read(1) + # END finish reading + + return data + + def readlines(self, size: int = -1) -> List[bytes]: + if self._nbr == self._size: + return [] + + # Leave all additional logic to our readline method, we just check the size. + out = [] + nbr = 0 + while True: + line = self.readline() + if not line: + break + out.append(line) + if size > -1: + nbr += len(line) + if nbr > size: + break + # END handle size constraint + # END readline loop + return out + + # skipcq: PYL-E0301 + def __iter__(self) -> "Git.CatFileContentStream": + return self + + def __next__(self) -> bytes: + line = self.readline() + if not line: + raise StopIteration + + return line + + next = __next__ + + def __del__(self) -> None: + bytes_left = self._size - self._nbr + if bytes_left: + # Read and discard - seeking is impossible within a stream. + # This includes any terminating newline. + self._stream.read(bytes_left + 1) + # END handle incomplete read + + +_CatFileContentStream.__name__ = "CatFileContentStream" +_CatFileContentStream.__qualname__ = "Git.CatFileContentStream" + + +_USE_SHELL_DEFAULT_MESSAGE = ( + "Git.USE_SHELL is deprecated, because only its default value of False is safe. " + "It will be removed in a future release." +) + +_USE_SHELL_DANGER_MESSAGE = ( + "Setting Git.USE_SHELL to True is unsafe and insecure, as the effect of special " + "shell syntax cannot usually be accounted for. This can result in a command " + "injection vulnerability and arbitrary code execution. Git.USE_SHELL is deprecated " + "and will be removed in a future release." +) + + +def _warn_use_shell(*, extra_danger: bool) -> None: + warnings.warn( + _USE_SHELL_DANGER_MESSAGE if extra_danger else _USE_SHELL_DEFAULT_MESSAGE, + DeprecationWarning, + stacklevel=3, + ) + + +class _GitMeta(type): + """Metaclass for :class:`Git`. + + This helps issue :class:`DeprecationWarning` if :attr:`Git.USE_SHELL` is used. + """ + + def __getattribute(cls, name: str) -> Any: + if name == "USE_SHELL": + _warn_use_shell(extra_danger=False) + return super().__getattribute__(name) + + def __setattr(cls, name: str, value: Any) -> Any: + if name == "USE_SHELL": + _warn_use_shell(extra_danger=value) + super().__setattr__(name, value) + + if not TYPE_CHECKING: + # To preserve static checking for undefined/misspelled attributes while letting + # the methods' bodies be type-checked, these are defined as non-special methods, + # then bound to special names out of view of static type checkers. (The original + # names invoke name mangling (leading "__") to avoid confusion in other scopes.) + __getattribute__ = __getattribute + __setattr__ = __setattr + + +GitMeta = _GitMeta +"""Alias of :class:`Git`'s metaclass, whether it is :class:`type` or a custom metaclass. + +Whether the :class:`Git` class has the default :class:`type` as its metaclass or uses a +custom metaclass is not documented and may change at any time. This statically checkable +metaclass alias is equivalent at runtime to ``type(Git)``. This should almost never be +used. Code that benefits from it is likely to be remain brittle even if it is used. + +In view of the :class:`Git` class's intended use and :class:`Git` objects' dynamic +callable attributes representing git subcommands, it rarely makes sense to inherit from +:class:`Git` at all. Using :class:`Git` in multiple inheritance can be especially tricky +to do correctly. Attempting uses of :class:`Git` where its metaclass is relevant, such +as when a sibling class has an unrelated metaclass and a shared lower bound metaclass +might have to be introduced to solve a metaclass conflict, is not recommended. + +:note: + The correct static type of the :class:`Git` class itself, and any subclasses, is + ``Type[Git]``. (This can be written as ``type[Git]`` in Python 3.9 later.) + + :class:`GitMeta` should never be used in any annotation where ``Type[Git]`` is + intended or otherwise possible to use. This alias is truly only for very rare and + inherently precarious situations where it is necessary to deal with the metaclass + explicitly. +""" + + +class Git(metaclass=_GitMeta): + """The Git class manages communication with the Git binary. + + It provides a convenient interface to calling the Git binary, such as in:: + + g = Git( git_dir ) + g.init() # calls 'git init' program + rval = g.ls_files() # calls 'git ls-files' program + + Debugging: + + * Set the :envvar:`GIT_PYTHON_TRACE` environment variable to print each invocation + of the command to stdout. + * Set its value to ``full`` to see details about the returned values. + """ + + __slots__ = ( + "_working_dir", + "cat_file_all", + "cat_file_header", + "_version_info", + "_version_info_token", + "_git_options", + "_persistent_git_options", + "_environment", + ) + + _excluded_ = ( + "cat_file_all", + "cat_file_header", + "_version_info", + "_version_info_token", + ) + + re_unsafe_protocol = re.compile(r"(.+)::.+") + + def __getstate__(self) -> Dict[str, Any]: + return slots_to_dict(self, exclude=self._excluded_) + + def __setstate__(self, d: Dict[str, Any]) -> None: + dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_) + + # CONFIGURATION + + git_exec_name = "git" + """Default git command that should work on Linux, Windows, and other systems.""" + + GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False) + """Enables debugging of GitPython's git commands.""" + + USE_SHELL: bool = False + """Deprecated. If set to ``True``, a shell will be used when executing git commands. + + Code that uses ``USE_SHELL = True`` or that passes ``shell=True`` to any GitPython + functions should be updated to use the default value of ``False`` instead. ``True`` + is unsafe unless the effect of syntax treated specially by the shell is fully + considered and accounted for, which is not possible under most circumstances. As + detailed below, it is also no longer needed, even where it had been in the past. + + It is in many if not most cases a command injection vulnerability for an application + to set :attr:`USE_SHELL` to ``True``. Any attacker who can cause a specially crafted + fragment of text to make its way into any part of any argument to any git command + (including paths, branch names, etc.) can cause the shell to read and write + arbitrary files and execute arbitrary commands. Innocent input may also accidentally + contain special shell syntax, leading to inadvertent malfunctions. + + In addition, how a value of ``True`` interacts with some aspects of GitPython's + operation is not precisely specified and may change without warning, even before + GitPython 4.0.0 when :attr:`USE_SHELL` may be removed. This includes: + + * Whether or how GitPython automatically customizes the shell environment. + + * Whether, outside of Windows (where :class:`subprocess.Popen` supports lists of + separate arguments even when ``shell=True``), this can be used with any GitPython + functionality other than direct calls to the :meth:`execute` method. + + * Whether any GitPython feature that runs git commands ever attempts to partially + sanitize data a shell may treat specially. Currently this is not done. + + Prior to GitPython 2.0.8, this had a narrow purpose in suppressing console windows + in graphical Windows applications. In 2.0.8 and higher, it provides no benefit, as + GitPython solves that problem more robustly and safely by using the + ``CREATE_NO_WINDOW`` process creation flag on Windows. + + Because Windows path search differs subtly based on whether a shell is used, in rare + cases changing this from ``True`` to ``False`` may keep an unusual git "executable", + such as a batch file, from being found. To fix this, set the command name or full + path in the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable or pass the + full path to :func:`git.refresh` (or invoke the script using a ``.exe`` shim). + + Further reading: + + * :meth:`Git.execute` (on the ``shell`` parameter). + * https://github.com/gitpython-developers/GitPython/commit/0d9390866f9ce42870d3116094cd49e0019a970a + * https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags + * https://github.com/python/cpython/issues/91558#issuecomment-1100942950 + * https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw + """ + + _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE" + _refresh_env_var = "GIT_PYTHON_REFRESH" + + GIT_PYTHON_GIT_EXECUTABLE = None + """Provide the full path to the git executable. Otherwise it assumes git is in the + executable search path. + + :note: + The git executable is actually found during the refresh step in the top level + ``__init__``. It can also be changed by explicitly calling :func:`git.refresh`. + """ + + _refresh_token = object() # Since None would match an initial _version_info_token. + + @classmethod + def refresh(cls, path: Union[None, PathLike] = None) -> bool: + """Update information about the git executable :class:`Git` objects will use. + + Called by the :func:`git.refresh` function in the top level ``__init__``. + + :param path: + Optional path to the git executable. If not absolute, it is resolved + immediately, relative to the current directory. (See note below.) + + :note: + The top-level :func:`git.refresh` should be preferred because it calls this + method and may also update other state accordingly. + + :note: + There are three different ways to specify the command that refreshing causes + to be used for git: + + 1. Pass no `path` argument and do not set the + :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable. The command + name ``git`` is used. It is looked up in a path search by the system, in + each command run (roughly similar to how git is found when running + ``git`` commands manually). This is usually the desired behavior. + + 2. Pass no `path` argument but set the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` + environment variable. The command given as the value of that variable is + used. This may be a simple command or an arbitrary path. It is looked up + in each command run. Setting :envvar:`GIT_PYTHON_GIT_EXECUTABLE` to + ``git`` has the same effect as not setting it. + + 3. Pass a `path` argument. This path, if not absolute, is immediately + resolved, relative to the current directory. This resolution occurs at + the time of the refresh. When git commands are run, they are run using + that previously resolved path. If a `path` argument is passed, the + :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not + consulted. + + :note: + Refreshing always sets the :attr:`Git.GIT_PYTHON_GIT_EXECUTABLE` class + attribute, which can be read on the :class:`Git` class or any of its + instances to check what command is used to run git. This attribute should + not be confused with the related :envvar:`GIT_PYTHON_GIT_EXECUTABLE` + environment variable. The class attribute is set no matter how refreshing is + performed. + """ + # Discern which path to refresh with. + if path is not None: + new_git = os.path.expanduser(path) + new_git = os.path.abspath(new_git) + else: + new_git = os.environ.get(cls._git_exec_env_var, cls.git_exec_name) + + # Keep track of the old and new git executable path. + old_git = cls.GIT_PYTHON_GIT_EXECUTABLE + old_refresh_token = cls._refresh_token + cls.GIT_PYTHON_GIT_EXECUTABLE = new_git + cls._refresh_token = object() + + # Test if the new git executable path is valid. A GitCommandNotFound error is + # raised by us. A PermissionError is raised if the git executable cannot be + # executed for whatever reason. + has_git = False + try: + cls().version() + has_git = True + except (GitCommandNotFound, PermissionError): + pass + + # Warn or raise exception if test failed. + if not has_git: + err = ( + dedent( + """\ + Bad git executable. + The git executable must be specified in one of the following ways: + - be included in your $PATH + - be set via $%s + - explicitly set via git.refresh() + """ + ) + % cls._git_exec_env_var + ) + + # Revert to whatever the old_git was. + cls.GIT_PYTHON_GIT_EXECUTABLE = old_git + cls._refresh_token = old_refresh_token + + if old_git is None: + # On the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is None) we only + # are quiet, warn, or error depending on the GIT_PYTHON_REFRESH value. + + # Determine what the user wants to happen during the initial refresh. We + # expect GIT_PYTHON_REFRESH to either be unset or be one of the + # following values: + # + # 0|q|quiet|s|silence|silent|n|none + # 1|w|warn|warning|l|log + # 2|r|raise|e|error|exception + + mode = os.environ.get(cls._refresh_env_var, "raise").lower() + + quiet = ["quiet", "q", "silence", "s", "silent", "none", "n", "0"] + warn = ["warn", "w", "warning", "log", "l", "1"] + error = ["error", "e", "exception", "raise", "r", "2"] + + if mode in quiet: + pass + elif mode in warn or mode in error: + err = dedent( + """\ + %s + All git commands will error until this is rectified. + + This initial message can be silenced or aggravated in the future by setting the + $%s environment variable. Use one of the following values: + - %s: for no message or exception + - %s: for a warning message (logging level CRITICAL, displayed by default) + - %s: for a raised exception + + Example: + export %s=%s + """ + ) % ( + err, + cls._refresh_env_var, + "|".join(quiet), + "|".join(warn), + "|".join(error), + cls._refresh_env_var, + quiet[0], + ) + + if mode in warn: + _logger.critical(err) + else: + raise ImportError(err) + else: + err = dedent( + """\ + %s environment variable has been set but it has been set with an invalid value. + + Use only the following values: + - %s: for no message or exception + - %s: for a warning message (logging level CRITICAL, displayed by default) + - %s: for a raised exception + """ + ) % ( + cls._refresh_env_var, + "|".join(quiet), + "|".join(warn), + "|".join(error), + ) + raise ImportError(err) + + # We get here if this was the initial refresh and the refresh mode was + # not error. Go ahead and set the GIT_PYTHON_GIT_EXECUTABLE such that we + # discern the difference between the first refresh at import time + # and subsequent calls to git.refresh or this refresh method. + cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name + else: + # After the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is no longer + # None) we raise an exception. + raise GitCommandNotFound(new_git, err) + + return has_git + + @classmethod + def is_cygwin(cls) -> bool: + return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE) + + @overload + @classmethod + def polish_url(cls, url: str, is_cygwin: Literal[False] = ...) -> str: ... + + @overload + @classmethod + def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> str: ... + + @classmethod + def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> PathLike: + """Remove any backslashes from URLs to be written in config files. + + Windows might create config files containing paths with backslashes, but git + stops liking them as it will escape the backslashes. Hence we undo the escaping + just to be sure. + """ + if is_cygwin is None: + is_cygwin = cls.is_cygwin() + + if is_cygwin: + url = cygpath(url) + else: + url = os.path.expandvars(url) + if url.startswith("~"): + url = os.path.expanduser(url) + url = url.replace("\\\\", "\\").replace("\\", "/") + return url + + @classmethod + def check_unsafe_protocols(cls, url: str) -> None: + """Check for unsafe protocols. + + Apart from the usual protocols (http, git, ssh), Git allows "remote helpers" + that have the form ``::
``. One of these helpers (``ext::``) + can be used to invoke any arbitrary command. + + See: + + - https://git-scm.com/docs/gitremote-helpers + - https://git-scm.com/docs/git-remote-ext + """ + match = cls.re_unsafe_protocol.match(url) + if match: + protocol = match.group(1) + raise UnsafeProtocolError( + f"The `{protocol}::` protocol looks suspicious, use `allow_unsafe_protocols=True` to allow it." + ) + + @classmethod + def check_unsafe_options(cls, options: List[str], unsafe_options: List[str]) -> None: + """Check for unsafe options. + + Some options that are passed to ``git `` can be used to execute + arbitrary commands. These are blocked by default. + """ + # Options can be of the form `foo`, `--foo bar`, or `--foo=bar`, so we need to + # check if they start with "--foo" or if they are equal to "foo". + bare_unsafe_options = [option.lstrip("-") for option in unsafe_options] + for option in options: + for unsafe_option, bare_option in zip(unsafe_options, bare_unsafe_options): + if option.startswith(unsafe_option) or option == bare_option: + raise UnsafeOptionError( + f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it." + ) + + AutoInterrupt: TypeAlias = _AutoInterrupt + + CatFileContentStream: TypeAlias = _CatFileContentStream + + def __init__(self, working_dir: Union[None, PathLike] = None) -> None: + """Initialize this instance with: + + :param working_dir: + Git directory we should work in. If ``None``, we always work in the current + directory as returned by :func:`os.getcwd`. + This is meant to be the working tree directory if available, or the + ``.git`` directory in case of bare repositories. + """ + super().__init__() + self._working_dir = expand_path(working_dir) + self._git_options: Union[List[str], Tuple[str, ...]] = () + self._persistent_git_options: List[str] = [] + + # Extra environment variables to pass to git commands + self._environment: Dict[str, str] = {} + + # Cached version slots + self._version_info: Union[Tuple[int, ...], None] = None + self._version_info_token: object = None + + # Cached command slots + self.cat_file_header: Union[None, TBD] = None + self.cat_file_all: Union[None, TBD] = None + + def __getattribute__(self, name: str) -> Any: + if name == "USE_SHELL": + _warn_use_shell(extra_danger=False) + return super().__getattribute__(name) + + def __getattr__(self, name: str) -> Any: + """A convenience method as it allows to call the command as if it was an object. + + :return: + Callable object that will execute call :meth:`_call_process` with your + arguments. + """ + if name.startswith("_"): + return super().__getattribute__(name) + return lambda *args, **kwargs: self._call_process(name, *args, **kwargs) + + def set_persistent_git_options(self, **kwargs: Any) -> None: + """Specify command line options to the git executable for subsequent + subcommand calls. + + :param kwargs: + A dict of keyword arguments. + These arguments are passed as in :meth:`_call_process`, but will be passed + to the git command rather than the subcommand. + """ + + self._persistent_git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) + + @property + def working_dir(self) -> Union[None, PathLike]: + """:return: Git directory we are working on""" + return self._working_dir + + @property + def version_info(self) -> Tuple[int, ...]: + """ + :return: Tuple with integers representing the major, minor and additional + version numbers as parsed from :manpage:`git-version(1)`. Up to four fields + are used. + + This value is generated on demand and is cached. + """ + # Refreshing is global, but version_info caching is per-instance. + refresh_token = self._refresh_token # Copy token in case of concurrent refresh. + + # Use the cached version if obtained after the most recent refresh. + if self._version_info_token is refresh_token: + assert self._version_info is not None, "Bug: corrupted token-check state" + return self._version_info + + # Run "git version" and parse it. + process_version = self._call_process("version") + version_string = process_version.split(" ")[2] + version_fields = version_string.split(".")[:4] + leading_numeric_fields = itertools.takewhile(str.isdigit, version_fields) + self._version_info = tuple(map(int, leading_numeric_fields)) + + # This value will be considered valid until the next refresh. + self._version_info_token = refresh_token + return self._version_info + + @overload + def execute( + self, + command: Union[str, Sequence[Any]], + *, + as_process: Literal[True], + ) -> "AutoInterrupt": ... + + @overload + def execute( + self, + command: Union[str, Sequence[Any]], + *, + as_process: Literal[False] = False, + stdout_as_string: Literal[True], + ) -> Union[str, Tuple[int, str, str]]: ... + + @overload + def execute( + self, + command: Union[str, Sequence[Any]], + *, + as_process: Literal[False] = False, + stdout_as_string: Literal[False] = False, + ) -> Union[bytes, Tuple[int, bytes, str]]: ... + + @overload + def execute( + self, + command: Union[str, Sequence[Any]], + *, + with_extended_output: Literal[False], + as_process: Literal[False], + stdout_as_string: Literal[True], + ) -> str: ... + + @overload + def execute( + self, + command: Union[str, Sequence[Any]], + *, + with_extended_output: Literal[False], + as_process: Literal[False], + stdout_as_string: Literal[False], + ) -> bytes: ... + + def execute( + self, + command: Union[str, Sequence[Any]], + istream: Union[None, BinaryIO] = None, + with_extended_output: bool = False, + with_exceptions: bool = True, + as_process: bool = False, + output_stream: Union[None, BinaryIO] = None, + stdout_as_string: bool = True, + kill_after_timeout: Union[None, float] = None, + with_stdout: bool = True, + universal_newlines: bool = False, + shell: Union[None, bool] = None, + env: Union[None, Mapping[str, str]] = None, + max_chunk_size: int = io.DEFAULT_BUFFER_SIZE, + strip_newline_in_stdout: bool = True, + **subprocess_kwargs: Any, + ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]: + R"""Handle executing the command, and consume and return the returned + information (stdout). + + :param command: + The command argument list to execute. + It should be a sequence of program arguments, or a string. The + program to execute is the first item in the args sequence or string. + + :param istream: + Standard input filehandle passed to :class:`subprocess.Popen`. + + :param with_extended_output: + Whether to return a (status, stdout, stderr) tuple. + + :param with_exceptions: + Whether to raise an exception when git returns a non-zero status. + + :param as_process: + Whether to return the created process instance directly from which + streams can be read on demand. This will render `with_extended_output` + and `with_exceptions` ineffective - the caller will have to deal with + the details. It is important to note that the process will be placed + into an :class:`AutoInterrupt` wrapper that will interrupt the process + once it goes out of scope. If you use the command in iterators, you + should pass the whole process instance instead of a single stream. + + :param output_stream: + If set to a file-like object, data produced by the git command will be + copied to the given stream instead of being returned as a string. + This feature only has any effect if `as_process` is ``False``. + + :param stdout_as_string: + If ``False``, the command's standard output will be bytes. Otherwise, it + will be decoded into a string using the default encoding (usually UTF-8). + The latter can fail, if the output contains binary data. + + :param kill_after_timeout: + Specifies a timeout in seconds for the git command, after which the process + should be killed. This will have no effect if `as_process` is set to + ``True``. It is set to ``None`` by default and will let the process run + until the timeout is explicitly specified. Uses of this feature should be + carefully considered, due to the following limitations: + + 1. This feature is not supported at all on Windows. + 2. Effectiveness may vary by operating system. ``ps --ppid`` is used to + enumerate child processes, which is available on most GNU/Linux systems + but not most others. + 3. Deeper descendants do not receive signals, though they may sometimes + terminate as a consequence of their parent processes being killed. + 4. `kill_after_timeout` uses ``SIGKILL``, which can have negative side + effects on a repository. For example, stale locks in case of + :manpage:`git-gc(1)` could render the repository incapable of accepting + changes until the lock is manually removed. + + :param with_stdout: + If ``True``, default ``True``, we open stdout on the created process. + + :param universal_newlines: + If ``True``, pipes will be opened as text, and lines are split at all known + line endings. + + :param shell: + Whether to invoke commands through a shell + (see :class:`Popen(..., shell=True) `). + If this is not ``None``, it overrides :attr:`USE_SHELL`. + + Passing ``shell=True`` to this or any other GitPython function should be + avoided, as it is unsafe under most circumstances. This is because it is + typically not feasible to fully consider and account for the effect of shell + expansions, especially when passing ``shell=True`` to other methods that + forward it to :meth:`Git.execute`. Passing ``shell=True`` is also no longer + needed (nor useful) to work around any known operating system specific + issues. + + :param env: + A dictionary of environment variables to be passed to + :class:`subprocess.Popen`. + + :param max_chunk_size: + Maximum number of bytes in one chunk of data passed to the `output_stream` + in one invocation of its ``write()`` method. If the given number is not + positive then the default value is used. + + :param strip_newline_in_stdout: + Whether to strip the trailing ``\n`` of the command stdout. + + :param subprocess_kwargs: + Keyword arguments to be passed to :class:`subprocess.Popen`. Please note + that some of the valid kwargs are already set by this method; the ones you + specify may not be the same ones. + + :return: + * str(output), if `extended_output` is ``False`` (Default) + * tuple(int(status), str(stdout), str(stderr)), + if `extended_output` is ``True`` + + If `output_stream` is ``True``, the stdout value will be your output stream: + + * output_stream, if `extended_output` is ``False`` + * tuple(int(status), output_stream, str(stderr)), + if `extended_output` is ``True`` + + Note that git is executed with ``LC_MESSAGES="C"`` to ensure consistent + output regardless of system language. + + :raise git.exc.GitCommandError: + + :note: + If you add additional keyword arguments to the signature of this method, you + must update the ``execute_kwargs`` variable housed in this module. + """ + # Remove password for the command if present. + redacted_command = remove_password_if_present(command) + if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process): + _logger.info(" ".join(redacted_command)) + + # Allow the user to have the command executed in their working dir. + try: + cwd = self._working_dir or os.getcwd() # type: Union[None, str] + if not os.access(str(cwd), os.X_OK): + cwd = None + except FileNotFoundError: + cwd = None + + # Start the process. + inline_env = env + env = os.environ.copy() + # Attempt to force all output to plain ASCII English, which is what some parsing + # code may expect. + # According to https://askubuntu.com/a/311796, we are setting LANGUAGE as well + # just to be sure. + env["LANGUAGE"] = "C" + env["LC_ALL"] = "C" + env.update(self._environment) + if inline_env is not None: + env.update(inline_env) + + if sys.platform == "win32": + if kill_after_timeout is not None: + raise GitCommandError( + redacted_command, + '"kill_after_timeout" feature is not supported on Windows.', + ) + cmd_not_found_exception = OSError + else: + cmd_not_found_exception = FileNotFoundError + # END handle + + stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb") + if shell is None: + # Get the value of USE_SHELL with no deprecation warning. Do this without + # warnings.catch_warnings, to avoid a race condition with application code + # configuring warnings. The value could be looked up in type(self).__dict__ + # or Git.__dict__, but those can break under some circumstances. This works + # the same as self.USE_SHELL in more situations; see Git.__getattribute__. + shell = super().__getattribute__("USE_SHELL") + _logger.debug( + "Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)", + redacted_command, + cwd, + "" if istream else "None", + shell, + universal_newlines, + ) + try: + proc = safer_popen( + command, + env=env, + cwd=cwd, + bufsize=-1, + stdin=(istream or DEVNULL), + stderr=PIPE, + stdout=stdout_sink, + shell=shell, + universal_newlines=universal_newlines, + encoding=defenc if universal_newlines else None, + **subprocess_kwargs, + ) + except cmd_not_found_exception as err: + raise GitCommandNotFound(redacted_command, err) from err + else: + # Replace with a typeguard for Popen[bytes]? + proc.stdout = cast(BinaryIO, proc.stdout) + proc.stderr = cast(BinaryIO, proc.stderr) + + if as_process: + return self.AutoInterrupt(proc, command) + + if sys.platform != "win32" and kill_after_timeout is not None: + # Help mypy figure out this is not None even when used inside communicate(). + timeout = kill_after_timeout + + def kill_process(pid: int) -> None: + """Callback to kill a process. + + This callback implementation would be ineffective and unsafe on Windows. + """ + p = Popen(["ps", "--ppid", str(pid)], stdout=PIPE) + child_pids = [] + if p.stdout is not None: + for line in p.stdout: + if len(line.split()) > 0: + local_pid = (line.split())[0] + if local_pid.isdigit(): + child_pids.append(int(local_pid)) + try: + os.kill(pid, signal.SIGKILL) + for child_pid in child_pids: + try: + os.kill(child_pid, signal.SIGKILL) + except OSError: + pass + # Tell the main routine that the process was killed. + kill_check.set() + except OSError: + # It is possible that the process gets completed in the duration + # after timeout happens and before we try to kill the process. + pass + return + + def communicate() -> Tuple[AnyStr, AnyStr]: + watchdog.start() + out, err = proc.communicate() + watchdog.cancel() + if kill_check.is_set(): + err = 'Timeout: the command "%s" did not complete in %d secs.' % ( + " ".join(redacted_command), + timeout, + ) + if not universal_newlines: + err = err.encode(defenc) + return out, err + + # END helpers + + kill_check = threading.Event() + watchdog = threading.Timer(timeout, kill_process, args=(proc.pid,)) + else: + communicate = proc.communicate + + # Wait for the process to return. + status = 0 + stdout_value: Union[str, bytes] = b"" + stderr_value: Union[str, bytes] = b"" + newline = "\n" if universal_newlines else b"\n" + try: + if output_stream is None: + stdout_value, stderr_value = communicate() + # Strip trailing "\n". + if stdout_value.endswith(newline) and strip_newline_in_stdout: # type: ignore[arg-type] + stdout_value = stdout_value[:-1] + if stderr_value.endswith(newline): # type: ignore[arg-type] + stderr_value = stderr_value[:-1] + + status = proc.returncode + else: + max_chunk_size = max_chunk_size if max_chunk_size and max_chunk_size > 0 else io.DEFAULT_BUFFER_SIZE + stream_copy(proc.stdout, output_stream, max_chunk_size) + stdout_value = proc.stdout.read() + stderr_value = proc.stderr.read() + # Strip trailing "\n". + if stderr_value.endswith(newline): # type: ignore[arg-type] + stderr_value = stderr_value[:-1] + status = proc.wait() + # END stdout handling + finally: + proc.stdout.close() + proc.stderr.close() + + if self.GIT_PYTHON_TRACE == "full": + cmdstr = " ".join(redacted_command) + + def as_text(stdout_value: Union[bytes, str]) -> str: + return not output_stream and safe_decode(stdout_value) or "" + + # END as_text + + if stderr_value: + _logger.info( + "%s -> %d; stdout: '%s'; stderr: '%s'", + cmdstr, + status, + as_text(stdout_value), + safe_decode(stderr_value), + ) + elif stdout_value: + _logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value)) + else: + _logger.info("%s -> %d", cmdstr, status) + # END handle debug printing + + if with_exceptions and status != 0: + raise GitCommandError(redacted_command, status, stderr_value, stdout_value) + + if isinstance(stdout_value, bytes) and stdout_as_string: # Could also be output_stream. + stdout_value = safe_decode(stdout_value) + + # Allow access to the command's status code. + if with_extended_output: + return (status, stdout_value, safe_decode(stderr_value)) + else: + return stdout_value + + def environment(self) -> Dict[str, str]: + return self._environment + + def update_environment(self, **kwargs: Any) -> Dict[str, Union[str, None]]: + """Set environment variables for future git invocations. Return all changed + values in a format that can be passed back into this function to revert the + changes. + + Examples:: + + old_env = self.update_environment(PWD='/tmp') + self.update_environment(**old_env) + + :param kwargs: + Environment variables to use for git processes. + + :return: + Dict that maps environment variables to their old values + """ + old_env = {} + for key, value in kwargs.items(): + # Set value if it is None. + if value is not None: + old_env[key] = self._environment.get(key) + self._environment[key] = value + # Remove key from environment if its value is None. + elif key in self._environment: + old_env[key] = self._environment[key] + del self._environment[key] + return old_env + + @contextlib.contextmanager + def custom_environment(self, **kwargs: Any) -> Iterator[None]: + """A context manager around the above :meth:`update_environment` method to + restore the environment back to its previous state after operation. + + Examples:: + + with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'): + repo.remotes.origin.fetch() + + :param kwargs: + See :meth:`update_environment`. + """ + old_env = self.update_environment(**kwargs) + try: + yield + finally: + self.update_environment(**old_env) + + def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]: + if len(name) == 1: + if value is True: + return ["-%s" % name] + elif value not in (False, None): + if split_single_char_options: + return ["-%s" % name, "%s" % value] + else: + return ["-%s%s" % (name, value)] + else: + if value is True: + return ["--%s" % dashify(name)] + elif value is not False and value is not None: + return ["--%s=%s" % (dashify(name), value)] + return [] + + def transform_kwargs(self, split_single_char_options: bool = True, **kwargs: Any) -> List[str]: + """Transform Python-style kwargs into git command line options.""" + args = [] + for k, v in kwargs.items(): + if isinstance(v, (list, tuple)): + for value in v: + args += self.transform_kwarg(k, value, split_single_char_options) + else: + args += self.transform_kwarg(k, v, split_single_char_options) + return args + + @classmethod + def _unpack_args(cls, arg_list: Sequence[str]) -> List[str]: + outlist = [] + if isinstance(arg_list, (list, tuple)): + for arg in arg_list: + outlist.extend(cls._unpack_args(arg)) + else: + outlist.append(str(arg_list)) + + return outlist + + def __call__(self, **kwargs: Any) -> "Git": + """Specify command line options to the git executable for a subcommand call. + + :param kwargs: + A dict of keyword arguments. + These arguments are passed as in :meth:`_call_process`, but will be passed + to the git command rather than the subcommand. + + Examples:: + + git(work_tree='/tmp').difftool() + """ + self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs) + return self + + @overload + def _call_process( + self, method: str, *args: None, **kwargs: None + ) -> str: ... # If no args were given, execute the call with all defaults. + + @overload + def _call_process( + self, + method: str, + istream: int, + as_process: Literal[True], + *args: Any, + **kwargs: Any, + ) -> "Git.AutoInterrupt": ... + + @overload + def _call_process( + self, method: str, *args: Any, **kwargs: Any + ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: ... + + def _call_process( + self, method: str, *args: Any, **kwargs: Any + ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: + """Run the given git command with the specified arguments and return the result + as a string. + + :param method: + The command. Contained ``_`` characters will be converted to hyphens, such + as in ``ls_files`` to call ``ls-files``. + + :param args: + The list of arguments. If ``None`` is included, it will be pruned. + This allows your commands to call git more conveniently, as ``None`` is + realized as non-existent. + + :param kwargs: + Contains key-values for the following: + + - The :meth:`execute()` kwds, as listed in ``execute_kwargs``. + - "Command options" to be converted by :meth:`transform_kwargs`. + - The ``insert_kwargs_after`` key which its value must match one of + ``*args``. + + It also contains any command options, to be appended after the matched arg. + + Examples:: + + git.rev_list('master', max_count=10, header=True) + + turns into:: + + git rev-list max-count 10 --header master + + :return: + Same as :meth:`execute`. If no args are given, used :meth:`execute`'s + default (especially ``as_process = False``, ``stdout_as_string = True``) and + return :class:`str`. + """ + # Handle optional arguments prior to calling transform_kwargs. + # Otherwise these'll end up in args, which is bad. + exec_kwargs = {k: v for k, v in kwargs.items() if k in execute_kwargs} + opts_kwargs = {k: v for k, v in kwargs.items() if k not in execute_kwargs} + + insert_after_this_arg = opts_kwargs.pop("insert_kwargs_after", None) + + # Prepare the argument list. + + opt_args = self.transform_kwargs(**opts_kwargs) + ext_args = self._unpack_args([a for a in args if a is not None]) + + if insert_after_this_arg is None: + args_list = opt_args + ext_args + else: + try: + index = ext_args.index(insert_after_this_arg) + except ValueError as err: + raise ValueError( + "Couldn't find argument '%s' in args %s to insert cmd options after" + % (insert_after_this_arg, str(ext_args)) + ) from err + # END handle error + args_list = ext_args[: index + 1] + opt_args + ext_args[index + 1 :] + # END handle opts_kwargs + + call = [self.GIT_PYTHON_GIT_EXECUTABLE] + + # Add persistent git options. + call.extend(self._persistent_git_options) + + # Add the git options, then reset to empty to avoid side effects. + call.extend(self._git_options) + self._git_options = () + + call.append(dashify(method)) + call.extend(args_list) + + return self.execute(call, **exec_kwargs) + + def _parse_object_header(self, header_line: str) -> Tuple[str, str, int]: + """ + :param header_line: + A line of the form:: + + type_string size_as_int + + :return: + (hex_sha, type_string, size_as_int) + + :raise ValueError: + If the header contains indication for an error due to incorrect input sha. + """ + tokens = header_line.split() + if len(tokens) != 3: + if not tokens: + err_msg = ( + f"SHA is empty, possible dubious ownership in the repository " + f"""at {self._working_dir}.\n If this is unintended run:\n\n """ + f""" "git config --global --add safe.directory {self._working_dir}" """ + ) + raise ValueError(err_msg) + else: + raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip())) + # END handle actual return value + # END error handling + + if len(tokens[0]) != 40: + raise ValueError("Failed to parse header: %r" % header_line) + return (tokens[0], tokens[1], int(tokens[2])) + + def _prepare_ref(self, ref: AnyStr) -> bytes: + # Required for command to separate refs on stdin, as bytes. + if isinstance(ref, bytes): + # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text. + refstr: str = ref.decode("ascii") + elif not isinstance(ref, str): + refstr = str(ref) # Could be ref-object. + else: + refstr = ref + + if not refstr.endswith("\n"): + refstr += "\n" + return refstr.encode(defenc) + + def _get_persistent_cmd(self, attr_name: str, cmd_name: str, *args: Any, **kwargs: Any) -> "Git.AutoInterrupt": + cur_val = getattr(self, attr_name) + if cur_val is not None: + return cur_val + + options = {"istream": PIPE, "as_process": True} + options.update(kwargs) + + cmd = self._call_process(cmd_name, *args, **options) + setattr(self, attr_name, cmd) + cmd = cast("Git.AutoInterrupt", cmd) + return cmd + + def __get_object_header(self, cmd: "Git.AutoInterrupt", ref: AnyStr) -> Tuple[str, str, int]: + if cmd.stdin and cmd.stdout: + cmd.stdin.write(self._prepare_ref(ref)) + cmd.stdin.flush() + return self._parse_object_header(cmd.stdout.readline()) + else: + raise ValueError("cmd stdin was empty") + + def get_object_header(self, ref: str) -> Tuple[str, str, int]: + """Use this method to quickly examine the type and size of the object behind the + given ref. + + :note: + The method will only suffer from the costs of command invocation once and + reuses the command in subsequent calls. + + :return: + (hexsha, type_string, size_as_int) + """ + cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True) + return self.__get_object_header(cmd, ref) + + def get_object_data(self, ref: str) -> Tuple[str, str, int, bytes]: + """Similar to :meth:`get_object_header`, but returns object data as well. + + :return: + (hexsha, type_string, size_as_int, data_string) + + :note: + Not threadsafe. + """ + hexsha, typename, size, stream = self.stream_object_data(ref) + data = stream.read(size) + del stream + return (hexsha, typename, size, data) + + def stream_object_data(self, ref: str) -> Tuple[str, str, int, "Git.CatFileContentStream"]: + """Similar to :meth:`get_object_data`, but returns the data as a stream. + + :return: + (hexsha, type_string, size_as_int, stream) + + :note: + This method is not threadsafe. You need one independent :class:`Git` + instance per thread to be safe! + """ + cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True) + hexsha, typename, size = self.__get_object_header(cmd, ref) + cmd_stdout = cmd.stdout if cmd.stdout is not None else io.BytesIO() + return (hexsha, typename, size, self.CatFileContentStream(size, cmd_stdout)) + + def clear_cache(self) -> "Git": + """Clear all kinds of internal caches to release resources. + + Currently persistent commands will be interrupted. + + :return: + self + """ + for cmd in (self.cat_file_all, self.cat_file_header): + if cmd: + cmd.__del__() + + self.cat_file_all = None + self.cat_file_header = None + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/git/compat.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d9a55a9f3cd42c587bcf7ae3de63004f927dd5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/compat.py @@ -0,0 +1,165 @@ +# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors +# +# This module is part of GitPython and is released under the +# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ + +"""Utilities to help provide compatibility with Python 3. + +This module exists for historical reasons. Code outside GitPython may make use of public +members of this module, but is unlikely to benefit from doing so. GitPython continues to +use some of these utilities, in some cases for compatibility across different platforms. +""" + +import locale +import os +import sys +import warnings + +from gitdb.utils.encoding import force_bytes, force_text # noqa: F401 + +# typing -------------------------------------------------------------------- + +from typing import ( + Any, # noqa: F401 + AnyStr, + Dict, # noqa: F401 + IO, # noqa: F401 + List, + Optional, + TYPE_CHECKING, + Tuple, # noqa: F401 + Type, # noqa: F401 + Union, + overload, +) + +# --------------------------------------------------------------------------- + + +_deprecated_platform_aliases = { + "is_win": os.name == "nt", + "is_posix": os.name == "posix", + "is_darwin": sys.platform == "darwin", +} + + +def _getattr(name: str) -> Any: + try: + value = _deprecated_platform_aliases[name] + except KeyError: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None + + warnings.warn( + f"{__name__}.{name} and other is_ aliases are deprecated. " + "Write the desired os.name or sys.platform check explicitly instead.", + DeprecationWarning, + stacklevel=2, + ) + return value + + +if not TYPE_CHECKING: # Preserve static checking for undefined/misspelled attributes. + __getattr__ = _getattr + + +def __dir__() -> List[str]: + return [*globals(), *_deprecated_platform_aliases] + + +is_win: bool +"""Deprecated alias for ``os.name == "nt"`` to check for native Windows. + +This is deprecated because it is clearer to write out :attr:`os.name` or +:attr:`sys.platform` checks explicitly, especially in cases where it matters which is +used. + +:note: + ``is_win`` is ``False`` on Cygwin, but is often wrongly assumed ``True``. To detect + Cygwin, use ``sys.platform == "cygwin"``. +""" + +is_posix: bool +"""Deprecated alias for ``os.name == "posix"`` to check for Unix-like ("POSIX") systems. + +This is deprecated because it clearer to write out :attr:`os.name` or +:attr:`sys.platform` checks explicitly, especially in cases where it matters which is +used. + +:note: + For POSIX systems, more detailed information is available in :attr:`sys.platform`, + while :attr:`os.name` is always ``"posix"`` on such systems, including macOS + (Darwin). +""" + +is_darwin: bool +"""Deprecated alias for ``sys.platform == "darwin"`` to check for macOS (Darwin). + +This is deprecated because it clearer to write out :attr:`os.name` or +:attr:`sys.platform` checks explicitly. + +:note: + For macOS (Darwin), ``os.name == "posix"`` as in other Unix-like systems, while + ``sys.platform == "darwin"``. +""" + +defenc = sys.getfilesystemencoding() +"""The encoding used to convert between Unicode and bytes filenames.""" + + +@overload +def safe_decode(s: None) -> None: ... + + +@overload +def safe_decode(s: AnyStr) -> str: ... + + +def safe_decode(s: Union[AnyStr, None]) -> Optional[str]: + """Safely decode a binary string to Unicode.""" + if isinstance(s, str): + return s + elif isinstance(s, bytes): + return s.decode(defenc, "surrogateescape") + elif s is None: + return None + else: + raise TypeError("Expected bytes or text, but got %r" % (s,)) + + +@overload +def safe_encode(s: None) -> None: ... + + +@overload +def safe_encode(s: AnyStr) -> bytes: ... + + +def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]: + """Safely encode a binary string to Unicode.""" + if isinstance(s, str): + return s.encode(defenc) + elif isinstance(s, bytes): + return s + elif s is None: + return None + else: + raise TypeError("Expected bytes or text, but got %r" % (s,)) + + +@overload +def win_encode(s: None) -> None: ... + + +@overload +def win_encode(s: AnyStr) -> bytes: ... + + +def win_encode(s: Optional[AnyStr]) -> Optional[bytes]: + """Encode Unicode strings for process arguments on Windows.""" + if isinstance(s, str): + return s.encode(locale.getpreferredencoding(False)) + elif isinstance(s, bytes): + return s + elif s is not None: + raise TypeError("Expected bytes or text, but got %r" % (s,)) + return None diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/git/config.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7699294417ca3965dc1909c31fc7af7b57d8d654 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/git/config.py @@ -0,0 +1,953 @@ +# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors +# +# This module is part of GitPython and is released under the +# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ + +"""Parser for reading and writing configuration files.""" + +__all__ = ["GitConfigParser", "SectionConstraint"] + +import abc +import configparser as cp +import fnmatch +from functools import wraps +import inspect +from io import BufferedReader, IOBase +import logging +import os +import os.path as osp +import re +import sys + +from git.compat import defenc, force_text +from git.util import LockFile + +# typing------------------------------------------------------- + +from typing import ( + Any, + Callable, + Generic, + IO, + List, + Dict, + Sequence, + TYPE_CHECKING, + Tuple, + TypeVar, + Union, + cast, +) + +from git.types import Lit_config_levels, ConfigLevels_Tup, PathLike, assert_never, _T + +if TYPE_CHECKING: + from io import BytesIO + + from git.repo.base import Repo + +T_ConfigParser = TypeVar("T_ConfigParser", bound="GitConfigParser") +T_OMD_value = TypeVar("T_OMD_value", str, bytes, int, float, bool) + +if sys.version_info[:3] < (3, 7, 2): + # typing.Ordereddict not added until Python 3.7.2. + from collections import OrderedDict + + OrderedDict_OMD = OrderedDict +else: + from typing import OrderedDict + + OrderedDict_OMD = OrderedDict[str, List[T_OMD_value]] # type: ignore[assignment, misc] + +# ------------------------------------------------------------- + +_logger = logging.getLogger(__name__) + +CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository") +"""The configuration level of a configuration file.""" + +CONDITIONAL_INCLUDE_REGEXP = re.compile(r"(?<=includeIf )\"(gitdir|gitdir/i|onbranch|hasconfig:remote\.\*\.url):(.+)\"") +"""Section pattern to detect conditional includes. + +See: https://git-scm.com/docs/git-config#_conditional_includes +""" + + +class MetaParserBuilder(abc.ABCMeta): # noqa: B024 + """Utility class wrapping base-class methods into decorators that assure read-only + properties.""" + + def __new__(cls, name: str, bases: Tuple, clsdict: Dict[str, Any]) -> "MetaParserBuilder": + """Equip all base-class methods with a needs_values decorator, and all non-const + methods with a :func:`set_dirty_and_flush_changes` decorator in addition to + that. + """ + kmm = "_mutating_methods_" + if kmm in clsdict: + mutating_methods = clsdict[kmm] + for base in bases: + methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_")) + for method_name, method in methods: + if method_name in clsdict: + continue + method_with_values = needs_values(method) + if method_name in mutating_methods: + method_with_values = set_dirty_and_flush_changes(method_with_values) + # END mutating methods handling + + clsdict[method_name] = method_with_values + # END for each name/method pair + # END for each base + # END if mutating methods configuration is set + + new_type = super().__new__(cls, name, bases, clsdict) + return new_type + + +def needs_values(func: Callable[..., _T]) -> Callable[..., _T]: + """Return a method for ensuring we read values (on demand) before we try to access + them.""" + + @wraps(func) + def assure_data_present(self: "GitConfigParser", *args: Any, **kwargs: Any) -> _T: + self.read() + return func(self, *args, **kwargs) + + # END wrapper method + return assure_data_present + + +def set_dirty_and_flush_changes(non_const_func: Callable[..., _T]) -> Callable[..., _T]: + """Return a method that checks whether given non constant function may be called. + + If so, the instance will be set dirty. Additionally, we flush the changes right to + disk. + """ + + def flush_changes(self: "GitConfigParser", *args: Any, **kwargs: Any) -> _T: + rval = non_const_func(self, *args, **kwargs) + self._dirty = True + self.write() + return rval + + # END wrapper method + flush_changes.__name__ = non_const_func.__name__ + return flush_changes + + +class SectionConstraint(Generic[T_ConfigParser]): + """Constrains a ConfigParser to only option commands which are constrained to + always use the section we have been initialized with. + + It supports all ConfigParser methods that operate on an option. + + :note: + If used as a context manager, will release the wrapped ConfigParser. + """ + + __slots__ = ("_config", "_section_name") + + _valid_attrs_ = ( + "get_value", + "set_value", + "get", + "set", + "getint", + "getfloat", + "getboolean", + "has_option", + "remove_section", + "remove_option", + "options", + ) + + def __init__(self, config: T_ConfigParser, section: str) -> None: + self._config = config + self._section_name = section + + def __del__(self) -> None: + # Yes, for some reason, we have to call it explicitly for it to work in PY3 ! + # Apparently __del__ doesn't get call anymore if refcount becomes 0 + # Ridiculous ... . + self._config.release() + + def __getattr__(self, attr: str) -> Any: + if attr in self._valid_attrs_: + return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs) + return super().__getattribute__(attr) + + def _call_config(self, method: str, *args: Any, **kwargs: Any) -> Any: + """Call the configuration at the given method which must take a section name as + first argument.""" + return getattr(self._config, method)(self._section_name, *args, **kwargs) + + @property + def config(self) -> T_ConfigParser: + """return: ConfigParser instance we constrain""" + return self._config + + def release(self) -> None: + """Equivalent to :meth:`GitConfigParser.release`, which is called on our + underlying parser instance.""" + return self._config.release() + + def __enter__(self) -> "SectionConstraint[T_ConfigParser]": + self._config.__enter__() + return self + + def __exit__(self, exception_type: str, exception_value: str, traceback: str) -> None: + self._config.__exit__(exception_type, exception_value, traceback) + + +class _OMD(OrderedDict_OMD): + """Ordered multi-dict.""" + + def __setitem__(self, key: str, value: _T) -> None: + super().__setitem__(key, [value]) + + def add(self, key: str, value: Any) -> None: + if key not in self: + super().__setitem__(key, [value]) + return + + super().__getitem__(key).append(value) + + def setall(self, key: str, values: List[_T]) -> None: + super().__setitem__(key, values) + + def __getitem__(self, key: str) -> Any: + return super().__getitem__(key)[-1] + + def getlast(self, key: str) -> Any: + return super().__getitem__(key)[-1] + + def setlast(self, key: str, value: Any) -> None: + if key not in self: + super().__setitem__(key, [value]) + return + + prior = super().__getitem__(key) + prior[-1] = value + + def get(self, key: str, default: Union[_T, None] = None) -> Union[_T, None]: + return super().get(key, [default])[-1] + + def getall(self, key: str) -> List[_T]: + return super().__getitem__(key) + + def items(self) -> List[Tuple[str, _T]]: # type: ignore[override] + """List of (key, last value for key).""" + return [(k, self[k]) for k in self] + + def items_all(self) -> List[Tuple[str, List[_T]]]: + """List of (key, list of values for key).""" + return [(k, self.getall(k)) for k in self] + + +def get_config_path(config_level: Lit_config_levels) -> str: + # We do not support an absolute path of the gitconfig on Windows. + # Use the global config instead. + if sys.platform == "win32" and config_level == "system": + config_level = "global" + + if config_level == "system": + return "/etc/gitconfig" + elif config_level == "user": + config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", "~"), ".config") + return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config"))) + elif config_level == "global": + return osp.normpath(osp.expanduser("~/.gitconfig")) + elif config_level == "repository": + raise ValueError("No repo to get repository configuration from. Use Repo._get_config_path") + else: + # Should not reach here. Will raise ValueError if does. Static typing will warn + # about missing elifs. + assert_never( # type: ignore[unreachable] + config_level, + ValueError(f"Invalid configuration level: {config_level!r}"), + ) + + +class GitConfigParser(cp.RawConfigParser, metaclass=MetaParserBuilder): + """Implements specifics required to read git style configuration files. + + This variation behaves much like the :manpage:`git-config(1)` command, such that the + configuration will be read on demand based on the filepath given during + initialization. + + The changes will automatically be written once the instance goes out of scope, but + can be triggered manually as well. + + The configuration file will be locked if you intend to change values preventing + other instances to write concurrently. + + :note: + The config is case-sensitive even when queried, hence section and option names + must match perfectly. + + :note: + If used as a context manager, this will release the locked file. + """ + + # { Configuration + t_lock = LockFile + """The lock type determines the type of lock to use in new configuration readers. + + They must be compatible to the :class:`~git.util.LockFile` interface. + A suitable alternative would be the :class:`~git.util.BlockingLockFile`. + """ + + re_comment = re.compile(r"^\s*[#;]") + # } END configuration + + optvalueonly_source = r"\s*(?P