Debian Codegraph @

tests/test_cases/bug_212_regression.py

raw
1 # google
2
3 # testing/plugin/pytestplugin.py
4 # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
5 # <see AUTHORS file>
6 #
7 # This module is part of SQLAlchemy and is released under
8 # the MIT License: https://www.opensource.org/licenses/mit-license.php
9 # mypy: ignore-errors
10
11 from __future__ import annotations
12
13 import argparse
14 import collections
15 from functools import update_wrapper
16 import inspect
17 import itertools
18 import operator
19 import os
20 import re
21 import sys
22 from typing import TYPE_CHECKING
23 import uuid
24
25 import pytest
26
27 try:
28 # installed by bootstrap.py
29 if not TYPE_CHECKING:
30 import sqla_plugin_base as plugin_base
31 except ImportError:
32 # assume we're a package, use traditional import
33 from . import plugin_base
34
35
36 def pytest_addoption(parser):
37 group = parser.getgroup("sqlalchemy")
38
39 def make_option(name, **kw):
40 callback_ = kw.pop("callback", None)
41 if callback_:
42
43 class CallableAction(argparse.Action):
44 def __call__(
45 self, parser, namespace, values, option_string=None
46 ):
47 callback_(option_string, values, parser)
48
49 kw["action"] = CallableAction
50
51 zeroarg_callback = kw.pop("zeroarg_callback", None)
52 if zeroarg_callback:
53
54 class CallableAction(argparse.Action):
55 def __init__(
56 self,
57 option_strings,
58 dest,
59 default=False,
60 required=False,
61 help=None, # noqa
62 ):
63 super().__init__(
64 option_strings=option_strings,
65 dest=dest,
66 nargs=0,
67 const=True,
68 default=default,
69 required=required,
70 help=help,
71 )
72
73 def __call__(
74 self, parser, namespace, values, option_string=None
75 ):
76 zeroarg_callback(option_string, values, parser)
77
78 kw["action"] = CallableAction
79
80 group.addoption(name, **kw)
81
82 plugin_base.setup_options(make_option)
83
84
85 def pytest_configure(config: pytest.Config):
86 plugin_base.read_config(config.rootpath)
87 if plugin_base.exclude_tags or plugin_base.include_tags:
88 new_expr = " and ".join(
89 list(plugin_base.include_tags)
90 + [f"not {tag}" for tag in plugin_base.exclude_tags]
91 )
92
93 if config.option.markexpr:
94 config.option.markexpr += f" and {new_expr}"
95 else:
96 config.option.markexpr = new_expr
97
98 if config.pluginmanager.hasplugin("xdist"):
99 config.pluginmanager.register(XDistHooks())
100
101 if hasattr(config, "workerinput"):
102 plugin_base.restore_important_follower_config(config.workerinput)
103 plugin_base.configure_follower(config.workerinput["follower_ident"])
104 else:
105 if config.option.write_idents and os.path.exists(
106 config.option.write_idents
107 ):
108 os.remove(config.option.write_idents)
109
110 plugin_base.pre_begin(config.option)
111
112 plugin_base.set_coverage_flag(
113 bool(getattr(config.option, "cov_source", False))
114 )
115
116 plugin_base.set_fixture_functions(PytestFixtureFunctions)
117
118 if config.option.dump_pyannotate:
119 global DUMP_PYANNOTATE
120 DUMP_PYANNOTATE = True
121
122
123 DUMP_PYANNOTATE = False
124
125
126 @pytest.fixture(autouse=True)
127 def collect_types_fixture():
128 if DUMP_PYANNOTATE:
129 from pyannotate_runtime import collect_types
130
131 collect_types.start()
132 yield
133 if DUMP_PYANNOTATE:
134 collect_types.stop()
135
136
137 def _log_sqlalchemy_info(session):
138 import sqlalchemy
139 from sqlalchemy import __version__
140 from sqlalchemy.util import has_compiled_ext
141 from sqlalchemy.util._has_cython import _CYEXTENSION_MSG
142
143 greet = "sqlalchemy installation"
144 site = "no user site" if sys.flags.no_user_site else "user site loaded"
145 msgs = [
146 f"SQLAlchemy {__version__} ({site})",
147 f"Path: {sqlalchemy.__file__}",
148 ]
149
150 if has_compiled_ext():
151 from sqlalchemy.engine import _util_cy
152
153 msgs.append(f"compiled extension enabled, e.g. {_util_cy.__file__} ")
154 else:
155 msgs.append(f"compiled extension not enabled; {_CYEXTENSION_MSG}")
156
157 pm = session.config.pluginmanager.get_plugin("terminalreporter")
158 if pm:
159 pm.write_sep("=", greet)
160 for m in msgs:
161 pm.write_line(m)
162 else:
163 # fancy pants reporter not found, fallback to plain print
164 print("=" * 25, greet, "=" * 25)
165 for m in msgs:
166 print(m)
167
168
169 def pytest_sessionstart(session):
170 from sqlalchemy.testing import asyncio
171
172 _log_sqlalchemy_info(session)
173 asyncio._assume_async(plugin_base.post_begin)
174
175
176 def pytest_sessionfinish(session):
177 from sqlalchemy.testing import asyncio
178
179 asyncio._maybe_async_provisioning(plugin_base.final_process_cleanup)
180
181 if session.config.option.dump_pyannotate:
182 from pyannotate_runtime import collect_types
183
184 collect_types.dump_stats(session.config.option.dump_pyannotate)
185
186
187 def pytest_unconfigure(config):
188 from sqlalchemy.testing import asyncio
189
190 asyncio._shutdown()
191
192
193 def pytest_collection_finish(session):
194 if session.config.option.dump_pyannotate:
195 from pyannotate_runtime import collect_types
196
197 lib_sqlalchemy = os.path.abspath("lib/sqlalchemy")
198
199 def _filter(filename):
200 filename = os.path.normpath(os.path.abspath(filename))
201 if "lib/sqlalchemy" not in os.path.commonpath(
202 [filename, lib_sqlalchemy]
203 ):
204 return None
205 if "testing" in filename:
206 return None
207
208 return filename
209
210 collect_types.init_types_collection(filter_filename=_filter)
211
212
213 class XDistHooks:
214 def pytest_configure_node(self, node):
215 from sqlalchemy.testing import provision
216 from sqlalchemy.testing import asyncio
217
218 # the master for each node fills workerinput dictionary
219 # which pytest-xdist will transfer to the subprocess
220
221 plugin_base.memoize_important_follower_config(node.workerinput)
222
223 node.workerinput["follower_ident"] = (
224 "test_%s" % uuid.uuid4().hex[0:12]
225 )
226
227 asyncio._maybe_async_provisioning(
228 provision.create_follower_db, node.workerinput["follower_ident"]
229 )
230
231 def pytest_testnodedown(self, node, error):
232 from sqlalchemy.testing import provision
233 from sqlalchemy.testing import asyncio
234
235 asyncio._maybe_async_provisioning(
236 provision.drop_follower_db, node.workerinput["follower_ident"]
237 )
238
239
240 def pytest_collection_modifyitems(session, config, items):
241 # look for all those classes that specify __backend__ and
242 # expand them out into per-database test cases.
243
244 # this is much easier to do within pytest_pycollect_makeitem, however
245 # pytest is iterating through cls.__dict__ as makeitem is
246 # called which causes a "dictionary changed size" error on py3k.
247 # I'd submit a pullreq for them to turn it into a list first, but
248 # it's to suit the rather odd use case here which is that we are adding
249 # new classes to a module on the fly.
250
251 from sqlalchemy.testing import asyncio
252
253 rebuilt_items = collections.defaultdict(
254 lambda: collections.defaultdict(list)
255 )
256
257 items[:] = [
258 item
259 for item in items
260 if item.getparent(pytest.Class) is not None
261 and not item.getparent(pytest.Class).name.startswith("_")
262 ]
263
264 test_classes = {item.getparent(pytest.Class) for item in items}
265
266 def collect(element):
267 for inst_or_fn in element.collect():
268 if isinstance(inst_or_fn, pytest.Collector):
269 yield from collect(inst_or_fn)
270 else:
271 yield inst_or_fn
272
273 def setup_test_classes():
274 for test_class in test_classes:
275 # transfer legacy __backend__ and __sparse_backend__ symbols
276 # to be markers
277 if getattr(test_class.cls, "__backend__", False) or getattr(
278 test_class.cls, "__only_on__", False
279 ):
280 add_markers = {"backend"}
281 elif getattr(test_class.cls, "__sparse_backend__", False):
282 add_markers = {"sparse_backend"}
283 else:
284 add_markers = frozenset()
285
286 existing_markers = {
287 mark.name for mark in test_class.iter_markers()
288 }
289 add_markers = add_markers - existing_markers
290 all_markers = existing_markers.union(add_markers)
291
292 for marker in add_markers:
293 test_class.add_marker(marker)
294
295 for sub_cls in plugin_base.generate_sub_tests(
296 test_class.cls, test_class.module, all_markers
297 ):
298 if sub_cls is not test_class.cls:
299 per_cls_dict = rebuilt_items[test_class.cls]
300
301 module = test_class.getparent(pytest.Module)
302
303 new_cls = pytest.Class.from_parent(
304 name=sub_cls.__name__, parent=module
305 )
306 for marker in add_markers:
307 new_cls.add_marker(marker)
308
309 for fn in collect(new_cls):
310 per_cls_dict[fn.name].append(fn)
311
312 # class requirements will sometimes need to access the DB to check
313 # capabilities, so need to do this for async
314 asyncio._maybe_async_provisioning(setup_test_classes)
315
316 newitems = []
317 for item in items:
318 cls_ = item.cls
319 if cls_ in rebuilt_items:
320 newitems.extend(rebuilt_items[cls_][item.name])
321 else:
322 newitems.append(item)
323
324 # seems like the functions attached to a test class aren't sorted already?
325 # is that true and why's that? (when using unittest, they're sorted)
326 items[:] = sorted(
327 newitems,
328 key=lambda item: (
329 item.getparent(pytest.Module).name,
330 item.getparent(pytest.Class).name,
331 item.name,
332 ),
333 )
334
335
336 def pytest_pycollect_makeitem(collector, name, obj):
337 if inspect.isclass(obj) and plugin_base.want_class(name, obj):
338 from sqlalchemy.testing import config
339
340 if config.any_async:
341 obj = _apply_maybe_async(obj)
342
343 return [
344 pytest.Class.from_parent(
345 name=parametrize_cls.__name__, parent=collector
346 )
347 for parametrize_cls in _parametrize_cls(collector.module, obj)
348 ]
349 elif (
350 inspect.isfunction(obj)
351 and collector.cls is not None
352 and plugin_base.want_method(collector.cls, obj)
353 ):
354 # None means, fall back to default logic, which includes
355 # method-level parametrize
356 return None
357 else:
358 # empty list means skip this item
359 return []
360
361
362 def _is_wrapped_coroutine_function(fn):
363 while hasattr(fn, "__wrapped__"):
364 fn = fn.__wrapped__
365
366 return inspect.iscoroutinefunction(fn)
367
368
369 def _apply_maybe_async(obj, recurse=True):
370 from sqlalchemy.testing import asyncio
371
372 for name, value in vars(obj).items():
373 if (
374 (callable(value) or isinstance(value, classmethod))
375 and not getattr(value, "_maybe_async_applied", False)
376 and (name.startswith("test_"))
377 and not _is_wrapped_coroutine_function(value)
378 ):
379 is_classmethod = False
380 if isinstance(value, classmethod):
381 value = value.__func__
382 is_classmethod = True
383
384 @_pytest_fn_decorator
385 def make_async(fn, *args, **kwargs):
386 return asyncio._maybe_async(fn, *args, **kwargs)
387
388 do_async = make_async(value)
389 if is_classmethod:
390 do_async = classmethod(do_async)
391 do_async._maybe_async_applied = True
392
393 setattr(obj, name, do_async)
394 if recurse:
395 for cls in obj.mro()[1:]:
396 if cls != object:
397 _apply_maybe_async(cls, False)
398 return obj
399
400
401 def _parametrize_cls(module, cls):
402 """implement a class-based version of pytest parametrize."""
403
404 if "_sa_parametrize" not in cls.__dict__:
405 return [cls]
406
407 _sa_parametrize = cls._sa_parametrize
408 classes = []
409 for full_param_set in itertools.product(
410 *[params for argname, params in _sa_parametrize]
411 ):
412 cls_variables = {}
413
414 for argname, param in zip(
415 [_sa_param[0] for _sa_param in _sa_parametrize], full_param_set
416 ):
417 if not argname:
418 raise TypeError("need argnames for class-based combinations")
419 argname_split = re.split(r",\s*", argname)
420 for arg, val in zip(argname_split, param.values):
421 cls_variables[arg] = val
422 parametrized_name = "_".join(
423 re.sub(r"\W", "", token)
424 for param in full_param_set
425 for token in param.id.split("-")
426 )
427 name = "%s_%s" % (cls.__name__, parametrized_name)
428 newcls = type.__new__(type, name, (cls,), cls_variables)
429 setattr(module, name, newcls)
430 classes.append(newcls)
431 return classes
432
433
434 _current_class = None
435
436
437 def pytest_runtest_setup(item):
438 from sqlalchemy.testing import asyncio
439
440 # pytest_runtest_setup runs *before* pytest fixtures with scope="class".
441 # plugin_base.start_test_class_outside_fixtures may opt to raise SkipTest
442 # for the whole class and has to run things that are across all current
443 # databases, so we run this outside of the pytest fixture system altogether
444 # and ensure asyncio greenlet if any engines are async
445
446 global _current_class
447
448 if isinstance(item, pytest.Function) and _current_class is None:
449 asyncio._maybe_async_provisioning(
450 plugin_base.start_test_class_outside_fixtures,
451 item.cls,
452 )
453 _current_class = item.getparent(pytest.Class)
454
455
456 @pytest.hookimpl(hookwrapper=True)
457 def pytest_runtest_teardown(item, nextitem):
458 # runs inside of pytest function fixture scope
459 # after test function runs
460
461 from sqlalchemy.testing import asyncio
462
463 asyncio._maybe_async(plugin_base.after_test, item)
464
465 yield
466 # this is now after all the fixture teardown have run, the class can be
467 # finalized. Since pytest v7 this finalizer can no longer be added in
468 # pytest_runtest_setup since the class has not yet been setup at that
469 # time.
470 # See https://github.com/pytest-dev/pytest/issues/9343
471 global _current_class, _current_report
472
473 if _current_class is not None and (
474 # last test or a new class
475 nextitem is None
476 or nextitem.getparent(pytest.Class) is not _current_class
477 ):
478 _current_class = None
479
480 try:
481 asyncio._maybe_async_provisioning(
482 plugin_base.stop_test_class_outside_fixtures, item.cls
483 )
484 except Exception as e:
485 # in case of an exception during teardown attach the original
486 # error to the exception message, otherwise it will get lost
487 if _current_report.failed:
488 if not e.args:
489 e.args = (
490 "__Original test failure__:\n"
491 + _current_report.longreprtext,
492 )
493 elif e.args[-1] and isinstance(e.args[-1], str):
494 args = list(e.args)
495 args[-1] += (
496 "\n__Original test failure__:\n"
497 + _current_report.longreprtext
498 )
499 e.args = tuple(args)
500 else:
501 e.args += (
502 "__Original test failure__",
503 _current_report.longreprtext,
504 )
505 raise
506 finally:
507 _current_report = None
508
509
510 def pytest_runtest_call(item):
511 # runs inside of pytest function fixture scope
512 # before test function runs
513
514 from sqlalchemy.testing import asyncio
515
516 asyncio._maybe_async(
517 plugin_base.before_test,
518 item,
519 item.module.__name__,
520 item.cls,
521 item.name,
522 )
523
524
525 _current_report = None
526
527
528 def pytest_runtest_logreport(report):
529 global _current_report
530 if report.when == "call":
531 _current_report = report
532
533
534 @pytest.fixture(scope="class")
535 def setup_class_methods(request):
536 from sqlalchemy.testing import asyncio
537
538 cls = request.cls
539
540 if hasattr(cls, "setup_test_class"):
541 asyncio._maybe_async(cls.setup_test_class)
542
543 yield
544
545 if hasattr(cls, "teardown_test_class"):
546 asyncio._maybe_async(cls.teardown_test_class)
547
548 asyncio._maybe_async(plugin_base.stop_test_class, cls)
549
550
551 @pytest.fixture(scope="function")
552 def setup_test_methods(request):
553 from sqlalchemy.testing import asyncio
554
555 # called for each test
556
557 self = request.instance
558
559 # before this fixture runs:
560
561 # 1. function level "autouse" fixtures under py3k (examples: TablesTest
562 # define tables / data, MappedTest define tables / mappers / data)
563
564 # 2. was for p2k. no longer applies
565
566 # 3. run outer xdist-style setup
567 if hasattr(self, "setup_test"):
568 asyncio._maybe_async(self.setup_test)
569
570 # alembic test suite is using setUp and tearDown
571 # xdist methods; support these in the test suite
572 # for the near term
573 if hasattr(self, "setUp"):
574 asyncio._maybe_async(self.setUp)
575
576 # inside the yield:
577 # 4. function level fixtures defined on test functions themselves,
578 # e.g. "connection", "metadata" run next
579
580 # 5. pytest hook pytest_runtest_call then runs
581
582 # 6. test itself runs
583
584 yield
585
586 # yield finishes:
587
588 # 7. function level fixtures defined on test functions
589 # themselves, e.g. "connection" rolls back the transaction, "metadata"
590 # emits drop all
591
592 # 8. pytest hook pytest_runtest_teardown hook runs, this is associated
593 # with fixtures close all sessions, provisioning.stop_test_class(),
594 # engines.testing_reaper -> ensure all connection pool connections
595 # are returned, engines created by testing_engine that aren't the
596 # config engine are disposed
597
598 asyncio._maybe_async(plugin_base.after_test_fixtures, self)
599
600 # 10. run xdist-style teardown
601 if hasattr(self, "tearDown"):
602 asyncio._maybe_async(self.tearDown)
603
604 if hasattr(self, "teardown_test"):
605 asyncio._maybe_async(self.teardown_test)
606
607 # 11. was for p2k. no longer applies
608
609 # 12. function level "autouse" fixtures under py3k (examples: TablesTest /
610 # MappedTest delete table data, possibly drop tables and clear mappers
611 # depending on the flags defined by the test class)
612
613
614 def _pytest_fn_decorator(target):
615 """Port of langhelpers.decorator with pytest-specific tricks."""
616
617 from sqlalchemy.util.langhelpers import format_argspec_plus
618 from sqlalchemy.util.compat import inspect_getfullargspec
619
620 def _exec_code_in_env(code, env, fn_name):
621 # note this is affected by "from __future__ import annotations" at
622 # the top; exec'ed code will use non-evaluated annotations
623 # which allows us to be more flexible with code rendering
624 # in format_argpsec_plus()
625 exec(code, env)
626 return env[fn_name]
627
628 def decorate(fn, add_positional_parameters=()):
629 spec = inspect_getfullargspec(fn)
630 if add_positional_parameters:
631 spec.args.extend(add_positional_parameters)
632
633 metadata = dict(
634 __target_fn="__target_fn", __orig_fn="__orig_fn", name=fn.__name__
635 )
636 metadata.update(format_argspec_plus(spec, grouped=False))
637 code = (
638 """\
639 def %(name)s%(grouped_args)s:
640 return %(__target_fn)s(%(__orig_fn)s, %(apply_kw)s)
641 """
642 % metadata
643 )
644 decorated = _exec_code_in_env(
645 code, {"__target_fn": target, "__orig_fn": fn}, fn.__name__
646 )
647 if not add_positional_parameters:
648 decorated.__defaults__ = getattr(fn, "__func__", fn).__defaults__
649 decorated.__wrapped__ = fn
650 return update_wrapper(decorated, fn)
651 else:
652 # this is the pytest hacky part. don't do a full update wrapper
653 # because pytest is really being sneaky about finding the args
654 # for the wrapped function
655 decorated.__module__ = fn.__module__
656 decorated.__name__ = fn.__name__
657 if hasattr(fn, "pytestmark"):
658 decorated.pytestmark = fn.pytestmark
659 return decorated
660
661 return decorate
662
663
664 class PytestFixtureFunctions(plugin_base.FixtureFunctions):
665 def skip_test_exception(self, *arg, **kw):
666 return pytest.skip.Exception(*arg, **kw)
667
668 @property
669 def add_to_marker(self):
670 return pytest.mark
671
672 def mark_base_test_class(self):
673 return pytest.mark.usefixtures(
674 "setup_class_methods", "setup_test_methods"
675 )
676
677 _combination_id_fns = {
678 "i": lambda obj: obj,
679 "r": repr,
680 "s": str,
681 "n": lambda obj: (
682 obj.__name__ if hasattr(obj, "__name__") else type(obj).__name__
683 ),
684 }
685
686 def combinations(self, *arg_sets, **kw):
687 """Facade for pytest.mark.parametrize.
688
689 Automatically derives argument names from the callable which in our
690 case is always a method on a class with positional arguments.
691
692 ids for parameter sets are derived using an optional template.
693
694 """
695 from sqlalchemy.testing import exclusions
696
697 if len(arg_sets) == 1 and hasattr(arg_sets[0], "__next__"):
698 arg_sets = list(arg_sets[0])
699
700 argnames = kw.pop("argnames", None)
701
702 def _filter_exclusions(args):
703 result = []
704 gathered_exclusions = []
705 for a in args:
706 if isinstance(a, exclusions.compound):
707 gathered_exclusions.append(a)
708 else:
709 result.append(a)
710
711 return result, gathered_exclusions
712
713 id_ = kw.pop("id_", None)
714
715 tobuild_pytest_params = []
716 has_exclusions = False
717 if id_:
718 _combination_id_fns = self._combination_id_fns
719
720 # because itemgetter is not consistent for one argument vs.
721 # multiple, make it multiple in all cases and use a slice
722 # to omit the first argument
723 _arg_getter = operator.itemgetter(
724 0,
725 *[
726 idx
727 for idx, char in enumerate(id_)
728 if char in ("n", "r", "s", "a")
729 ],
730 )
731 fns = [
732 (operator.itemgetter(idx), _combination_id_fns[char])
733 for idx, char in enumerate(id_)
734 if char in _combination_id_fns
735 ]
736
737 for arg in arg_sets:
738 if not isinstance(arg, tuple):
739 arg = (arg,)
740
741 fn_params, param_exclusions = _filter_exclusions(arg)
742
743 parameters = _arg_getter(fn_params)[1:]
744
745 if param_exclusions:
746 has_exclusions = True
747
748 tobuild_pytest_params.append(
749 (
750 parameters,
751 param_exclusions,
752 "-".join(
753 comb_fn(getter(arg)) for getter, comb_fn in fns
754 ),
755 )
756 )
757
758 else:
759 for arg in arg_sets:
760 if not isinstance(arg, tuple):
761 arg = (arg,)
762
763 fn_params, param_exclusions = _filter_exclusions(arg)
764
765 if param_exclusions:
766 has_exclusions = True
767
768 tobuild_pytest_params.append(
769 (fn_params, param_exclusions, None)
770 )
771
772 pytest_params = []
773 for parameters, param_exclusions, id_ in tobuild_pytest_params:
774 if has_exclusions:
775 parameters += (param_exclusions,)
776
777 param = pytest.param(*parameters, id=id_)
778 pytest_params.append(param)
779
780 def decorate(fn):
781 if inspect.isclass(fn):
782 if has_exclusions:
783 raise NotImplementedError(
784 "exclusions not supported for class level combinations"
785 )
786 if "_sa_parametrize" not in fn.__dict__:
787 fn._sa_parametrize = []
788 fn._sa_parametrize.append((argnames, pytest_params))
789 return fn
790 else:
791 _fn_argnames = inspect.getfullargspec(fn).args[1:]
792 if argnames is None:
793 _argnames = _fn_argnames
794 else:
795 _argnames = re.split(r", *", argnames)
796
797 if has_exclusions:
798 existing_exl = sum(
799 1 for n in _fn_argnames if n.startswith("_exclusions")
800 )
801 current_exclusion_name = f"_exclusions_{existing_exl}"
802 _argnames += [current_exclusion_name]
803
804 @_pytest_fn_decorator
805 def check_exclusions(fn, *args, **kw):
806 _exclusions = args[-1]
807 if _exclusions:
808 exlu = exclusions.compound().add(*_exclusions)
809 fn = exlu(fn)
810 return fn(*args[:-1], **kw)
811
812 fn = check_exclusions(
813 fn,
814 add_positional_parameters=(current_exclusion_name,),
815 )
816
817 return pytest.mark.parametrize(_argnames, pytest_params)(fn)
818
819 return decorate
820
821 def param_ident(self, *parameters):
822 ident = parameters[0]
823 return pytest.param(*parameters[1:], id=ident)
824
825 def fixture(self, *arg, **kw):
826 from sqlalchemy.testing import config
827 from sqlalchemy.testing import asyncio
828
829 # wrapping pytest.fixture function. determine if
830 # decorator was called as @fixture or @fixture().
831 if len(arg) > 0 and callable(arg[0]):
832 # was called as @fixture(), we have the function to wrap.
833 fn = arg[0]
834 arg = arg[1:]
835 else:
836 # was called as @fixture, don't have the function yet.
837 fn = None
838
839 # create a pytest.fixture marker. because the fn is not being
840 # passed, this is always a pytest.FixtureFunctionMarker()
841 # object (or whatever pytest is calling it when you read this)
842 # that is waiting for a function.
843 fixture = pytest.fixture(*arg, **kw)
844
845 # now apply wrappers to the function, including fixture itself
846
847 def wrap(fn):
848 if config.any_async:
849 fn = asyncio._maybe_async_wrapper(fn)
850 # other wrappers may be added here
851
852 # now apply FixtureFunctionMarker
853 fn = fixture(fn)
854
855 return fn
856
857 if fn:
858 return wrap(fn)
859 else:
860 return wrap
861
862 def get_current_test_name(self):
863 return os.environ.get("PYTEST_CURRENT_TEST")
864
865 def async_test(self, fn):
866 from sqlalchemy.testing import asyncio
867
868 @_pytest_fn_decorator
869 def decorate(fn, *args, **kwargs):
870 asyncio._run_coroutine_function(fn, *args, **kwargs)
871
872 return decorate(fn)