다음과 같은 고정물을 작성할 수있는 재미있는 데코레이터를 만들었습니다.
@fixture_taking_arguments
def dog(request, /, name, age=69):
return f"{name} the dog aged {age}"
여기, 왼쪽 /
에는 다른 조명기가 있고 오른쪽에는 다음을 사용하여 제공되는 매개 변수가 있습니다.
@dog.arguments("Buddy", age=7)
def test_with_dog(dog):
assert dog == "Buddy the dog aged 7"
이것은 함수 인수가 작동하는 방식과 동일하게 작동합니다. age
인수를 제공하지 않으면 69
대신 기본값 인이 사용됩니다. 을 제공하지 않거나 데코레이터를 name
생략 dog.arguments
하면 일반 TypeError: dog() missing 1 required positional argument: 'name'
. argument를 취하는 다른 조명기가 있다면 name
이것과 충돌하지 않습니다.
비동기 픽스쳐도 지원됩니다.
또한 이것은 멋진 설정 계획을 제공합니다.
$ pytest test_dogs_and_owners.py --setup-plan
SETUP F dog['Buddy', age=7]
...
SETUP F dog['Champion']
SETUP F owner (fixtures used: dog)['John Travolta']
전체 예 :
from plugin import fixture_taking_arguments
@fixture_taking_arguments
def dog(request, /, name, age=69):
return f"{name} the dog aged {age}"
@fixture_taking_arguments
def owner(request, dog, /, name="John Doe"):
yield f"{name}, owner of {dog}"
@dog.arguments("Buddy", age=7)
def test_with_dog(dog):
assert dog == "Buddy the dog aged 7"
@dog.arguments("Champion")
class TestChampion:
def test_with_dog(self, dog):
assert dog == "Champion the dog aged 69"
def test_with_default_owner(self, owner, dog):
assert owner == "John Doe, owner of Champion the dog aged 69"
assert dog == "Champion the dog aged 69"
@owner.arguments("John Travolta")
def test_with_named_owner(self, owner):
assert owner == "John Travolta, owner of Champion the dog aged 69"
데코레이터의 코드 :
import pytest
from dataclasses import dataclass
from functools import wraps
from inspect import signature, Parameter, isgeneratorfunction, iscoroutinefunction, isasyncgenfunction
from itertools import zip_longest, chain
_NOTHING = object()
def _omittable_parentheses_decorator(decorator):
@wraps(decorator)
def wrapper(*args, **kwargs):
if not kwargs and len(args) == 1 and callable(args[0]):
return decorator()(args[0])
else:
return decorator(*args, **kwargs)
return wrapper
@dataclass
class _ArgsKwargs:
args: ...
kwargs: ...
def __repr__(self):
return ", ".join(chain(
(repr(v) for v in self.args),
(f"{k}={v!r}" for k, v in self.kwargs.items())))
def _flatten_arguments(sig, args, kwargs):
assert len(sig.parameters) == len(args) + len(kwargs)
for name, arg in zip_longest(sig.parameters, args, fillvalue=_NOTHING):
yield arg if arg is not _NOTHING else kwargs[name]
def _get_actual_args_kwargs(sig, args, kwargs):
request = kwargs["request"]
try:
request_args, request_kwargs = request.param.args, request.param.kwargs
except AttributeError:
request_args, request_kwargs = (), {}
return tuple(_flatten_arguments(sig, args, kwargs)) + request_args, request_kwargs
@_omittable_parentheses_decorator
def fixture_taking_arguments(*pytest_fixture_args, **pytest_fixture_kwargs):
def decorator(func):
original_signature = signature(func)
def new_parameters():
for param in original_signature.parameters.values():
if param.kind == Parameter.POSITIONAL_ONLY:
yield param.replace(kind=Parameter.POSITIONAL_OR_KEYWORD)
new_signature = original_signature.replace(parameters=list(new_parameters()))
if "request" not in new_signature.parameters:
raise AttributeError("Target function must have positional-only argument `request`")
is_async_generator = isasyncgenfunction(func)
is_async = is_async_generator or iscoroutinefunction(func)
is_generator = isgeneratorfunction(func)
if is_async:
@wraps(func)
async def wrapper(*args, **kwargs):
args, kwargs = _get_actual_args_kwargs(new_signature, args, kwargs)
if is_async_generator:
async for result in func(*args, **kwargs):
yield result
else:
yield await func(*args, **kwargs)
else:
@wraps(func)
def wrapper(*args, **kwargs):
args, kwargs = _get_actual_args_kwargs(new_signature, args, kwargs)
if is_generator:
yield from func(*args, **kwargs)
else:
yield func(*args, **kwargs)
wrapper.__signature__ = new_signature
fixture = pytest.fixture(*pytest_fixture_args, **pytest_fixture_kwargs)(wrapper)
fixture_name = pytest_fixture_kwargs.get("name", fixture.__name__)
def parametrizer(*args, **kwargs):
return pytest.mark.parametrize(fixture_name, [_ArgsKwargs(args, kwargs)], indirect=True)
fixture.arguments = parametrizer
return fixture
return decorator