Merge branch 'main' into Improvement-remove-prune_dependency_tree

This commit is contained in:
Sadra Barikbin 2023-08-23 19:58:11 +03:30 committed by GitHub
commit 08d8b71b99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 537 additions and 251 deletions

View File

@ -27,7 +27,7 @@ jobs:
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v4 uses: actions/setup-python@v4
with: with:
python-version: "3.8" python-version: "3.11"
cache: pip cache: pip
- name: requests-cache - name: requests-cache
uses: actions/cache@v3 uses: actions/cache@v3

View File

@ -5,7 +5,7 @@ repos:
- id: black - id: black
args: [--safe, --quiet] args: [--safe, --quiet]
- repo: https://github.com/asottile/blacken-docs - repo: https://github.com/asottile/blacken-docs
rev: 1.15.0 rev: 1.16.0
hooks: hooks:
- id: blacken-docs - id: blacken-docs
additional_dependencies: [black==23.7.0] additional_dependencies: [black==23.7.0]
@ -56,7 +56,7 @@ repos:
hooks: hooks:
- id: python-use-type-annotations - id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1 rev: v1.5.1
hooks: hooks:
- id: mypy - id: mypy
files: ^(src/|testing/) files: ^(src/|testing/)

View File

@ -0,0 +1,5 @@
(This entry is meant to assist plugins which access private pytest internals to instantiate ``FixtureRequest`` objects.)
:class:`~pytest.FixtureRequest` is now an abstract class which can't be instantiated directly.
A new concrete ``TopRequest`` subclass of ``FixtureRequest`` has been added for the ``request`` fixture in test functions,
as counterpart to the existing ``SubRequest`` subclass for the ``request`` fixture in fixture functions.

View File

@ -0,0 +1,2 @@
Corrected the spelling of ``Config.ArgsSource.INVOCATION_DIR``.
The previous spelling ``INCOVATION_DIR`` remains as an alias.

View File

@ -0,0 +1 @@
Removes unhelpful error message from assertion rewrite mechanism when exceptions raised in __iter__ methods, and instead treats them as un-iterable.

View File

@ -34,7 +34,7 @@ a function/method call.
**Assert** is where we look at that resulting state and check if it looks how **Assert** is where we look at that resulting state and check if it looks how
we'd expect after the dust has settled. It's where we gather evidence to say the we'd expect after the dust has settled. It's where we gather evidence to say the
behavior does or does not aligns with what we expect. The ``assert`` in our test behavior does or does not align with what we expect. The ``assert`` in our test
is where we take that measurement/observation and apply our judgement to it. If is where we take that measurement/observation and apply our judgement to it. If
something should be green, we'd say ``assert thing == "green"``. something should be green, we'd say ``assert thing == "green"``.

File diff suppressed because it is too large Load Diff

View File

@ -237,7 +237,7 @@ pytest.mark.xfail
Marks a test function as *expected to fail*. Marks a test function as *expected to fail*.
.. py:function:: pytest.mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=False) .. py:function:: pytest.mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=xfail_strict)
:type condition: bool or str :type condition: bool or str
:param condition: :param condition:
@ -249,10 +249,10 @@ Marks a test function as *expected to fail*.
:keyword Type[Exception] raises: :keyword Type[Exception] raises:
Exception subclass (or tuple of subclasses) expected to be raised by the test function; other exceptions will fail the test. Exception subclass (or tuple of subclasses) expected to be raised by the test function; other exceptions will fail the test.
:keyword bool run: :keyword bool run:
If the test function should actually be executed. If ``False``, the function will always xfail and will Whether the test function should actually be executed. If ``False``, the function will always xfail and will
not be executed (useful if a function is segfaulting). not be executed (useful if a function is segfaulting).
:keyword bool strict: :keyword bool strict:
* If ``False`` (the default) the function will be shown in the terminal output as ``xfailed`` if it fails * If ``False`` the function will be shown in the terminal output as ``xfailed`` if it fails
and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This
is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later. is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.
* If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it
@ -260,6 +260,8 @@ Marks a test function as *expected to fail*.
that are always failing and there should be a clear indication if they unexpectedly start to pass (for example that are always failing and there should be a clear indication if they unexpectedly start to pass (for example
a new release of a library fixes a known bug). a new release of a library fixes a known bug).
Defaults to :confval:`xfail_strict`, which is ``False`` by default.
Custom marks Custom marks
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -1638,11 +1640,11 @@ passed multiple times. The expected format is ``name=value``. For example::
Additionally, ``pytest`` will attempt to intelligently identify and ignore a Additionally, ``pytest`` will attempt to intelligently identify and ignore a
virtualenv by the presence of an activation script. Any directory deemed to virtualenv by the presence of an activation script. Any directory deemed to
be the root of a virtual environment will not be considered during test be the root of a virtual environment will not be considered during test
collection unless ``collectinvirtualenv`` is given. Note also that collection unless ``--collect-in-virtualenv`` is given. Note also that
``norecursedirs`` takes precedence over ``collectinvirtualenv``; e.g. if ``norecursedirs`` takes precedence over ``--collect-in-virtualenv``; e.g. if
you intend to run tests in a virtualenv with a base directory that matches you intend to run tests in a virtualenv with a base directory that matches
``'.*'`` you *must* override ``norecursedirs`` in addition to using the ``'.*'`` you *must* override ``norecursedirs`` in addition to using the
``collectinvirtualenv`` flag. ``--collect-in-virtualenv`` flag.
.. confval:: python_classes .. confval:: python_classes

View File

@ -17,7 +17,12 @@ python_classes = ["Test", "Acceptance"]
python_functions = ["test"] python_functions = ["test"]
# NOTE: "doc" is not included here, but gets tested explicitly via "doctesting". # NOTE: "doc" is not included here, but gets tested explicitly via "doctesting".
testpaths = ["testing"] testpaths = ["testing"]
norecursedirs = ["testing/example_scripts"] norecursedirs = [
"testing/example_scripts",
".*",
"build",
"dist",
]
xfail_strict = true xfail_strict = true
filterwarnings = [ filterwarnings = [
"error", "error",

View File

@ -44,6 +44,7 @@ DEVELOPMENT_STATUS_CLASSIFIERS = (
) )
ADDITIONAL_PROJECTS = { # set of additional projects to consider as plugins ADDITIONAL_PROJECTS = { # set of additional projects to consider as plugins
"logassert", "logassert",
"nuts",
} }

View File

@ -132,7 +132,7 @@ def isiterable(obj: Any) -> bool:
try: try:
iter(obj) iter(obj)
return not istext(obj) return not istext(obj)
except TypeError: except Exception:
return False return False

View File

@ -953,7 +953,8 @@ class Config:
#: Command line arguments. #: Command line arguments.
ARGS = enum.auto() ARGS = enum.auto()
#: Invocation directory. #: Invocation directory.
INCOVATION_DIR = enum.auto() INVOCATION_DIR = enum.auto()
INCOVATION_DIR = INVOCATION_DIR # backwards compatibility alias
#: 'testpaths' configuration value. #: 'testpaths' configuration value.
TESTPATHS = enum.auto() TESTPATHS = enum.auto()
@ -1278,7 +1279,7 @@ class Config:
else: else:
result = [] result = []
if not result: if not result:
source = Config.ArgsSource.INCOVATION_DIR source = Config.ArgsSource.INVOCATION_DIR
result = [str(invocation_dir)] result = [str(invocation_dir)]
return result, source return result, source

View File

@ -32,7 +32,7 @@ from _pytest.compat import safe_getattr
from _pytest.config import Config from _pytest.config import Config
from _pytest.config.argparsing import Parser from _pytest.config.argparsing import Parser
from _pytest.fixtures import fixture from _pytest.fixtures import fixture
from _pytest.fixtures import FixtureRequest from _pytest.fixtures import TopRequest
from _pytest.nodes import Collector from _pytest.nodes import Collector
from _pytest.nodes import Item from _pytest.nodes import Item
from _pytest.outcomes import OutcomeException from _pytest.outcomes import OutcomeException
@ -261,7 +261,7 @@ class DoctestItem(Item):
self.runner = runner self.runner = runner
self.dtest = dtest self.dtest = dtest
self.obj = None self.obj = None
self.fixture_request: Optional[FixtureRequest] = None self.fixture_request: Optional[TopRequest] = None
@classmethod @classmethod
def from_parent( # type: ignore def from_parent( # type: ignore
@ -571,7 +571,7 @@ class DoctestModule(Module):
) )
def _setup_fixtures(doctest_item: DoctestItem) -> FixtureRequest: def _setup_fixtures(doctest_item: DoctestItem) -> TopRequest:
"""Used by DoctestTextfile and DoctestItem to setup fixture information.""" """Used by DoctestTextfile and DoctestItem to setup fixture information."""
def func() -> None: def func() -> None:
@ -582,7 +582,7 @@ def _setup_fixtures(doctest_item: DoctestItem) -> FixtureRequest:
doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined] doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined]
node=doctest_item, func=func, cls=None, funcargs=False node=doctest_item, func=func, cls=None, funcargs=False
) )
fixture_request = FixtureRequest(doctest_item, _ispytest=True) # type: ignore[arg-type] fixture_request = TopRequest(doctest_item, _ispytest=True) # type: ignore[arg-type]
fixture_request._fillfixtures() fixture_request._fillfixtures()
return fixture_request return fixture_request

View File

@ -1,3 +1,4 @@
import abc
import dataclasses import dataclasses
import functools import functools
import inspect import inspect
@ -313,26 +314,32 @@ class FuncFixtureInfo:
name2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]] name2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]]
class FixtureRequest: class FixtureRequest(abc.ABC):
"""A request for a fixture from a test or fixture function. """The type of the ``request`` fixture.
A request object gives access to the requesting test context and has A request object gives access to the requesting test context and has a
an optional ``param`` attribute in case the fixture is parametrized ``param`` attribute in case the fixture is parametrized.
indirectly.
""" """
def __init__(self, pyfuncitem: "Function", *, _ispytest: bool = False) -> None: def __init__(
self,
pyfuncitem: "Function",
fixturename: Optional[str],
arg2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]],
arg2index: Dict[str, int],
fixture_defs: Dict[str, "FixtureDef[Any]"],
*,
_ispytest: bool = False,
) -> None:
check_ispytest(_ispytest) check_ispytest(_ispytest)
#: Fixture for which this request is being performed. #: Fixture for which this request is being performed.
self.fixturename: Optional[str] = None self.fixturename: Final = fixturename
self._pyfuncitem = pyfuncitem self._pyfuncitem: Final = pyfuncitem
self._fixturemanager = pyfuncitem.session._fixturemanager
self._scope = Scope.Function
# The FixtureDefs for each fixture name requested by this item. # The FixtureDefs for each fixture name requested by this item.
# Starts from the statically-known fixturedefs resolved during # Starts from the statically-known fixturedefs resolved during
# collection. Dynamically requested fixtures (using # collection. Dynamically requested fixtures (using
# `request.getfixturevalue("foo")`) are added dynamically. # `request.getfixturevalue("foo")`) are added dynamically.
self._arg2fixturedefs = pyfuncitem._fixtureinfo.name2fixturedefs.copy() self._arg2fixturedefs: Final = arg2fixturedefs
# A fixture may override another fixture with the same name, e.g. a fixture # A fixture may override another fixture with the same name, e.g. a fixture
# in a module can override a fixture in a conftest, a fixture in a class can # in a module can override a fixture in a conftest, a fixture in a class can
# override a fixture in the module, and so on. # override a fixture in the module, and so on.
@ -342,10 +349,10 @@ class FixtureRequest:
# The fixturedefs list in _arg2fixturedefs for a given name is ordered from # The fixturedefs list in _arg2fixturedefs for a given name is ordered from
# furthest to closest, so we use negative indexing -1, -2, ... to go from # furthest to closest, so we use negative indexing -1, -2, ... to go from
# last to first. # last to first.
self._arg2index: Dict[str, int] = {} self._arg2index: Final = arg2index
# The evaluated argnames so far, mapping to the FixtureDef they resolved # The evaluated argnames so far, mapping to the FixtureDef they resolved
# to. # to.
self._fixture_defs: Dict[str, FixtureDef[Any]] = {} self._fixture_defs: Final = fixture_defs
# Notes on the type of `param`: # Notes on the type of `param`:
# -`request.param` is only defined in parametrized fixtures, and will raise # -`request.param` is only defined in parametrized fixtures, and will raise
# AttributeError otherwise. Python typing has no notion of "undefined", so # AttributeError otherwise. Python typing has no notion of "undefined", so
@ -356,6 +363,15 @@ class FixtureRequest:
# for now just using Any. # for now just using Any.
self.param: Any self.param: Any
@property
def _fixturemanager(self) -> "FixtureManager":
return self._pyfuncitem.session._fixturemanager
@property
@abc.abstractmethod
def _scope(self) -> Scope:
raise NotImplementedError()
@property @property
def scope(self) -> _ScopeName: def scope(self) -> _ScopeName:
"""Scope string, one of "function", "class", "module", "package", "session".""" """Scope string, one of "function", "class", "module", "package", "session"."""
@ -369,25 +385,10 @@ class FixtureRequest:
return result return result
@property @property
@abc.abstractmethod
def node(self): def node(self):
"""Underlying collection node (depends on current request scope).""" """Underlying collection node (depends on current request scope)."""
scope = self._scope raise NotImplementedError()
if scope is Scope.Function:
# This might also be a non-function Item despite its attribute name.
node: Optional[Union[nodes.Item, nodes.Collector]] = self._pyfuncitem
elif scope is Scope.Package:
# FIXME: _fixturedef is not defined on FixtureRequest (this class),
# but on SubRequest (a subclass).
node = get_scope_package(self._pyfuncitem, self._fixturedef) # type: ignore[attr-defined]
else:
node = get_scope_node(self._pyfuncitem, scope)
if node is None and scope is Scope.Class:
# Fallback to function item itself.
node = self._pyfuncitem
assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
scope, self._pyfuncitem
)
return node
def _getnextfixturedef(self, argname: str) -> "FixtureDef[Any]": def _getnextfixturedef(self, argname: str) -> "FixtureDef[Any]":
fixturedefs = self._arg2fixturedefs.get(argname, None) fixturedefs = self._arg2fixturedefs.get(argname, None)
@ -473,11 +474,11 @@ class FixtureRequest:
"""Pytest session object.""" """Pytest session object."""
return self._pyfuncitem.session # type: ignore[no-any-return] return self._pyfuncitem.session # type: ignore[no-any-return]
@abc.abstractmethod
def addfinalizer(self, finalizer: Callable[[], object]) -> None: def addfinalizer(self, finalizer: Callable[[], object]) -> None:
"""Add finalizer/teardown function to be called without arguments after """Add finalizer/teardown function to be called without arguments after
the last test within the requesting test context finished execution.""" the last test within the requesting test context finished execution."""
# XXX usually this method is shadowed by fixturedef specific ones. raise NotImplementedError()
self.node.addfinalizer(finalizer)
def applymarker(self, marker: Union[str, MarkDecorator]) -> None: def applymarker(self, marker: Union[str, MarkDecorator]) -> None:
"""Apply a marker to a single test function invocation. """Apply a marker to a single test function invocation.
@ -498,13 +499,6 @@ class FixtureRequest:
""" """
raise self._fixturemanager.FixtureLookupError(None, self, msg) raise self._fixturemanager.FixtureLookupError(None, self, msg)
def _fillfixtures(self) -> None:
item = self._pyfuncitem
fixturenames = getattr(item, "fixturenames", self.fixturenames)
for argname in fixturenames:
if argname not in item.funcargs:
item.funcargs[argname] = self.getfixturevalue(argname)
def getfixturevalue(self, argname: str) -> Any: def getfixturevalue(self, argname: str) -> Any:
"""Dynamically run a named fixture function. """Dynamically run a named fixture function.
@ -638,6 +632,98 @@ class FixtureRequest:
finalizer = functools.partial(fixturedef.finish, request=subrequest) finalizer = functools.partial(fixturedef.finish, request=subrequest)
subrequest.node.addfinalizer(finalizer) subrequest.node.addfinalizer(finalizer)
@final
class TopRequest(FixtureRequest):
"""The type of the ``request`` fixture in a test function."""
def __init__(self, pyfuncitem: "Function", *, _ispytest: bool = False) -> None:
super().__init__(
fixturename=None,
pyfuncitem=pyfuncitem,
arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs.copy(),
arg2index={},
fixture_defs={},
_ispytest=_ispytest,
)
@property
def _scope(self) -> Scope:
return Scope.Function
@property
def node(self):
return self._pyfuncitem
def __repr__(self) -> str:
return "<FixtureRequest for %r>" % (self.node)
def _fillfixtures(self) -> None:
item = self._pyfuncitem
fixturenames = getattr(item, "fixturenames", self.fixturenames)
for argname in fixturenames:
if argname not in item.funcargs:
item.funcargs[argname] = self.getfixturevalue(argname)
def addfinalizer(self, finalizer: Callable[[], object]) -> None:
self.node.addfinalizer(finalizer)
@final
class SubRequest(FixtureRequest):
"""The type of the ``request`` fixture in a fixture function requested
(transitively) by a test function."""
def __init__(
self,
request: FixtureRequest,
scope: Scope,
param: Any,
param_index: int,
fixturedef: "FixtureDef[object]",
*,
_ispytest: bool = False,
) -> None:
super().__init__(
pyfuncitem=request._pyfuncitem,
fixturename=fixturedef.argname,
fixture_defs=request._fixture_defs,
arg2fixturedefs=request._arg2fixturedefs,
arg2index=request._arg2index,
_ispytest=_ispytest,
)
self._parent_request: Final[FixtureRequest] = request
self._scope_field: Final = scope
self._fixturedef: Final = fixturedef
if param is not NOTSET:
self.param = param
self.param_index: Final = param_index
def __repr__(self) -> str:
return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
@property
def _scope(self) -> Scope:
return self._scope_field
@property
def node(self):
scope = self._scope
if scope is Scope.Function:
# This might also be a non-function Item despite its attribute name.
node: Optional[Union[nodes.Item, nodes.Collector]] = self._pyfuncitem
elif scope is Scope.Package:
node = get_scope_package(self._pyfuncitem, self._fixturedef)
else:
node = get_scope_node(self._pyfuncitem, scope)
if node is None and scope is Scope.Class:
# Fallback to function item itself.
node = self._pyfuncitem
assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
scope, self._pyfuncitem
)
return node
def _check_scope( def _check_scope(
self, self,
argname: str, argname: str,
@ -672,44 +758,7 @@ class FixtureRequest:
) )
return lines return lines
def __repr__(self) -> str:
return "<FixtureRequest for %r>" % (self.node)
@final
class SubRequest(FixtureRequest):
"""A sub request for handling getting a fixture from a test function/fixture."""
def __init__(
self,
request: "FixtureRequest",
scope: Scope,
param: Any,
param_index: int,
fixturedef: "FixtureDef[object]",
*,
_ispytest: bool = False,
) -> None:
check_ispytest(_ispytest)
self._parent_request = request
self.fixturename = fixturedef.argname
if param is not NOTSET:
self.param = param
self.param_index = param_index
self._scope = scope
self._fixturedef = fixturedef
self._pyfuncitem = request._pyfuncitem
self._fixture_defs = request._fixture_defs
self._arg2fixturedefs = request._arg2fixturedefs
self._arg2index = request._arg2index
self._fixturemanager = request._fixturemanager
def __repr__(self) -> str:
return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
def addfinalizer(self, finalizer: Callable[[], object]) -> None: def addfinalizer(self, finalizer: Callable[[], object]) -> None:
"""Add finalizer/teardown function to be called without arguments after
the last test within the requesting test context finished execution."""
self._fixturedef.addfinalizer(finalizer) self._fixturedef.addfinalizer(finalizer)
def _schedule_finalizers( def _schedule_finalizers(

View File

@ -461,7 +461,9 @@ if TYPE_CHECKING:
*conditions: Union[str, bool], *conditions: Union[str, bool],
reason: str = ..., reason: str = ...,
run: bool = ..., run: bool = ...,
raises: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = ..., raises: Union[
None, Type[BaseException], Tuple[Type[BaseException], ...]
] = ...,
strict: bool = ..., strict: bool = ...,
) -> MarkDecorator: ) -> MarkDecorator:
... ...

View File

@ -233,6 +233,9 @@ def xfail(reason: str = "") -> NoReturn:
This function should be called only during testing (setup, call or teardown). This function should be called only during testing (setup, call or teardown).
No other code is executed after using ``xfail()`` (it is implemented
internally by raising an exception).
:param reason: :param reason:
The message to show the user as reason for the xfail. The message to show the user as reason for the xfail.

View File

@ -829,7 +829,7 @@ class Pytester:
return self._makefile(ext, args, kwargs) return self._makefile(ext, args, kwargs)
def makeconftest(self, source: str) -> Path: def makeconftest(self, source: str) -> Path:
"""Write a contest.py file. """Write a conftest.py file.
:param source: The contents. :param source: The contents.
:returns: The conftest.py file. :returns: The conftest.py file.

View File

@ -1829,7 +1829,7 @@ class Function(PyobjMixin, nodes.Item):
def _initrequest(self) -> None: def _initrequest(self) -> None:
self.funcargs: Dict[str, object] = {} self.funcargs: Dict[str, object] = {}
self._request = fixtures.FixtureRequest(self, _ispytest=True) self._request = fixtures.TopRequest(self, _ispytest=True)
@property @property
def function(self): def function(self):

View File

@ -1,5 +1,7 @@
# PYTHON_ARGCOMPLETE_OK # PYTHON_ARGCOMPLETE_OK
"""pytest: unit and functional testing with Python.""" """pytest: unit and functional testing with Python."""
from typing import TYPE_CHECKING
from _pytest import __version__ from _pytest import __version__
from _pytest import version_tuple from _pytest import version_tuple
from _pytest._code import ExceptionInfo from _pytest._code import ExceptionInfo
@ -165,8 +167,9 @@ __all__ = [
"yield_fixture", "yield_fixture",
] ]
if not TYPE_CHECKING:
def __getattr__(name: str) -> object: def __getattr__(name: str) -> object:
if name == "Instance": if name == "Instance":
# The import emits a deprecation warning. # The import emits a deprecation warning.
from _pytest.python import Instance from _pytest.python import Instance

View File

@ -272,7 +272,7 @@ def test_importing_instance_is_deprecated(pytester: Pytester) -> None:
pytest.PytestDeprecationWarning, pytest.PytestDeprecationWarning,
match=re.escape("The pytest.Instance collector type is deprecated"), match=re.escape("The pytest.Instance collector type is deprecated"),
): ):
pytest.Instance pytest.Instance # type:ignore[attr-defined]
with pytest.warns( with pytest.warns(
pytest.PytestDeprecationWarning, pytest.PytestDeprecationWarning,

View File

@ -4,10 +4,9 @@ import textwrap
from pathlib import Path from pathlib import Path
import pytest import pytest
from _pytest import fixtures
from _pytest.compat import getfuncargnames from _pytest.compat import getfuncargnames
from _pytest.config import ExitCode from _pytest.config import ExitCode
from _pytest.fixtures import FixtureRequest from _pytest.fixtures import TopRequest
from _pytest.monkeypatch import MonkeyPatch from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import get_public_names from _pytest.pytester import get_public_names
from _pytest.pytester import Pytester from _pytest.pytester import Pytester
@ -659,7 +658,7 @@ class TestRequestBasic:
""" """
) )
assert isinstance(item, Function) assert isinstance(item, Function)
req = fixtures.FixtureRequest(item, _ispytest=True) req = TopRequest(item, _ispytest=True)
assert req.function == item.obj assert req.function == item.obj
assert req.keywords == item.keywords assert req.keywords == item.keywords
assert hasattr(req.module, "test_func") assert hasattr(req.module, "test_func")
@ -701,9 +700,7 @@ class TestRequestBasic:
(item1,) = pytester.genitems([modcol]) (item1,) = pytester.genitems([modcol])
assert isinstance(item1, Function) assert isinstance(item1, Function)
assert item1.name == "test_method" assert item1.name == "test_method"
arg2fixturedefs = fixtures.FixtureRequest( arg2fixturedefs = TopRequest(item1, _ispytest=True)._arg2fixturedefs
item1, _ispytest=True
)._arg2fixturedefs
assert len(arg2fixturedefs) == 1 assert len(arg2fixturedefs) == 1
assert arg2fixturedefs["something"][0].argname == "something" assert arg2fixturedefs["something"][0].argname == "something"
@ -969,7 +966,7 @@ class TestRequestBasic:
modcol = pytester.getmodulecol("def test_somefunc(): pass") modcol = pytester.getmodulecol("def test_somefunc(): pass")
(item,) = pytester.genitems([modcol]) (item,) = pytester.genitems([modcol])
assert isinstance(item, Function) assert isinstance(item, Function)
req = fixtures.FixtureRequest(item, _ispytest=True) req = TopRequest(item, _ispytest=True)
assert req.path == modcol.path assert req.path == modcol.path
def test_request_fixturenames(self, pytester: Pytester) -> None: def test_request_fixturenames(self, pytester: Pytester) -> None:
@ -1128,7 +1125,7 @@ class TestRequestMarking:
""" """
) )
assert isinstance(item1, Function) assert isinstance(item1, Function)
req1 = fixtures.FixtureRequest(item1, _ispytest=True) req1 = TopRequest(item1, _ispytest=True)
assert "xfail" not in item1.keywords assert "xfail" not in item1.keywords
req1.applymarker(pytest.mark.xfail) req1.applymarker(pytest.mark.xfail)
assert "xfail" in item1.keywords assert "xfail" in item1.keywords
@ -4036,7 +4033,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "m1 f1".split() assert request.fixturenames == "m1 f1".split()
def test_func_closure_with_native_fixtures( def test_func_closure_with_native_fixtures(
@ -4085,7 +4082,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
# order of fixtures based on their scope and position in the parameter list # order of fixtures based on their scope and position in the parameter list
assert ( assert (
request.fixturenames request.fixturenames
@ -4113,7 +4110,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "m1 f1".split() assert request.fixturenames == "m1 f1".split()
def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None: def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None:
@ -4147,7 +4144,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "s1 m1 c1 f2 f1".split() assert request.fixturenames == "s1 m1 c1 f2 f1".split()
def test_func_closure_same_scope_closer_root_first( def test_func_closure_same_scope_closer_root_first(
@ -4190,7 +4187,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "p_sub m_conf m_sub m_test f1".split() assert request.fixturenames == "p_sub m_conf m_sub m_test f1".split()
def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None: def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None:
@ -4235,7 +4232,7 @@ class TestScopeOrdering:
) )
items, _ = pytester.inline_genitems() items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function) assert isinstance(items[0], Function)
request = FixtureRequest(items[0], _ispytest=True) request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split() assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split()
def test_multiple_packages(self, pytester: Pytester) -> None: def test_multiple_packages(self, pytester: Pytester) -> None:

View File

@ -685,6 +685,25 @@ class TestAssertionRewrite:
assert msg is not None assert msg is not None
assert "<MY42 object> < 0" in msg assert "<MY42 object> < 0" in msg
def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
class A:
def __iter__(self):
raise ValueError()
def __eq__(self, o: object) -> bool:
return self is o
def __repr__(self):
return "<A object>"
assert A() == A()
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*E*assert <A object> == <A object>"])
def test_formatchar(self) -> None: def test_formatchar(self) -> None:
def f() -> None: def f() -> None:
assert "%test" == "test" # type: ignore[comparison-overlap] assert "%test" == "test" # type: ignore[comparison-overlap]

View File

@ -507,6 +507,24 @@ class TestParseIni:
result = pytester.runpytest("--foo=1") result = pytester.runpytest("--foo=1")
result.stdout.fnmatch_lines("* no tests ran in *") result.stdout.fnmatch_lines("* no tests ran in *")
def test_args_source_args(self, pytester: Pytester):
config = pytester.parseconfig("--", "test_filename.py")
assert config.args_source == Config.ArgsSource.ARGS
def test_args_source_invocation_dir(self, pytester: Pytester):
config = pytester.parseconfig()
assert config.args_source == Config.ArgsSource.INVOCATION_DIR
def test_args_source_testpaths(self, pytester: Pytester):
pytester.makeini(
"""
[pytest]
testpaths=*
"""
)
config = pytester.parseconfig()
assert config.args_source == Config.ArgsSource.TESTPATHS
class TestConfigCmdlineParsing: class TestConfigCmdlineParsing:
def test_parsing_again_fails(self, pytester: Pytester) -> None: def test_parsing_again_fails(self, pytester: Pytester) -> None:

View File

@ -2,6 +2,7 @@ from pathlib import Path
import pytest import pytest
from _pytest.compat import LEGACY_PATH from _pytest.compat import LEGACY_PATH
from _pytest.fixtures import TopRequest
from _pytest.legacypath import TempdirFactory from _pytest.legacypath import TempdirFactory
from _pytest.legacypath import Testdir from _pytest.legacypath import Testdir
@ -91,7 +92,7 @@ def test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None:
modcol = pytester.getmodulecol("def test_somefunc(): pass") modcol = pytester.getmodulecol("def test_somefunc(): pass")
(item,) = pytester.genitems([modcol]) (item,) = pytester.genitems([modcol])
assert isinstance(item, pytest.Function) assert isinstance(item, pytest.Function)
req = pytest.FixtureRequest(item, _ispytest=True) req = TopRequest(item, _ispytest=True)
assert req.path == modcol.path assert req.path == modcol.path
assert req.fspath == modcol.fspath # type: ignore[attr-defined] assert req.fspath == modcol.fspath # type: ignore[attr-defined]

View File

@ -12,6 +12,7 @@ envlist =
pypy3 pypy3
py38-{pexpect,xdist,unittestextras,numpy,pluggymain,pylib} py38-{pexpect,xdist,unittestextras,numpy,pluggymain,pylib}
doctesting doctesting
doctesting-coverage
plugins plugins
py38-freeze py38-freeze
docs docs