Debian Codegraph @

tests/patcher_psycopg_test.py

raw
1 import os
2
3 from tests import patcher_test, skip_unless
4 from tests import get_database_auth
5 from tests.db_pool_test import postgres_requirement
6
7 psycopg_test_file = """
8 import os
9 import sys
10 import eventlet
11 eventlet.monkey_patch()
12 from eventlet import patcher
13 if not patcher.is_monkey_patched('psycopg'):
14 print("Psycopg not monkeypatched")
15 sys.exit(0)
16
17 count = [0]
18 def tick(totalseconds, persecond):
19 for i in range(totalseconds*persecond):
20 count[0] += 1
21 eventlet.sleep(1.0/persecond)
22
23 dsn = os.environ['PSYCOPG_TEST_DSN']
24 import psycopg2
25 def fetch(num, secs):
26 conn = psycopg2.connect(dsn)
27 cur = conn.cursor()
28 for i in range(num):
29 cur.execute("select pg_sleep(%s)", (secs,))
30
31 f = eventlet.spawn(fetch, 2, 1)
32 t = eventlet.spawn(tick, 2, 100)
33 f.wait()
34 assert count[0] > 100, count[0]
35 print("done")
36 """
37
38
39 class PatchingPsycopg(patcher_test.ProcessBase):
40 @skip_unless(postgres_requirement)
41 def test_psycopg_patched(self):
42 if 'PSYCOPG_TEST_DSN' not in os.environ:
43 # construct a non-json dsn for the subprocess
44 psycopg_auth = get_database_auth()['psycopg2']
45 if isinstance(psycopg_auth, str):
46 dsn = psycopg_auth
47 else:
48 dsn = " ".join(["%s=%s" % (k, v) for k, v in psycopg_auth.items()])
49 os.environ['PSYCOPG_TEST_DSN'] = dsn
50 self.write_to_tempfile("psycopg_patcher", psycopg_test_file)
51 output, lines = self.launch_subprocess('psycopg_patcher.py')
52 if lines[0].startswith('Psycopg not monkeypatched'):
53 print("Can't test psycopg2 patching; it's not installed.")
54 return
55 # if there's anything wrong with the test program it'll have a stack trace
56 assert lines[0].startswith('done'), output