diff options
| author | Sergey Shepelev <temotor@gmail.com> | 2014-04-02 15:48:28 +0400 |
|---|---|---|
| committer | Sergey Shepelev <temotor@gmail.com> | 2015-02-21 16:51:18 +0300 |
| commit | c6e5320f6b4b881aa7de77e4814167ccb8c2bf7c (patch) | |
| tree | 89aaf1c1423200f8da42f1d86a2dbfba344a08ae | |
| parent | a6ce444265d36fb23361809d40da73caf4864487 (diff) | |
| download | eventlet-run_python.tar.gz | |
tests: ProcessBase -> run_pythonrun_python
Extracted inline code to permanent files
Python3 compatibility of test files
tests.run_python: new_tmp flag to create new temporary directory and
pass it to child process via environ[TMP].
The directory with any files is removed when child process is
finished.
tests.rmtree: silent version of shutil.rmtree()
40 files changed, 758 insertions, 646 deletions
diff --git a/tests/__init__.py b/tests/__init__.py index f2e7e4e..fa8e34b 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -9,9 +9,11 @@ try: import resource except ImportError: resource = None +import shutil import signal import subprocess import sys +import tempfile import unittest import warnings @@ -305,22 +307,44 @@ def get_database_auth(): return retval -def run_python(path): +def rmtree(path): + try: + shutil.rmtree(path) + except (IOError, OSError) as e: + # Reraise unless ENOENT: No such file or directory + # (ok if directory has already been deleted) + if e.errno != errno.ENOENT: + raise + + +def run_python(path, env=None, new_tmp=False): if not path.endswith('.py'): path += '.py' path = os.path.abspath(path) dir_ = os.path.dirname(path) + new_env = os.environ.copy() new_env['PYTHONPATH'] = os.pathsep.join(sys.path + [dir_]) - p = subprocess.Popen( - [sys.executable, path], - env=new_env, - stderr=subprocess.STDOUT, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - ) - output, _ = p.communicate() - return output + if env: + new_env.update(env) + temp_path = tempfile.gettempdir() + if new_tmp: + temp_path = tempfile.mkdtemp(prefix='tmp-eventlet-test-') + new_env['TMP'] = temp_path + + try: + p = subprocess.Popen( + [sys.executable, path], + env=new_env, + stderr=subprocess.STDOUT, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) + output, _ = p.communicate() + return output.decode('utf-8', 'replace') + finally: + if new_tmp: + rmtree(temp_path) certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') diff --git a/tests/env_test.py b/tests/env_test.py index f8931c1..71f7129 100644 --- a/tests/env_test.py +++ b/tests/env_test.py @@ -1,114 +1,66 @@ -import os -from eventlet.support import six -from tests.patcher_test import ProcessBase -from tests import skip_with_pyevent +import tests -class Socket(ProcessBase): +class Socket(tests.LimitedTestCase): def test_patched_thread(self): - new_mod = """from eventlet.green import socket -socket.gethostbyname('localhost') -socket.getaddrinfo('localhost', 80) -""" - os.environ['EVENTLET_TPOOL_DNS'] = 'yes' - try: - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 1, lines) - finally: - del os.environ['EVENTLET_TPOOL_DNS'] + env = {'EVENTLET_TPOOL_DNS': 'yes'} + output = tests.run_python('tests/env_test_socket_getaddrinfo.py', env=env) + lines = output.splitlines() + self.assertEqual(len(lines), 2, lines) -class Tpool(ProcessBase): - @skip_with_pyevent - def test_tpool_size(self): - expected = "40" - normal = "20" - new_mod = """from eventlet import tpool -import eventlet -import time -current = [0] -highwater = [0] -def count(): - current[0] += 1 - time.sleep(0.1) - if current[0] > highwater[0]: - highwater[0] = current[0] - current[0] -= 1 -expected = %s -normal = %s -p = eventlet.GreenPool() -for i in range(expected*2): - p.spawn(tpool.execute, count) -p.waitall() -assert highwater[0] > 20, "Highwater %%s <= %%s" %% (highwater[0], normal) -""" - os.environ['EVENTLET_THREADPOOL_SIZE'] = expected - try: - self.write_to_tempfile("newmod", new_mod % (expected, normal)) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 1, lines) - finally: - del os.environ['EVENTLET_THREADPOOL_SIZE'] +class Tpool(tests.LimitedTestCase): + longMessage = True + maxDiff = None - def test_tpool_negative(self): - new_mod = """from eventlet import tpool -import eventlet -import time -def do(): - print("should not get here") -try: - tpool.execute(do) -except AssertionError: - print("success") -""" - os.environ['EVENTLET_THREADPOOL_SIZE'] = "-1" - try: - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, lines) - self.assertEqual(lines[0], "success", output) - finally: - del os.environ['EVENTLET_THREADPOOL_SIZE'] + @tests.skip_with_pyevent + def test_tpool_size_default(self): + # modify this together with default value in eventlet.tpool + expected = 20 + env = {'eventlet_test_limit': str(expected + 20)} + output = tests.run_python('tests/env_test_tpool_size.py', env=env) + lines = output.splitlines() + self.assertEqual(len(lines), 1, output) + highwater = int(output.strip()) + self.assertEqual(highwater, expected, output) - def test_tpool_zero(self): - new_mod = """from eventlet import tpool -import eventlet -import time -def do(): - print("ran it") -tpool.execute(do) -""" - os.environ['EVENTLET_THREADPOOL_SIZE'] = "0" - try: - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 4, lines) - self.assertEqual(lines[-2], 'ran it', lines) - assert 'Warning' in lines[1] or 'Warning' in lines[0], lines - finally: - del os.environ['EVENTLET_THREADPOOL_SIZE'] + @tests.skip_with_pyevent + def test_tpool_size_custom(self): + expected = 40 + env = { + 'EVENTLET_THREADPOOL_SIZE': str(expected), + 'eventlet_test_limit': str(expected + 20), + } + output = tests.run_python('tests/env_test_tpool_size.py', env=env) + lines = output.splitlines() + self.assertEqual(len(lines), 1, output) + highwater = int(output.strip()) + self.assertEqual(highwater, expected, output) + def test_tpool_negative(self): + env = {'EVENTLET_THREADPOOL_SIZE': '-1'} + output = tests.run_python('tests/env_test_tpool_size.py', env=env) + lines = output.splitlines() + self.assert_(len(lines) > 1, output) + highwater = int(lines[-1]) + self.assert_('AssertionError' in output, output) + self.assertEqual(highwater, 0, output) -class Hub(ProcessBase): + def test_tpool_zero(self): + env = {'EVENTLET_THREADPOOL_SIZE': '0'} + output = tests.run_python('tests/env_test_tpool_size.py', env=env) + lines = output.splitlines() + self.assert_(len(lines) > 1, output) + self.assert_('Warning' in output, output) + self.assertEqual(lines[-1], '1', output) - def setUp(self): - super(Hub, self).setUp() - self.old_environ = os.environ.get('EVENTLET_HUB') - os.environ['EVENTLET_HUB'] = 'selects' - def tearDown(self): - if self.old_environ: - os.environ['EVENTLET_HUB'] = self.old_environ - else: - del os.environ['EVENTLET_HUB'] - super(Hub, self).tearDown() +class Hub(tests.LimitedTestCase): def test_eventlet_hub(self): - new_mod = """from eventlet import hubs -print(hubs.get_hub()) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, "\n".join(lines)) - assert "selects" in lines[0] + for hub in ('selects',): + env = {'EVENTLET_HUB': 'selects'} + output = tests.run_python('tests/env_test_hub.py', env=env) + lines = output.splitlines() + self.assertEqual(len(lines), 1, output) + self.assert_(hub in output, output) diff --git a/tests/env_test_hub.py b/tests/env_test_hub.py new file mode 100644 index 0000000..0511d48 --- /dev/null +++ b/tests/env_test_hub.py @@ -0,0 +1,6 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet import hubs + print(hubs.get_hub()) diff --git a/tests/env_test_socket_getaddrinfo.py b/tests/env_test_socket_getaddrinfo.py new file mode 100644 index 0000000..5fd6119 --- /dev/null +++ b/tests/env_test_socket_getaddrinfo.py @@ -0,0 +1,7 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet.green import socket + print(socket.gethostbyname('localhost')) + print(socket.getaddrinfo('localhost', 80)) diff --git a/tests/env_test_tpool_size.py b/tests/env_test_tpool_size.py new file mode 100644 index 0000000..ecf4be4 --- /dev/null +++ b/tests/env_test_tpool_size.py @@ -0,0 +1,23 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet import tpool + import eventlet + import os + import threading + import time + + limit = int(os.environ.get('eventlet_test_limit', '1')) + thread_ids = set() + + def count(): + tid = threading.current_thread().ident + thread_ids.add(tid) + time.sleep(0.1) + + p = eventlet.GreenPool() + for i in range(limit): + p.spawn(tpool.execute, count) + p.waitall() + print(len(thread_ids)) diff --git a/tests/fork_test.py b/tests/fork_test.py index f15883f..e6a4fc1 100644 --- a/tests/fork_test.py +++ b/tests/fork_test.py @@ -1,52 +1,8 @@ -from tests.patcher_test import ProcessBase +import tests -class ForkTest(ProcessBase): - def test_simple(self): - newmod = ''' -import eventlet -import os -import sys -import signal -from eventlet.support import bytes_to_str, six -mydir = %r -signal_file = os.path.join(mydir, "output.txt") -pid = os.fork() -if (pid != 0): - eventlet.Timeout(10) - try: - port = None - while True: - try: - contents = open(signal_file, "rb").read() - port = int(contents.split()[0]) - break - except (IOError, IndexError, ValueError, TypeError): - eventlet.sleep(0.1) - eventlet.connect(('127.0.0.1', port)) - while True: - try: - contents = open(signal_file, "rb").read() - result = contents.split()[1] - break - except (IOError, IndexError): - eventlet.sleep(0.1) - print('result {0}'.format(bytes_to_str(result))) - finally: - os.kill(pid, signal.SIGTERM) -else: - try: - s = eventlet.listen(('', 0)) - fd = open(signal_file, "wb") - fd.write(six.b(str(s.getsockname()[1]))) - fd.write(b"\\n") - fd.flush() - s.accept() - fd.write(b"done") - fd.flush() - finally: - fd.close() -''' - self.write_to_tempfile("newmod", newmod % self.tempdir) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(lines[0], "result done", output) +def test_fork_simple(): + output = tests.run_python('tests/fork_test_simple.py', new_tmp=True) + lines = output.splitlines() + assert len(lines) == 1, output + assert lines[0] == 'result done', output diff --git a/tests/fork_test_simple.py b/tests/fork_test_simple.py new file mode 100644 index 0000000..ac8d1ea --- /dev/null +++ b/tests/fork_test_simple.py @@ -0,0 +1,52 @@ +from __future__ import print_function +# no standard tests in this file, ignore +__test__ = False + + +def parent(pid): + import signal + + eventlet.Timeout(1) + try: + port = None + while True: + try: + contents = open(signal_path, 'rb').read() + port = int(contents.split()[0]) + break + except (IOError, IndexError, ValueError, TypeError): + eventlet.sleep(0.1) + eventlet.connect(('127.0.0.1', port)) + while True: + try: + contents = open(signal_path, 'rb').read() + result = contents.split()[1] + break + except (IOError, IndexError): + eventlet.sleep(0.1) + print('result {0}'.format(result.decode())) + finally: + os.kill(pid, signal.SIGTERM) + + +def child(): + sock = eventlet.listen(('', 0)) + with open(signal_path, 'wb') as fd: + msg = '{0}\n'.format(sock.getsockname()[1]).encode() + fd.write(msg) + fd.flush() + sock.accept() + fd.write(b'done') + +if __name__ == '__main__': + import eventlet + import os + + signal_path = os.path.join(os.environ['TMP'], 'fork_test_simple_signal.txt') + pid = os.fork() + if pid > 0: + parent(pid) + elif pid == 0: + child() + else: + print('fork failed') diff --git a/tests/hub_test.py b/tests/hub_test.py index 07e502a..7020b97 100644 --- a/tests/hub_test.py +++ b/tests/hub_test.py @@ -1,15 +1,12 @@ -from __future__ import with_statement import sys - -import tests -from tests import LimitedTestCase, main, skip_with_pyevent, skip_if_no_itimer, skip_unless -from tests.patcher_test import ProcessBase import time + import eventlet from eventlet import hubs from eventlet.event import Event from eventlet.semaphore import Semaphore from eventlet.support import greenlets, six +import tests DELAY = 0.001 @@ -19,10 +16,10 @@ def noop(): pass -class TestTimerCleanup(LimitedTestCase): +class TestTimerCleanup(tests.LimitedTestCase): TEST_TIMEOUT = 2 - @skip_with_pyevent + @tests.skip_with_pyevent def test_cancel_immediate(self): hub = hubs.get_hub() stimers = hub.get_timers_count() @@ -36,7 +33,7 @@ class TestTimerCleanup(LimitedTestCase): self.assert_less_than_equal(hub.get_timers_count(), 1000 + stimers) self.assert_less_than_equal(hub.timers_canceled, 1000) - @skip_with_pyevent + @tests.skip_with_pyevent def test_cancel_accumulated(self): hub = hubs.get_hub() stimers = hub.get_timers_count() @@ -53,7 +50,7 @@ class TestTimerCleanup(LimitedTestCase): self.assert_less_than_equal(hub.get_timers_count(), 1000 + stimers) self.assert_less_than_equal(hub.timers_canceled, 1000) - @skip_with_pyevent + @tests.skip_with_pyevent def test_cancel_proportion(self): # if fewer than half the pending timers are canceled, it should # not clean them out @@ -85,7 +82,7 @@ class TestTimerCleanup(LimitedTestCase): eventlet.sleep() -class TestScheduleCall(LimitedTestCase): +class TestScheduleCall(tests.LimitedTestCase): def test_local(self): lst = [1] @@ -111,7 +108,7 @@ class TestScheduleCall(LimitedTestCase): self.assertEqual(lst, [1, 2, 3]) -class TestDebug(LimitedTestCase): +class TestDebug(tests.LimitedTestCase): def test_debug_listeners(self): hubs.get_hub().set_debug_listeners(True) @@ -122,7 +119,7 @@ class TestDebug(LimitedTestCase): hubs.get_hub().set_timer_exceptions(False) -class TestExceptionInMainloop(LimitedTestCase): +class TestExceptionInMainloop(tests.LimitedTestCase): def test_sleep(self): # even if there was an error in the mainloop, the hub should continue @@ -149,9 +146,9 @@ class TestExceptionInMainloop(LimitedTestCase): delay, DELAY) -class TestExceptionInGreenthread(LimitedTestCase): +class TestExceptionInGreenthread(tests.LimitedTestCase): - @skip_unless(greenlets.preserves_excinfo) + @tests.skip_unless(greenlets.preserves_excinfo) def test_exceptionpreservation(self): # events for controlling execution order gt1event = Event() @@ -206,7 +203,7 @@ class TestExceptionInGreenthread(LimitedTestCase): g.kill() -class TestHubSelection(LimitedTestCase): +class TestHubSelection(tests.LimitedTestCase): def test_explicit_hub(self): oldhub = hubs.get_hub() @@ -217,10 +214,10 @@ class TestHubSelection(LimitedTestCase): hubs._threadlocal.hub = oldhub -class TestHubBlockingDetector(LimitedTestCase): +class TestHubBlockingDetector(tests.LimitedTestCase): TEST_TIMEOUT = 10 - @skip_with_pyevent + @tests.skip_with_pyevent def test_block_detect(self): def look_im_blocking(): import time @@ -231,8 +228,8 @@ class TestHubBlockingDetector(LimitedTestCase): self.assertRaises(RuntimeError, gt.wait) debug.hub_blocking_detection(False) - @skip_with_pyevent - @skip_if_no_itimer + @tests.skip_with_pyevent + @tests.skip_if_no_itimer def test_block_detect_with_itimer(self): def look_im_blocking(): import time @@ -245,7 +242,7 @@ class TestHubBlockingDetector(LimitedTestCase): debug.hub_blocking_detection(False) -class TestSuspend(LimitedTestCase): +class TestSuspend(tests.LimitedTestCase): TEST_TIMEOUT = 3 longMessage = True maxDiff = None @@ -283,25 +280,25 @@ except eventlet.Timeout: shutil.rmtree(self.tempdir) -class TestBadFilenos(LimitedTestCase): +class TestBadFilenos(tests.LimitedTestCase): - @skip_with_pyevent + @tests.skip_with_pyevent def test_repeated_selects(self): from eventlet.green import select self.assertRaises(ValueError, select.select, [-1], [], []) self.assertRaises(ValueError, select.select, [-1], [], []) -class TestFork(LimitedTestCase): +class TestFork(tests.LimitedTestCase): - @skip_with_pyevent + @tests.skip_with_pyevent def test_fork(self): output = tests.run_python('tests/hub_test_fork.py') lines = output.splitlines() self.assertEqual(lines, [b"accept blocked", b"child died ok"], output) -class TestDeadRunLoop(LimitedTestCase): +class TestDeadRunLoop(tests.LimitedTestCase): TEST_TIMEOUT = 2 class CustomException(Exception): @@ -361,43 +358,14 @@ class Foo(object): pass -class TestDefaultHub(ProcessBase): +class TestDefaultHub(tests.LimitedTestCase): def test_kqueue_unsupported(self): # https://github.com/eventlet/eventlet/issues/38 # get_hub on windows broken by kqueue - module_source = r''' -from __future__ import print_function - -# Simulate absence of kqueue even on platforms that support it. -import select -try: - del select.kqueue -except AttributeError: - pass - -from eventlet.support.six.moves import builtins - -original_import = builtins.__import__ - -def fail_import(name, *args, **kwargs): - if 'epoll' in name: - raise ImportError('disabled for test') - if 'kqueue' in name: - print('kqueue tried') - return original_import(name, *args, **kwargs) - -builtins.__import__ = fail_import - - -import eventlet.hubs -eventlet.hubs.get_default_hub() -print('ok') -''' - self.write_to_tempfile('newmod', module_source) - output, _ = self.launch_subprocess('newmod.py') + output = tests.run_python('tests/hub_test_kqueue_unsupported.py') self.assertEqual(output, 'kqueue tried\nok\n') if __name__ == '__main__': - main() + tests.main() diff --git a/tests/hub_test_kqueue_unsupported.py b/tests/hub_test_kqueue_unsupported.py new file mode 100644 index 0000000..2c477d5 --- /dev/null +++ b/tests/hub_test_kqueue_unsupported.py @@ -0,0 +1,31 @@ +# https://github.com/eventlet/eventlet/issues/38 +# get_hub on windows broken by kqueue +from __future__ import print_function + +# no standard tests in this file, ignore +__test__ = False + + +if __name__ == '__main__': + # Simulate absence of kqueue even on platforms that support it. + import select + try: + del select.kqueue + except AttributeError: + pass + + from eventlet.support.six.moves import builtins + original_import = builtins.__import__ + + def fail_import(name, *args, **kwargs): + if 'epoll' in name: + raise ImportError('disabled for test') + if 'kqueue' in name: + print('kqueue tried') + return original_import(name, *args, **kwargs) + + builtins.__import__ = fail_import + + import eventlet.hubs + eventlet.hubs.get_default_hub() + print('ok') diff --git a/tests/mysqldb_test_monkey_patch.py b/tests/mysqldb_test_monkey_patch.py index a76178e..66e15de 100644 --- a/tests/mysqldb_test_monkey_patch.py +++ b/tests/mysqldb_test_monkey_patch.py @@ -1,12 +1,13 @@ from __future__ import print_function -from eventlet import patcher # no standard tests in this file, ignore __test__ = False if __name__ == '__main__': import MySQLdb as m + from eventlet import patcher from eventlet.green import MySQLdb as gm + patcher.monkey_patch(all=True, MySQLdb=True) print("mysqltest {0}".format(",".join(sorted(patcher.already_patched.keys())))) print("connect {0}".format(m.connect == gm.connect)) diff --git a/tests/patcher_psycopg_test.py b/tests/patcher_psycopg_test.py index 83ffdfa..eb83b4c 100644 --- a/tests/patcher_psycopg_test.py +++ b/tests/patcher_psycopg_test.py @@ -1,56 +1,25 @@ import os from eventlet.support import six - -from tests import patcher_test, skip_unless -from tests import get_database_auth +import tests from tests.db_pool_test import postgres_requirement -psycopg_test_file = """ -import os -import sys -import eventlet -eventlet.monkey_patch() -from eventlet import patcher -if not patcher.is_monkey_patched('psycopg'): - print("Psycopg not monkeypatched") - sys.exit(0) - -count = [0] -def tick(totalseconds, persecond): - for i in range(totalseconds*persecond): - count[0] += 1 - eventlet.sleep(1.0/persecond) - -dsn = os.environ['PSYCOPG_TEST_DSN'] -import psycopg2 -def fetch(num, secs): - conn = psycopg2.connect(dsn) - cur = conn.cursor() - for i in range(num): - cur.execute("select pg_sleep(%s)", (secs,)) - -f = eventlet.spawn(fetch, 2, 1) -t = eventlet.spawn(tick, 2, 100) -f.wait() -assert count[0] > 100, count[0] -print("done") -""" - -class PatchingPsycopg(patcher_test.ProcessBase): - @skip_unless(postgres_requirement) +class PatchingPsycopg(tests.LimitedTestCase): + @tests.skip_unless(postgres_requirement) def test_psycopg_patched(self): - if 'PSYCOPG_TEST_DSN' not in os.environ: + dsn = os.environ.get('PSYCOPG_TEST_DSN') + if dsn is None: # construct a non-json dsn for the subprocess - psycopg_auth = get_database_auth()['psycopg2'] - if isinstance(psycopg_auth, str): + psycopg_auth = tests.get_database_auth()['psycopg2'] + if isinstance(psycopg_auth, six.string_types): dsn = psycopg_auth else: - dsn = " ".join(["%s=%s" % (k, v) for k, v in six.iteritems(psycopg_auth)]) - os.environ['PSYCOPG_TEST_DSN'] = dsn - self.write_to_tempfile("psycopg_patcher", psycopg_test_file) - output, lines = self.launch_subprocess('psycopg_patcher.py') + dsn = " ".join("%s=%s" % (k, v) for k, v in six.iteritems(psycopg_auth)) + env = {'PSYCOPG_TEST_DSN': dsn} + output = tests.run_python('tests/patcher_psycopg_test_patched.py', env=env) + lines = output.splitlines() + assert len(lines) > 0, output if lines[0].startswith('Psycopg not monkeypatched'): print("Can't test psycopg2 patching; it's not installed.") return diff --git a/tests/patcher_psycopg_test_patched.py b/tests/patcher_psycopg_test_patched.py new file mode 100644 index 0000000..9be75ef --- /dev/null +++ b/tests/patcher_psycopg_test_patched.py @@ -0,0 +1,37 @@ +from __future__ import print_function +# no standard tests in this file, ignore +__test__ = False + + +def fetch(dsn, num, secs): + conn = psycopg2.connect(dsn) + cur = conn.cursor() + for i in range(num): + cur.execute("select pg_sleep(%s)", [secs]) + + +def tick(count, totalseconds, persecond): + for i in range(totalseconds * persecond): + count[0] += 1 + eventlet.sleep(1.0 / persecond) + + +if __name__ == '__main__': + import os + import sys + import eventlet + eventlet.monkey_patch() + from eventlet import patcher + if not patcher.is_monkey_patched('psycopg'): + print("Psycopg not monkeypatched") + sys.exit(0) + + dsn = os.environ['PSYCOPG_TEST_DSN'] + import psycopg2 + + count = [0] + f = eventlet.spawn(fetch, dsn, 2, 1) + t = eventlet.spawn(tick, count, 2, 100) + f.wait() + assert count[0] > 100, count[0] + print("done") diff --git a/tests/patcher_test.py b/tests/patcher_test.py index 3ace281..23fe7b1 100644 --- a/tests/patcher_test.py +++ b/tests/patcher_test.py @@ -1,179 +1,59 @@ -import os -import shutil -import sys -import tempfile +import tests -from eventlet.support import six -from tests import LimitedTestCase, main, run_python, skip_with_pyevent - -base_module_contents = """ -import socket -import urllib -print("base {0} {1}".format(socket, urllib)) -""" - -patching_module_contents = """ -from eventlet.green import socket -from eventlet.green import urllib -from eventlet import patcher -print('patcher {0} {1}'.format(socket, urllib)) -patcher.inject('base', globals(), ('socket', socket), ('urllib', urllib)) -del patcher -""" - -import_module_contents = """ -import patching -import socket -print("importing {0} {1} {2} {3}".format(patching, socket, patching.socket, patching.urllib)) -""" - - -class ProcessBase(LimitedTestCase): - TEST_TIMEOUT = 3 # starting processes is time-consuming - - def setUp(self): - super(ProcessBase, self).setUp() - self._saved_syspath = sys.path - self.tempdir = tempfile.mkdtemp('_patcher_test') - - def tearDown(self): - super(ProcessBase, self).tearDown() - sys.path = self._saved_syspath - shutil.rmtree(self.tempdir) - - def write_to_tempfile(self, name, contents): - filename = os.path.join(self.tempdir, name) - if not filename.endswith('.py'): - filename = filename + '.py' - with open(filename, "w") as fd: - fd.write(contents) - - def launch_subprocess(self, filename): - path = os.path.join(self.tempdir, filename) - output = run_python(path) - if six.PY3: - output = output.decode('utf-8') - separator = '\n' - else: - separator = b'\n' - lines = output.split(separator) - return output, lines - - def run_script(self, contents, modname=None): - if modname is None: - modname = "testmod" - self.write_to_tempfile(modname, contents) - return self.launch_subprocess(modname) - - -class ImportPatched(ProcessBase): +class TestImportPatched(tests.LimitedTestCase): def test_patch_a_module(self): - self.write_to_tempfile("base", base_module_contents) - self.write_to_tempfile("patching", patching_module_contents) - self.write_to_tempfile("importing", import_module_contents) - output, lines = self.launch_subprocess('importing.py') - assert lines[0].startswith('patcher'), repr(output) - assert lines[1].startswith('base'), repr(output) - assert lines[2].startswith('importing'), repr(output) - assert 'eventlet.green.socket' in lines[1], repr(output) - assert 'eventlet.green.urllib' in lines[1], repr(output) - assert 'eventlet.green.socket' in lines[2], repr(output) - assert 'eventlet.green.urllib' in lines[2], repr(output) - assert 'eventlet.green.httplib' not in lines[2], repr(output) + output = tests.run_python('tests/patcher_test_import_module.py') + lines = output.splitlines() + assert lines[0].startswith('patcher'), output + assert lines[1].startswith('base'), output + assert lines[2].startswith('importing'), output + assert 'eventlet.green.socket' in lines[1], output + assert 'eventlet.green.urllib' in lines[1], output + assert 'eventlet.green.socket' in lines[2], output + assert 'eventlet.green.urllib' in lines[2], output + assert 'eventlet.green.httplib' not in lines[2], output def test_import_patched_defaults(self): - self.write_to_tempfile("base", """ -import socket -try: - import urllib.request as urllib -except ImportError: - import urllib -print("base {0} {1}".format(socket, urllib))""") - - new_mod = """ -from eventlet import patcher -base = patcher.import_patched('base') -print("newmod {0} {1} {2}".format(base, base.socket, base.urllib.socket.socket)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - assert lines[0].startswith('base'), repr(output) - assert lines[1].startswith('newmod'), repr(output) - assert 'eventlet.green.socket' in lines[1], repr(output) - assert 'GreenSocket' in lines[1], repr(output) + output = tests.run_python('tests/patcher_test_import_defaults.py') + lines = output.splitlines() + assert lines[0].startswith('base'), output + assert lines[1].startswith('defaults'), output + assert 'eventlet.green.socket' in lines[1], output + assert 'GreenSocket' in lines[1], output -class MonkeyPatch(ProcessBase): +class TestMonkeyPatch(tests.LimitedTestCase): def test_patched_modules(self): - new_mod = """ -from eventlet import patcher -patcher.monkey_patch() -import socket -try: - import urllib.request as urllib -except ImportError: - import urllib -print("newmod {0} {1}".format(socket.socket, urllib.socket.socket)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - assert lines[0].startswith('newmod'), repr(output) - self.assertEqual(lines[0].count('GreenSocket'), 2, repr(output)) + output = tests.run_python('tests/patcher_test_monkey_patched_modules.py') + lines = output.splitlines() + assert len(lines) > 0, output + assert lines[0].startswith('child'), output + assert lines[0].count('GreenSocket') == 2, output def test_early_patching(self): - new_mod = """ -from eventlet import patcher -patcher.monkey_patch() -import eventlet -eventlet.sleep(0.01) -print("newmod") -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, repr(output)) - assert lines[0].startswith('newmod'), repr(output) + output = tests.run_python('tests/patcher_test_monkey_early_patching.py') + assert output == u'ok\n' def test_late_patching(self): - new_mod = """ -import eventlet -eventlet.sleep(0.01) -from eventlet import patcher -patcher.monkey_patch() -eventlet.sleep(0.01) -print("newmod") -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, repr(output)) - assert lines[0].startswith('newmod'), repr(output) + output = tests.run_python('tests/patcher_test_monkey_late_patching.py') + assert output == u'ok\n' def test_typeerror(self): - new_mod = """ -from eventlet import patcher -patcher.monkey_patch(finagle=True) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - assert lines[-2].startswith('TypeError'), repr(output) - assert 'finagle' in lines[-2], repr(output) + output = tests.run_python('tests/patcher_test_monkey_typeerror.py') + assert "TypeError: monkey_patch() got an unexpected keyword argument 'finagle'" in output, output def assert_boolean_logic(self, call, expected, not_expected=''): - expected_list = ", ".join(['"%s"' % x for x in expected.split(',') if len(x)]) - not_expected_list = ", ".join(['"%s"' % x for x in not_expected.split(',') if len(x)]) - new_mod = """ -from eventlet import patcher -%s -for mod in [%s]: - assert patcher.is_monkey_patched(mod), mod -for mod in [%s]: - assert not patcher.is_monkey_patched(mod), mod -print("already_patched {0}".format(",".join(sorted(patcher.already_patched.keys())))) -""" % (call, expected_list, not_expected_list) - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') + env = { + 'call': call, + 'expected': expected, + 'not_expected': not_expected, + } + output = tests.run_python('tests/patcher_test_assert_boolean_logic.py', env=env) + lines = output.splitlines() + assert len(lines) > 0, output ap = 'already_patched' - assert lines[0].startswith(ap), repr(output) + assert lines[0].startswith(ap), output patched_modules = lines[0][len(ap):].strip() # psycopg might or might not be patched based on installed modules patched_modules = patched_modules.replace("psycopg,", "") @@ -221,203 +101,82 @@ print("already_patched {0}".format(",".join(sorted(patcher.already_patched.keys( 'select') -test_monkey_patch_threading = """ -def test_monkey_patch_threading(): - tickcount = [0] - - def tick(): - from eventlet.support import six - for i in six.moves.range(1000): - tickcount[0] += 1 - eventlet.sleep() - - def do_sleep(): - tpool.execute(time.sleep, 0.5) - - eventlet.spawn(tick) - w1 = eventlet.spawn(do_sleep) - w1.wait() - print(tickcount[0]) - assert tickcount[0] > 900 - tpool.killall() -""" - - -class Tpool(ProcessBase): +class TestTpool(tests.LimitedTestCase): TEST_TIMEOUT = 3 - @skip_with_pyevent + @tests.skip_with_pyevent def test_simple(self): - new_mod = """ -import eventlet -from eventlet import patcher -patcher.monkey_patch() -from eventlet import tpool -print("newmod {0}".format(tpool.execute(len, "hi"))) -print("newmod {0}".format(tpool.execute(len, "hi2"))) -tpool.killall() -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 3, output) - assert lines[0].startswith('newmod'), repr(output) - assert '2' in lines[0], repr(output) - assert '3' in lines[1], repr(output) - - @skip_with_pyevent - def test_unpatched_thread(self): - new_mod = """import eventlet -eventlet.monkey_patch(time=False, thread=False) -from eventlet import tpool -import time -""" - new_mod += test_monkey_patch_threading - new_mod += "\ntest_monkey_patch_threading()\n" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, lines) + output = tests.run_python('tests/patcher_test_tpool_simple.py') + lines = output.splitlines() + assert len(lines) == 2, output + assert lines == ['child 2', 'child 3'], output - @skip_with_pyevent + @tests.skip_with_pyevent def test_patched_thread(self): - new_mod = """import eventlet -eventlet.monkey_patch(time=False, thread=True) -from eventlet import tpool -import time -""" - new_mod += test_monkey_patch_threading - new_mod += "\ntest_monkey_patch_threading()\n" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod.py') - self.assertEqual(len(lines), 2, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_tpool_patched_thread.py') + assert output == u'1000\n', output + @tests.skip_with_pyevent + def test_unpatched_thread(self): + output = tests.run_python('tests/patcher_test_tpool_unpatched_thread.py') + assert output == u'1000\n', output -class Subprocess(ProcessBase): - def test_monkeypatched_subprocess(self): - new_mod = """import eventlet -eventlet.monkey_patch() -from eventlet.green import subprocess -subprocess.Popen(['true'], stdin=subprocess.PIPE) -print("done") -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(output, "done\n", output) +class TestSubprocess(tests.LimitedTestCase): + def test_monkeypatched_subprocess(self): + output = tests.run_python('tests/patcher_test_subprocess_monkey_patched.py') + assert output == u'done\n', output -class Threading(ProcessBase): - def test_orig_thread(self): - new_mod = """import eventlet -eventlet.monkey_patch() -from eventlet import patcher -import threading -_threading = patcher.original('threading') -def test(): - print(repr(threading.currentThread())) -t = _threading.Thread(target=test) -t.start() -t.join() -print(len(threading._active)) -print(len(_threading._active)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 4, "\n".join(lines)) +class TestThreading(tests.LimitedTestCase): + def test_original(self): + output = tests.run_python('tests/patcher_test_threading_original.py') + lines = output.splitlines() + assert len(lines) == 3, output assert lines[0].startswith('<Thread'), lines[0] - self.assertEqual(lines[1], "1", lines[1]) - self.assertEqual(lines[2], "1", lines[2]) + assert lines[1] == '1', lines[1] + assert lines[2] == '1', lines[2] - def test_threading(self): - new_mod = """import eventlet -eventlet.monkey_patch() -import threading -def test(): - print(repr(threading.currentThread())) -t = threading.Thread(target=test) -t.start() -t.join() -print(len(threading._active)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) + def test_patched(self): + output = tests.run_python('tests/patcher_test_threading_patched.py') + lines = output.splitlines() + assert len(lines) == 2, output assert lines[0].startswith('<_MainThread'), lines[0] - self.assertEqual(lines[1], "1", lines[1]) + assert lines[1] == '1', lines[1] def test_tpool(self): - new_mod = """import eventlet -eventlet.monkey_patch() -from eventlet import tpool -import threading -def test(): - print(repr(threading.currentThread())) -tpool.execute(test) -print(len(threading._active)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_threading_tpool.py') + lines = output.splitlines() + assert len(lines) == 2, output assert lines[0].startswith('<Thread'), lines[0] - self.assertEqual(lines[1], "1", lines[1]) + assert lines[1] == '1', lines[1] def test_greenlet(self): - new_mod = """import eventlet -eventlet.monkey_patch() -from eventlet import event -import threading -evt = event.Event() -def test(): - print(repr(threading.currentThread())) - evt.send() -eventlet.spawn_n(test) -evt.wait() -print(len(threading._active)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_threading_greenlet.py') + lines = output.splitlines() + assert len(lines) == 2, output assert lines[0].startswith('<_MainThread'), lines[0] - self.assertEqual(lines[1], "1", lines[1]) + assert lines[1] == '1', lines[1] def test_greenthread(self): - new_mod = """import eventlet -eventlet.monkey_patch() -import threading -def test(): - print(repr(threading.currentThread())) -t = eventlet.spawn(test) -t.wait() -print(len(threading._active)) -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_threading_greenthread.py') + lines = output.splitlines() + assert len(lines) == 2, output assert lines[0].startswith('<_GreenThread'), lines[0] - self.assertEqual(lines[1], "1", lines[1]) + assert lines[1] == '1', lines[1] def test_keyerror(self): - new_mod = """import eventlet -eventlet.monkey_patch() -""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 1, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_threading_keyerror.py') + assert output == u'', output -class Os(ProcessBase): +class TestOs(tests.LimitedTestCase): def test_waitpid(self): - new_mod = """import subprocess -import eventlet -eventlet.monkey_patch(all=False, os=True) -process = subprocess.Popen("sleep 0.1 && false", shell=True) -print(process.wait())""" - self.write_to_tempfile("newmod", new_mod) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 2, "\n".join(lines)) - self.assertEqual('1', lines[0], repr(output)) - - -class GreenThreadWrapper(ProcessBase): + output = tests.run_python('tests/patcher_test_os_waitpid.py') + assert output == u'1\n', output + + +class TestGreenThreadWrapper(tests.LimitedTestCase): prologue = """import eventlet eventlet.monkey_patch() import threading @@ -430,76 +189,39 @@ t.wait() """ def test_join(self): - self.write_to_tempfile("newmod", self.prologue + """ - def test2(): - global t2 - t2 = threading.currentThread() - eventlet.spawn(test2) -""" + self.epilogue + """ -print(repr(t2)) -t2.join() -""") - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 2, "\n".join(lines)) - assert lines[0].startswith('<_GreenThread'), lines[0] + output = tests.run_python('tests/patcher_test_greenthreadwrapper_join.py') + assert output.startswith('<_GreenThread'), output def test_name(self): - self.write_to_tempfile("newmod", self.prologue + """ - print(t.name) - print(t.getName()) - print(t.get_name()) - t.name = 'foo' - print(t.name) - print(t.getName()) - print(t.get_name()) - t.setName('bar') - print(t.name) - print(t.getName()) - print(t.get_name()) -""" + self.epilogue) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 10, "\n".join(lines)) + output = tests.run_python('tests/patcher_test_greenthreadwrapper_name.py') + lines = output.splitlines() + assert len(lines) == 9, output for i in range(0, 3): - self.assertEqual(lines[i], "GreenThread-1", lines[i]) + assert lines[i] == "GreenThread-1", lines[i] for i in range(3, 6): - self.assertEqual(lines[i], "foo", lines[i]) + assert lines[i] == "foo", lines[i] for i in range(6, 9): - self.assertEqual(lines[i], "bar", lines[i]) + assert lines[i] == "bar", lines[i] def test_ident(self): - self.write_to_tempfile("newmod", self.prologue + """ - print(id(t._g)) - print(t.ident) -""" + self.epilogue) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) - self.assertEqual(lines[0], lines[1]) + output = tests.run_python('tests/patcher_test_greenthreadwrapper_ident.py') + lines = output.splitlines() + assert len(lines) == 2, output + assert lines[0] == lines[1], output def test_is_alive(self): - self.write_to_tempfile("newmod", self.prologue + """ - print(t.is_alive()) - print(t.isAlive()) -""" + self.epilogue) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) - self.assertEqual(lines[0], "True", lines[0]) - self.assertEqual(lines[1], "True", lines[1]) + output = tests.run_python('tests/patcher_test_greenthreadwrapper_is_alive.py') + assert output == u'True\nTrue\n', output def test_is_daemon(self): - self.write_to_tempfile("newmod", self.prologue + """ - print(t.is_daemon()) - print(t.isDaemon()) -""" + self.epilogue) - output, lines = self.launch_subprocess('newmod') - self.assertEqual(len(lines), 3, "\n".join(lines)) - self.assertEqual(lines[0], "True", lines[0]) - self.assertEqual(lines[1], "True", lines[1]) + output = tests.run_python('tests/patcher_test_greenthreadwrapper_is_daemon.py') + assert output == u'True\nTrue\n', output def test_importlib_lock(): - output = run_python('tests/patcher_test_importlib_lock.py') + output = tests.run_python('tests/patcher_test_importlib_lock.py') assert output.rstrip() == b'ok' if __name__ == '__main__': - main() + tests.main() diff --git a/tests/patcher_test_assert_boolean_logic.py b/tests/patcher_test_assert_boolean_logic.py new file mode 100644 index 0000000..d5a81cb --- /dev/null +++ b/tests/patcher_test_assert_boolean_logic.py @@ -0,0 +1,19 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import os + from eventlet import patcher + from eventlet.support import six + + call = os.environ['call'] + expected = os.environ['expected'].split(',') + not_expected = os.environ['not_expected'].split(',') + + six.exec_(call) + + for mod in expected: + assert patcher.is_monkey_patched(mod), mod + for mod in not_expected: + assert not patcher.is_monkey_patched(mod), mod + print("already_patched {0}".format(",".join(sorted(patcher.already_patched.keys())))) diff --git a/tests/patcher_test_base.py b/tests/patcher_test_base.py new file mode 100644 index 0000000..35039a0 --- /dev/null +++ b/tests/patcher_test_base.py @@ -0,0 +1,6 @@ +# no standard tests in this file, ignore +__test__ = False + +import socket +import urllib +print("base {0} {1}".format(socket, urllib)) diff --git a/tests/patcher_test_greenthreadwrapper_ident.py b/tests/patcher_test_greenthreadwrapper_ident.py new file mode 100644 index 0000000..7dc1f67 --- /dev/null +++ b/tests/patcher_test_greenthreadwrapper_ident.py @@ -0,0 +1,15 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + t = threading.currentThread() + print(id(t._g)) + print(t.ident) + + t = eventlet.spawn(test) + t.wait() diff --git a/tests/patcher_test_greenthreadwrapper_is_alive.py b/tests/patcher_test_greenthreadwrapper_is_alive.py new file mode 100644 index 0000000..c234bb3 --- /dev/null +++ b/tests/patcher_test_greenthreadwrapper_is_alive.py @@ -0,0 +1,15 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + t = threading.currentThread() + print(t.is_alive()) + print(t.isAlive()) + + t = eventlet.spawn(test) + t.wait() diff --git a/tests/patcher_test_greenthreadwrapper_is_daemon.py b/tests/patcher_test_greenthreadwrapper_is_daemon.py new file mode 100644 index 0000000..ab74fc0 --- /dev/null +++ b/tests/patcher_test_greenthreadwrapper_is_daemon.py @@ -0,0 +1,15 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + t = threading.currentThread() + print(t.is_daemon()) + print(t.isDaemon()) + + t = eventlet.spawn(test) + t.wait() diff --git a/tests/patcher_test_greenthreadwrapper_join.py b/tests/patcher_test_greenthreadwrapper_join.py new file mode 100644 index 0000000..20918c2 --- /dev/null +++ b/tests/patcher_test_greenthreadwrapper_join.py @@ -0,0 +1,21 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + t2 = None + + def test(): + def test2(): + global t2 + t2 = threading.currentThread() + eventlet.spawn(test2) + + t = eventlet.spawn(test) + t.wait() + + print(repr(t2)) + t2.join() diff --git a/tests/patcher_test_greenthreadwrapper_name.py b/tests/patcher_test_greenthreadwrapper_name.py new file mode 100644 index 0000000..e9b1ff2 --- /dev/null +++ b/tests/patcher_test_greenthreadwrapper_name.py @@ -0,0 +1,24 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + t = threading.currentThread() + print(t.name) + print(t.getName()) + print(t.get_name()) + t.name = 'foo' + print(t.name) + print(t.getName()) + print(t.get_name()) + t.setName('bar') + print(t.name) + print(t.getName()) + print(t.get_name()) + + t = eventlet.spawn(test) + t.wait() diff --git a/tests/patcher_test_import_defaults.py b/tests/patcher_test_import_defaults.py new file mode 100644 index 0000000..307a8d8 --- /dev/null +++ b/tests/patcher_test_import_defaults.py @@ -0,0 +1,8 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet import patcher + + base = patcher.import_patched('patcher_test_base') + print("defaults {0} {1} {2}".format(base, base.socket, base.urllib.socket.socket)) diff --git a/tests/patcher_test_import_module.py b/tests/patcher_test_import_module.py new file mode 100644 index 0000000..e86a9b8 --- /dev/null +++ b/tests/patcher_test_import_module.py @@ -0,0 +1,14 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import patcher_test_patching + import socket + + patcher_test_patching.prepare() + print("importing {0} {1} {2} {3}".format( + patcher_test_patching, + socket, + patcher_test_patching.socket, + patcher_test_patching.urllib, + )) diff --git a/tests/patcher_test_monkey_early_patching.py b/tests/patcher_test_monkey_early_patching.py new file mode 100644 index 0000000..46a7581 --- /dev/null +++ b/tests/patcher_test_monkey_early_patching.py @@ -0,0 +1,8 @@ +# no standard tests in this file, ignore +__test__ = False + +from eventlet import patcher +patcher.monkey_patch() +import eventlet +eventlet.sleep(0.01) +print("ok") diff --git a/tests/patcher_test_monkey_late_patching.py b/tests/patcher_test_monkey_late_patching.py new file mode 100644 index 0000000..9a28ffa --- /dev/null +++ b/tests/patcher_test_monkey_late_patching.py @@ -0,0 +1,9 @@ +# no standard tests in this file, ignore +__test__ = False + +import eventlet +eventlet.sleep(0.01) +from eventlet import patcher +patcher.monkey_patch() +eventlet.sleep(0.01) +print("ok") diff --git a/tests/patcher_test_monkey_patched_modules.py b/tests/patcher_test_monkey_patched_modules.py new file mode 100644 index 0000000..44530d2 --- /dev/null +++ b/tests/patcher_test_monkey_patched_modules.py @@ -0,0 +1,9 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet import patcher + patcher.monkey_patch() + import socket + import urllib + print("child {0} {1}".format(socket.socket, urllib.socket.socket)) diff --git a/tests/patcher_test_monkey_threading.py b/tests/patcher_test_monkey_threading.py new file mode 100644 index 0000000..9de0210 --- /dev/null +++ b/tests/patcher_test_monkey_threading.py @@ -0,0 +1,25 @@ +# no standard tests in this file, ignore +__test__ = False + +import eventlet +from eventlet import tpool + + +def check_tpool_patched(): + tickcount = [0] + + def tick(): + from eventlet.support import six + for i in six.moves.range(1000): + tickcount[0] += 1 + eventlet.sleep() + + def do_sleep(): + tpool.execute(time.sleep, 0.5) + + eventlet.spawn(tick) + w1 = eventlet.spawn(do_sleep) + w1.wait() + print(tickcount[0]) + assert tickcount[0] > 900 + tpool.killall() diff --git a/tests/patcher_test_monkey_typeerror.py b/tests/patcher_test_monkey_typeerror.py new file mode 100644 index 0000000..0ee1a67 --- /dev/null +++ b/tests/patcher_test_monkey_typeerror.py @@ -0,0 +1,6 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + from eventlet import patcher + patcher.monkey_patch(finagle=True) diff --git a/tests/patcher_test_os_waitpid.py b/tests/patcher_test_os_waitpid.py new file mode 100644 index 0000000..a6f421a --- /dev/null +++ b/tests/patcher_test_os_waitpid.py @@ -0,0 +1,9 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import subprocess + import eventlet + eventlet.monkey_patch(all=False, os=True) + process = subprocess.Popen("sleep 0.1 && false", shell=True) + print(process.wait()) diff --git a/tests/patcher_test_patching.py b/tests/patcher_test_patching.py new file mode 100644 index 0000000..56a4c4c --- /dev/null +++ b/tests/patcher_test_patching.py @@ -0,0 +1,11 @@ +# no standard tests in this file, ignore +__test__ = False + +from eventlet.green import socket +from eventlet.green import urllib + + +def prepare(): + from eventlet import patcher + print('patcher {0} {1}'.format(socket, urllib)) + patcher.inject('patcher_test_base', globals(), ('socket', socket), ('urllib', urllib)) diff --git a/tests/patcher_test_subprocess_monkey_patched.py b/tests/patcher_test_subprocess_monkey_patched.py new file mode 100644 index 0000000..c9049b5 --- /dev/null +++ b/tests/patcher_test_subprocess_monkey_patched.py @@ -0,0 +1,10 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + from eventlet.green import subprocess + + subprocess.Popen(['true'], stdin=subprocess.PIPE).wait() + print("done") diff --git a/tests/patcher_test_threading_greenlet.py b/tests/patcher_test_threading_greenlet.py new file mode 100644 index 0000000..83fe8a3 --- /dev/null +++ b/tests/patcher_test_threading_greenlet.py @@ -0,0 +1,17 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + from eventlet import event + import threading + evt = event.Event() + + def test(): + print(repr(threading.currentThread())) + evt.send() + + eventlet.spawn_n(test) + evt.wait() + print(len(threading._active)) diff --git a/tests/patcher_test_threading_greenthread.py b/tests/patcher_test_threading_greenthread.py new file mode 100644 index 0000000..dba5834 --- /dev/null +++ b/tests/patcher_test_threading_greenthread.py @@ -0,0 +1,14 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + print(repr(threading.currentThread())) + + t = eventlet.spawn(test) + t.wait() + print(len(threading._active)) diff --git a/tests/patcher_test_threading_keyerror.py b/tests/patcher_test_threading_keyerror.py new file mode 100644 index 0000000..23975fa --- /dev/null +++ b/tests/patcher_test_threading_keyerror.py @@ -0,0 +1,6 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() diff --git a/tests/patcher_test_threading_original.py b/tests/patcher_test_threading_original.py new file mode 100644 index 0000000..893fc80 --- /dev/null +++ b/tests/patcher_test_threading_original.py @@ -0,0 +1,18 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + from eventlet import patcher + import threading + _threading = patcher.original('threading') + + def test(): + print(repr(threading.currentThread())) + + t = _threading.Thread(target=test) + t.start() + t.join() + print(len(threading._active)) + print(len(_threading._active)) diff --git a/tests/patcher_test_threading_patched.py b/tests/patcher_test_threading_patched.py new file mode 100644 index 0000000..78ac9aa --- /dev/null +++ b/tests/patcher_test_threading_patched.py @@ -0,0 +1,15 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + import threading + + def test(): + print(repr(threading.currentThread())) + + t = threading.Thread(target=test) + t.start() + t.join() + print(len(threading._active)) diff --git a/tests/patcher_test_threading_tpool.py b/tests/patcher_test_threading_tpool.py new file mode 100644 index 0000000..4cd3398 --- /dev/null +++ b/tests/patcher_test_threading_tpool.py @@ -0,0 +1,14 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch() + from eventlet import tpool + import threading + + def test(): + print(repr(threading.currentThread())) + + tpool.execute(test) + print(len(threading._active)) diff --git a/tests/patcher_test_tpool_patched_thread.py b/tests/patcher_test_tpool_patched_thread.py new file mode 100644 index 0000000..a284abd --- /dev/null +++ b/tests/patcher_test_tpool_patched_thread.py @@ -0,0 +1,9 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch(time=False, thread=True) + + import patcher_test_tpool_util + patcher_test_tpool_util.check_tpool_patched() diff --git a/tests/patcher_test_tpool_simple.py b/tests/patcher_test_tpool_simple.py new file mode 100644 index 0000000..99a5e2b --- /dev/null +++ b/tests/patcher_test_tpool_simple.py @@ -0,0 +1,11 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + from eventlet import patcher + patcher.monkey_patch() + from eventlet import tpool + print("child {0}".format(tpool.execute(len, "hi"))) + print("child {0}".format(tpool.execute(len, "hi2"))) + tpool.killall() diff --git a/tests/patcher_test_tpool_unpatched_thread.py b/tests/patcher_test_tpool_unpatched_thread.py new file mode 100644 index 0000000..0be290c --- /dev/null +++ b/tests/patcher_test_tpool_unpatched_thread.py @@ -0,0 +1,9 @@ +# no standard tests in this file, ignore +__test__ = False + +if __name__ == '__main__': + import eventlet + eventlet.monkey_patch(time=False, thread=False) + + import patcher_test_tpool_util + patcher_test_tpool_util.check_tpool_patched() diff --git a/tests/patcher_test_tpool_util.py b/tests/patcher_test_tpool_util.py new file mode 100644 index 0000000..cb4ee8c --- /dev/null +++ b/tests/patcher_test_tpool_util.py @@ -0,0 +1,27 @@ +# no standard tests in this file, ignore +__test__ = False + + +def check_tpool_patched(): + import time + + import eventlet + from eventlet import tpool + from eventlet.support import six + + tickcount = [0] + + def tick(): + for i in six.moves.range(1000): + tickcount[0] += 1 + eventlet.sleep() + + def do_sleep(): + tpool.execute(time.sleep, 0.5) + + eventlet.spawn(tick) + w1 = eventlet.spawn(do_sleep) + w1.wait() + print(tickcount[0]) + assert tickcount[0] > 900 + tpool.killall() |
