-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_testbase.py
792 lines (646 loc) · 23.4 KB
/
_testbase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import asyncio
import atexit
import contextlib
import functools
import importlib.util
import inspect
import json
import logging
import pathlib
import os
import re
import subprocess
import sys
import tempfile
import time
import unittest
import warnings
import gel
from gel import asyncio_client
from gel import blocking_client
from gel.orm.introspection import get_schema_json, GelORMWarning
from gel.orm.sqla import ModelGenerator as SQLAModGen
from gel.orm.sqlmodel import ModelGenerator as SQLModGen
from gel.orm.django.generator import ModelGenerator as DjangoModGen
log = logging.getLogger(__name__)
@contextlib.contextmanager
def silence_asyncio_long_exec_warning():
def flt(log_record):
msg = log_record.getMessage()
return not msg.startswith('Executing ')
logger = logging.getLogger('asyncio')
logger.addFilter(flt)
try:
yield
finally:
logger.removeFilter(flt)
def _get_wsl_path(win_path):
return (
re.sub(r'^([A-Z]):', lambda m: f'/mnt/{m.group(1)}', win_path)
.replace("\\", '/')
.lower()
)
_default_cluster = None
def _start_cluster(*, cleanup_atexit=True):
global _default_cluster
if isinstance(_default_cluster, Exception):
# when starting a server fails
# don't retry starting one for every TestCase
# because repeating the failure can take a while
raise _default_cluster
if _default_cluster:
return _default_cluster
try:
tmpdir = tempfile.TemporaryDirectory()
status_file = os.path.join(tmpdir.name, 'server-status')
# if running on windows adjust the path for WSL
status_file_unix = _get_wsl_path(status_file)
env = os.environ.copy()
# Make sure the PYTHONPATH of _this_ process does
# not interfere with the server's.
env.pop('PYTHONPATH', None)
gel_server = env.get('EDGEDB_SERVER_BINARY', 'edgedb-server')
version_args = [gel_server, '--version']
if sys.platform == 'win32':
version_args = ['wsl', '-u', 'edgedb'] + version_args
version_res = subprocess.run(
version_args,
capture_output=True,
text=True,
)
is_gel = version_res.stdout.startswith('gel-server,')
version_line = version_res.stdout
is_gel = version_line.startswith('gel-server,')
# The default role became admin in nightly build 9024 for 6.0
if is_gel:
if '6.0-dev' in version_line:
rev = int(version_line.split('.')[2].split('+')[0])
has_admin = rev >= 9024
else:
has_admin = True
else:
has_admin = False
role = 'admin' if has_admin else 'edgedb'
args = [
gel_server,
"--temp-dir",
"--testmode",
f"--emit-server-status={status_file_unix}",
"--port=auto",
"--auto-shutdown",
f"--bootstrap-command=ALTER ROLE {role} {{SET password := 'test'}}",
]
help_args = [gel_server, "--help"]
if sys.platform == 'win32':
help_args = ['wsl', '-u', 'edgedb'] + help_args
supported_opts = subprocess.run(
help_args,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
env=env,
cwd=tmpdir.name,
).stdout
if "--tls-cert-mode" in supported_opts:
args.append("--tls-cert-mode=generate_self_signed")
elif "--generate-self-signed-cert" in supported_opts:
args.append("--generate-self-signed-cert")
if sys.platform == 'win32':
args = ['wsl', '-u', 'edgedb'] + args
if env.get('EDGEDB_DEBUG_SERVER'):
server_stdout = None
else:
server_stdout = subprocess.DEVNULL
p = subprocess.Popen(
args,
env=env,
cwd=tmpdir.name,
stdout=server_stdout,
stderr=subprocess.STDOUT,
)
for _ in range(600):
if p.poll() is not None:
raise RuntimeError(
'Database server crashed before signalling READY status.'
' Run with `env EDGEDB_DEBUG_SERVER=1` to debug.')
try:
with open(status_file, 'rb') as f:
for line in f:
if line.startswith(b'READY='):
break
else:
raise RuntimeError('not ready')
break
except Exception:
time.sleep(1)
else:
raise RuntimeError('server status file not found')
data = json.loads(line.split(b'READY=')[1])
con_args = dict(host='localhost', port=data['port'])
if 'tls_cert_file' in data:
if sys.platform == 'win32':
con_args['tls_ca_file'] = os.path.join(
tmpdir.name, "edbtlscert.pem"
)
subprocess.check_call(
[
'wsl',
'-u',
'edgedb',
'cp',
data['tls_cert_file'],
_get_wsl_path(con_args['tls_ca_file'])
]
)
else:
con_args['tls_ca_file'] = data['tls_cert_file']
client = gel.create_client(password='test', **con_args)
client.ensure_connected()
client.execute("""
# Set session_idle_transaction_timeout to 5 minutes.
CONFIGURE INSTANCE SET session_idle_transaction_timeout :=
<duration>'5 minutes';
""")
_default_cluster = {
'proc': p,
'client': client,
'con_args': con_args,
}
if 'tls_cert_file' in data:
# Keep the temp dir which we also copied the cert from WSL
_default_cluster['_tmpdir'] = tmpdir
atexit.register(client.close)
except Exception as e:
_default_cluster = e
raise e
return _default_cluster
class TestCaseMeta(type(unittest.TestCase)):
_database_names = set()
@staticmethod
def _iter_methods(bases, ns):
for base in bases:
for methname in dir(base):
if not methname.startswith('test_'):
continue
meth = getattr(base, methname)
if not inspect.iscoroutinefunction(meth):
continue
yield methname, meth
for methname, meth in ns.items():
if not methname.startswith('test_'):
continue
if not inspect.iscoroutinefunction(meth):
continue
yield methname, meth
@classmethod
def wrap(mcls, meth):
@functools.wraps(meth)
def wrapper(self, *args, __meth__=meth, **kwargs):
try_no = 1
while True:
try:
# There might be unobvious serializability
# anomalies across the test suite, so, rather
# than hunting them down every time, simply
# retry the test.
self.loop.run_until_complete(
__meth__(self, *args, **kwargs))
except gel.TransactionSerializationError:
if try_no == 3:
raise
else:
self.loop.run_until_complete(self.client.execute(
'ROLLBACK;'
))
try_no += 1
else:
break
return wrapper
@classmethod
def add_method(mcls, methname, ns, meth):
ns[methname] = mcls.wrap(meth)
def __new__(mcls, name, bases, ns):
for methname, meth in mcls._iter_methods(bases, ns.copy()):
if methname in ns:
del ns[methname]
mcls.add_method(methname, ns, meth)
cls = super().__new__(mcls, name, bases, ns)
if not ns.get('BASE_TEST_CLASS') and hasattr(cls, 'get_database_name'):
dbname = cls.get_database_name()
if name in mcls._database_names:
raise TypeError(
f'{name} wants duplicate database name: {dbname}')
mcls._database_names.add(name)
return cls
class TestCase(unittest.TestCase, metaclass=TestCaseMeta):
@classmethod
def setUpClass(cls):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
cls.loop = loop
@classmethod
def tearDownClass(cls):
cls.loop.close()
asyncio.set_event_loop(None)
def add_fail_notes(self, **kwargs):
if not hasattr(self, 'fail_notes'):
self.fail_notes = {}
self.fail_notes.update(kwargs)
@contextlib.contextmanager
def annotate(self, **kwargs):
# Annotate the test in case the nested block of code fails.
try:
yield
except Exception:
self.add_fail_notes(**kwargs)
raise
@contextlib.contextmanager
def assertRaisesRegex(self, exception, regex, msg=None,
**kwargs):
with super().assertRaisesRegex(exception, regex, msg=msg):
try:
yield
except BaseException as e:
if isinstance(e, exception):
for attr_name, expected_val in kwargs.items():
val = getattr(e, attr_name)
if val != expected_val:
raise self.failureException(
f'{exception.__name__} context attribute '
f'{attr_name!r} is {val} (expected '
f'{expected_val!r})') from e
raise
def addCleanup(self, func, *args, **kwargs):
@functools.wraps(func)
def cleanup():
res = func(*args, **kwargs)
if inspect.isawaitable(res):
self.loop.run_until_complete(res)
super().addCleanup(cleanup)
class ClusterTestCase(TestCase):
BASE_TEST_CLASS = True
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.cluster = _start_cluster(cleanup_atexit=True)
class TestAsyncIOClient(gel.AsyncIOClient):
def _clear_codecs_cache(self):
self._impl.codecs_registry.clear_cache()
@property
def connection(self):
return self._impl._holders[0]._con
@property
def dbname(self):
return self._impl._working_params.database
@property
def is_proto_lt_1_0(self):
return self.connection._protocol.is_legacy
class TestClient(gel.Client):
@property
def connection(self):
return self._impl._holders[0]._con
@property
def is_proto_lt_1_0(self):
return self.connection._protocol.is_legacy
@property
def dbname(self):
return self._impl._working_params.database
class ConnectedTestCaseMixin:
is_client_async = True
@classmethod
def make_test_client(
cls, *,
cluster=None,
database='edgedb',
user='edgedb',
password='test',
host=...,
port=...,
connection_class=...,
):
conargs = cls.get_connect_args(
cluster=cluster, database=database, user=user, password=password)
if host is not ...:
conargs['host'] = host
if port is not ...:
conargs['port'] = port
if connection_class is ...:
connection_class = (
asyncio_client.AsyncIOConnection
if cls.is_client_async
else blocking_client.BlockingIOConnection
)
return (TestAsyncIOClient if cls.is_client_async else TestClient)(
connection_class=connection_class,
max_concurrency=1,
**conargs,
)
@classmethod
def get_connect_args(cls, *,
cluster=None,
database='edgedb',
user='edgedb',
password='test'):
conargs = cls.cluster['con_args'].copy()
conargs.update(dict(user=user,
password=password,
database=database))
return conargs
@classmethod
def adapt_call(cls, coro):
return cls.loop.run_until_complete(coro)
class DatabaseTestCase(ClusterTestCase, ConnectedTestCaseMixin):
SETUP = None
TEARDOWN = None
SCHEMA = None
DEFAULT_MODULE = 'test'
SETUP_METHOD = None
TEARDOWN_METHOD = None
BASE_TEST_CLASS = True
TEARDOWN_RETRY_DROP_DB = 1
def setUp(self):
if self.SETUP_METHOD:
self.adapt_call(
self.client.execute(self.SETUP_METHOD))
super().setUp()
def tearDown(self):
try:
if self.TEARDOWN_METHOD:
self.adapt_call(
self.client.execute(self.TEARDOWN_METHOD))
finally:
try:
if self.client.connection.is_in_transaction():
raise AssertionError(
'test connection is still in transaction '
'*after* the test')
finally:
super().tearDown()
@classmethod
def setUpClass(cls):
super().setUpClass()
dbname = cls.get_database_name()
cls.admin_client = None
class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP')
# Only open an extra admin connection if necessary.
if not class_set_up:
script = f'CREATE DATABASE {dbname};'
cls.admin_client = cls.make_test_client()
cls.adapt_call(cls.admin_client.execute(script))
cls.client = cls.make_test_client(database=dbname)
if not class_set_up:
script = cls.get_setup_script()
if script:
# The setup is expected to contain a CREATE MIGRATION,
# which needs to be wrapped in a transaction.
if cls.is_client_async:
async def execute():
async for tr in cls.client.transaction():
async with tr:
await tr.execute(script)
else:
def execute():
for tr in cls.client.transaction():
with tr:
tr.execute(script)
cls.adapt_call(execute())
@classmethod
def get_database_name(cls):
if cls.__name__.startswith('TestEdgeQL'):
dbname = cls.__name__[len('TestEdgeQL'):]
elif cls.__name__.startswith('Test'):
dbname = cls.__name__[len('Test'):]
else:
dbname = cls.__name__
return dbname.lower()
@classmethod
def get_setup_script(cls):
script = ''
schema = []
# Look at all SCHEMA entries and potentially create multiple
# modules, but always create the test module, if not `default`.
if cls.DEFAULT_MODULE != 'default':
schema.append(f'\nmodule {cls.DEFAULT_MODULE} {{}}')
for name, val in cls.__dict__.items():
m = re.match(r'^SCHEMA(?:_(\w+))?', name)
if m:
module_name = (
m.group(1) or cls.DEFAULT_MODULE
).lower().replace('_', '::')
with open(val, 'r') as sf:
module = sf.read()
schema.append(f'\nmodule {module_name} {{ {module} }}')
# Don't wrap the script into a transaction here, so that
# potentially it's easier to stitch multiple such scripts
# together in a fashion similar to what `edb inittestdb` does.
script += f'\nSTART MIGRATION TO {{ {"".join(schema)} }};'
script += f'\nPOPULATE MIGRATION; \nCOMMIT MIGRATION;'
if cls.SETUP:
if not isinstance(cls.SETUP, (list, tuple)):
scripts = [cls.SETUP]
else:
scripts = cls.SETUP
for scr in scripts:
if '\n' not in scr and os.path.exists(scr):
with open(scr, 'rt') as f:
setup = f.read()
else:
setup = scr
script += '\n' + setup
return script.strip(' \n')
@classmethod
def tearDownClass(cls):
script = ''
if cls.TEARDOWN:
script = cls.TEARDOWN.strip()
try:
if script:
cls.adapt_call(
cls.client.execute(script))
finally:
try:
if cls.is_client_async:
cls.adapt_call(cls.client.aclose())
else:
cls.client.close()
dbname = cls.get_database_name()
script = f'DROP DATABASE {dbname};'
retry = cls.TEARDOWN_RETRY_DROP_DB
for i in range(retry):
try:
cls.adapt_call(
cls.admin_client.execute(script))
except gel.errors.ExecutionError:
if i < retry - 1:
time.sleep(0.1)
else:
raise
except gel.errors.UnknownDatabaseError:
break
except Exception:
log.exception('error running teardown')
# skip the exception so that original error is shown instead
# of finalizer error
finally:
try:
if cls.admin_client is not None:
if cls.is_client_async:
cls.adapt_call(
cls.admin_client.aclose())
else:
cls.admin_client.close()
finally:
super().tearDownClass()
class AsyncQueryTestCase(DatabaseTestCase):
BASE_TEST_CLASS = True
class SyncQueryTestCase(DatabaseTestCase):
BASE_TEST_CLASS = True
TEARDOWN_RETRY_DROP_DB = 5
is_client_async = False
@classmethod
def adapt_call(cls, result):
return result
class ORMTestCase(SyncQueryTestCase):
MODEL_PACKAGE = None
DEFAULT_MODULE = 'default'
@classmethod
def setUpClass(cls):
# ORMs rely on psycopg2 to connect to Postgres and thus we
# need it to run tests. Unfortunately not all test environemnts might
# have psycopg2 installed, as long as we run this in the test
# environments that have this, it is fine since we're not expecting
# different functionality based on flavours of psycopg2.
if importlib.util.find_spec("psycopg2") is None:
raise unittest.SkipTest("need psycopg2 for ORM tests")
with warnings.catch_warnings():
warnings.simplefilter("ignore", GelORMWarning)
super().setUpClass()
class_set_up = os.environ.get('EDGEDB_TEST_CASES_SET_UP')
if not class_set_up:
# We'll need a temp directory to setup the generated Python
# package
cls.tmpormdir = tempfile.TemporaryDirectory()
sys.path.append(cls.tmpormdir.name)
# Now that the DB is setup, generate the ORM models from it
cls.spec = get_schema_json(cls.client)
cls.setupORM()
@classmethod
def setupORM(cls):
raise NotImplementedError
@classmethod
def tearDownClass(cls):
super().tearDownClass()
# cleanup the temp modules
sys.path.remove(cls.tmpormdir.name)
cls.tmpormdir.cleanup()
class SQLATestCase(ORMTestCase):
@classmethod
def setupORM(cls):
gen = SQLAModGen(
outdir=os.path.join(cls.tmpormdir.name, cls.MODEL_PACKAGE),
basemodule=cls.MODEL_PACKAGE,
)
gen.render_models(cls.spec)
@classmethod
def get_dsn_for_sqla(cls):
cargs = cls.get_connect_args(database=cls.get_database_name())
dsn = (
f'postgresql://{cargs["user"]}:{cargs["password"]}'
f'@{cargs["host"]}:{cargs["port"]}/{cargs["database"]}'
)
return dsn
class SQLModelTestCase(ORMTestCase):
@classmethod
def setupORM(cls):
gen = SQLModGen(
outdir=os.path.join(cls.tmpormdir.name, cls.MODEL_PACKAGE),
basemodule=cls.MODEL_PACKAGE,
)
gen.render_models(cls.spec)
@classmethod
def get_dsn_for_sqla(cls):
cargs = cls.get_connect_args(database=cls.get_database_name())
dsn = (
f'postgresql://{cargs["user"]}:{cargs["password"]}'
f'@{cargs["host"]}:{cargs["port"]}/{cargs["database"]}'
)
return dsn
APPS_PY = '''\
from django.apps import AppConfig
class TestConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = {name!r}
'''
SETTINGS_PY = '''\
from pathlib import Path
mysettings = dict(
INSTALLED_APPS=[
'{appname}.apps.TestConfig',
'gel.orm.django.gelmodels.apps.GelPGModel',
],
DATABASES={{
'default': {{
'ENGINE': 'django.db.backends.postgresql',
'NAME': {database!r},
'USER': {user!r},
'PASSWORD': {password!r},
'HOST': {host!r},
'PORT': {port!r},
}}
}},
)
'''
class DjangoTestCase(ORMTestCase):
@classmethod
def setupORM(cls):
pkgbase = os.path.join(cls.tmpormdir.name, cls.MODEL_PACKAGE)
# Set up the package for testing Django models
os.mkdir(pkgbase)
open(os.path.join(pkgbase, '__init__.py'), 'w').close()
with open(os.path.join(pkgbase, 'apps.py'), 'wt') as f:
print(
APPS_PY.format(name=cls.MODEL_PACKAGE),
file=f,
)
with open(os.path.join(pkgbase, 'settings.py'), 'wt') as f:
cargs = cls.get_connect_args(database=cls.get_database_name())
print(
SETTINGS_PY.format(
appname=cls.MODEL_PACKAGE,
database=cargs["database"],
user=cargs["user"],
password=cargs["password"],
host=cargs["host"],
port=cargs["port"],
),
file=f,
)
models = os.path.join(pkgbase, 'models.py')
gen = DjangoModGen(out=models)
gen.render_models(cls.spec)
_lock_cnt = 0
def gen_lock_key():
global _lock_cnt
_lock_cnt += 1
return os.getpid() * 1000 + _lock_cnt
if os.environ.get('USE_UVLOOP'):
import uvloop
uvloop.install()