Compare commits

...

845 Commits

Author SHA1 Message Date
Ran Benita
71849cc05c Merge pull request #12055 from bluetech/cherry-pick-release
Cherry-pick 8.1.0 release notes
2024-03-03 23:29:47 +02:00
Ran Benita
e410705561 Cherry-pick 8.1.0 release notes
(cherry picked from commit 0a536810dc)
2024-03-03 23:27:02 +02:00
Ran Benita
00043f7f10 Merge pull request #12038 from bluetech/fixtures-rm-arg2index
fixtures: avoid mutable arg2index state in favor of looking up the request chain
2024-03-03 15:45:34 +02:00
Ran Benita
f4e10251a4 Merge pull request #12048 from bluetech/fixture-teardown-excgroup
fixtures: use exception group when multiple finalizers raise in fixture teardown
2024-03-03 15:09:36 +02:00
Ran Benita
43492f5707 Merge pull request #12051 from jakkdl/test_debugging_pythonbreakpoint
[minor/QoL] monkeypatch.delenv PYTHONBREAKPOINT in two tests that previously failed/skipped
2024-03-03 15:07:19 +02:00
github-actions[bot]
82fe28dae4 [automated] Update plugin list (#12049)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-03-03 12:50:42 +00:00
jakkdl
5e2ee7175c monkeypatch.delenv PYTHONBREAKPOINT in two tests that previously failed/skipped 2024-03-03 13:48:29 +01:00
Bruno Oliveira
89ee4493cc Merge pull request #11997 from nicoddemus/11475-importlib
Change importlib to first try to import modules using the standard mechanism
2024-03-03 09:43:14 -03:00
mrbean-bremen
8248946a55 Do not collect symlinked tests under Windows (#12050)
The check for short paths under Windows via os.path.samefile, introduced in #11936, also found similar tests in symlinked tests in the GH Actions CI.

Fixes #12039.

Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
2024-03-03 09:41:31 -03:00
Ran Benita
434282e17f fixtures: use exception group when multiple finalizers raise in fixture teardown
Previously, if more than one fixture finalizer raised, only the first
was reported, and the other errors were lost.

Use an exception group to report them all. This is similar to the change
we made in node teardowns (in `SetupState`).
2024-03-02 23:39:11 +02:00
Bruno Oliveira
d6134bc21e doc: document consider_namespace_packages option 2024-03-02 16:13:48 -03:00
Bruno Oliveira
aac720abc9 testing/test_pathlib: parametrize namespace package option
Test with namespace packages support even when it will not find namespace packages to ensure it will at least not give weird results or crashes.
2024-03-02 16:13:48 -03:00
Bruno Oliveira
111c0d910e Add consider_namespace_packages ini option
Fix #11475
2024-03-02 16:13:48 -03:00
Bruno Oliveira
199d4e2b73 pathlib: import signature and docs for import_path 2024-03-02 16:13:48 -03:00
Bruno Oliveira
5746b8e696 doc: update and improve import mode docs 2024-03-02 16:13:48 -03:00
Bruno Oliveira
c85fce39b6 Change importlib to first try to import modules using the standard mechanism
As detailed in
https://github.com/pytest-dev/pytest/issues/11475#issuecomment-1937043670,
currently with `--import-mode=importlib` pytest will try to import every
file by using a unique module name, regardless if that module could be
imported using the normal import mechanism without touching `sys.path`.

This has the consequence that non-test modules available in `sys.path`
(via other mechanism, such as being installed into a virtualenv,
PYTHONPATH, etc) would end up being imported as standalone modules,
instead of imported with their expected module names.

To illustrate:

```
.env/
  lib/
    site-packages/
      anndata/
        core.py
```

Given `anndata` is installed into the virtual environment, `python -c
"import anndata.core"` works, but pytest with `importlib` mode would
import that module as a standalone module named
`".env.lib.site-packages.anndata.core"`, because importlib module was
designed to import test files which are not reachable from `sys.path`,
but now it is clear that normal modules should be imported using the
standard mechanisms if possible.

Now `imporlib` mode will first try to import the module normally,
without changing `sys.path`, and if that fails it falls back to
importing the module as a standalone module.

This also makes `importlib` respect namespace packages.

This supersedes #11931.

Fix #11475
Close #11931
2024-03-02 16:13:48 -03:00
Bruno Oliveira
067daf9f7d pathlib: consider namespace packages in resolve_pkg_root_and_module_name
This applies to `append` and `prepend` import modes; support for
`importlib` mode will be added in a separate change.
2024-03-02 16:13:48 -03:00
Bruno Oliveira
5867426455 pathlib: handle filenames starting with . in module_name_from_path 2024-03-02 16:13:48 -03:00
Bruno Oliveira
4dea18308b pathlib: extract a function _import_module_using_spec
Will be reused.
2024-03-02 16:13:48 -03:00
Bruno Oliveira
7524e60d8f pathlib: extract a function resolve_pkg_root_and_module_name
Will be reused.
2024-03-02 16:13:48 -03:00
Bruno Oliveira
dcf01fd39a testing/test_pathlib: add an importlib test
Ensure the implementation isn't changed to trigger such a bug.
2024-03-02 16:13:48 -03:00
Bruno Oliveira
300ceb435e testing/test_doctest: make test_importmode more realistic 2024-03-02 16:13:48 -03:00
Bruno Oliveira
887e251abb testing/test_pathlib: remove test_issue131_on__init__
The test seems wrong, and we haven't been able to figure out what it's
trying to test (the original issue is lost in time).
2024-03-02 16:13:48 -03:00
Ran Benita
6ed005161d Merge pull request #12043 from bluetech/pyargs-root
Fix collection failures due to permission errors when using `--pyargs`
2024-03-02 21:09:20 +02:00
Ran Benita
31026a2df2 main: only include package parents in collection tree for --pyargs collection arguments
(diff better viewed ignoring whitespace)

In pytest<8, the collection tree for `pyargs` arguments in an invocation
like this:

    pytest --collect-only --pyargs pyflakes.test.test_undefined_names

looked like this:

```
<Package test>
  <Module test_undefined_names.py>
    <UnitTestCase Test>
      <TestCaseFunction test_annotationUndefined>
      ... snipped ...
```

The pytest 8 collection improvements changed it to this:

```
<Dir pytest>
  <Dir .tox>
    <Dir venv>
      <Dir lib>
        <Dir python3.11>
          <Dir site-packages>
            <Package pyflakes>
              <Package test>
                <Module test_undefined_names.py>
                  <UnitTestCase Test>
                    <TestCaseFunction test_annotationUndefined>
                    ... snipped ...
```

Besides being egregious (and potentially even worse than the above,
going all the way to the root, for system-installed packages, as is
apparently common in CI), this also caused permission errors when trying
to probe some of those intermediate directories.

This change makes `--pyargs` arguments no longer try to add parent
directories to the collection tree according to the `--confcutdir` like
they're regular arguments. Instead, only add the parents that are in the
import path. This now looks like this:

```
<Package .tox/venv/lib/python3.11/site-packages/pyflakes>
  <Package test>
    <Module test_undefined_names.py>
      <UnitTestCase Test>
        <TestCaseFunction test_annotationUndefined>
        ... snipped ...
```

Fix #11904.
2024-03-02 20:26:02 +02:00
Ran Benita
f20e32c982 main: slight refactor to collection argument parents logic
No logical change, preparation for the next commit.
2024-03-02 20:26:02 +02:00
Ran Benita
1612d4e393 main: add module_name to CollectionArgument
This is available when the argument is a `--pyargs` argument (resolved
from a python module path). Will be used in an upcoming commit.
2024-03-02 20:26:02 +02:00
Ran Benita
5e0d11746c main: model the result of resolve_collection_arguments as a dataclass
In preparation of adding more info to it.
2024-03-02 20:25:57 +02:00
Ran Benita
b6bf58abe8 Merge pull request #12042 from donhui/docs-0301
docs: update plugins number
2024-03-01 15:20:33 +02:00
Ran Benita
ff4c3b2873 main: add missing import importlib.util
Used in `resolve_collection_argument`. It's implicitly imported by some
other import, but some type checkers don't recognize this.
2024-03-01 13:28:27 +02:00
donghui
4db5e53709 docs: update plugins number 2024-03-01 05:43:57 +08:00
Ran Benita
c967d508d6 Merge pull request #12037 from bluetech/fixtures-getnextfixturedef-parent
fixtures: remove unneeded optimization from `_getnextfixturedef`
2024-02-28 09:28:15 +02:00
Ran Benita
bd45ccd2ca fixtures: avoid mutable arg2index state in favor of looking up the request chain
pytest allows a fixture to request its own name (directly or
indirectly), in which case the fixture with the same name but one level
up is used.

To know which fixture should be used next, pytest keeps a mutable
item-global dict `_arg2index` which maintains this state. This is not
great:

- Mutable state like this is hard to understand and reason about.

- It is conceptually buggy; the indexing is global (e.g. if requesting
  `fix1` and `fix2`, the indexing is shared between them), but actually
  different branches of the subrequest tree should not affect each
  other.

  This is not an issue in practice because pytest keeps a cache of the
  fixturedefs it resolved anyway (`_fixture_defs`), but if the cache is
  removed it becomes evident.

Instead of the `_arg2index` state, count how many `argname`s deep we are
in the subrequest tree ("the fixture stack") and use that for the index.

This way, no global mutable state and the logic is very localized and
easier to understand.

This is slower, however fixture stacks should not be so deep that this
matters much, I hope.
2024-02-27 22:24:26 +02:00
Ran Benita
c83c1c4bda fixtures: add _iter_chain helper method
Will be reused in the next commit.
2024-02-27 22:24:26 +02:00
Ran Benita
686f9e0720 fixtures: remove unneeded optimization from _getnextfixturedef
According to my understanding, this code, which handles obtaining the
relevant fixturedefs when a dynamic `getfixturevalue` is used, has an
optimization where it only grabs fixturedefs that are visible to the
*parent* of the item, instead of the item itself, under the assumption
that a fixturedef can't be visible to a single item, only to a
collector.

Remove this optimization for the following reasons:
- It doesn't save much (one loop iteration in `matchfactories`)
- It slightly complicates the complex fixtures code
- If some plugin wants to make a fixture visible only to a single item,
  why not let it?
- In the static case (`getfixtureclosure`), this optimization is not
  done (despite the confusing name `parentnode`, it is *not* the parent
  node). This is inconsistent.
2024-02-27 22:22:07 +02:00
dependabot[bot]
98b008ff6c build(deps): Bump anyio[curio,trio] in /testing/plugins_integration (#12033)
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 4.2.0 to 4.3.0.
- [Release notes](https://github.com/agronholm/anyio/releases)
- [Changelog](https://github.com/agronholm/anyio/blob/master/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/4.2.0...4.3.0)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-26 10:51:07 -03:00
Bruno Oliveira
73edefdd64 Merge pull request #12031 from pytest-dev/update-plugin-list/patch-affc652f1
[automated] Update plugin list
2024-02-24 21:50:44 -03:00
Bruno Oliveira
ffd727e9d6 Fix mention of the prefix for pytest plugins in plugin_list 2024-02-24 21:35:51 -03:00
pytest bot
b6eb985d55 [automated] Update plugin list 2024-02-25 00:19:33 +00:00
Ran Benita
affc652f1c Merge pull request #12030 from bluetech/cherry-pick-release
Cherry pick 8.0.2 release notes
2024-02-25 00:31:52 +02:00
Ran Benita
7460b1aa31 Cherry pick 8.0.2 release notes
(cherry picked from commit e53f798932)
2024-02-25 00:25:49 +02:00
Patrick Lannigan
84bd31de64 New verbosity_test_case ini option (#11653)
Allow for the output of test case execution to be controlled independently from the application verbosity level. 

`verbosity_test_case` is the new ini setting to adjust this functionality.

Fix #11639
2024-02-24 16:27:54 -03:00
Ran Benita
a2a9aa6cde Merge pull request #12027 from bluetech/sys-last-exc
runner: add support for `sys.last_exc` for post-mortem debugging on Python>=3.12
2024-02-23 22:41:14 +02:00
robotherapist
c09f74619b runner: add support for sys.last_exc for post-mortem debugging on Python>=3.12
Fix #11850
2024-02-23 15:59:32 +02:00
Ran Benita
b510adf9ef Merge pull request #12023 from bluetech/fixtures-cleanups-2
fixtures: remove an unneeded suppress
2024-02-23 15:35:17 +02:00
Ran Benita
93cd7ba857 Merge pull request #12022 from bluetech/revert-11721
Revert "Fix teardown error reporting when `--maxfail=1` (#11721)"
2024-02-23 15:34:32 +02:00
Bruno Oliveira
8d9b95dcdb Fix collection of short paths on Windows (#11936)
Passing a short path in the command line was causing the matchparts check to fail, because ``Path(short_path) != Path(long_path)``.

Using ``os.path.samefile`` as fallback ensures the comparsion works on Windows when comparing short/long paths.

Fix #11895
2024-02-23 07:51:15 -03:00
Ran Benita
ad651ddfce fixtures: remove an unneeded suppress
In `CallSpec2.setmulti` the `params` and `_arg2scope` dicts are always
set together.

Further, the `get_parametrized_fixture_keys` accesses `_arg2scope` for
all argnames without a check, which I think rules out that the code
protects against plugin shenanigans.

After removing the suppress, adjust the comment and code to make more
sense.
2024-02-23 11:51:49 +02:00
Ran Benita
00d9640abc Revert "Fix teardown error reporting when --maxfail=1 (#11721)"
Fix #12021.
Reopens #11706.

This reverts commit 12b9bd5801.

This change caused a bad regression in pytest-xdist:
https://github.com/pytest-dev/pytest-xdist/issues/1024

pytest-xdist necessarily has special handling of `--maxfail` and session
fixture teardown get executed multiple times with the change.

Since I'm not sure how to adapt pytest-xdist myself, revert for now.

I kept the sticky `shouldstop`/`shouldfail` changes as they are good
ideas regardless I think.
2024-02-23 11:45:26 +02:00
Ran Benita
010ce2ab0f Add typing to from_parent return values (#11916)
Up to now the return values of `from_parent` were untyped, this is an
attempt to make it work with `typing.Self`.
2024-02-22 23:35:57 -08:00
Eric Larson
1640f2e454 ENH: Improve warning stacklevel (#12014)
* ENH: Improve warning stacklevel

* TST: Add test

* TST: Ping

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* MAINT: Changelog

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-02-22 22:11:05 -08:00
Bruno Oliveira
59e9a58cc9 Remove Anthony from Tidelift participants (#12020)
As discussed in the core development channels, @asottile asked to no longer be a Tidelift participant, at least for the time being.
2024-02-22 21:04:11 -03:00
Ran Benita
691d8fcafb Merge pull request #12019 from bluetech/fixtures-simplify
fixtures: remove a no longer needed sort
2024-02-22 21:52:56 +02:00
Ben Leith
c5c729e27a Add --log-file-mode option to the logging plugin, enabling appending to log-files (#11979)
Previously, the mode was hard-coded to be "w" which truncates the file before logging.

Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
2024-02-21 12:02:19 +00:00
Ran Benita
9bea1be215 fixtures: remove a no longer needed sort
Dicts these days preserve order, so the sort is no longer needed to
achieve determinism.

As shown by the `test_dynamic_parametrized_ordering` test, this can
change the ordering of items, but only in equivalent ways (same number
of setups/teardowns per scope), it will just respect the user's given
ordering better (hence `vxlan` items now ordered before `vlan` items
compared to the previous ordering).
2024-02-21 10:17:25 +02:00
Ran Benita
2007cf6296 fixtures: remove a level of indentation
A bit easier to follow.
2024-02-21 10:17:24 +02:00
Ran Benita
79def57cc6 python: small code cleanup 2024-02-21 10:17:24 +02:00
Ran Benita
8a410d0ba6 Merge pull request #12013 from bluetech/doctest-test
testing: add a regression test for `setup_module` + `--doctest-modules`
2024-02-20 22:22:01 +02:00
Ran Benita
a37cff3ca8 testing: add a regression test for setup_module + --doctest-modules
Refs #12011 (only fails on 8.0.1, not main).
2024-02-20 09:36:00 +02:00
pre-commit-ci[bot]
95f21f96cc [pre-commit.ci] pre-commit autoupdate (#12012)
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.2.1 → v0.2.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.1...v0.2.2)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-02-19 21:36:03 -03:00
Bruno Oliveira
998fee1679 Clarify PytestPluginManager._is_in_confcutdir (#12007)
Follow up to #12006, let's put some comments clarifying `is_in_confcutdir` semantics, as this is not the first time someone misunderstands it.

Also removed an obsolete comment in `_loadconftestmodules`: we already set the `confcutdir` based on `rootdir`/`initfile` if not explicitly given.

Co-authored-by: Ran Benita <ran@unusedvar.com>
2024-02-18 17:27:47 -03:00
Bruno Oliveira
40011b838b Allow Sphinx 7.x (#12002)
Thanks to https://github.com/pytest-dev/pytest/issues/11988#issuecomment-1950318888, the problem was our custom template.

The solution was to copy the template from Sphinx 7 and remove the header.
2024-02-18 07:21:05 -03:00
Bruno Oliveira
b37696703b Merge pull request #12003 from pytest-dev/update-plugin-list/patch-cefb3e227
[automated] Update plugin list
2024-02-17 22:35:26 -03:00
Bruno Oliveira
abf6a60567 Fix 'pytest_' mention: it was being considered a rst reference 2024-02-17 22:21:30 -03:00
pytest bot
52da8dd66c [automated] Update plugin list 2024-02-18 00:19:26 +00:00
Bruno Oliveira
cefb3e2277 Disallow Sphinx 6 and 7 (#12000)
Using Sphinx 6.x and 7.x the search bar disappears. Restrict to Sphinx 5.x for now until we find a solution.

Reverts #11568
Fixes #11988
2024-02-17 17:46:58 -03:00
Bruno Oliveira
5f241f388b Revert sys.platform verification to simple comparison (#11998)
As the comment above it states, we need to keep the comparison simple so mypy can understand it, otherwise it will fail to properly handle this on Windows and will flag ``os.getuid()`` missing.
2024-02-17 16:10:21 -03:00
Ran Benita
aebeb33137 Merge pull request #11996 from bluetech/getstatementrange-index-error
code: fix `IndexError` crash in `getstatementrange_ast`
2024-02-17 18:59:10 +02:00
Ran Benita
9f13d41d7b code: fix IndexError crash in getstatementrange_ast
Fix #11953.
2024-02-17 18:43:55 +02:00
Ran Benita
984478109f Merge pull request #11995 from bluetech/cherry-pick-release
Cherry pick 8.0.1 release notes
2024-02-17 00:27:55 +02:00
Ran Benita
22b541e4eb Merge pull request #11993 from pytest-dev/release-8.0.1
Prepare release 8.0.1

(cherry picked from commit 68524d4858)
2024-02-17 00:11:27 +02:00
Ran Benita
fbe18fc7a9 Merge pull request #11991 from bluetech/warns-fix
recwarn: fix pytest.warns handling of Warnings with multiple arguments
2024-02-16 14:29:19 +02:00
Reagan Lee
9b838f491f recwarn: fix pytest.warns handling of Warnings with multiple arguments
Fix #11906
2024-02-16 14:14:24 +02:00
Ran Benita
6ef0cf150a Merge pull request #11959 from eerovaher/warn-message-type
Allow using `warnings.warn()` with a `Warning`
2024-02-16 14:00:37 +02:00
Eero Vaher
0475b1c925 Allow using warnings.warn() with Warnings
Test:

`warnings.warn()` expects that its first argument is a `str` or a
`Warning`, but since 9454fc38d3
`pytest.warns()` no longer allows `Warning` instances unless the first
argument the `Warning` was initialized with is a `str`. Furthermore, if
the `Warning` was created without arguments then `pytest.warns()` raises
an unexpected `IndexError`. The new tests reveal the problem.

Fix:

`pytest.warns()` now allows using `warnings.warn()` with a `Warning`
instance, as is required by Python, with one exception. If the warning
used is a `UserWarning` that was created by passing it arguments and the
first argument was not a `str` then `pytest.raises()` still considers
that an error. This is because if an invalid type was used in
`warnings.warn()` then Python creates a `UserWarning` anyways and it
becomes impossible for `pytest` to figure out if that was done
automatically or not.

[ran: rebased on previous commit]
2024-02-16 13:41:59 +02:00
Ran Benita
dcf9da92be recwarn: minor style improvements
In preparation for next commit.
2024-02-16 13:41:27 +02:00
Ran Benita
8e56795b77 Merge pull request #11989 from bluetech/plugin-list-underscore
scripts/update-plugin-list: include packages starting with "pytest_" (underscore)
2024-02-16 13:01:25 +02:00
Ran Benita
718cd40015 Merge pull request #11920 from bluetech/warn-skip
recwarn: let base exceptions propagate through `pytest.warns` again
2024-02-16 12:22:52 +02:00
Ran Benita
288201b8f5 recwarn: let base exceptions propagate through pytest.warns again
Fix #11907.
2024-02-16 12:07:56 +02:00
Ran Benita
c6313a06fb scripts/update-plugin-list: include packages starting with "pytest_" (underscore)
Fix #11985.
2024-02-16 12:03:38 +02:00
dependabot[bot]
5d7a5a9343 build(deps): Bump codecov/codecov-action from 3 to 4 (#11921)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 3 to 4.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-14 16:11:30 -03:00
dependabot[bot]
cbb5c82c39 build(deps): Bump peter-evans/create-pull-request from 5.0.2 to 6.0.0 (#11922)
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 5.0.2 to 6.0.0.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](153407881e...b1ddad2c99)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-14 16:11:20 -03:00
Bruno Oliveira
acafd003aa Consider pyproject.toml files for config if no other config files were found (#11962)
Today `pyproject.toml` is the standard for declaring a Python project root, so seems reasonable to consider it for the ini configuration (and specially `rootdir`) in case we do not find other suitable candidates.

Related to #11311
2024-02-14 16:08:45 -03:00
Bruno Oliveira
46e6fb12c7 Consider paths and pathlists relative to cwd in case of an absent ini-file (#11963)
Previously this would trigger an `AssertionError`.

While it could be considered a bug-fix, but given it now can be relied upon, it is probably better to consider it an improvement.

Fix #11311
2024-02-14 15:53:28 -03:00
Dave Hall
fe7907d78c Add logot to plugin list (#11972) 2024-02-14 15:50:34 -03:00
Ran Benita
5bb1363435 Merge pull request #11957 from bluetech/fix-session-collect-order
main: fix reversed collection order in Session
2024-02-13 09:44:13 +02:00
pre-commit-ci[bot]
ca84327f15 [pre-commit.ci] pre-commit autoupdate (#11967)
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.2.0 → v0.2.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.0...v0.2.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-02-13 06:19:40 +01:00
dependabot[bot]
3b798e5422 build(deps): Bump pytest-asyncio in /testing/plugins_integration (#11965)
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.23.3 to 0.23.5.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.23.3...v0.23.5)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-12 11:06:14 -03:00
Pierre Sassoulas
526b971221 Merge pull request #11961 Add some autofixable refactor rules from pylint 2024-02-11 19:52:29 +01:00
github-actions[bot]
23dfb52974 [automated] Update plugin list (#11964)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-02-10 21:50:24 -03:00
Pierre Sassoulas
7da04c963f [ruff] Add unwanted pylint message to the ignore list 2024-02-10 23:42:36 +01:00
Pierre Sassoulas
b922270ce7 [performance] Micro-optimization in '_traceback_filter'
Should be around 40% faster according to this simplified small benchmark:

python -m timeit "a=[0, 1, 2, 3, 4];b=list((e if i in {0, len(a) -1} else str(e)) for i, e in enumerate(a))"
200000 loops, best of 5: 1.12 usec per loop
python -m timeit "a=[0, 1, 2, 3, 4];b=list((a[0], *(str(e) for e in a[1:-1]), a[-1]))"
500000 loops, best of 5: 651 nsec per loop

python -m timeit "a=[0, 1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16];b=list((e if i in {0, len(a) -1} else str(e)) for i, e in enumerate(a))"
100000 loops, best of 5: 3.31 usec per loop
python -m timeit "a=[0, 1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16];b=list((a[0], *(str(e) for e in a[1:-1]), a[-1]))"
200000 loops, best of 5: 1.72 usec per loop
2024-02-10 20:23:48 +01:00
Pierre Sassoulas
1180348303 [ruff] Add 'consider-using-in' from pylint
See https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/consider-using-in.html
An automated fix from ruff is available (but it's unsafe for now).
2024-02-10 15:47:44 +01:00
Florian Bruhin
7690a0ddf1 Improve error message when using @pytest.fixture twice (#11670)
* Improve error message when using @pytest.fixture twice

While obvious in hindsight, this error message confused me. I thought my fixture
function was used in a test function twice, since the wording is ambiguous.

Also, the error does not tell me *which* function is the culprit.

Finally, this adds a test, which wasn't done in
cfd16d0dac where this was originally implemented.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-02-09 14:59:04 +01:00
Ran Benita
29a5f94428 Merge pull request #11956 from bluetech/ruff-warning
Fix ruff deprecation warning + enable few more rules
2024-02-09 15:32:11 +02:00
Ran Benita
ea57c40c43 main: fix reversed collection order in Session
Since we're working with a stack (last in first out), we need to append
to it in reverse to preserve the order when popped.

Fix #11937.
2024-02-09 15:24:44 +02:00
Ran Benita
a182e10b06 Enable lint PGH004 - Use specific rule codes when using noqa 2024-02-09 11:14:36 +02:00
Ran Benita
d1ee6d154f Enable flake8-pie 2024-02-09 11:08:33 +02:00
Ran Benita
d02618d173 Fix ruff deprecation warning
warning: The top-level linter settings are deprecated in favour of their counterparts in the `lint` section. Please update the following options in `pyproject.toml`:
  - 'ignore' -> 'lint.ignore'
  - 'select' -> 'lint.select'
2024-02-09 10:48:05 +02:00
whysage
9454fc38d3 closes: 10865 Fix muted exception (#11804)
* feat: 10865

* feat: 10865 refactor code and tests

* feat: 10865 add test skip for pypy

* feat: 10865 add test with valid warning

* feat: 10865 fix v2 for codecov

* feat: 10865 fix conflict
2024-02-07 16:47:56 -08:00
Ran Benita
101328aba5 Merge pull request #11947 from bluetech/hypothesis-revert
Revert "testing: temporarily disable test due to hypothesis issue (#1836)"
2024-02-07 22:44:58 +02:00
Ran Benita
42785cca44 Revert "testing: temporarily disable test due to hypothesis issue (#11836)"
This reverts commit 5cd0535395.
2024-02-07 22:13:23 +02:00
Ran Benita
6c0b6c2f92 Merge pull request #11941 from bluetech/doctest-parsefactories
doctest: fix autouse fixtures possibly not getting picked up
2024-02-07 22:09:17 +02:00
Ran Benita
9cd14b4ffb doctest: fix autouse fixtures possibly not getting picked up
Fix #11929.

Figured out what's going on. We have the following collection tree:

```
<Dir pyspacewar>
  <Dir src>
    <Package pyspacewar>
      <Package tests>
        <DoctestModule test_main.py>
          <DoctestItem pyspacewar.tests.test_main.doctest_main>
```

And the `test_main.py` contains an autouse fixture (`fake_game_ui`) that
`doctest_main` needs in order to run properly. The fixture doesn't run!
It doesn't run because nothing collects the fixtures from (calls
`parsefactories()` on) the `test_main.py` `DoctestModule`.

How come it only started happening with commit
ab63ebb3dc07b89670b96ae97044f48406c44fa0? Turns out it mostly only
worked accidentally. Each `DoctestModule` is also collected as a normal
`Module`, with the `Module` collected after the `DoctestModule`. For
example, if we add a non-doctest test to `test_main.py`, the collection
tree looks like this:

```
<Dir pyspacewar>
  <Dir src>
    <Package pyspacewar>
      <Package tests>
        <DoctestModule test_main.py>
          <DoctestItem pyspacewar.tests.test_main.doctest_main>
        <Module test_main.py>
          <Function test_it>
```

Now, `Module` *does* collect fixtures. When autouse fixtures are
collected, they are added to the `_nodeid_autousenames` dict.

Before ab63ebb3dc, `DoctestItem` consults
`_nodeid_autousenames` at *setup* time. At this point, the `Module` has
collected and so it ended up picking the autouse fixture (this relies on
another "accident", that the `DoctestModule` and `Module` have the same
node ID).

After ab63ebb3dc, `DoctestItem` consults
`_nodeid_autousenames` at *collection* time (= when it's created). At
this point, the `Module` hasn't collected yet, so the autouse fixture is
not picked out.

The fix is simple -- have `DoctestModule.collect()` call
`parsefactories`. From some testing I've done it shouldn't have negative
consequences (I hope).
2024-02-07 21:53:51 +02:00
dependabot[bot]
4c894f20a1 build(deps): Bump django in /testing/plugins_integration (#11946)
Bumps [django](https://github.com/django/django) from 5.0 to 5.0.2.
- [Commits](https://github.com/django/django/compare/5.0...5.0.2)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-07 15:37:56 -03:00
Ran Benita
6e5008f19f doctest: don't open code the module import
Currently, `DoctestModule` does `import_path` on its own. This changes
it to use `importtestmodule` as `Module` does. The behavioral changes
are:

- Much better error messages on import errors.

- Handles a few more error cases (see `importtestmodule`). This
  technically expands the cover of `--doctest-ignore-import-errors` but
  I think it makes sense.

- Considers `pytest_plugins` in the module.

- Populates `self.obj` as properly (without double-imports) as is
  expected from a `PyCollector`.

This is also needed for the next commit.
2024-02-06 23:46:23 +02:00
Pierre Sassoulas
b9d02c5b53 Merge pull request #11932 Add pre-commit hook and fix pyproject.toml
- [pyproject-fmt] Add pre-commit hook and autofix existing
- Proper setuptools version for pyproject.toml
2024-02-06 15:14:07 +01:00
Pierre Sassoulas
d1095426c1 Update setuptools version to the one that support pyproject.toml 2024-02-06 14:40:31 +01:00
Pierre Sassoulas
757778f5f6 [pyproject-fmt] Add pre-commit hook and autofix existing 2024-02-06 14:40:31 +01:00
Pierre Sassoulas
404d31a942 Merge pull request #11930 from Pierre-Sassoulas/setup.cfg-to-pyproject.toml
Migration from ``setup.cfg`` to ``pyproject.toml``
2024-02-05 22:40:44 +01:00
Pierre Sassoulas
0d91539614 Merge pull request #11935 from pytest-dev/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2024-02-05 21:46:11 +01:00
pre-commit-ci[bot]
835e8032f4 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.1.15 → v0.2.0](https://github.com/astral-sh/ruff-pre-commit/compare/v0.1.15...v0.2.0)
2024-02-05 20:29:38 +00:00
Pierre Sassoulas
c76ea72331 [pyproject.toml] Moving 'package_data' (py.typed) from setup.cfg 2024-02-05 21:04:33 +01:00
Pierre Sassoulas
dab1583ce1 [pyproject.toml] Remove setup_requires / package_dir in setup.cfg already exists 2024-02-05 21:04:12 +01:00
Pierre Sassoulas
411c2cbf9d [pyproject.toml] Translate dynamic option to pyproject.toml 2024-02-05 21:03:28 +01:00
Pierre Sassoulas
c3583dee0b [pyproject.toml] Translate 'metadata:platforms' to pyproject.toml 2024-02-05 21:03:26 +01:00
Pierre Sassoulas
a1d99e4bdd [pyproject.toml] Move information from setup.cfg to pyproject.toml 2024-02-05 21:02:32 +01:00
Ran Benita
aaa9ca7327 Merge pull request #11918 from pytest-dev/update-plugin-list/patch-20b18f0f9
[automated] Update plugin list
2024-02-05 13:49:09 +02:00
Ran Benita
29094983d7 Merge pull request #11923 from pytest-dev/dependabot/pip/testing/plugins_integration/pytest-django-4.8.0
build(deps): Bump pytest-django from 4.7.0 to 4.8.0 in /testing/plugins_integration
2024-02-05 13:32:11 +02:00
Ran Benita
b8e56557c6 Merge pull request #11925 from pytest-dev/dependabot/pip/testing/plugins_integration/pytest-sugar-1.0.0
build(deps): Bump pytest-sugar from 0.9.7 to 1.0.0 in /testing/plugins_integration
2024-02-05 13:31:50 +02:00
Ran Benita
304ccb4ad7 Merge pull request #11928 from bluetech/setup-cfg-cleanups
Some setup.cfg cleanups
2024-02-05 13:29:49 +02:00
Ran Benita
90634a6060 setup.cfg: remove zip_safe
The setuptools docs say it's obsolete and no longer needed:
https://setuptools.pypa.io/en/latest/deprecated/zip_safe.html#understanding-the-zip-safe-flag
2024-02-05 12:21:37 +02:00
Ran Benita
ccbae95ad4 setup.cfg: remove redundant packages/py_modules
The `package_dir` already achieves this.
2024-02-05 12:16:52 +02:00
Ran Benita
cd9b241047 setup.cfg: remove [devpi:upload] section
Not needed since bfe2cbe875.
2024-02-05 12:08:21 +02:00
Ran Benita
5c67cb2cf5 setup.cfg: remove [check-manifest] section
Not used since 731c35fcab.
2024-02-05 11:59:48 +02:00
Ran Benita
2fc7926bae setup.cfg: remove [build_sphinx] section
Legacy thing that is no longer needed.
2024-02-05 11:59:32 +02:00
Ran Benita
79de84941a setup.cfg: move mypy configuration from setup.cfg to pyproject.toml
TOML is a nicer format than the INI format setup.cfg uses.
2024-02-05 11:59:27 +02:00
Pierre Sassoulas
0d1f4c63fa Merge pull request #11914 - Activate flake8-bugbear and flake8-pyi 2024-02-05 09:37:37 +01:00
dependabot[bot]
2d4e27daf2 build(deps): Bump pytest-sugar in /testing/plugins_integration
Bumps [pytest-sugar](https://github.com/Teemu/pytest-sugar) from 0.9.7 to 1.0.0.
- [Release notes](https://github.com/Teemu/pytest-sugar/releases)
- [Changelog](https://github.com/Teemu/pytest-sugar/blob/main/CHANGES.rst)
- [Commits](https://github.com/Teemu/pytest-sugar/compare/v0.9.7...v1.0.0)

---
updated-dependencies:
- dependency-name: pytest-sugar
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-05 03:39:30 +00:00
dependabot[bot]
2e50788b6d build(deps): Bump pytest-django in /testing/plugins_integration
Bumps [pytest-django](https://github.com/pytest-dev/pytest-django) from 4.7.0 to 4.8.0.
- [Release notes](https://github.com/pytest-dev/pytest-django/releases)
- [Changelog](https://github.com/pytest-dev/pytest-django/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-django/compare/v4.7.0...v4.8.0)

---
updated-dependencies:
- dependency-name: pytest-django
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-05 03:39:23 +00:00
Pierre Sassoulas
3101c026b9 [flake8-bugbear] Remove hidden global state to import only once 2024-02-04 23:08:38 +01:00
Pierre Sassoulas
e193a263c7 [flake8-pyi] Add checks for flake8-pyi and fix existing 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
4eb246d4e1 [flake8-bugbear] noqa B023 not bound by design 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
41ff3584d7 [flake8-bugbear] Fixes a B017 we can actually fix and noqa the two others 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
b62d4b3527 [flake8-bugbear] Remove misleading multiple characters in lstrip
See https://pylint.readthedocs.io/en/stable/user_guide/messages/error/bad-str-strip-call.html
2024-02-04 19:27:23 +01:00
Pierre Sassoulas
e7bab63537 [flake8-bugbear] noqa all the useless comparison that are justified 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
52fba25ff9 [flake8-bugbear] Fix all the useless expressions that are justified 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
fcb818b73c [flake8-bugbear] Re-raise all exceptions with proper exception chaining 2024-02-04 19:27:23 +01:00
Pierre Sassoulas
7eef4619d5 [flake8-bugbear] Add checks from flake8 bugbear 2024-02-04 19:27:16 +01:00
Ran Benita
e28f35c296 Merge pull request #11915 from bluetech/compat-string-types
compat: a couple of minor cleanups
2024-02-04 16:51:43 +02:00
pytest bot
b28bb01c4e [automated] Update plugin list 2024-02-04 00:19:52 +00:00
Ran Benita
3ba4095400 compat: inline helpers into ascii_escaped
The helpers don't add much.
2024-02-03 18:42:05 +02:00
Ran Benita
99e8129ba3 compat: get rid of STRING_TYPES
I think it only obfuscates the code, also calling `bytes` a string type
is pretty misleading in Python 3.
2024-02-03 18:38:38 +02:00
Ran Benita
20b18f0f9a Merge pull request #11913 from bluetech/ruff-version-ignore
Ignore isort on _version.py
2024-02-02 21:55:40 +02:00
Ran Benita
cb5f738858 Ignore isort on _version.py
The file is generated. This makes `ruff src/` run cleanly (when not
running through pre-commit).
2024-02-02 21:29:30 +02:00
Pierre Sassoulas
5be64c31cb Merge pull request #11912 from Pierre-Sassoulas/activate-ruff-checks
[pre-commit] Activate ruff checks and fix existing issues
2024-02-02 20:22:18 +01:00
Pierre Sassoulas
233ab89f13 [ruff] Fix all consider [*cats, garfield] instead of cats + [garfield] 2024-02-02 15:18:38 +01:00
Pierre Sassoulas
8967c527ff [ruff] Activate use next(iter(x)) instead of list(x)[0] and fix issue 2024-02-02 15:18:38 +01:00
Pierre Sassoulas
180a16a344 [ruff] Fix ambiguous characters found in string and comment 2024-02-02 15:18:38 +01:00
Pierre Sassoulas
514376fe29 [ruff] Add ruff's check and autofix existing issues 2024-02-02 15:18:38 +01:00
Pierre Sassoulas
bdfc5c80d8 Merge pull request #11901 from Pierre-Sassoulas/migrate-from-isort-to-ruff
Migrate from ``autoflake``, ``black``, ``isort``, ``pyupgrade``, ``flake8`` and ``pydocstyle``, to ``ruff``
2024-02-02 09:42:07 +01:00
Pierre Sassoulas
9ef905e7a0 [.git-blame-ignore-revs] Add migration to ruff/ruff format and blacken-docs 2024's style 2024-02-02 09:28:09 +01:00
Pierre Sassoulas
4588653b24 Migrate from autoflake, black, isort, pyupgrade, flake8 and pydocstyle, to ruff
ruff is faster and handle everything we had prior.

isort configuration done based on the indication from
https://github.com/astral-sh/ruff/issues/4670, previousely based on
reorder-python-import (#11896)

flake8-docstrings was a wrapper around pydocstyle (now archived) that
explicitly asks to use ruff in https://github.com/PyCQA/pydocstyle/pull/658.

flake8-typing-import is useful mainly for project that support python 3.7
and the one useful check will be implemented in https://github.com/astral-sh/ruff/issues/2302

We need to keep blacken-doc because ruff does not handle detection
of python code inside .md and .rst. The direct link to the repo is
now used to avoid a redirection.

Manual fixes:
- Lines that became too long
- % formatting that was not done automatically
- type: ignore that were moved around
- noqa of hard to fix issues (UP031 generally)
- fmt: off and fmt: on that is not really identical
  between black and ruff
- autofix re-order in pre-commit from faster to slower

Co-authored-by: Ran Benita <ran@unusedvar.com>
2024-02-02 09:27:00 +01:00
Pierre Sassoulas
046f64751b Fix a duplicate assignment in test_config.py
Taken from https://github.com/pytest-dev/pytest/pull/11885 that was closed.
2024-01-31 13:59:25 +01:00
Pierre Sassoulas
4546d5445a Upgrade blacken-doc to black's 2024 style (#11899) 2024-01-31 13:53:21 +01:00
Bruno Oliveira
de161f8791 Merge pull request #11896 from nicoddemus/isort
Replace reorder-python-imports by isort due to black incompatibility
2024-01-31 08:04:39 -03:00
Bruno Oliveira
3be2a9d655 Update and rename .gitblameignore to .git-blame-ignore-revs
Seems like `.git-blame-ignore-revs` is the standard used and also automatically detected by GitHub:

https://github.blog/changelog/2022-03-24-ignore-commits-in-the-blame-view-beta/
2024-01-31 07:50:49 -03:00
John Litborn
e885013c6b fix incorrect example for group_contains (#11892) 2024-01-30 12:00:38 -08:00
Bruno Oliveira
8b54596639 Run pre-commit on all files
Running pre-commit on all files after replacing reorder-python-imports by isort.
2024-01-30 16:35:46 -03:00
Bruno Oliveira
899a6cf2ce Replace reorder-python-imports by isort due to black incompatibility
Unfortunately black and reorder-python-imports are no longer compatible, and from the looks of it probably will not be compatible anytime soon:

https://github.com/asottile/reorder-python-imports/issues/367
https://github.com/asottile/reorder-python-imports/issues/366
https://github.com/psf/black/issues/4175

This replaces `reorder-python-imports` by `isort` configured in a way to yield roughtly the same results.

Closes #11885
2024-01-30 16:35:45 -03:00
Clément Robert
407d984142 Fix an edge case where ExceptionInfo._stringify_exception could crash pytest.raises (#11879)
Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
Co-authored-by: Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
2024-01-30 17:20:30 +02:00
Bruno Oliveira
21bec6cfbe Add changelog entry about FixtureManager.getfixtureclosure changing (#11887)
As discussed in #11868.
2024-01-30 09:41:18 -03:00
Bruno Oliveira
cb57bf50b1 Pin back pytest-asyncio to 8.0.0 compatible release (#11889)
The current version (0.23.4) explicitly does not support pytest 8 yet, so we fallback to the previous release in the hope that at least our integration tests pass.
2024-01-30 06:58:22 -03:00
dependabot[bot]
c0dfc45186 build(deps): Bump hynek/build-and-inspect-python-package (#11877)
Bumps [hynek/build-and-inspect-python-package](https://github.com/hynek/build-and-inspect-python-package) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/hynek/build-and-inspect-python-package/releases)
- [Changelog](https://github.com/hynek/build-and-inspect-python-package/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hynek/build-and-inspect-python-package/compare/v2.0.0...v2.0.1)

---
updated-dependencies:
- dependency-name: hynek/build-and-inspect-python-package
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-29 10:42:51 -03:00
dependabot[bot]
5855f65d0f build(deps): Bump pytest-asyncio in /testing/plugins_integration (#11878)
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.23.3 to 0.23.4.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.23.3...v0.23.4)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-29 10:42:27 -03:00
Russell Martin
14d3707818 Catch OSError from getpass.getuser() (#11875)
- Previously, `getpass.getuser()` would leak an ImportError if the
  USERNAME environment variable was not set on Windows because the `pwd`
  module cannot be imported.
- Starting in Python 3.13.0a3, it only raises `OSError`.

Fixes #11874
2024-01-28 23:07:18 -03:00
github-actions[bot]
8853a57532 [automated] Update plugin list (#11867)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-01-28 13:28:28 +00:00
Bruno Oliveira
878af85aef mypy: disallow untyped defs by default (#11862)
Change our mypy configuration to disallow untyped defs by default, which ensures *new* files added to the code base are fully typed.

To avoid having to type-annotate everything now, add `# mypy: allow-untyped-defs` to files which are not fully type annotated yet.

As we fully type annotate those modules, we can then just remove that directive from the top.
2024-01-28 10:12:42 -03:00
Ran Benita
e7b43b2121 Merge pull request #11859 from bluetech/numbered-dir-scandir
pathlib: speed up `make_numbered_dir` given a large tmp root
2024-01-28 00:05:39 +02:00
Ran Benita
d0f427aec4 Merge pull request #11865 from bluetech/cherry-pick-release
Cherry pick 8.0.0 release notes
2024-01-28 00:03:06 +02:00
Ran Benita
c6da0d20d2 Merge pull request #11864 from bluetech/release-8.0.0
Prepare release version 8.0.0

(cherry picked from commit 24c681d4ee)
2024-01-28 00:00:15 +02:00
Dương Quốc Khánh
a164ed6400 logging: avoid rounding microsecond to 1_000_000 (#11861)
Rounding microsecond might cause it to reach `1_000_000`, which raises a TypeError.
2024-01-27 10:40:31 -03:00
Ran Benita
eb9013d42c pathlib: speed up make_numbered_dir given a large tmp root
The function currently uses `find_suffixes` which iterates the entire
directory searching for files with the given suffix. In some cases
though, like in pytest's selftest, the directory can get big:

    $ ls /tmp/pytest-of-ran/pytest-0/
    7686

and iterating it many times can get slow.

This doesn't fix the underlying issue (iterating the directory) but at
least speeds it up a bit by using `os.scandir` instead of
`path.iterdir`. So `make_numbered_dir` is still slow for pytest's
selftests, but reduces ~10s for me.
2024-01-25 19:19:02 +02:00
Ran Benita
ac2cd72e5f Merge pull request #11856 from bluetech/pluggy-unblock
config: use `pluginmanager.unblock` instead of accessing pluggy's internals
2024-01-25 10:42:13 +02:00
Ran Benita
bca4bb0738 config: use pluginmanager.unblock instead of accessing pluggy's internals
The function was added in pluggy 1.4.0.
2024-01-25 10:20:44 +02:00
Ran Benita
2a77f8d88b Merge pull request #11854 from bluetech/runner-inline-2
runner: inline `call_runtest_hook`
2024-01-24 10:36:28 +02:00
Ran Benita
d972957303 hookspec: document conftest behavior for all hooks (#9496)
Have each hook explain how implementing it in conftests works. This is part of the functional specification of a hook.
2024-01-23 16:08:16 +02:00
Joachim B Haga
44bf7a2ec0 Mark some xfails from #10042 as non-strict (#11832)
Related to #10042, some tests in `test_debugging.py` are actually flaky and should not be considered strict xfailures.
2024-01-22 18:29:14 -03:00
Ran Benita
5ab8972bb5 runner: inline call_runtest_hook
- Reduce the common stacktrace by an entry - this is mostly for benefit
  of devs looking at crash logs.

- Reduce 6 slow `ihook` calls per test to 3.
2024-01-22 16:26:55 +02:00
github-actions[bot]
21440521fa [automated] Update plugin list (#11848)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-01-22 10:14:58 -03:00
dependabot[bot]
79ae968131 build(deps): Bump actions/cache from 3 to 4 (#11852)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-22 10:11:09 -03:00
Ran Benita
c3fc717ff7 Merge pull request #11843 from bluetech/writing-plugins
doc/writing_plugins: correct inaccuracies re. initial conftest loading
2024-01-19 14:30:20 +02:00
clee2000
d71ef04f11 Escape skip reason in junitxml (#11842)
Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
2024-01-18 22:08:26 -03:00
Ran Benita
111ad26f71 doc/writing_plugins: correct inaccuracies re. initial conftest loading 2024-01-18 22:17:55 +02:00
Ran Benita
2178ee86d7 Merge pull request #11826 from bluetech/no-cwd
Prefer using the invocation dir over CWD
2024-01-18 19:02:37 +02:00
Ran Benita
a6dd90a414 python: use invocation dir instead of cwd in fixture-printing code
We should aim to remove all `cwd()` calls except one, otherwise things
will go bad if the working directory changes. Use the invocation dir
instead.
2024-01-18 12:35:32 +02:00
Ran Benita
676f38d04a findpaths: rely on invocation_dir instead of cwd
We should aim to remove all `cwd()` calls except one, otherwise things
will go bad if the working directory changes. Use the invocation dir
instead.
2024-01-18 12:35:32 +02:00
Ran Benita
212c55218b helpconfig: add invocation dir to debug output
The current WD is not supposed to matter, the invocation dir is what
should be relevant. But keep them both for debugging.
2024-01-18 12:35:32 +02:00
Ran Benita
34fafe4c6b config: avoid Path.cwd() call in _set_initial_conftests
We should aim to remove all `cwd()` calls except one, otherwise things
will go bad if the working directory changes. Use the invocation dir
instead.
2024-01-18 12:35:32 +02:00
faph
eefc9d47fc [DOCS] Clarify tmp_path directory location and retention (#11830)
Fixes #11789 and #11790
2024-01-18 07:21:49 -03:00
Bruno Oliveira
7fd561e4ba Properly attach packages to the GH release notes (#11839)
Follow up to https://github.com/pytest-dev/pytest/pull/11754, noticed that the latest GitHub release does not contain the attached files.

Output log from the action:

```
🤔 Pattern 'dist/*' does not match any files.
```
2024-01-17 22:11:10 +00:00
Ran Benita
da9749cd97 Merge pull request #11838 from bluetech/cherry-pick-release
Prepare release version 8.0.0rc2
2024-01-17 23:53:41 +02:00
Ran Benita
ca5bbd0a9f Merge pull request #11835 from pytest-dev/release-8.0.0rc2
Prepare release version 8.0.0rc2

(cherry picked from commit 97960bdd14)
2024-01-17 23:45:21 +02:00
Ran Benita
5cd0535395 testing: temporarily disable test due to hypothesis issue (#11836)
Ref: https://github.com/pytest-dev/pytest/pull/11825#issuecomment-1894094641
2024-01-17 22:53:04 +02:00
Ran Benita
0f5aa5a7d2 Merge pull request #11825 from woutdenolf/fix_missing_fixture_issue
avoid using __file__ in pytest_plugin_registered as can be wrong on Windows
2024-01-17 15:29:29 +02:00
Ran Benita
9ea2e0a79f fixtures: avoid slow pm.get_name(plugin) call by using the new plugin_name hook parameter 2024-01-17 15:06:45 +02:00
Ran Benita
0f5ecd83c4 hookspecs: add plugin_name parameter to the pytest_plugin_registered hook
We have a use case for this in the next commit.

The name can be obtained by using `manager.get_name(plugin)`, however
this is currently O(num plugins) in pluggy, which would be good to
avoid. Besides, it seems generally useful.
2024-01-17 15:06:42 +02:00
Ran Benita
6b9bba2edb pre-commit: add pluggy to mypy deps
Otherwise mypy doesn't fully recognize pluggy's typing for some reason
or another.
2024-01-17 15:01:55 +02:00
woutdenolf
6e9f566d79 avoid using __file__ in pytest_plugin_registered as can be wrong on Windows 2024-01-17 15:01:04 +02:00
Ran Benita
a6708b9254 Merge pull request #11822 from bluetech/doc-hookspec
hookspec: minor doc tweaks
2024-01-16 18:34:33 +02:00
Florian Bruhin
e895c9d38c doc: Remove sold out training (#11823) 2024-01-16 14:53:10 +01:00
Ran Benita
c973ccb622 hookspec: modernize a reference 2024-01-15 23:47:19 +02:00
Ran Benita
dd1447cfe5 hookspec: move pytest_load_initial_conftests up
Reflect the order in which the plugins are called.
2024-01-15 23:46:07 +02:00
Ran Benita
9ad8b9fc36 hookspec: remove explicit :param types
Duplicates info in the type annotations which sphinx understands.
2024-01-15 23:35:53 +02:00
Florian Bruhin
348e6de102 doc: Update training dates and add pytest sprint (#11819) 2024-01-15 21:04:08 +01:00
Ran Benita
9af6d46371 Merge pull request #11817 from bluetech/conftesterror-cleanup
config: stop using exception triplets in `ConftestImportError`
2024-01-15 13:26:46 +02:00
Ran Benita
e1074f9c3d config: stop using exception triplets in ConftestImportError
In recent python versions all of the info is on the exception object
itself so no reason to deal with the annoying tuple.
2024-01-15 09:47:55 +02:00
Ran Benita
6e74601466 Merge pull request #11815 from bluetech/iter_parents-rename
nodes: rename `iterparents()` -> `iter_parents()`
2024-01-15 09:46:59 +02:00
Ronny Pfannschmidt
3acbdc2f79 Merge pull request #11814 from bluetech/pycache-ignore-collect
main,python: move `__pycache__` ignore to `pytest_ignore_collect`
2024-01-14 17:26:34 +01:00
Ran Benita
707642ad35 nodes: rename iterparents() -> iter_parents()
After the fact I remembered there is `node.iter_markers()` so let's be
consistent with that rather than with `listchain()`.
2024-01-14 15:17:41 +02:00
Ran Benita
2413d1b214 main,python: move __pycache__ ignore to pytest_ignore_collect
This removes one thing that directory collectors need to worry about.

This adds one hook dispatch per `__pycache__` file, but I think it's
worth it for consistency.
2024-01-14 15:05:15 +02:00
Ran Benita
2bb0eca347 Merge pull request #11795 from lesteve/improve-assert-mod-not-in-mods-error-message
Improve assert mod not in mods error message
2024-01-14 13:39:14 +02:00
Loïc Estève
1c9d6834fd Improve assert mod not in mods error message
[ran: tweaked message, made the formatting lazy]
2024-01-14 13:21:54 +02:00
github-actions[bot]
c6ed86453f [automated] Update plugin list (#11811)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-01-14 01:04:53 -03:00
Ran Benita
e403bbf1a9 Merge pull request #11708 from fcharras/FIX/crash_during_conftest_collection
FIX key formating divergence when inspecting plugin dictionary.
2024-01-13 21:45:36 +02:00
Franck Charras
a7c2549321 Fix assert mod not in mods crash
Fix #27806.

Co-authored-by: Loïc Estève <loic.esteve@ymail.com>
Co-authored-by: Ran Benita <ran@unusedvar.com>
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2024-01-13 20:19:28 +02:00
Ran Benita
d65bcd9a3b Merge pull request #11808 from bluetech/doctest-conftest
doctest: remove special conftest handling
2024-01-13 19:50:20 +02:00
Ran Benita
06dbd3c21c doctest: remove special conftest handling
(Diff better viewed ignoring whitespace)

Since e1c66ab0ad, conftest loading is
handled at the directory level before sub-nodes are collected, so there
is no need for the doctest plugin to handle it specially.

This was probably the case even before
e1c66ab0ad, but I haven't verified this.
2024-01-13 11:18:41 +02:00
Ran Benita
1b78de4e21 Merge pull request #11803 from pytest-dev/package-scope-note
Add note about package scope
2024-01-12 22:15:33 +02:00
mrbean-bremen
82fda31e99 Clarify package scope
The behavior of package scope is surprising to some
(as seen by related questions on SO), this should clarify it a bit.
2024-01-12 20:03:30 +01:00
Ran Benita
5645fa45fb Merge pull request #11801 from bluetech/node-iterchain
nodes: add `Node.iterchain()` function
2024-01-12 11:01:48 +02:00
Ran Benita
5bd5b80afd nodes: add Node.iterparents() function
This is a useful addition to the existing `listchain`. While `listchain`
returns top-to-bottom, `iterparents` is bottom-to-top and doesn't require
an internal full iteration + `reverse`.
2024-01-11 23:19:45 +02:00
Ran Benita
bd58c09500 Merge pull request #11799 from bluetech/rm-nose-compat_co_firstlineno
python: remove support for nose's `compat_co_firstlineno`
2024-01-11 13:13:30 +02:00
Faisal Fawad
996e45d66a Slight change to tmp_path documentation to more clearly illustrate its behavior (#11800) 2024-01-11 11:01:07 +00:00
Ran Benita
c7d85c5dc6 python: remove support for nose's compat_co_firstlineno
Since we're removing nose support, let's also drop support for this
attribute.

From doing a code search on github, this seems completely unused outside
of nose, except for some projects which used to use it, but no longer
do.
2024-01-10 19:22:19 +02:00
Ronny Pfannschmidt
b1c430820f Merge pull request #11794 from bluetech/fixturedef-ref-cycle
A few cleanups
2024-01-10 06:44:14 +01:00
Ran Benita
35a3863b15 config: clarify a bit of code in _importconftest 2024-01-09 23:49:03 +02:00
Ran Benita
368fa2c03e fixtures: remove unhelpful FixtureManager.{FixtureLookupError,FixtureLookupErrorRepr}
Couldn't find any reason for this indirection, nor any plugins which
rely on it. Seems like historically it was done to avoid some imports...
2024-01-09 23:33:07 +02:00
Ran Benita
372c17e228 fixtures: avoid FixtureDef <-> FixtureManager reference cycle
There is no need to store the FixtureManager on each FixtureDef.
2024-01-09 23:29:58 +02:00
Ran Benita
c4a356eaee Merge pull request #11718 from pytest-dev/dependabot/github_actions/hynek/build-and-inspect-python-package-2.0.0
build(deps): Bump hynek/build-and-inspect-python-package from 1.5.4 to 2.0.0
2024-01-09 21:44:43 +02:00
dependabot[bot]
2270cab1c2 build(deps): Bump actions/download-artifact from 3 to 4
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-09 21:12:42 +02:00
dependabot[bot]
956d0e5e9d build(deps): Bump hynek/build-and-inspect-python-package
Bumps [hynek/build-and-inspect-python-package](https://github.com/hynek/build-and-inspect-python-package) from 1.5.4 to 2.0.0.
- [Release notes](https://github.com/hynek/build-and-inspect-python-package/releases)
- [Changelog](https://github.com/hynek/build-and-inspect-python-package/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hynek/build-and-inspect-python-package/compare/v1.5.4...v2.0.0)

---
updated-dependencies:
- dependency-name: hynek/build-and-inspect-python-package
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-09 21:12:27 +02:00
pre-commit-ci[bot]
7bc8385924 [pre-commit.ci] pre-commit autoupdate (#11792)
updates:
- [github.com/PyCQA/flake8: 6.1.0 → 7.0.0](https://github.com/PyCQA/flake8/compare/6.1.0...7.0.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-01-08 21:19:35 +00:00
Ran Benita
9b7e10a3c0 Merge pull request #11788 from pytest-dev/dependabot/pip/testing/plugins_integration/pytest-asyncio-0.23.3
build(deps): Bump pytest-asyncio from 0.23.2 to 0.23.3 in /testing/plugins_integration
2024-01-08 22:40:47 +02:00
dependabot[bot]
913d93debb build(deps): Bump pytest-asyncio in /testing/plugins_integration
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.23.2 to 0.23.3.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.23.2...v0.23.3)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-08 20:24:22 +00:00
Ran Benita
97dfc3429e Merge pull request #11785 from bluetech/matchfactories-nodes
fixtures: match fixtures based on actual node hierarchy, not textual nodeids
2024-01-08 22:23:08 +02:00
Ran Benita
992d0f082f fixtures: match fixtures based on actual node hierarchy, not textual nodeids
Refs #11662.

--- Problem

Each fixture definition has a "visibility", the `FixtureDef.baseid`
attribute. This is nodeid-like string. When a certain `node` requests a
certain fixture name, we match node's nodeid against the fixture
definitions with this name.

The matching currently happens on the *textual* representation of the
nodeid - we split `node.nodeid` to its "parent nodeids" and then check
if the fixture's `baseid` is in there.

While this has worked so far, we really should try to avoid textual
manipulation of nodeids as much as possible. It has also caused problem
in an odd case of a `Package` in the root directory: the `Package` gets
nodeid `.`, while a `Module` in it gets nodeid `test_module.py`. And
textually, `.` is not a parent of `test_module.py`.

--- Solution

Avoid this entirely by just checking the node hierarchy itself. This is
made possible by the fact that we now have proper `Directory` nodes
(`Dir` or `Package`) for the entire hierarchy.

Also do the same for `_getautousenames` which is a similar deal.

The `iterparentnodeids` function is no longer used and is removed.
2024-01-08 21:36:51 +02:00
Ran Benita
b968f63ca5 Merge pull request #11780 from bluetech/register-fixture
Add an internal "register fixture" API and use it replace object patching for fixture injection
2024-01-08 21:24:54 +02:00
Ran Benita
c8792bd080 python,unittest: replace obj fixture patching with FixtureManager._register_fixture
Instead of modifying user objects like modules and classes that we
really shouldn't be touching, use the new `_register_fixture` internal
API to do it directly.
2024-01-08 21:02:59 +02:00
Ran Benita
3234c79ee5 fixtures: add an internal API for registering a fixture
Add a function on the `FixtureManager` to register a fixture with
pytest. Currently this can only be done through `parsefactories`.

My aim is to eventually make something like this available to plugins,
as it's a pretty common need.
2024-01-08 21:02:59 +02:00
Ran Benita
851b72f289 Merge pull request #11776 from bluetech/unittest-xunit-inline
unittest: inline `_make_xunit_fixture`
2024-01-08 21:02:24 +02:00
Ran Benita
1d7349d18c Merge pull request #11774 from bluetech/fspath-cleanups
Small `fspath` cleanups
2024-01-08 21:01:56 +02:00
github-actions[bot]
5747a6c06e [automated] Update plugin list (#11784)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2024-01-07 10:20:38 -03:00
Fabian Sturm
13eacdad8a Add summary for xfails with -rxX option (#11574)
Co-authored-by: Brian Okken <1568356+okken@users.noreply.github.com>
2024-01-05 09:59:19 -03:00
Ran Benita
a616adf3ae unittest: inline _make_xunit_fixture
The indirection makes things harder to follow in this case IMO.
2024-01-05 14:37:03 +02:00
Ran Benita
685e52ec30 nodes: fix attribute name fspath -> path in get_fslocation_from_item 2024-01-04 22:32:34 +02:00
Ran Benita
7b4ab8134e fixtures: remove unnecessary fspath workaround 2024-01-04 22:32:34 +02:00
Ran Benita
c2a4a8d518 Merge pull request #11769 from neutrinoceros/fix_warns_docstring
Fix a mistake in pytest.warns' docstring (expect_warning accepts tuples, not any sequence)
2024-01-04 14:27:49 +02:00
Clément Robert
ac96256272 Fix a mistake in pytest.warns' docstring (expect_warning accepts tuples, not any sequence) 2024-01-04 11:51:12 +01:00
Bruno Oliveira
d38193646d Update docstring of scripts/generate-gh-release-notes.py (#11767)
Follow up to #11754.
2024-01-04 07:29:20 -03:00
Bruno Oliveira
cd07177906 Merge pull request #11754 from nicoddemus/release-notes
Improve GitHub release workflow
2024-01-03 20:14:48 -03:00
Bruno Oliveira
6321b74fae Enable type-checking in scripts/ 2024-01-03 19:47:56 -03:00
Bruno Oliveira
5aa289e478 Improve GitHub release workflow
This changes the existing script to just generate the release notes and delegate the actual publishing to the `softprops/action-gh-release@v1` action.

This allows us to delete the custom code, which failed recently in https://github.com/pytest-dev/pytest/actions/runs/7370258570/job/20056477756.
2024-01-03 19:47:56 -03:00
Ben Brown
12b9bd5801 Fix teardown error reporting when --maxfail=1 (#11721)
Co-authored-by: Ran Benita <ran@unusedvar.com>
2024-01-03 19:39:24 +02:00
Ran Benita
f017df443a Merge pull request #11757 from bluetech/rm-removed-in-8
Remove pytest 8 deprecations
2024-01-03 16:53:10 +02:00
Ran Benita
1ba07450e4 doc/deprecations: fix incorrect title level 2024-01-03 14:29:45 +02:00
Ran Benita
215f4d1fab Remove PytestRemovedIn8Warning
Per our deprecation policy.
2024-01-03 14:29:45 +02:00
Ran Benita
6c89f9261c Remove deprecated py.path (fspath) node constructor arguments 2024-01-03 14:29:45 +02:00
Ran Benita
a98f02d423 Remove deprecated py.path hook arguments 2024-01-03 14:29:42 +02:00
Marc Bresson
effc2b0529 Clarified markers ini property. Fix #11738 (#11739) 2024-01-03 14:20:54 +02:00
Ran Benita
2c5c97b6d1 Merge pull request #11760 from bluetech/fix-highlight-empty-source
terminalwriter: fix crash trying to highlight empty source
2024-01-03 09:38:29 +02:00
Ran Benita
cb5a42c836 terminalwriter: fix crash trying to highlight empty source
For quick checking I don't know how we can reach here with an empty
source, so test just checks the function directly.

Fix #11758.
2024-01-02 19:37:24 +02:00
Ran Benita
0f18a7fe5e Remove deprecated nose support 2024-01-02 12:20:47 +02:00
Ran Benita
0591569b4b Remove deprecated pytest.{exit,fail,skip}(msg=...) argument 2024-01-02 12:20:47 +02:00
Ran Benita
477959ef7d Remove deprecated pytest.Instance backward compat 2024-01-02 12:20:47 +02:00
Ran Benita
4147c92b21 Remove deprecated pytest.warns(None) 2024-01-02 12:20:47 +02:00
Ran Benita
10fbb2325f Remove deprecated Parser.addoption backward compatibilities 2024-01-02 12:20:47 +02:00
Ran Benita
1f8b39ed32 Remove deprecated --strict option 2024-01-02 12:20:47 +02:00
Ran Benita
f4e7b0d6e0 Remove deprecated pytest_cmdline_preparse hook 2024-01-02 12:20:47 +02:00
Ran Benita
f13724e2e3 Remove deprecated {FSCollector,Package}.{gethookproxy,isinitpath} 2024-01-02 12:20:47 +02:00
Ran Benita
a53984a55b Merge pull request #11756 from pytest-dev/cherry-pick-release
Cherry pick 8.0.0rc1 release notes
2024-01-02 11:20:03 +02:00
Ran Benita
d3c7ba310c Merge pull request #11744 from pytest-dev/release-8.0.0rc1
Prepare release 8.0.0rc1

(cherry picked from commit 665e4e58d3)
2024-01-02 10:59:26 +02:00
Ran Benita
6bec880283 Merge pull request #11753 from bluetech/cherry-pick-release
Cherry-pick 7.4.4 release notes
2023-12-31 14:26:50 +02:00
Ran Benita
a1b6b7473b Merge pull request #11752 from pytest-dev/release-7.4.4
Prepare release 7.4.4

(cherry picked from commit 18dcd9d38d)
2023-12-31 14:15:46 +02:00
Ran Benita
3701d1218b Merge pull request #11746 from pytest-dev/update-plugin-list/patch-acd445a3f
[automated] Update plugin list
2023-12-31 10:26:34 +02:00
Ran Benita
d220880924 nodes: fix tracebacks from collection errors are not getting pruned (#11711)
Fix #11710.
2023-12-31 10:14:23 +02:00
Ran Benita
640f84a5aa Merge pull request #11745 from bluetech/change-marked-fixture-removal
Change "Marks applied to fixtures" removal from 8 to 9
2023-12-31 10:10:20 +02:00
pytest bot
460c38915d [automated] Update plugin list 2023-12-31 00:20:30 +00:00
Ran Benita
a71a95b54c Change "Marks applied to fixtures" removal from 8 to 9
The deprecation has only been added in 8.0, so can't be removed in 8.
That will have to wait for 9.
2023-12-30 22:14:40 +02:00
Ran Benita
acd445a3f3 Merge pull request #11646 from bluetech/pkg-collect
Rework Session and Package collection
2023-12-30 12:51:48 +02:00
Ran Benita
c7ee55993b Merge pull request #11736 from pytest-dev/update-plugin-list/patch-52db918a2
[automated] Update plugin list
2023-12-30 12:49:17 +02:00
Ran Benita
b9855b244d Merge pull request #11737 from pytest-dev/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-12-30 12:35:31 +02:00
pre-commit-ci[bot]
1e5aab1b2b [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/psf/black: 23.12.0 → 23.12.1](https://github.com/psf/black/compare/23.12.0...23.12.1)
- [github.com/pre-commit/mirrors-mypy: v1.7.1 → v1.8.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.7.1...v1.8.0)
2023-12-25 20:43:18 +00:00
pytest bot
f93c0fc34e [automated] Update plugin list 2023-12-24 00:20:08 +00:00
Michał Górny
52db918a27 Fix handling empty values of NO_COLOR and FORCE_COLOR (#11712)
* Fix handling empty values of NO_COLOR and FORCE_COLOR

Fix handling NO_COLOR and FORCE_COLOR environment variables to correctly
be ignored when they are set to an empty value, as defined
in the specification:

> Command-line software which adds ANSI color to its output by default
> should check for a NO_COLOR environment variable that, when present
> *and not an empty string* (regardless of its value), prevents
> the addition of ANSI color.

(emphasis mine, https://no-color.org/)

The same is true of FORCE_COLOR, https://force-color.org/.

* Streamline testing for FORCE_COLOR and NO_COLOR

Streamline the tests for FORCE_COLOR and NO_COLOR variables, and cover
all possible cases (unset, set to empty, set to "1").  Combine the two
assert functions into one taking boolean parameters.  Mock file.isatty
in all circumstances to ensure that the environment variables take
precedence over the fallback value resulting from isatty check (or that
the fallback is actually used, in the case of both FORCE_COLOR
and NO_COLOR being unset).
2023-12-23 10:12:13 +02:00
Ran Benita
54a0ee02ea Merge pull request #11732 from bluetech/typing-tweaks
Some minor typing tweaks
2023-12-22 13:00:52 +02:00
Benjamin Schubert
88ae27da08 Add syntactic highlights to the error explanations (#11661)
* Put a 'reset' color in front of the highlighting

When doing the highlighting, some lexers will not set the initial color
explicitly, which may lead to the red from the errors being propagated
to the start of the expression

* Add syntactic highlighting to the error explanations

This updates the various error reporting to highlight python code when
displayed, to increase readability and make it easier to understand
2023-12-21 17:11:56 +00:00
Ran Benita
e06a3d02f8 Merge pull request #11715 from pytest-dev/update-plugin-list/patch-047ba83da
[automated] Update plugin list
2023-12-21 17:16:29 +02:00
Ran Benita
75f292d9df Some minor typing tweaks 2023-12-19 23:29:27 +02:00
pre-commit-ci[bot]
581762fcba [pre-commit.ci] pre-commit autoupdate (#11722)
updates:
- [github.com/psf/black: 23.11.0 → 23.12.0](https://github.com/psf/black/compare/23.11.0...23.12.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-12-18 21:43:27 +00:00
Benjamin Schubert
803b190a17 Merge pull request #11660 from BenjaminSchubert/bschubert/simplify-pprint
Remove more unused pprint features
2023-12-18 09:04:35 +00:00
Benjamin Schubert
283a746dad pprint: Remove conversion to int, we only accept those 2023-12-18 08:35:57 +00:00
Benjamin Schubert
64b5b665cf pprint: Remove the option to add underscore for numbers
This is never used, we can remove this. If we wanted instead, we could
always enable it
2023-12-18 08:35:57 +00:00
Benjamin Schubert
6aa35f772f pprint: Remove the option to sort dictionaries, we always do it 2023-12-18 08:35:57 +00:00
Benjamin Schubert
03b24e5b30 pprint: Remove the format method, it's not used outside of pprint
Let's reduce the API surface for the bundled PrettyPrinter to what we
really need and use
2023-12-18 08:35:57 +00:00
dependabot[bot]
7541c5a999 build(deps): Bump anyio[curio,trio] in /testing/plugins_integration (#11717)
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 4.1.0 to 4.2.0.
- [Release notes](https://github.com/agronholm/anyio/releases)
- [Changelog](https://github.com/agronholm/anyio/blob/master/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/4.1.0...4.2.0)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-18 06:33:59 +01:00
pytest bot
27f7cee238 [automated] Update plugin list 2023-12-17 00:20:43 +00:00
Arthur Richard
047ba83dab Improve pytest.exit docs (#11698)
Fixes #11695
2023-12-14 08:14:36 -03:00
Tom Mortimer-Jones
2b86d2bddc Typo in fixtures.rst (#11699) 2023-12-13 13:24:43 +01:00
dependabot[bot]
dfc910ee90 build(deps): Bump django from 4.2.7 to 5.0 in /testing/plugins_integration (#11692)
* build(deps): Bump django in /testing/plugins_integration

Bumps [django](https://github.com/django/django) from 4.2.7 to 5.0.
- [Commits](https://github.com/django/django/compare/4.2.7...5.0)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump python version on the plugin job

https://github.com/pytest-dev/pytest/pull/11692#issuecomment-1849963332

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
2023-12-11 14:18:43 +00:00
dependabot[bot]
ab307b3402 build(deps): Bump actions/setup-python from 4 to 5 (#11690)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 09:46:13 +01:00
dependabot[bot]
8ce76c307e build(deps): Bump actions/stale from 8 to 9 (#11691)
Bumps [actions/stale](https://github.com/actions/stale) from 8 to 9.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v8...v9)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 09:28:50 +01:00
dependabot[bot]
ef8bf82a78 build(deps): Bump pytest-asyncio in /testing/plugins_integration (#11693)
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.23.1 to 0.23.2.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.23.1...v0.23.2)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 09:24:52 +01:00
Ran Benita
e1c66ab0ad Different fix for conftest loading
--- Current main

In current main (before pervious commit), calls to gethookproxy/ihook
are the trigger for loading non-initial conftests. This basically means
that conftest loading is done almost as a random side-effect,
uncontrolled and very non-obvious. And it also dashes any hope of making
gethookproxy faster (gethookproxy shows up prominently in pytest
profiles).

I've wanted to improve this for a while, #11268 was the latest step
towards that.

--- PR before change

In this PR, I ran into a problem.

Previously, Session and Package did all of the directory traversals
inside of their collect, which loaded the conftests as a side effect. If
the conftest loading failed, it will occur inside of the collect() and
cause it to be reported as a failure.

Now I've changed things such that Session.collect and Package.collect no
longer recurse, but just collect their immediate descendants, and
genitems does the recursive expansion work.

The problem though is that genitems() doesn't run inside of specific
collector's collect context. So when it loads a conftest, and the
conftest loading fails, the exception isn't handled by any CollectReport
and causes an internal error instead.

The way I've fixed this problem is by loading the conftests eagerly in a
pytest_collect_directory post-wrapper, but only during genitems to make
sure the directory is actually selected.

This solution in turn caused the conftests to be collected too early;
specifically, the plugins are loaded during the parent's collect(), one
after the other as the directory entries are collected. So when the
ihook is hoisted out of the loop, new plugins are loaded inside the
loop, and due to the way the hook proxy works, they are added to the
ihook even though they're supposed to be scoped to the child collectors.
So no hoisting.

--- PR after change

Now I've come up with a better solution: since now the collection tree
actually reflects the filesystem tree, what we really want is to load
the conftest of a directory right before we run its collect(). A
conftest can affect a directory's collect() (e.g. with a
pytest_ignore_collect hookimpl), but it cannot affect how the directory
node itself is collected. So I just moved the conftest loading to be
done right before calling collect, but still inside the CollectReport
context.

This allows the hoisting, and also removes conftest loading from
gethookproxy since it's no longer necessary. And it will probably enable
further cleanups. So I'm happy with it.
2023-12-10 17:01:39 +02:00
Ran Benita
385796ba49 Rework Session and Package collection
Fix #7777.
2023-12-10 17:01:39 +02:00
Ran Benita
f411c8d6d7 main: add with_parents parameter to isinitpath
Will be used in upcoming commit.
2023-12-10 16:32:54 +02:00
Ran Benita
c7fcb3f281 Merge pull request #11689 from pytest-dev/update-plugin-list/patch-d1675646f
[automated] Update plugin list
2023-12-10 09:59:06 +02:00
Ran Benita
c1339628d6 Merge pull request #11684 from bluetech/docs-nitpicky
docs: enable Sphinx nitpicky mode
2023-12-10 09:42:30 +02:00
Ran Benita
397769c45e Merge pull request #11677 from bluetech/nodes-abc
nodes,python: mark abstract node classes as ABCs
2023-12-10 09:41:46 +02:00
pytest bot
5381cd083f [automated] Update plugin list 2023-12-10 00:20:38 +00:00
Ran Benita
0ae02e2165 nodes,python: mark abstract node classes as ABCs
Fixes #11676
2023-12-07 16:41:07 +02:00
Ran Benita
2aa8743bbe doc: enable Sphinx nitpicky mode
See:
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-nitpicky

This ensures we have no more broken references.
2023-12-07 12:14:45 +02:00
Ran Benita
ee91d095f6 doc: fix more broken Sphinx references 2023-12-07 11:50:02 +02:00
Ran Benita
f76af423b0 doc/reference: document FixtureLookupError 2023-12-07 11:50:02 +02:00
Ran Benita
4918883336 python_api: remove unused function _non_numeric_type_error 2023-12-07 11:03:52 +02:00
Ran Benita
d1675646f2 Merge pull request #11678 from pytest-dev/doc-nitpicks
doc: fix some broken Sphinx references
2023-12-07 09:40:52 +02:00
Ran Benita
9056db4de5 doc: fix some broken Sphinx references 2023-12-07 00:30:35 +02:00
Ran Benita
a5ee9f2ecd doc: document pytest.{hookspec,hookimpl} in the API Reference
Makes sense for them to be there; also allows for Sphinx refs.
2023-12-07 00:11:42 +02:00
Benjamin Schubert
a536f49d91 Separate the various parts of the error report with newlines (#11659)
Previously the error report would have all sections glued together:

- The assertion representation
- The error explanation
- The full diff

This makes it hard to see at a glance where which one starts and ends.

One of the representation (dataclasses, tuples, attrs) does display a
newlines at the start already.

Let's add a newlines before the error explanation and before the full
diff, so we get an easier to read report.

This has one disadvantage: we get one line less in the least verbose
mode, where the output gets truncated.
2023-12-06 09:25:00 +00:00
Ran Benita
cd269f0e6d Merge pull request #11668 from bluetech/rm-setup-py
Remove `setup.py`
2023-12-05 17:29:43 +02:00
Ran Benita
b8118ab70d Remove setup.py
Fix #11667.
2023-12-04 22:45:59 +02:00
dependabot[bot]
022f1b4de5 build(deps): Bump pytest-bdd in /testing/plugins_integration (#11665)
Bumps [pytest-bdd](https://github.com/pytest-dev/pytest-bdd) from 7.0.0 to 7.0.1.
- [Release notes](https://github.com/pytest-dev/pytest-bdd/releases)
- [Changelog](https://github.com/pytest-dev/pytest-bdd/blob/master/CHANGES.rst)
- [Commits](https://github.com/pytest-dev/pytest-bdd/compare/7.0.0...7.0.1)

---
updated-dependencies:
- dependency-name: pytest-bdd
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-12-04 13:58:18 +00:00
dependabot[bot]
db8c6f1da8 build(deps): Bump pytest-asyncio in /testing/plugins_integration (#11664)
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.21.1 to 0.23.1.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.21.1...v0.23.1)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-04 10:41:34 -03:00
dependabot[bot]
3e14c4b3c4 build(deps): Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11 (#11663)
Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.10 to 1.8.11.
- [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases)
- [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.10...v1.8.11)

---
updated-dependencies:
- dependency-name: pypa/gh-action-pypi-publish
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-04 10:41:20 -03:00
github-actions[bot]
714ce2e872 [automated] Update plugin list (#11658)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-12-03 11:49:36 -03:00
touilleWoman
5689d806cf Fix "Customizing Colors" documentation section (#11652)
Fixes #11573
2023-12-01 11:25:01 -03:00
Ran Benita
0f6c17ca83 Merge pull request #11654 from pytest-dev/testing-unnecessary-skip
testing: remove a no longer necessary skip
2023-12-01 00:28:23 +02:00
Ran Benita
ef699f8c17 testing: remove a no longer necessary skip
pytest-xdist was released at 2019-02-15, seems enough time.
2023-11-30 19:53:31 +02:00
Ran Benita
81c06b3955 Merge pull request #11650 from bluetech/tr-test-isolation
testing: fix isolation issue in `tr` fixture
2023-11-28 20:14:20 +02:00
Ran Benita
968510b6aa testing: fix isolation issue in tr fixture
The default for `_prepareconfig` is to use `sys.argv`, which in this
case are the flags passed to (top-level) `pytest`. This is not the
intention, the tests themselves should not be affected by it.
2023-11-28 19:54:24 +02:00
Ran Benita
5782aab017 Merge pull request #11648 from bluetech/fix-locale-encoding
pytester: avoid EncodingWarning from `locale.getpreferredencoding`
2023-11-28 18:12:28 +02:00
Ran Benita
ad1bccdead pytester: avoid EncodingWarning from locale.getpreferredencoding
When running `tox -e py-lsof` I get a deluge of this warning:

```
src/pytest/.tox/py-lsof-numpy-pexpect/lib/python3.11/site-packages/_pytest/pytester.py:130: EncodingWarning: UTF-8 Mode affects locale.getpreferredencoding(). Consider locale.getencoding() instead.
```

Use `locale.getencoding` instead.
2023-11-28 17:40:58 +02:00
Benjamin Schubert
172bf89ad1 Merge pull request #11644 from BenjaminSchubert/bschubert/pprint-cleanup
Various cleanups of the vendored pprint module
2023-11-27 22:54:46 +00:00
Benjamin Schubert
88c3546006 pprint: use a set instead of a dict for the context
This is really what the context is doing, we don't need to use a dict
for it
2023-11-27 22:40:09 +00:00
Benjamin Schubert
50607297f4 pprint: Remove tracking of whether an object is readable
This information is not used anywhere
2023-11-27 22:40:09 +00:00
Benjamin Schubert
767f08cecd pprint: Remove tracking of whether the object is recursive
This information is not used anywhere, we can simplify by just not
tracking it
2023-11-27 22:40:09 +00:00
Benjamin Schubert
e5a448cd5f pprint: Type annotate the module
This will make it easier to refactor
2023-11-27 22:40:09 +00:00
Benjamin Schubert
64e72b79f6 pprint: Remove unused arguments on PrettyPrinter 2023-11-27 22:40:09 +00:00
pre-commit-ci[bot]
c4375f14b8 [pre-commit.ci] pre-commit autoupdate (#11645)
updates:
- [github.com/pre-commit/mirrors-mypy: v1.7.0 → v1.7.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.7.0...v1.7.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-11-27 20:55:06 +00:00
Benjamin Schubert
2d1710e0e9 Improve the full diff by having more consistent indentation in the PrettyPrinter (#11571)
The normal default pretty printer is not great when objects are nested
and it can get hard to read the diff.

Instead, provide a pretty printer that behaves more like when json get
indented, which allows for smaller, more meaningful differences, at
the expense of a slightly longer diff.

This does not touch the other places where the pretty printer is used,
and only updated the full diff one.
2023-11-27 16:47:18 +02:00
Ran Benita
fe8cda051b Merge pull request #11642 from pytest-dev/dependabot/pip/testing/plugins_integration/anyio-curiotrio--4.1.0
build(deps): Bump anyio[curio,trio] from 4.0.0 to 4.1.0 in /testing/plugins_integration
2023-11-27 10:22:45 +02:00
Ran Benita
df963fded7 Merge pull request #11641 from pytest-dev/dependabot/pip/testing/plugins_integration/pytest-rerunfailures-13.0
build(deps): Bump pytest-rerunfailures from 12.0 to 13.0 in /testing/plugins_integration
2023-11-27 10:20:09 +02:00
dependabot[bot]
6053bb8d6a build(deps): Bump anyio[curio,trio] in /testing/plugins_integration
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/agronholm/anyio/releases)
- [Changelog](https://github.com/agronholm/anyio/blob/master/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/4.0.0...4.1.0)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-27 03:05:25 +00:00
dependabot[bot]
03220f7c9e build(deps): Bump pytest-rerunfailures in /testing/plugins_integration
Bumps [pytest-rerunfailures](https://github.com/pytest-dev/pytest-rerunfailures) from 12.0 to 13.0.
- [Changelog](https://github.com/pytest-dev/pytest-rerunfailures/blob/master/CHANGES.rst)
- [Commits](https://github.com/pytest-dev/pytest-rerunfailures/compare/12.0...13.0)

---
updated-dependencies:
- dependency-name: pytest-rerunfailures
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-27 03:05:20 +00:00
Michał Górny
85e0f676c5 Reset color-related envvars for testing (#11638)
Reset color-related environment variables in a fixture to prevent them
from affecting test results.  Otherwise, some of the tests fail
e.g. if NO_COLOR is set in the calling environment.
2023-11-26 11:09:18 -03:00
github-actions[bot]
e0d5754d5d [automated] Update plugin list (#11640)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-11-26 11:09:03 -03:00
Jens Tröger
acab13fcc9 Add new filtering() method to LogCaptureFixture class (#11625)
Fixes #11610
2023-11-24 09:38:34 -03:00
Simon Blanchard
a42530a09d Fix for operation on closed file in faulthandler teardown (#11584) 2023-11-22 22:05:00 +02:00
Ran Benita
fdb8bbf154 Merge pull request #11626 from BenjaminSchubert/bschubert/vendored-pprint
Vendor in and absorb the pprint module from upstream
2023-11-20 18:13:34 +02:00
Benjamin Schubert
53d7b5ed3e Add some tests for the pprint module 2023-11-20 13:00:08 +00:00
Benjamin Schubert
19934b2b0c Merge the AlwaysDispathPrettyPrinter into the now vendored PrettyPrinter
We don't need to keep the separation anymore, and this will make it
easier to extend
2023-11-20 13:00:00 +00:00
Benjamin Schubert
2953120003 Fix typing information for the pprint module
There is more type information that could be added. We can add those
later to make it easier, this is jsut the minimum to allow linting to
pass
2023-11-20 13:00:00 +00:00
Benjamin Schubert
5fae5ef73e Apply project-wide formatting standard to the pprint module (black) 2023-11-20 13:00:00 +00:00
Benjamin Schubert
66f2f20eff Run pyupgrade on the pprint module 2023-11-20 13:00:00 +00:00
Benjamin Schubert
2322668344 Remove unneeded pprint interfaces
There are parts of the original pprint module that we won't need, let's
limit the surface and remove the unnecessary code
2023-11-20 13:00:00 +00:00
Benjamin Schubert
eb6ad08e5d Vendor in the pprint module to allow further modifications
We already have the AlwaysDispatchingPrettyPrinter override of the
default pretty printer. In order to make more in depth changes, we
need to copy the upstream version in, as it doesn't lend itself well to
being extended.

This does a verbatime copy, adding provenance information at the top.
2023-11-20 13:00:00 +00:00
Anthony Sottile
0916191827 use name-independent github actions badge (#11628)
if we were ever to change the `name:` field in `test.yml` this would suddenly break -- this references the workflow file directly (and is what github generates now for badges)
2023-11-19 13:19:30 -03:00
github-actions[bot]
476bab84f7 [automated] Update plugin list (#11627)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-11-19 11:57:25 -03:00
Patrick Lannigan
9dc1fc4523 Add verbosity_assertions and config.get_verbosity
Fixes #11387
2023-11-19 11:56:29 -03:00
Avasam
80442ae2f2 Use False, instead of None as default for _XfailMarkDecorator's condition param and update doc (#11600) 2023-11-17 10:42:05 +02:00
Miro Hrončok
223e030604 XFAIL TestLocalPath.test_make_numbered_dir_multiprocess_safe (#11611)
The tested py.path.local.make_numbered_dir function is *not*
multiprocess safe, because is uses os.listdir which itself is not.

The os.listdir documentation explicitly states that:

> If a file is removed from or added to the directory during the call
> of this function, whether a name for that file be included is unspecified.

This can lead to a race when:

 1. process A attempts to create directory N
 2. the creation fails, as another process already created it in the meantime
 3. process A calls listdir to determine a more recent maxnum
 4. processes B+ repeatedly create newer directories and they delete directory N
 5. process A doesn't have directory N or any newer directory in listdir result
 6. process A attempts to create directory N again and raises

For details, see https://github.com/pytest-dev/pytest/issues/11603#issuecomment-1805708144
and bellow.

Additionally, the test itself has a race in batch_make_numbered_dirs.
When this functions attempts to write to repro-N/foo,
repro-N may have already been removed by another process.

For details, see https://github.com/pytest-dev/pytest/issues/11603#issuecomment-1804714313
and bellow.

---

The tested py.path.local.make_numbered_dir function is not used in pytest.
There is a different implementation in _pytest.pathlib.

Closes #11603
2023-11-14 11:41:35 -03:00
Bruno Oliveira
1eca302c4d Merge pull request #11613 from pytest-dev/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2023-11-14 07:50:59 -03:00
Bruno Oliveira
970d11cf34 Explicitly export error and path from py
Required by mypy 1.7.0
2023-11-14 07:29:40 -03:00
pre-commit-ci[bot]
d4c56c72d8 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/psf/black: 23.10.1 → 23.11.0](https://github.com/psf/black/compare/23.10.1...23.11.0)
- [github.com/pre-commit/mirrors-mypy: v1.6.1 → v1.7.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.6.1...v1.7.0)
2023-11-13 21:00:52 +00:00
dependabot[bot]
442b09ed9f build(deps): Bump pytest-django in /testing/plugins_integration (#11609)
Bumps [pytest-django](https://github.com/pytest-dev/pytest-django) from 4.6.0 to 4.7.0.
- [Release notes](https://github.com/pytest-dev/pytest-django/releases)
- [Changelog](https://github.com/pytest-dev/pytest-django/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-django/compare/v4.6.0...v4.7.0)

---
updated-dependencies:
- dependency-name: pytest-django
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-13 09:29:21 +01:00
dependabot[bot]
9417aeb2d8 build(deps): Bump pytest-html in /testing/plugins_integration (#11608)
Bumps [pytest-html](https://github.com/pytest-dev/pytest-html) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/pytest-dev/pytest-html/releases)
- [Changelog](https://github.com/pytest-dev/pytest-html/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-html/compare/4.1.0...4.1.1)

---
updated-dependencies:
- dependency-name: pytest-html
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-13 09:28:54 +01:00
github-actions[bot]
99f7738810 [automated] Update plugin list (#11607)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-11-12 10:41:08 -03:00
Sharad Nair
7c7bdf4574 Sanitize ini-options default handling #11282 (#11594)
Fixes #11282
2023-11-11 13:08:18 -03:00
Ran Benita
6fe43912be Merge pull request #11591 from pytest-dev/dependabot/pip/testing/plugins_integration/twisted-23.10.0
build(deps): Bump twisted from 23.8.0 to 23.10.0 in /testing/plugins_integration
2023-11-08 09:29:18 +02:00
github-actions[bot]
e701df5eb6 [automated] Update plugin list (#11587)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-11-06 18:40:44 -03:00
dependabot[bot]
92cd7950e6 build(deps): Bump pytest-django in /testing/plugins_integration (#11592)
Bumps [pytest-django](https://github.com/pytest-dev/pytest-django) from 4.5.2 to 4.6.0.
- [Release notes](https://github.com/pytest-dev/pytest-django/releases)
- [Changelog](https://github.com/pytest-dev/pytest-django/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-django/compare/v4.5.2...v4.6.0)

---
updated-dependencies:
- dependency-name: pytest-django
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-06 09:26:10 +01:00
dependabot[bot]
ef2216c21b build(deps): Bump hynek/build-and-inspect-python-package (#11589)
Bumps [hynek/build-and-inspect-python-package](https://github.com/hynek/build-and-inspect-python-package) from 1.5.3 to 1.5.4.
- [Release notes](https://github.com/hynek/build-and-inspect-python-package/releases)
- [Changelog](https://github.com/hynek/build-and-inspect-python-package/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hynek/build-and-inspect-python-package/compare/v1.5.3...v1.5.4)

---
updated-dependencies:
- dependency-name: hynek/build-and-inspect-python-package
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-06 07:50:49 +01:00
dependabot[bot]
01a248d2a9 build(deps): Bump pytest-html in /testing/plugins_integration (#11590)
Bumps [pytest-html](https://github.com/pytest-dev/pytest-html) from 4.0.2 to 4.1.0.
- [Release notes](https://github.com/pytest-dev/pytest-html/releases)
- [Changelog](https://github.com/pytest-dev/pytest-html/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-html/compare/4.0.2...4.1.0)

---
updated-dependencies:
- dependency-name: pytest-html
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-06 07:49:53 +01:00
dependabot[bot]
1a7641cf88 build(deps): Bump twisted in /testing/plugins_integration
Bumps [twisted](https://github.com/twisted/twisted) from 23.8.0 to 23.10.0.
- [Release notes](https://github.com/twisted/twisted/releases)
- [Changelog](https://github.com/twisted/twisted/blob/trunk/NEWS.rst)
- [Commits](https://github.com/twisted/twisted/compare/twisted-23.8.0...twisted-23.10.0)

---
updated-dependencies:
- dependency-name: twisted
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-06 03:58:57 +00:00
Bruno Oliveira
70f03dbc3e Adjustments to assert raises docs (#11586)
Followup from #11578.
2023-11-04 12:37:47 -03:00
Bruno Oliveira
1e02797d15 Improve pytest.raises docs (#11578) 2023-11-04 10:24:57 +00:00
neilmartin2000
13e5ef0102 Created link to PEP-8 in documentation (#11582) 2023-11-03 15:05:05 -03:00
dependabot[bot]
1ea10c20df build(deps): Bump django in /testing/plugins_integration (#11579)
Bumps [django](https://github.com/django/django) from 4.2.6 to 4.2.7.
- [Commits](https://github.com/django/django/compare/4.2.6...4.2.7)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-03 08:27:47 -03:00
Ran Benita
8fb7e8b31e Merge pull request #11567 from bluetech/fix-ref-tocdepth
doc/reference: fix sidebar TOC depth
2023-10-30 09:01:54 +02:00
Ran Benita
0d74a1c8a0 doc: allow Sphinx 6.x and 7.x (#11568)
They seem to work fine, let's allow them.
2023-10-29 23:00:27 +01:00
Ran Benita
730c7ca0b1 Merge pull request #11566 from pytest-dev/update-plugin-list/patch-738ae2da9
[automated] Update plugin list
2023-10-29 22:48:26 +02:00
Ran Benita
4ecf313604 doc/reference: fix sidebar TOC depth
Previously, the sidebar TOC had unlimited depth, making it useless and
interfering with the content. This seems to have regressed in pytest
7.2.x going by the RTD version selector.
2023-10-29 21:55:17 +02:00
pytest bot
d0a09d8627 [automated] Update plugin list 2023-10-29 00:19:06 +00:00
Zac Hatfield-Dodds
738ae2da9d Merge pull request #11564 from nicoddemus/empty-string-parametrize-11563
Fix crash using empty string for parametrized value more than once
2023-10-27 16:51:31 -04:00
Bruno Oliveira
7156a97f9a Fix crash using empty string for parametrized value more than once
Fixes #11563.
2023-10-27 17:26:12 -03:00
Ziad Kermadi
ed8701a57f Mention -q and -s in the docs (#11558)
Fixes #11507.
2023-10-27 14:35:45 -03:00
Bruno Oliveira
247436819a Update build-and-inspect-python-package action (#11561)
This should fix the action for Python 3.12.

Ref: hynek/build-and-inspect-python-package#72
2023-10-27 08:32:02 -03:00
Bruno Oliveira
c1728948ac Fix tag name generated by deploy workflow (#11550)
Traditionally pytest publishes tags in the form `X.Y.Z`, however the deploy workflow (copied from somewhere else) published tags in the form `vX.Y.Z`.

This is the root cause of #11548, because it tried to publish the release notes for tag `X.Y.Z` (which did not exist).

Fix #11548
2023-10-25 13:19:47 -03:00
Bruno Oliveira
dcd8b145d9 Add deploy instructions using the command-line (#11547)
Tested this to trigger the deploy of #11546.
2023-10-25 10:04:06 -03:00
Bruno Oliveira
c7e9b22f37 Merge pull request #11546 from pytest-dev/release-7.4.3 (#11549)
Prepare release 7.4.3

(cherry picked from commit 53df6164b4)
2023-10-24 16:50:13 -03:00
Benjamin Schubert
fbe3e29a55 Color the full diff that pytest shows as a diff (#11530)
Related to #11520
2023-10-24 08:42:21 -03:00
pre-commit-ci[bot]
667b9fd7fd [pre-commit.ci] pre-commit autoupdate (#11543)
updates:
- [github.com/psf/black: 23.9.1 → 23.10.1](https://github.com/psf/black/compare/23.9.1...23.10.1)
- [github.com/pre-commit/mirrors-mypy: v1.6.0 → v1.6.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.6.0...v1.6.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-24 03:42:43 +02:00
Carsten Grohmann
38f7c1e346 Use pytestconfig instead of request.config in cache example (#11542)
to be consistent with the API documentation.
2023-10-23 15:45:16 -03:00
Bruno Oliveira
bcd9664370 Merge pull request #11531 from nicoddemus/ensure-logging-cleanup
Ensure logging tests always cleanup after themselves
2023-10-23 10:55:18 -03:00
Bruno Oliveira
7e69ce7449 Add full type annotations to logging/test_fixture.py 2023-10-23 10:46:55 -03:00
Bruno Oliveira
395bbae8a2 Ensure logging tests always cleanup after themselves
Logging has many global states, and we did foresee this by creating a ``cleanup_disabled_logging`` fixture,
however one might still forget to use it and failures leak later -- sometimes not even in the same PR, because the order
of the tests might change in the future, specially when running under xdist.

This problem surfaced during pytest-dev/pytest#11530, where tests unrelated to the change started to fail.
2023-10-23 10:46:55 -03:00
Bruno Oliveira
ee53433542 Configure ReadTheDocs to fail on warnings (#11535)
* Configure ReadTheDocs to fail on warnings

Important to catch broken links and references.

* Remove dead link to distutils configuration docs
2023-10-23 09:56:33 -03:00
dependabot[bot]
304ab8495e build(deps): Bump pytest-mock in /testing/plugins_integration (#11539)
Bumps [pytest-mock](https://github.com/pytest-dev/pytest-mock) from 3.11.1 to 3.12.0.
- [Release notes](https://github.com/pytest-dev/pytest-mock/releases)
- [Changelog](https://github.com/pytest-dev/pytest-mock/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-mock/compare/v3.11.1...v3.12.0)

---
updated-dependencies:
- dependency-name: pytest-mock
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-23 09:01:08 -03:00
pre-commit-ci[bot]
40e9abd66b [pre-commit.ci] pre-commit autoupdate (#11510)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/pre-commit/mirrors-mypy: v1.5.1 → v1.6.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.5.1...v1.6.0)

* Ignore two typing errors after updating to mypy 1.6.0

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
2023-10-23 08:05:40 -03:00
github-actions[bot]
cac1eed0ea [automated] Update plugin list (#11534)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-10-21 23:43:14 -03:00
dependabot[bot]
cdddd6d695 build(deps): Bump pytest-bdd in /testing/plugins_integration (#11506)
Bumps [pytest-bdd](https://github.com/pytest-dev/pytest-bdd) from 6.1.1 to 7.0.0.
- [Release notes](https://github.com/pytest-dev/pytest-bdd/releases)
- [Changelog](https://github.com/pytest-dev/pytest-bdd/blob/master/CHANGES.rst)
- [Commits](https://github.com/pytest-dev/pytest-bdd/compare/6.1.1...7.0.0)

---
updated-dependencies:
- dependency-name: pytest-bdd
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-16 08:08:50 -03:00
github-actions[bot]
dd68f9c95a [automated] Update plugin list (#11504)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-10-15 10:03:38 -03:00
ryanpudd
3ab70cd561 Use hyphenated cmdline options in docs (#11490)
Fix #11091
2023-10-10 21:16:24 +00:00
dependabot[bot]
23825f2983 build(deps): Bump django in /testing/plugins_integration (#11491)
Bumps [django](https://github.com/django/django) from 4.2.5 to 4.2.6.
- [Commits](https://github.com/django/django/compare/4.2.5...4.2.6)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-10 17:50:54 -03:00
pre-commit-ci[bot]
fb3a46dd8a [pre-commit.ci] pre-commit autoupdate (#11492)
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.5.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.5.0)
- [github.com/asottile/pyupgrade: v3.14.0 → v3.15.0](https://github.com/asottile/pyupgrade/compare/v3.14.0...v3.15.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-10 06:33:25 +02:00
Zac Hatfield-Dodds
3d6d93d0c2 Merge pull request #11486 from pytest-dev/RonnyPfannschmidt-contributing-tags 2023-10-09 11:29:49 -07:00
github-actions[bot]
2401d76655 [automated] Update plugin list (#11487)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-10-09 08:32:49 -03:00
Tanya Agarwal
af9b1dcc24 Duplicated parameters in parametrize marker (#11489)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
2023-10-08 10:26:31 -07:00
Ronny Pfannschmidt
696859fc43 Update CONTRIBUTING.rst
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-10-07 16:16:18 +02:00
Ronny Pfannschmidt
e966dcd93c Update CONTRIBUTING.rst to mention tag fetches
closes #11485
2023-10-07 15:54:45 +02:00
pre-commit-ci[bot]
54623f0f33 [pre-commit.ci] pre-commit autoupdate (#11478)
updates:
- [github.com/asottile/reorder-python-imports: v3.11.0 → v3.12.0](https://github.com/asottile/reorder-python-imports/compare/v3.11.0...v3.12.0)
- [github.com/asottile/pyupgrade: v3.13.0 → v3.14.0](https://github.com/asottile/pyupgrade/compare/v3.13.0...v3.14.0)
- [github.com/asottile/setup-cfg-fmt: v2.4.0 → v2.5.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.4.0...v2.5.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-03 11:47:19 +00:00
Reagan Lee
9bbfe995ee Add more comprehensive set assertion rewrites (#11469)
Fixes #10617
2023-10-02 18:37:52 -03:00
github-actions[bot]
d015bc1b8f [automated] Update plugin list (#11472)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-10-02 08:39:53 -03:00
pre-commit-ci[bot]
b73b4c464c [pre-commit.ci] pre-commit autoupdate (#11468)
updates:
- [github.com/asottile/pyupgrade: v3.11.0 → v3.13.0](https://github.com/asottile/pyupgrade/compare/v3.11.0...v3.13.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-09-26 09:31:39 +00:00
Ran Benita
1a16bac131 Merge pull request #11315 from bluetech/pytest-monkeypatch-chdir
pytester: use `monkeypatch.chdir()` for dir changing
2023-09-25 12:10:14 +03:00
Ran Benita
81192ca85f pytester: use monkeypatch.chdir() for dir changing
The current method as the following problem, described by Sadra
Barikbin:

The tests that request both `pytester` and `monkeypatch` and use
`monkeypatch.chdir` without context, relying on `monkeypatch`'s teardown
to restore cwd. This doesn't work because the following sequence of
actions take place:

- `monkeypatch` is set up.
- `pytester` is set up. It saves the original cwd and changes it to a
  new one dedicated to the test function.
- Test function calls `monkeypatch.chdir()` without context.
  `monkeypatch` saves cwd, which is not the original one, before
  changing it.
- `pytester` is torn down. It restores the cwd to the original one.
- `monkeypatch` is torn down. It restores cwd to what it has saved.

The solution here is to have pytester use `monkeypatch.chdir()` itself,
then everything is handled correctly.
2023-09-25 11:31:09 +03:00
Ran Benita
486a9ed057 Merge pull request #11464 from pytest-dev/update-plugin-list/patch-d2b214220
[automated] Update plugin list
2023-09-24 16:03:45 +03:00
Ran Benita
4ae102c003 Merge pull request #11446 from bluetech/pluggy-typing
Improve pluggy-related typing
2023-09-24 15:42:58 +03:00
pytest bot
c614590ec9 [automated] Update plugin list 2023-09-24 00:18:30 +00:00
Warren Markham
d2b214220f Add class docstring to NodeMeta (#11427) 2023-09-20 09:08:07 -03:00
Simon Blanchard
a38ad254ef Handle ValueError raised during faulthandler teardown code (#11453)
Fixes #11439
2023-09-20 09:06:43 -03:00
pre-commit-ci[bot]
9f22d3281c [pre-commit.ci] pre-commit autoupdate (#11451)
updates:
- [github.com/asottile/reorder-python-imports: v3.10.0 → v3.11.0](https://github.com/asottile/reorder-python-imports/compare/v3.10.0...v3.11.0)
- [github.com/asottile/pyupgrade: v3.10.1 → v3.11.0](https://github.com/asottile/pyupgrade/compare/v3.10.1...v3.11.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-09-19 11:51:41 +02:00
Sharad Nair
9a58e6283d Fixes issue #11314 - log_file_format does not default to log_format (#11444)
* Fixes issue #11314 -

* Incorporated review comments for issue #11314

* Update changelog/11314.improvement.rst

Co-authored-by: Bruno Oliveira <bruno@soliv.dev>

---------

Co-authored-by: Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
Co-authored-by: Bruno Oliveira <bruno@soliv.dev>
2023-09-18 16:50:04 +00:00
github-actions[bot]
8bac8d7807 [automated] Update plugin list (#11443)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-09-18 13:20:47 -03:00
dependabot[bot]
5e081162df build(deps): Bump pytest-html in /testing/plugins_integration (#11449)
Bumps [pytest-html](https://github.com/pytest-dev/pytest-html) from 4.0.1 to 4.0.2.
- [Release notes](https://github.com/pytest-dev/pytest-html/releases)
- [Changelog](https://github.com/pytest-dev/pytest-html/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-html/compare/4.0.1...4.0.2)

---
updated-dependencies:
- dependency-name: pytest-html
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-18 11:10:48 -03:00
Chris Mahoney
8062743f6b Change deprecated_call to handle FutureWarning (#11448)
Fixes #11447
2023-09-18 09:34:05 -03:00
Zac Hatfield-Dodds
8b7f94f145 Merge pull request #11424 from lanzz/exceptioninfo-groupcontains 2023-09-17 16:51:57 -07:00
Mihail Milushev
5ace48ca5b Fix a minor mistake in docs ("`match method" is actually talking about the match` keyword parameter) 2023-09-17 22:28:32 +01:00
Mihail Milushev
e7caaa0b3e Document the new ExceptionInfo.group_contains() method 2023-09-17 22:28:32 +01:00
Mihail Milushev
a47fcb4873 code review: kwarg-only match, replace recursive with depth 2023-09-17 22:28:32 +01:00
Mihail Milushev
ab8f5ce7f4 Add new ExceptionInfo.group_contains assertion helper method
Tests if a captured exception group contains an expected exception.
Will raise `AssertionError` if the wrapped exception is not an exception group.
Supports recursive search into nested exception groups.
2023-09-17 22:28:32 +01:00
Ran Benita
f43a8db618 Improve pluggy-related typing 2023-09-17 21:32:55 +03:00
pomponchik
6c2feb75d2 Add flask_fixture to the manual plugin list
Fixes #11435
2023-09-12 19:17:20 -03:00
pre-commit-ci[bot]
fcb8e73288 [pre-commit.ci] pre-commit autoupdate (#11434)
updates:
- [github.com/psf/black: 23.7.0 → 23.9.1](https://github.com/psf/black/compare/23.7.0...23.9.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-09-12 08:37:19 -03:00
Bruno Oliveira
241f2a890e Force terminal width when running tests (#11425)
Related to #11423
2023-09-11 09:22:56 -03:00
dependabot[bot]
39f9306357 build(deps): Bump pytest-html in /testing/plugins_integration (#11431)
Bumps [pytest-html](https://github.com/pytest-dev/pytest-html) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/pytest-dev/pytest-html/releases)
- [Changelog](https://github.com/pytest-dev/pytest-html/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-html/compare/4.0.0...4.0.1)

---
updated-dependencies:
- dependency-name: pytest-html
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-11 06:50:46 -03:00
dependabot[bot]
e0d04bdfab build(deps): Bump django in /testing/plugins_integration (#11430)
Bumps [django](https://github.com/django/django) from 4.2.4 to 4.2.5.
- [Commits](https://github.com/django/django/compare/4.2.4...4.2.5)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-11 06:50:32 -03:00
dependabot[bot]
1949b09fd3 build(deps): Bump actions/checkout from 3 to 4 (#11429)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-11 06:50:08 -03:00
Ran Benita
3d1c52f203 Merge pull request #11428 from ShurikMen/fix_tests_signature
Fix invalid signature in TestSorting tests
2023-09-11 10:30:45 +03:00
Aleksandr Brodin
a60c23c3d8 fix invalid signature 2023-09-11 09:59:00 +07:00
github-actions[bot]
24a6ee1ffd [automated] Update plugin list (#11422)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-09-10 13:09:41 +00:00
Bruno Oliveira
e2acc1a99b Fix --import-mode=importlib when root contains __init__.py file (#11420)
We cannot have an empty module name when importing a `__init__.py` file that
is at the rootdir.

Fixes #11417
2023-09-10 09:57:40 -03:00
Warren Markham
71f265f1f3 Refactor: use division operator to join paths (#11413)
Starting with `resolve_package_path` and its associated tests,
this refactoring seeks to make path concatenation more
readable and consistent within tests/functions.

As discussed in #11413:

- code is free to use either `/` and `joinpath`
- consistency within a function is more important than consistency across the codebase
- it is nice to use `/` when it is more readable
- it is nice to use `joinpath` when there is little context
- be mindful that `joinpath` may be clearer when joining multiple segments
2023-09-09 09:16:22 -03:00
Marc Mueller
7259e8db98 Fix assert rewriting with assignment expressions (#11414)
Fixes #11239
2023-09-09 09:09:31 -03:00
Ronny Pfannschmidt
dd7beb39d6 Merge pull request #11416 from bluetech/fixtures-getfixtureclosure
fixtures: more tweaks
2023-09-08 19:48:34 +02:00
Ran Benita
6ad9499c9c doctest: some missing type annotations 2023-09-08 15:59:17 +03:00
Ran Benita
2ed2e9208d doctest: remove unnecessary Optionals 2023-09-08 15:59:17 +03:00
Ran Benita
ab63ebb3dc doctest: inline _setup_fixtures, make more similar to Function
There used to be two callers to `_setup_fixtures()`, now there's only
one, so inline it and make `DoctestItem` more similar to `Function`.

(Eventually we may want to generalize `TopRequest` from taking
`Function` directly to some "fixture-supporting item", removing the
remaining `type: ignore` here and allowing plugins to do it in a stable
manner).
2023-09-08 15:59:17 +03:00
Ran Benita
b3a981d385 fixtures: remove getfixtureinfo(funcargs) in favor of None func
Since we already broke plugins using this (private) interface in this
version (pytest-play, pytest-wdl), might as well do a cleanup.
2023-09-08 15:59:17 +03:00
Sadra Barikbin
48b0395648 fixtures: clean up getfixtureclosure()
Some code cleanups - no functional changes.
2023-09-08 15:53:49 +03:00
Ran Benita
9c11275553 fixtures: change getfixtureclosure(ignore_args) to a set
Only used for containment checks so a Set is more appropriate than a
list.
2023-09-08 15:53:49 +03:00
Bruno Oliveira
e5c81fa41a Adjustments to the release process (#11410)
As discussed in #11408:

* Improve documentation for the release process.
* Fix the description for the PRs created by the `prepare release pr` workflow.
* Fix pushing tag in the `deploy` workflow.
2023-09-08 07:22:16 -03:00
Bruno Oliveira
0a06db0729 Merge pull request #11408 from pytest-dev/release-7.4.2 (#11409)
Prepare release 7.4.2

(cherry picked from commit b0c4775a28)
2023-09-07 16:10:19 -03:00
Bruno Oliveira
5936a79fdb Use _pytest.pathlib.safe_exists in get_dirs_from_args (#11407)
Related to #11394
2023-09-07 15:44:47 -03:00
Bruno Oliveira
28ccf476b9 Fix crash when passing a very long cmdline argument (#11404)
Fixes #11394
2023-09-07 12:49:25 -03:00
Fraser Stark
333e4eba6b Change PytestReturnNotNoneWarning to return a normal warning (#11211)
Fixes #10465
2023-09-07 15:11:59 +00:00
Ronny Pfannschmidt
e787d2ed48 Merge pull request #11317 from tjsmart/fix-issue-11237
Fix doctest collection of `functools.cached_property` objects.
2023-09-07 14:39:02 +02:00
Florian Bruhin
f6b6478868 doc: Remove done training (#11399) 2023-09-06 15:22:27 +02:00
Stefaan Lippens
3ce63bc768 Improve plugin list disclaimer (#11397)
Closes #11391
2023-09-06 07:34:38 -03:00
Ran Benita
faa8f2ea08 Merge pull request #11393 from pytest-dev/fixtures-tweaks
Fixtures tweaks
2023-09-06 09:15:28 +03:00
Bruno Oliveira
194a782e38 Fix import_path for packages (#11390)
For packages, `import_path` receives the path to the package's `__init__.py` file, however module names (as they live in `sys.modules`) should not include the `__init__` part.

For example, `app/core/__init__.py` should be imported as `app.core`, not as `app.core.__init__`.

Fix #11306
2023-09-05 19:42:40 -03:00
Ran Benita
bc71561ad9 python: avoid an Any 2023-09-05 22:32:46 +03:00
Ran Benita
574e0f45d9 fixtures: avoid using the mildly expensive fixturenames property
Avoid creating a list copy + 2 sets + a linear search through the list
(in the common case).
2023-09-05 22:15:37 +03:00
Ran Benita
b8906b29a7 fixtures: require item.fixturenames to exist in _fillfixtures
I could find 2 plugins that would be broken by this (pytest-play and
pytest-wdl), but they will be better served by just copying
`_fillfixtures` instead of use the private function.
2023-09-05 22:15:37 +03:00
Ran Benita
d2b5177dd6 fixtures: avoid some redundant work in _fillfixtures 2023-09-05 22:15:37 +03:00
Ran Benita
65c01f531b fixtures: use the item fixturenames in request.fixturenames
`_pyfuncitem.fixturenames` is just an alias for
`_pyfuncitem._fixtureinfo.names_closure` (at least in core pytest), so
let's do the less abstraction-breaking thing.
2023-09-05 22:15:37 +03:00
Ran Benita
82bd63d318 doctest: add fixturenames field to DoctestItem
The field is used in `_fillfixtures`, in preference to
`request.fixturenames`, which also includes already-computed which is
not needed.
2023-09-05 22:15:37 +03:00
Ran Benita
d4872f5df7 fixtures: tiny code cleanup 2023-09-05 22:15:37 +03:00
Ran Benita
8d815ca55b python: type some CallSpec2 fields as immutable
Knowing that a field is immutable makes it easier to understand the
code.
2023-09-05 22:15:37 +03:00
pre-commit-ci[bot]
8032d21271 [pre-commit.ci] pre-commit autoupdate (#11389)
updates:
- [github.com/PyCQA/autoflake: v2.2.0 → v2.2.1](https://github.com/PyCQA/autoflake/compare/v2.2.0...v2.2.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-09-05 10:09:33 -03:00
dependabot[bot]
9c8937b480 build(deps): Bump pytest-html in /testing/plugins_integration (#11384)
Bumps [pytest-html](https://github.com/pytest-dev/pytest-html) from 3.2.0 to 4.0.0.
- [Release notes](https://github.com/pytest-dev/pytest-html/releases)
- [Changelog](https://github.com/pytest-dev/pytest-html/blob/master/docs/changelog.rst)
- [Commits](https://github.com/pytest-dev/pytest-html/compare/v3.2.0...4.0.0)

---
updated-dependencies:
- dependency-name: pytest-html
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-04 08:08:10 -03:00
dependabot[bot]
0d8b87f161 build(deps): Bump anyio[curio,trio] in /testing/plugins_integration (#11383)
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 3.7.1 to 4.0.0.
- [Release notes](https://github.com/agronholm/anyio/releases)
- [Changelog](https://github.com/agronholm/anyio/blob/master/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/3.7.1...4.0.0)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-04 08:08:01 -03:00
dependabot[bot]
65c73a09e7 build(deps): Bump twisted in /testing/plugins_integration (#11385)
Bumps [twisted](https://github.com/twisted/twisted) from 22.8.0 to 23.8.0.
- [Release notes](https://github.com/twisted/twisted/releases)
- [Changelog](https://github.com/twisted/twisted/blob/trunk/NEWS.rst)
- [Commits](https://github.com/twisted/twisted/compare/twisted-22.8.0...twisted-23.8.0)

---
updated-dependencies:
- dependency-name: twisted
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-04 08:07:56 -03:00
Israel Fruchter
917ce9aa01 Fix user_properties not saved to XML if fixture errors during teardown
Move handling of user_properties to `finalize()`.

Previously if a fixture failed during teardown, `pytest_runtest_logreport` would not be called with "teardown", resulting in the user properties not being saved on the JUnit XML file.

Fixes: #11367
2023-09-03 14:33:54 -03:00
github-actions[bot]
4e3a0874df [automated] Update plugin list (#11380)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-09-02 22:13:17 -03:00
Bruno Oliveira
ba0da81f88 Merge pull request #11379 from nicoddemus/cherry-pick-release
Merge pull request #11377 from pytest-dev/release-7.4.1
2023-09-02 13:21:07 -03:00
Bruno Oliveira
f08782d8d0 Merge pull request #11377 from pytest-dev/release-7.4.1
Prepare release 7.4.1

(cherry picked from commit 82eb86f707)
2023-09-02 12:45:58 -03:00
dependabot[bot]
5b528bd131 build(deps): Bump pypa/gh-action-pypi-publish from 1.8.8 to 1.8.10 (#11310)
Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.8 to 1.8.10.
- [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases)
- [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.8...v1.8.10)

---
updated-dependencies:
- dependency-name: pypa/gh-action-pypi-publish
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-02 12:04:30 -03:00
Bruno Oliveira
e4794b26b2 Merge pull request #11378 from nicoddemus/improve-ci-workflow
Improve CI workflow
2023-09-02 11:59:25 -03:00
Bruno Oliveira
ab6cae2126 Improve CI workflow
* Build the package only once, and test on all platforms.
* Deploy is now triggered manually via an Action, which is then responsible for tagging the repository after the package has been uploaded successfully.
* Drop 'docs': we nowadays rely on readthedocs preview PR builds.
2023-09-02 10:29:02 -03:00
Sourabh Beniwal
afb8d66e42 Update CONTRIBUTING.rst (#11368)
Chnaged Status: easy to good first issue, and updated the URL
2023-08-30 11:52:14 +00:00
Sean Patrick Malloy
76ba7db6ce Improve docs for last-failed-no-failures
Improve documentation for last-failed-no-failures to make the different options and the functionality more clear.

Closes #11354
2023-08-29 00:14:45 +00:00
Ran Benita
941b203c94 Merge pull request #11360 from seanjedi/issue_11356-fixing-precommit-issue-with-flake8
fix: fixing an issue with pre-commit with mypy and flake8
2023-08-28 11:26:37 +03:00
Sean Malloy
19d6b12b2a fix: fixing an issue with pre-commit with mypy and flake8 2023-08-27 15:03:42 -07:00
github-actions[bot]
17e8f2b3fc [automated] Update plugin list (#11358)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-08-27 11:29:17 -03:00
Warren Markham
ff23347f1f Fix platform-dependent type-check errors (#11345)
Use more explicit `sys.platform` checks, instead of the previous check using `in`, which mypy understands.

Fixes #11343
2023-08-27 09:40:24 -03:00
Ran Benita
00fedcc439 Merge pull request #11353 from bluetech/pluggy-typing
Fixes for typed pluggy
2023-08-26 22:59:35 +03:00
Ran Benita
77f7f59b2a Fixes for typed pluggy
Since version 1.3 pluggy added typing, which requires some fixes to
please mypy.
2023-08-26 22:13:24 +03:00
Jon Parise
7500fe44b2 Correct the spelling of ArgSource.INVOCATION_DIR (#11333)
Config.ArgsSource.INCOVATION_DIR remains as a backwards compatibility
alias.
2023-08-23 09:21:17 +00:00
Ha Pam
23b899f31f Fix a typo in anatomy.rst (#11341) 2023-08-23 10:17:09 +02:00
Ran Benita
43d1398fc7 Merge pull request #11334 from WarrenTheRabbit/fix-docstring-spelling-in-pytester-1
doc: fix docstring spelling in pytester
2023-08-22 14:44:06 +03:00
Zac Hatfield-Dodds
03832fa31e Merge pull request #11326 from DetachHead/DetachHead-patch-1
use `if not TYPE_CHECKING` on `pytest.__getattr__` to prevent type checkers from using it
2023-08-22 03:53:46 -07:00
pre-commit-ci[bot]
8f36fd5454 [pre-commit.ci] pre-commit autoupdate (#11335)
updates:
- [github.com/asottile/blacken-docs: 1.15.0 → 1.16.0](https://github.com/asottile/blacken-docs/compare/1.15.0...1.16.0)
- [github.com/pre-commit/mirrors-mypy: v1.5.0 → v1.5.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.5.0...v1.5.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-08-22 08:10:48 +00:00
DetachHead
cada6c105a ignore mypy error on deprecated Instance usage 2023-08-22 17:57:59 +10:00
WarrenTheRabbit
3f446b68fd doc: fix docstring spelling in pytester 2023-08-22 14:36:39 +10:00
Zac Hatfield-Dodds
050f402816 Merge pull request #11308 from reaganjlee/iter-reporting
Improve reporting from __iter__ exceptions
2023-08-21 16:27:42 -07:00
Reagan Lee
d1722d5c18 fix test for codecov 2023-08-21 15:49:39 -07:00
github-actions[bot]
4deb38b2ed [automated] Update plugin list (#11329)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-08-21 13:19:58 +00:00
Ran Benita
370eacd3ca doc/reference: replace Unicode dashes with ascii - in cli flags (#11323) 2023-08-21 14:40:03 +02:00
DetachHead
010e1742d8 use python 3.11 for update-plugin-list (#11328) 2023-08-21 12:29:41 +00:00
Ran Benita
6e5f10b28f Merge pull request #11320 from ubaumann/add_nuts
add nuts to plugin list
2023-08-21 14:50:31 +03:00
pre-commit-ci[bot]
dd5ae0c3b8 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-08-21 08:03:06 +00:00
DetachHead
fc653d0d12 use if not TYPE_CHECKING on pytest.__getattr__ to prevent type checkers from using it 2023-08-21 18:00:28 +10:00
Tyler Smart
a357c7abc8 Ignore dip in branch coverage (since py3.13+ isn't tested in CI) 2023-08-20 20:55:30 -06:00
Reagan Lee
61133ba83d un-iterable fix 2023-08-20 14:46:09 -07:00
Reagan Lee
049eec8474 Revert iter raises checks
This reverts commit e938580257.

Revert "improve error msg and test"

This reverts commit c0cf822ca1.

Revert "error msg"

This reverts commit ec1053cc16.

Revert "changelog"

This reverts commit d2dc8a70b5.

Revert "simplify code / take out user-gen typeerror case"

This reverts commit b9cb87d862.
2023-08-20 14:06:42 -07:00
Ran Benita
37bb186175 Merge pull request #11322 from bluetech/testing-norecursedirs
testing: add `.*` to `norecursedirs`
2023-08-20 16:37:16 +03:00
Ran Benita
3cb3cd1a08 testing: add .* to norecursedirs
Setting `norecursedirs` overrides the default, so we end up scanning
dot-directories and such which slows down collection unnecessarily
(150ms on my working directory).
2023-08-20 12:16:38 +03:00
Tyler Smart
7a625481da PR suggestions 2023-08-19 22:20:40 -06:00
Ran Benita
0ddfdfcc04 Merge pull request #11321 from tjsmart/fix-doctesting
Add doctesting-coverage to envlist
2023-08-20 00:26:42 +03:00
Tyler Smart
87bfc83aa0 Add doctesting-coverage to envlist 2023-08-19 12:18:17 -06:00
Tyler Smart
ebd571bb18 Move _from_module override to pre-existsing DocTestFinder subclass 2023-08-19 12:04:59 -06:00
ubaumann
176d728b7b add nuts to plugin list
Adding https://github.com/network-unit-testing-system/nuts to the plugin list.
2023-08-18 23:34:40 +02:00
Tyler Smart
d4fb6ac9f7 Fix doctest collection of functools.cached_property objects. 2023-08-16 00:55:16 -06:00
Ran Benita
15fadd8c5c Merge pull request #11219 from bluetech/fixtures2
fixtures: make FixtureRequest abstract, add TopRequest subclass
2023-08-15 21:52:46 +03:00
pre-commit-ci[bot]
73d754bd74 [pre-commit.ci] pre-commit autoupdate (#11313)
updates:
- [github.com/pre-commit/mirrors-mypy: v1.4.1 → v1.5.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.4.1...v1.5.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-08-15 07:56:42 +00:00
Ran Benita
10056865d2 Merge pull request #11309 from bluetech/docs-xfail
doc: fix a few `xfail` nits
2023-08-12 18:58:37 +03:00
Ran Benita
1827d8d5f9 doc: fix a few pytest.mark.xfail nits
Refs #9027, #10094.
2023-08-12 18:30:58 +03:00
Ran Benita
9e164fc4fe fixtures: make FixtureRequest abstract, add TopRequest subclass
Fix #11218.
2023-08-12 11:55:08 +03:00
Reagan Lee
c0cf822ca1 improve error msg and test 2023-08-11 10:33:34 -07:00
Reagan Lee
ec1053cc16 error msg 2023-08-11 10:03:19 -07:00
Reagan Lee
d2dc8a70b5 changelog 2023-08-11 09:48:53 -07:00
Reagan Lee
b9cb87d862 simplify code / take out user-gen typeerror case 2023-08-10 17:43:01 -07:00
Reagan Lee
e938580257 check for user-generated exceptions 2023-08-10 17:37:48 -07:00
Reagan Lee
47c0fc3d78 tests 2023-08-10 16:36:22 -07:00
Ran Benita
556e075d23 Merge pull request #11301 from bluetech/fixtures-resolve-directness
python: use clearer terminology for `_resolve_arg_value_types`
2023-08-10 09:05:58 +03:00
Ran Benita
3ad3fc6b8f python: use clearer terminology for _resolve_arg_value_types 2023-08-09 20:36:24 +03:00
Sadra Barikbin
09b78737a5 Move fixtures.py::add_funcarg_pseudo_fixture_def to Metafunc.parametrize (#11220)
To remove fixtures.py::add_funcargs_pseudo_fixture_def and add its logic
i.e. registering funcargs as params and making corresponding fixturedefs,
right to Metafunc.parametrize in which parametrization takes place.

To remove funcargs from metafunc attributes as we populate metafunc
params and make pseudo fixturedefs simultaneously and there's no need to
keep funcargs separately.
2023-08-09 17:13:45 +00:00
Ran Benita
b2186e2455 Merge pull request #11268 from bluetech/conftest-load
config: split `_getconftestmodules` and `_loadconftestmodules`
2023-08-08 14:44:29 +03:00
Bruno Oliveira
18bc6c9a0e Merge pull request #11292 from pytest-dev/dependabot/pip/testing/plugins_integration/django-4.2.4
build(deps): Bump django from 4.2.3 to 4.2.4 in /testing/plugins_integration
2023-08-07 08:15:17 -03:00
Bruno Oliveira
24c9aa6c30 Merge pull request #11291 from calestyo/improve-duplicate-values-documentation
Improve duplicate values documentation
2023-08-07 08:14:39 -03:00
dependabot[bot]
9c67b7aeb6 build(deps): Bump django in /testing/plugins_integration
Bumps [django](https://github.com/django/django) from 4.2.3 to 4.2.4.
- [Commits](https://github.com/django/django/compare/4.2.3...4.2.4)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-07 03:39:31 +00:00
Christoph Anton Mitterer
1cc58ed67f improve exception message on duplicate parametrization
Signed-off-by: Christoph Anton Mitterer <mail@christoph.anton.mitterer.name>
2023-08-06 17:43:37 +02:00
Christoph Anton Mitterer
84a342e27c doc: parametrize() can be called multiple times only on different args
Signed-off-by: Christoph Anton Mitterer <mail@christoph.anton.mitterer.name>
2023-08-06 17:39:31 +02:00
Sadra Barikbin
e8a8a5f320 python: fix scope assignment for indirect parameter sets (#11277)
Previously, when assigning a scope for a fully-indirect parameter set,
when there are multiple fixturedefs for a param (i.e. same-name fixture
chain), the highest scope was used, but it should be the lowest scope,
since that's the effective scope of the fixture.
2023-08-06 13:59:54 +00:00
Florian Bruhin
1c04a92503 doc: Link pytest.main to how-to guide (#11287) 2023-08-06 12:39:11 +02:00
Christoph Anton Mitterer
cc0adf6bf3 doc: update information about assertion messages (#11285)
It was pointed out[0] that the previous behaviour has been obsoleted by
commit 37bd1e03cb.

[0] https://github.com/pytest-dev/pytest/issues/11265#issuecomment-1666581197

Signed-off-by: Christoph Anton Mitterer <mail@christoph.anton.mitterer.name>
2023-08-05 19:30:41 +00:00
Christoph Anton Mitterer
b8b74331b4 Improve docs for Parametrizing conditional raising (#11279)
What one typically actually wants in such a case is both, checking for some
resulting values *and* checking for some expected exception.

Since this is easily possible with the `nullcontext` context manager, adapt the
example accordingly (needlessly using a different name rather just confuses people).

Signed-off-by: Christoph Anton Mitterer <mail@christoph.anton.mitterer.name>
2023-08-03 13:31:17 -03:00
Sadra Barikbin
4797deab99 Add FixtureArgKey class to represent fixture deps in fixtures.py (#11231) 2023-08-02 14:28:31 +03:00
pre-commit-ci[bot]
c9163402e0 [pre-commit.ci] pre-commit autoupdate (#11269)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/PyCQA/flake8: 6.0.0 → 6.1.0](https://github.com/PyCQA/flake8/compare/6.0.0...6.1.0)
- [github.com/asottile/pyupgrade: v3.9.0 → v3.10.1](https://github.com/asottile/pyupgrade/compare/v3.9.0...v3.10.1)

* Use is instead of type comparison with equal to appease the linter

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
2023-08-01 23:52:09 +02:00
Ran Benita
01ac13a77d config: split _getconftestmodules and _loadconftestmodules
Previously, the `_getconftestmodules` function was used both to load
conftest modules for a path (during `pytest_load_initial_conftests`),
and to retrieve conftest modules for a path (during hook dispatch and
for fetching `collect_ignore`). This made things muddy - it is usually
nicer to have clear separation between "command" and "query" functions,
when they occur in separate phases.

So split into "load" and "get".

Currently, `gethookproxy` still loads conftest itself. I hope to change
this in the future.
2023-08-01 09:46:17 +03:00
Ran Benita
485c555812 Merge pull request #11138 from bluetech/pkg-mod
python: change `Package` to no longer be a `Module`/`File`
2023-07-28 23:15:08 +03:00
Ran Benita
a21fb87a90 python: change Package to no longer be a Module/File
Fix #11137.
2023-07-28 22:49:24 +03:00
Ran Benita
c754da10d2 Merge pull request #11256 from bluetech/scope-pkg-crash
fixtures: fix crash when `parametrize(scope="package")` is used without a Package
2023-07-28 22:48:47 +03:00
Ran Benita
71e627aa8f fixtures: fix crash when parametrize(scope="package") is used without a Package
There as handling for `scope="class"` without a class, but not for
`scope="package"` without a package. It would fail the assert.
2023-07-28 16:13:02 +03:00
Uday Kumar
d3552ef4c0 Clarify doc for running tests by nodeid section (#11249) 2023-07-28 07:06:38 +00:00
Ran Benita
448563caaa Merge pull request #11253 from bluetech/11243-cherry-picks
11243 cherry picks
2023-07-27 10:19:40 +03:00
Sadra Barikbin
e8aa906e06 fixtures: move _get_direct_parametrize_args to a standalone function
So it can be used independently of the FixtureManager.
2023-07-27 09:38:42 +03:00
Sadra Barikbin
12054a4972 config: avoid list[], set[], dict[]
Should wait with this until Python 3.8 is dropped.
2023-07-27 09:33:34 +03:00
Ran Benita
430ad145c1 Merge pull request #11244 from bluetech/rootdir-tweaks
Rootdir tweaks
2023-07-27 09:16:13 +03:00
Ran Benita
13e2b00258 config: don't pass the entire Config to determine_setup()
Seems better to make the function a bit more pure, and avoids the
circular import.
2023-07-24 00:00:34 +03:00
Ran Benita
4e42421ebf config: fix an incorrect type
Was a mistake in d97d44a97a.
2023-07-24 00:00:34 +03:00
Ran Benita
161ba87300 doc/usage: clarify "Run tests by node ids"
Fix #11107, #11235.
2023-07-24 00:00:25 +03:00
Ran Benita
f2b6040e9e Merge pull request #11238 from bluetech/doc-not-indirect
doc/example/parametrize: a few fixes/improvements
2023-07-23 13:07:40 +03:00
Florian Bruhin
e3247834e2 Remove ep2023 training (#11241) 2023-07-22 20:16:59 +02:00
bowugit
0b4a557087 Extend pytest.raises to support Exception having __repr__ method and initialized with kwargs (#11073)
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-07-20 13:29:29 -03:00
Bruno Oliveira
ffdcce67f4 Merge pull request #10927 from RonnyPfannschmidt/pypi-json-for-plugin-list
update-plugin-list: use json, use http caching, use gh action caches
2023-07-20 10:42:32 -03:00
Ronny Pfannschmidt
1ded74739b update-plugin-list: use json, use http caching, use gh action caches
this change
* switches from html index usage to json index usage
* adds using requests-cache as http cache to trim down runtime
* adds gh action caches for pip and the new http cache
2023-07-20 15:04:41 +02:00
Ran Benita
497a1d798a doc/example/parametrize: a few fixes/improvements
Remove "Indirect" from a few section names -- not actually indirect.

Also few minor updates to the related multipython.py example.
2023-07-20 09:51:11 +03:00
Isaac Virshup
1de0923e83 Have pytest.raises match against exception __notes__ (#11227)
The doctest is skipped because add_note is only available in 3.11,

Closes #11223
2023-07-18 08:39:39 -03:00
Ronny Pfannschmidt
7c30f674c5 Merge pull request #11228 from bluetech/fixtures-check-scope-test
fixtures: add a test for a currently non-covered scope mismatch scenario
2023-07-18 08:59:55 +02:00
Ran Benita
396bfbf30b fixtures: add a test for a currently non-covered scope mismatch scenario
This test makes clear the need for the `_check_scope()` call in the
`pytest_setup_fixture` impl in fixtures.py, which otherwise seems
redundant with the one in `_compute_fixture_value`.
2023-07-18 00:01:40 +03:00
Ran Benita
02ba39bfcd Merge pull request #11215 from bluetech/fixtures-tweaks2
fixtures: minor tweaks
2023-07-17 17:30:24 +03:00
Ran Benita
29010d23a6 Merge pull request #11217 from bluetech/fixtures-skip-xunit-loc
fixtures: show test as skip location if skipped from an xunit setup function
2023-07-17 17:30:06 +03:00
dependabot[bot]
de1f6f58ba build(deps): Bump pypa/gh-action-pypi-publish from 1.8.7 to 1.8.8 (#11221)
Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.7 to 1.8.8.
- [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases)
- [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.7...v1.8.8)

---
updated-dependencies:
- dependency-name: pypa/gh-action-pypi-publish
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-17 09:31:06 +02:00
dependabot[bot]
cfda801ebf build(deps): Bump pytest-asyncio in /testing/plugins_integration (#11222)
Bumps [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) from 0.21.0 to 0.21.1.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v0.21.0...v0.21.1)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-17 09:27:38 +02:00
Ran Benita
c5262b0c42 fixtures: show test as skip location if skipped from an xunit setup function
Fix #11216.
2023-07-16 23:26:04 +03:00
Ran Benita
ff6e110161 fixtures: remove inaccurate comment
unittest TestCases can also use `usefixtures`. Just remove this comment,
it's not very helpful.
2023-07-16 23:19:33 +03:00
Ran Benita
0e0ed2af95 fixtures: some code comments and minor improvements 2023-07-16 23:19:33 +03:00
Ran Benita
a3fbf24389 unittest: hide access to _request
Let the parent class (Function) do this. Tiny bit better abstraction.
There seems to be no reason for the `hasattr` bit.
2023-07-16 23:19:33 +03:00
Ran Benita
bf451d47a1 Merge pull request #11213 from bluetech/py38-literal
Use typing.Literal without TYPE_CHECKING checks
2023-07-16 23:17:12 +03:00
Ran Benita
578fbe3dfd Merge pull request #11214 from pytest-dev/update-plugin-list/patch-32f480814
[automated] Update plugin list
2023-07-16 13:07:40 +03:00
pytest bot
a668719626 [automated] Update plugin list 2023-07-16 00:28:56 +00:00
Ran Benita
04e0db7e48 Use typing.Literal without TYPE_CHECKING checks
Literal was added in Python 3.8 which we now require so can use it
freely.
2023-07-16 01:11:21 +03:00
Ran Benita
32f480814c Merge pull request #11209 from bluetech/fixtures-doc-comments
fixtures: some tweaks & improvements
2023-07-15 19:40:48 +03:00
Ran Benita
40ed678885 fixtures: remove two unused functions
Not used since 310b67b227.
2023-07-15 10:06:06 +03:00
Ran Benita
fb55615d5e Export FixtureDef
FixtureDef is used in the `pytest_fixture_setup` hook so needs to be
public. However since its current internals are quite dubious (and not
all marked with `_` prefix) I've added an explicit note that only
documented fields/methods are considered public.

Refs #7469.
2023-07-15 10:06:06 +03:00
Ran Benita
9d0ddb4625 fixtures: change FixtureDef.cached_result[2] from exception triplet to exception
Fix #11208.
2023-07-15 10:06:06 +03:00
Ran Benita
01f38aca44 fixtures: expand comments and annotations on fixture internals 2023-07-15 10:06:06 +03:00
Ran Benita
78d81ef865 Merge pull request #11123 from bluetech/new-style-wrappers
Switch to new-style pluggy hook wrappers
2023-07-15 10:03:35 +03:00
Ran Benita
b41acaea12 Switch to new-style pluggy hook wrappers
Fix #11122.
2023-07-14 22:47:48 +03:00
pre-commit-ci[bot]
7008385253 [pre-commit.ci] pre-commit autoupdate (#11195)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/psf/black: 23.3.0 → 23.7.0](https://github.com/psf/black/compare/23.3.0...23.7.0)
- [github.com/asottile/blacken-docs: 1.14.0 → 1.15.0](https://github.com/asottile/blacken-docs/compare/1.14.0...1.15.0)
- [github.com/asottile/pyupgrade: v3.8.0 → v3.9.0](https://github.com/asottile/pyupgrade/compare/v3.8.0...v3.9.0)

* Update .pre-commit-config.yaml

* Update .pre-commit-config.yaml

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-07-11 11:37:07 +00:00
Ran Benita
b25a3adff5 Merge pull request #11192 from bluetech/py38-extra
A few more Python>=3.8 simplifications
2023-07-11 01:13:17 +03:00
Ran Benita
ecfab4dc8b fixtures: fix a typing ignore TODO
From understanding the code better I see this is the correct fix.
The fixturedefs can be None if `request.getfixturevalue("doesnotexist")`
is used.

In practice there is no change in behavior because this mapping is used
as `self._arg2fixturedefs.get(argname, None)` which ends up the same.
2023-07-11 00:19:29 +03:00
Ran Benita
2c80de532f fixtures: replace a startswith("conftest.py") with == "conftest.py"
I can't imagine why we would want to test for a prefix here.
2023-07-10 23:27:11 +03:00
Ran Benita
7967b2e710 fixtures: change a lambda to partial
It makes for a more debuggable repr. Before:

    <function FixtureRequest._schedule_finalizers.<locals>.<lambda> at 0x7fe4ae32d440>

After:

    functools.partial(<bound method FixtureDef.finish of <FixtureDef argname='hello_package' scope='package' baseid=''>>, request=<SubRequest 'hello_package' for <Function test_hello>>)
2023-07-10 23:27:11 +03:00
Ran Benita
f1c9570a0e A few more Python>=3.8 simplifications 2023-07-10 23:20:11 +03:00
dependabot[bot]
b20e7f6d0c build(deps): Bump anyio[curio,trio] in /testing/plugins_integration (#11191)
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 3.7.0 to 3.7.1.
- [Changelog](https://github.com/agronholm/anyio/blob/master/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/3.7.0...3.7.1)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-10 10:23:47 -03:00
dependabot[bot]
b91d5a3112 build(deps): Bump pytest-rerunfailures in /testing/plugins_integration (#11190)
Bumps [pytest-rerunfailures](https://github.com/pytest-dev/pytest-rerunfailures) from 11.1.2 to 12.0.
- [Changelog](https://github.com/pytest-dev/pytest-rerunfailures/blob/master/CHANGES.rst)
- [Commits](https://github.com/pytest-dev/pytest-rerunfailures/compare/11.1.2...12.0)

---
updated-dependencies:
- dependency-name: pytest-rerunfailures
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-10 10:23:33 -03:00
dependabot[bot]
4e75bff71a build(deps): Bump pypa/gh-action-pypi-publish from 1.8.5 to 1.8.7 (#11189)
Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.5 to 1.8.7.
- [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases)
- [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.5...v1.8.7)

---
updated-dependencies:
- dependency-name: pypa/gh-action-pypi-publish
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-10 10:23:12 -03:00
antosikv
99ab8ae884 Clarify docs for pytest.main default behavior (#11187)
Add explicit mentions of the default behavior to both API reference and
how-to section about ways to invoke pytest.

Co-authored-by: Ran Benita <ran@unusedvar.com>
2023-07-09 12:30:33 -03:00
Ran Benita
782cacf86b Merge pull request #11184 from pytest-dev/update-plugin-list/patch-fd7a4d242
[automated] Update plugin list
2023-07-09 17:09:12 +03:00
pytest bot
a3b4220d76 [automated] Update plugin list 2023-07-09 00:29:15 +00:00
Bruno Oliveira
fd7a4d2429 Merge pull request #11106 from bluetech/docs-ref-collection-objs
reference: improve the node types docs a bit
2023-07-08 15:41:22 -03:00
Ran Benita
b73ec8e5d1 doc: fix EncodingWarnings in examples (#11158)
Otherwise the warnings show in the regen output.
2023-07-08 15:40:05 -03:00
Zac Hatfield-Dodds
d790e96765 Merge pull request #11178 from kenny-y-dev/add-none-support-approxmapping 2023-07-08 10:40:42 -07:00
Kenny Y
d4265448a5 Update src/_pytest/python_api.py
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-07-08 08:41:42 -04:00
Kenny Y
db37e34613 Merge branch 'main' into add-none-support-approxmapping 2023-07-07 15:55:19 -04:00
Kenny Y
c5b13099e6 Fix error assertion handling in approx when None in dict comparison
Dict comparsion in the ApproxMapping class did not check if values were None before attempting to subtract for max_abs_diff stat, which was throwing an TypeError instead of being handled by pytest error assertion. Check for None has been added before these calculations, so that None will properly show as Obtained/Expected in pytest assert message
2023-07-07 14:42:59 -04:00
Zac Hatfield-Dodds
97ed533f63 Merge pull request #11169 from hugovk/test-me-rm-3.7 2023-07-06 22:28:44 -07:00
Ran Benita
f5a9aa0b84 Merge pull request #11175 from pytest-dev/dependabot/pip/testing/plugins_integration/django-4.2.3
build(deps): Bump django from 4.2.2 to 4.2.3 in /testing/plugins_integration
2023-07-06 11:51:44 +03:00
Zac Hatfield-Dodds
901316b3f4 Merge pull request #8502 from mickeypash/patch-2 2023-07-06 00:28:20 -07:00
Zac Hatfield-Dodds
b81003f6fb Incorporate legend into main table 2023-07-06 00:04:15 -07:00
mickeypash
ddd773ecb1 [docs] add table nose x pytest naming comparison 2023-07-05 23:46:32 -07:00
dependabot[bot]
44604f49cd build(deps): Bump django in /testing/plugins_integration
Bumps [django](https://github.com/django/django) from 4.2.2 to 4.2.3.
- [Commits](https://github.com/django/django/compare/4.2.2...4.2.3)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-05 22:57:45 +00:00
Zac Hatfield-Dodds
2203897086 Merge pull request #11173 from bluetech/enc-warning-detox
tox: turn off PYTHONWARNDEFAULTENCODING for pre-commit, sphinx etc.
2023-07-05 09:48:26 -07:00
Ran Benita
119cec0279 tox: turn off PYTHONWARNDEFAULTENCODING for pre-commit, sphinx etc.
Fix #11157.
2023-07-05 19:05:08 +03:00
Florian Bruhin
b5bc53e441 Update open trainings (#11171) 2023-07-04 23:19:24 +02:00
Zac Hatfield-Dodds
084d756ae6 Merge pull request #11143 from tushar-deepsource/patch-1 2023-07-04 10:47:13 -07:00
Zac Hatfield-Dodds
d7dbadbffc Merge pull request #11160 from lesnek/ml/fix/warinings-recorder-pop 2023-07-04 10:20:04 -07:00
Zac Hatfield-Dodds
cb732f7f49 Merge branch 'main' into patch-1 2023-07-04 10:17:06 -07:00
Zac Hatfield-Dodds
7775e494b1 Further tweaks from code review 2023-07-04 10:00:29 -07:00
Hugo van Kemenade
1f5058e972 Use same Black version for blacken-docs as regular Black check 2023-07-04 18:55:08 +03:00
Hugo van Kemenade
6baf9f2d31 Update docs and code after dropping EOL 3.7 2023-07-04 18:55:08 +03:00
Lesnek
c4876c7106 chore(CR): Add changes from code review 2023-07-04 11:49:11 +02:00
Milan Lesnek
6badb6f01e Apply suggestions from code review
chore(changelog): describe better the fix

Co-authored-by: Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
2023-07-04 10:30:19 +02:00
Lesnek
4517af1e28 test(warnings-recorder): Add attribute error test 2023-07-04 10:30:19 +02:00
Lesnek
3d0dedb5ec test(warnings-recorder): Add attribute error test 2023-07-04 10:30:19 +02:00
Lesnek
7b7bd304aa fix(warnings-recorder): Add handling of rest 2023-07-04 10:30:19 +02:00
Lesnek
2706271f66 test(warnings-recorder): Add another warning 2023-07-04 10:30:19 +02:00
Lesnek
8ac3c645fa fix(warnings-recorder): Match also subclass of warning in pop 2023-07-04 10:30:19 +02:00
Lesnek
18e87c9831 test(warnings-recorder): Add non working subclass behaviour of pop 2023-07-04 10:30:19 +02:00
pre-commit-ci[bot]
6995257cf4 [pre-commit.ci] pre-commit autoupdate (#11165)
updates:
- [github.com/asottile/pyupgrade: v3.7.0 → v3.8.0](https://github.com/asottile/pyupgrade/compare/v3.7.0...v3.8.0)
- [github.com/asottile/setup-cfg-fmt: v2.3.0 → v2.4.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.3.0...v2.4.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-07-04 07:00:14 +00:00
Ronny Pfannschmidt
bea56b30af Switch to deploy environment and configure for pypi oidc (#10925)
Closes #10871
Closes #10870
2023-07-03 12:52:58 -03:00
github-actions[bot]
b847084224 [automated] Update plugin list (#11159)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-07-03 11:45:17 -03:00
Akhilesh Ramakrishnan
024e62e6d2 Added Akhilesh Ramakrishnan to AUTHORS (#11153)
* Added Akhilesh Ramakrishnan to AUTHORS

PR#10338

* Fix typo in changelog
2023-07-03 13:49:50 +02:00
Ronny Pfannschmidt
f9410fddcd Merge pull request #11155 from RonnyPfannschmidt/fix-10447-maker-mro-order-needs-reverse
fix #10447 - consider marks in reverse mro order to give base classes priority
2023-07-02 22:23:00 +02:00
Ronny Pfannschmidt
561f1a993b fix #10447 - consider marks in reverse mro order to give base classes priority 2023-07-01 22:27:18 +02:00
Bruno Oliveira
b77d0deaf5 Fix duplicated imports with importlib mode and doctest-modules (#11148)
The initial implementation (in #7246) introduced the `importlib` mode, which
never added the imported module to `sys.modules`, so it included a test
to ensure calling `import_path` twice would yield different modules.

Not adding modules to `sys.modules` proved problematic, so we began to add the imported module to `sys.modules`
in #7870, but failed to realize that given we are now changing `sys.modules`, we might
as well avoid importing it more than once.

Then #10088 came along, passing `importlib` also when importing application modules
(as opposed to only test modules before), which caused problems due to imports
having side-effects and the expectation being that they are imported only once.

With this PR, `import_path` returns the module immediately if already in
`sys.modules`.

Fix #10811
Fix #10341
2023-07-01 15:37:46 +00:00
akhilramkee
2f7415cfbc Add child modules as attributes of parent modules. (#10338)
Failing to add child modules as attributes of parent module will prevent them from being accessible through parent module.

Fix #10337
2023-07-01 15:12:41 +00:00
Zac Hatfield-Dodds
ba60649680 Merge pull request #11129 from Cheukting/warn_in_expt 2023-06-30 21:58:42 -07:00
Zac Hatfield-Dodds
679bd6f2ed Merge pull request #10937 from reaganjlee/re-emit 2023-06-30 21:21:37 -07:00
Zac Hatfield-Dodds
a50ea1b8e7 Merge pull request #11152 from Zac-HD/drop-py37 2023-06-30 20:56:47 -07:00
Zac Hatfield-Dodds
0353a94cd1 Explicit GC for PyPy, take 2 2023-06-30 20:33:12 -07:00
Zac Hatfield-Dodds
0311fc3384 Apply suggestions from code review
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-06-30 20:18:25 -07:00
Zac Hatfield-Dodds
7fdc8391e2 Explicit GC for PyPy 2023-06-30 16:23:18 -07:00
Cheukting
15524f34d2 capture warning when exception is raised (fix #9036) 2023-06-30 16:04:37 -07:00
Zac Hatfield-Dodds
2d48171e88 Tweak docs on review 2023-06-30 15:29:03 -07:00
Zac Hatfield-Dodds
7022fb455d Update tests for re-emitted warnings 2023-06-30 15:29:03 -07:00
Zac Hatfield-Dodds
a1b37022af Refactor warns() exit logic 2023-06-30 15:29:02 -07:00
Reagan Lee
9279ea2882 Emit unmatched warnings from pytest.warns() 2023-06-30 15:29:02 -07:00
Zac Hatfield-Dodds
165fbbd12a Drop py37 from CI 2023-06-30 15:19:19 -07:00
Zac Hatfield-Dodds
f617bab0a2 Update pre-commit config 2023-06-30 15:07:07 -07:00
Zac Hatfield-Dodds
f4e3b4ad98 Drop Python 3.7 2023-06-30 14:55:42 -07:00
Ran Benita
81cfb3fc87 Merge pull request #11017 from erik-hasse/caplog-root-logger-docs
add a warning about modifying the root logger during tests
2023-06-28 09:28:46 +03:00
pre-commit-ci[bot]
dd5f3773d9 [pre-commit.ci] pre-commit autoupdate (#11145)
updates:
- [github.com/PyCQA/autoflake: v2.1.1 → v2.2.0](https://github.com/PyCQA/autoflake/compare/v2.1.1...v2.2.0)
- [github.com/pre-commit/mirrors-mypy: v1.3.0 → v1.4.1](https://github.com/pre-commit/mirrors-mypy/compare/v1.3.0...v1.4.1)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-06-27 05:28:11 +00:00
Ran Benita
e132d6488f Merge pull request #11139 from pytest-dev/update-plugin-list/patch-fe51121f3
[automated] Update plugin list
2023-06-26 15:33:14 +03:00
pre-commit-ci[bot]
4719d998d8 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-06-26 11:34:03 +00:00
Tushar Sadhwani
5332656906 Add changelog and author 2023-06-26 17:02:33 +05:30
Tushar Sadhwani
a14fc10cac add a test function to the test 2023-06-26 13:06:11 +05:30
Tushar Sadhwani
05d7e60904 Add test 2023-06-26 12:37:23 +05:30
Tushar Sadhwani
4ebb2b94c2 fix code for py37 2023-06-26 12:19:42 +05:30
Tushar Sadhwani
9859c110cc Ensure the docstring is a string 2023-06-26 12:14:41 +05:30
Zac Hatfield-Dodds
5eaf8207eb Merge pull request #8428 from graingert/warn-when-a-mark-is-applied-to-a-fixture 2023-06-25 10:21:18 -07:00
Thomas Grainger
518ca37cae Update doc/en/deprecations.rst 2023-06-25 16:09:04 +01:00
Thomas Grainger
45f1a462d5 Apply suggestions from code review
Co-authored-by: Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
2023-06-25 16:08:53 +01:00
Thomas Grainger
4cd95eeabf Merge branch 'main' into warn-when-a-mark-is-applied-to-a-fixture 2023-06-25 16:08:11 +01:00
pytest bot
1306b84241 [automated] Update plugin list 2023-06-25 00:27:02 +00:00
Ran Benita
fe51121f39 Merge pull request #11042 from bluetech/pkg-init-argpath
python: change `pytest pkg/__init__.py` to only collect the `__init__.py` Module
2023-06-23 21:09:00 +03:00
Ran Benita
c8b1790ee7 python: change pytest pkg/__init__.py to only collect the __init__.py Module
Previously it would collect the entire package, but this is not what
users expect.

Refs #3749
Fixes #8976
Fixes #9263
Fixes #9313
2023-06-23 20:42:50 +03:00
Ran Benita
2870157234 Merge pull request #11133 from bluetech/removed-in-8-error
Change PytestRemovedIn8Warning to error by default, add PytestRemovedIn9Warning
2023-06-23 20:13:17 +03:00
Ran Benita
1b7896f83d Add PytestRemovedIn9Warning
It's good to have it available already in all 8.* versions, even if it's
not used yet.
2023-06-23 16:42:26 +03:00
Ran Benita
a4a189ad99 Change PytestRemovedIn8Warning to error by default
Per our backward compatibility policy.
2023-06-23 16:42:24 +03:00
Ran Benita
57d352460c Merge pull request #11132 from bluetech/cherry-pick-release
Cherry-pick 7.4.0 release notes
2023-06-23 14:48:46 +03:00
Ran Benita
a14745550a Merge pull request #11131 from pytest-dev/release-7.4.0
Prepare release 7.4.0

(cherry picked from commit fb03d1388b)
2023-06-23 14:19:51 +03:00
Ran Benita
64319dbc01 Merge pull request #11128 from bluetech/pythonpath-note
reference: add note that `pythonpath` does not affect `-p`
2023-06-22 18:12:37 +03:00
Ran Benita
1e8135df16 reference: add note that pythonpath does not affect -p
Fix #11118.
2023-06-22 15:45:20 +03:00
Zac Hatfield-Dodds
1e32a4b570 Merge pull request #10935 from nondescryptid/10328 2023-06-21 11:04:10 -07:00
Ran Benita
faa1f9d2ad Merge pull request #11125 from bluetech/initial-conftests-testpaths
config: fix the paths considered for initial conftest discovery
2023-06-21 09:21:27 +03:00
Ran Benita
14890329dc config: fix the paths considered for initial conftest discovery
Fixes #11104.

See the issue for a description of the problem.

Now, we use the same logic for initial conftest paths as we do for
deciding the initial args, which was the idea behind checking
`namespace.file_or_dir` and `testpaths` previously.

This fixes the issue of `testpaths` being considered for initial
conftests even when it's not used for the args.

(Another issue in faeb16146b was that the
`testpaths` were not glob-expanded, this is also fixed.)
2023-06-21 09:01:42 +03:00
Ran Benita
d97d44a97a config: extract initial paths/nodeids args logic to a function
Will be reused in the next commit.
2023-06-20 21:28:48 +03:00
Zac Hatfield-Dodds
f6b995e9d5 Use utf-8 debug file 2023-06-20 04:55:40 -07:00
Zac Hatfield-Dodds
661b938fca Add encoding in more tests 2023-06-20 04:55:40 -07:00
Zac Hatfield-Dodds
7e510769b4 Encoding for subprocess.run 2023-06-20 04:55:39 -07:00
nondescryptid
a704605cf1 Fix encoding warnings 2023-06-20 04:55:39 -07:00
pre-commit-ci[bot]
797b924fc4 [pre-commit.ci] pre-commit autoupdate (#11124)
updates:
- [github.com/asottile/blacken-docs: 1.13.0 → 1.14.0](https://github.com/asottile/blacken-docs/compare/1.13.0...1.14.0)
- [github.com/asottile/reorder-python-imports: v3.9.0 → v3.10.0](https://github.com/asottile/reorder-python-imports/compare/v3.9.0...v3.10.0)
- [github.com/asottile/pyupgrade: v3.6.0 → v3.7.0](https://github.com/asottile/pyupgrade/compare/v3.6.0...v3.7.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-06-20 06:38:36 +00:00
Zac Hatfield-Dodds
b5ec092525 Merge pull request #9149 from Vijay-Arora/main 2023-06-19 20:35:01 -07:00
Zac Hatfield-Dodds
5b35518389 Apply suggestions from code review
Co-authored-by: Ronnie Dutta <61982285+MetRonnie@users.noreply.github.com>
2023-06-19 20:06:21 -07:00
dependabot[bot]
8528052a95 build(deps): Bump peter-evans/create-pull-request from 5.0.0 to 5.0.2 (#11120)
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 5.0.0 to 5.0.2.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](5b4a9f6a9e...153407881e)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-19 19:22:49 -03:00
dependabot[bot]
1eb83706b6 build(deps): Bump pytest-mock in /testing/plugins_integration (#11119)
Bumps [pytest-mock](https://github.com/pytest-dev/pytest-mock) from 3.10.0 to 3.11.1.
- [Release notes](https://github.com/pytest-dev/pytest-mock/releases)
- [Changelog](https://github.com/pytest-dev/pytest-mock/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-mock/compare/v3.10.0...v3.11.1)

---
updated-dependencies:
- dependency-name: pytest-mock
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-19 04:15:50 +00:00
github-actions[bot]
fa09f6dcc6 [automated] Update plugin list (#11117)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-06-18 09:40:52 -03:00
Florian Bruhin
b55c02c3c9 doc: Add ep2023 training (#11113) 2023-06-15 14:17:14 +02:00
Ran Benita
bd88a6412d reference: separate node types to their own section
I think it's helpful to separate the node classes from the other
objects, as they have their own unique usage.

I've chosen not to alphabetize the order, but to use a logical order
instead.

Also slightly improve the docstrings.
2023-06-14 15:57:56 +03:00
Ran Benita
264e7ac327 reference: add doc for Package
We document the other py collectors, we should document `Package` as
well.
2023-06-14 09:51:37 +03:00
pre-commit-ci[bot]
b7a142f4ba [pre-commit.ci] pre-commit autoupdate (#11103)
updates:
- [github.com/asottile/pyupgrade: v3.4.0 → v3.6.0](https://github.com/asottile/pyupgrade/compare/v3.4.0...v3.6.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-06-13 05:36:28 +00:00
dependabot[bot]
2d824329eb build(deps): Bump django in /testing/plugins_integration (#11102)
Bumps [django](https://github.com/django/django) from 4.2.1 to 4.2.2.
- [Commits](https://github.com/django/django/compare/4.2.1...4.2.2)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-12 04:19:01 +00:00
Ran Benita
ecb23106d8 Merge pull request #11097 from bluetech/cherry-pick-release
Cherry-pick 7.3.2 release notes
2023-06-10 22:57:31 +03:00
Ran Benita
8174a30164 changelog: add note to norecursedir/pytest_ignore_collect change (#11095) 2023-06-10 19:34:59 +00:00
Ran Benita
0142bb6687 Merge pull request #11096 from pytest-dev/release-7.3.2
Prepare release 7.3.2

(cherry picked from commit 5dcd2be466)
2023-06-10 22:31:49 +03:00
Ran Benita
52cf700f1b Merge pull request #10894 from pytest-dev/py312-ci
Python 3.12 support
2023-06-10 20:46:02 +03:00
Ran Benita
6b3ece5bdb ci; use check-latest: true for -dev pythons
When testing -dev python versions, we want to always use the latest.
2023-06-09 11:29:15 +03:00
Ran Benita
4059000834 testing/python/collect: replace use of deprecated/removed imp module 2023-06-07 17:05:52 +03:00
Ran Benita
7d5207a736 Declare support for Python 3.12 2023-06-07 17:05:52 +03:00
Ran Benita
3e65a461c7 ci: start testing Python 3.12-dev 2023-06-07 17:05:52 +03:00
Ran Benita
fc3b5b2610 testing: install setuptools to fix pkg_resources import in a test
Since Python 3.12, setuptools is no longer installed by default in
venvs. We have a test which uses it, so add it to the testing extra.
2023-06-07 17:05:52 +03:00
Ran Benita
9335a0b445 Avoid ast deprecation warnings on Python 3.12
Fix #10977.
2023-06-07 17:05:52 +03:00
Ran Benita
0ded3297a9 Merge pull request #11086 from pytest-dev/update-plugin-list/patch-32de8e289
[automated] Update plugin list
2023-06-07 09:02:06 +03:00
pytest bot
fc9cbbd4c4 [automated] Update plugin list 2023-06-06 14:05:44 +00:00
Ran Benita
1a17539065 Merge pull request #10853 from stefmolin/patch-1
Update fixture scope in package/directory fixture example.
2023-06-06 17:04:45 +03:00
Ran Benita
32de8e2893 Merge pull request #11082 from bluetech/norecursedir-in-hook
main: move norecursedir check to main's pytest_ignore_collect
2023-06-06 12:44:03 +03:00
Ran Benita
5d4a342a7a Merge pull request #11076 from pytest-dev/update-plugin-list/patch-b5ff089d2
[automated] Update plugin list
2023-06-06 12:37:46 +03:00
Facundo Batista
1790f17228 Introduced a hardcoded list of project to include as plugins beyond those found by their names. (#11077) 2023-06-06 12:15:57 +03:00
pre-commit-ci[bot]
ee8baa2676 [pre-commit.ci] pre-commit autoupdate (#11084)
updates:
- [github.com/asottile/setup-cfg-fmt: v2.2.0 → v2.3.0](https://github.com/asottile/setup-cfg-fmt/compare/v2.2.0...v2.3.0)
2023-06-06 12:13:38 +03:00
Ran Benita
ae38b076da main: move norecursedir check to main's pytest_ignore_collect
Fix #11081
2023-06-05 17:21:45 +03:00
dependabot[bot]
85c5bd26b6 build(deps): Bump pytest-xvfb in /testing/plugins_integration (#11079)
Bumps [pytest-xvfb](https://github.com/The-Compiler/pytest-xvfb) from 2.0.0 to 3.0.0.
- [Changelog](https://github.com/The-Compiler/pytest-xvfb/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/The-Compiler/pytest-xvfb/compare/v2.0.0...v3.0.0)

---
updated-dependencies:
- dependency-name: pytest-xvfb
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-05 12:06:55 +02:00
Ran Benita
e1204e1e23 Merge pull request #11078 from bluetech/pkg-roots-path
main: change pkg_roots to work with `Path`s instead of string paths
2023-06-04 21:45:45 +03:00
Ran Benita
313b61471f main: change pkg_roots to work with Paths instead of string paths
- Works better on Windows (case sensitivity)
- Simpler code
2023-06-04 20:43:34 +03:00
pytest bot
1daa8129c6 [automated] Update plugin list 2023-06-04 00:26:58 +00:00
Ran Benita
b5ff089d2c Merge pull request #11069 from bluetech/lf-file
cacheprovider: make file-skipping work with any File, not just Modules
2023-06-03 18:50:50 +03:00
Ran Benita
fda8024622 cacheprovider: make file-skipping work with any File, not just Modules
No reason for `--lf`'s whole-file-skipping feature to not for for
non-Python files.

Fix #11068.
2023-06-03 09:32:26 +03:00
Ran Benita
4b823a42ce Merge pull request #11059 from bluetech/lf-skip-across
cacheprovider: fix file-skipping functionality across packages
2023-06-03 09:31:04 +03:00
Ran Benita
6c9b277ce4 Merge pull request #11070 from bluetech/pkg-redundant-methods
python: remove redundant methods from Package
2023-06-02 18:58:21 +03:00
Ran Benita
3de43e5102 python: remove redundant methods from Package
They are already inherited exactly the same from FSCollector.
2023-06-02 16:08:04 +03:00
Ran Benita
c76ae74bd7 cacheprovider: fix file-skipping functionality across packages
Continuation of fc538c5766.
Fixes #11054 again.
2023-05-30 23:16:43 +03:00
Ran Benita
24534cdd29 Merge pull request #11043 from bluetech/confcutdir-rootpath
config: fallback confcutdir to rootpath if inipath is not set
2023-05-30 20:21:20 +03:00
Ran Benita
99c78aa93a Merge pull request #10921 from bluetech/tb-simplify-2
Fix hidden traceback entries of chained exceptions getting shown
2023-05-30 20:09:13 +03:00
Ran Benita
3a6bdcd76b Merge pull request #11055 from bluetech/lf-skipped-package
cacheprovider: fix file-skipping feature for files in packages
2023-05-30 20:04:06 +03:00
Ran Benita
4a1bba25b9 config: fallback confcutdir to rootpath if inipath is not set
Currently, if `--confcutdir` is not set, `inipath.parent` is used, and
if `initpath` is not set, then `confcutdir` is None, which means there
is no cutoff.

Having no cutoff is not great, it means we potentially start probing
stuff all the way up to the filesystem root directory. So let's add
another fallback, to `rootpath`, which is always something reasonable.
2023-05-30 19:52:59 +03:00
Alessio Izzo
9e1add75f7 Fix warlus operator behavior when called by a function (#11041)
In #10758 we introduced the support for the use of the walrus operator in the test cases. There was a case which was not handled that caused a bug report #11028. This PR aims to fix the issue and also to improve how the walrus operator is handled in the AssertionRewriter class.

Closes #11028
2023-05-30 11:59:24 -03:00
theirix
4da9026766 Handle microseconds with custom logging.Formatter (#11047)
Added handling of %f directive to print microseconds in log format options, such as log-date-format. It is impossible to do with a standard logging.Formatter because it uses time.strftime which doesn't know about milliseconds and %f. In this PR I added a custom Formatter which converts LogRecord to a datetime.datetime object and formats it with %f flag. This behaviour is enabled only if a microsecond flag is specified in a format string.

Also added a few tests to check the standard and changed behavior.

Closes #10991
2023-05-30 09:35:33 -03:00
Kenny Y
7c231baa64 Add warning when testpaths is set but paths are not found by glob (#11044)
Closes #11013

---------

Co-authored-by: Ran Benita <ran@unusedvar.com>
2023-05-30 07:06:13 -03:00
Ran Benita
fc538c5766 cacheprovider: fix file-skipping feature for files in packages
`--lf` has a feature where if a certain `Module` (python file) does not
contain any failed tests, it is skipped entirely at the collector level
instead of being collected and each item skipped individually. When this
happens the collection summary looks like this:

    run-last-failure: rerun previous 1 failure (skipped 1 file)

However, this feature didn't work for `Module`s inside of `Package`s,
only for those directly beneath the `Session`.

Fix #11054.
2023-05-29 22:55:44 +03:00
dependabot[bot]
fbfd4b5005 build(deps): Bump anyio[curio,trio] in /testing/plugins_integration (#11050)
Bumps [anyio[curio,trio]](https://github.com/agronholm/anyio) from 3.6.2 to 3.7.0.
- [Changelog](https://github.com/agronholm/anyio/blob/3.7.0/docs/versionhistory.rst)
- [Commits](https://github.com/agronholm/anyio/compare/3.6.2...3.7.0)

---
updated-dependencies:
- dependency-name: anyio[curio,trio]
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-29 07:55:42 +02:00
dependabot[bot]
ec752537ea build(deps): Bump pytest-cov in /testing/plugins_integration (#11051)
Bumps [pytest-cov](https://github.com/pytest-dev/pytest-cov) from 4.0.0 to 4.1.0.
- [Changelog](https://github.com/pytest-dev/pytest-cov/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest-cov/compare/v4.0.0...v4.1.0)

---
updated-dependencies:
- dependency-name: pytest-cov
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-29 07:55:13 +02:00
Ran Benita
dd667336ce nodes: apply same traceback filtering for chained exceptions as main exception
Fix #1904.
2023-05-28 17:20:50 +03:00
Ran Benita
29d16d2939 Merge pull request #11046 from pytest-dev/update-plugin-list/patch-4f3f36c39
[automated] Update plugin list
2023-05-28 16:02:07 +03:00
pytest bot
5313d50e18 [automated] Update plugin list 2023-05-28 00:22:05 +00:00
Chris Mahoney
4f3f36c396 Add alias --config-file to -c (#11036)
Fixes #11031

Signed-off-by: Chris Mahoney <chrismahoey@hotmail.com>
Co-authored-by: Chris Mahoney <chrismahoey@hotmail.com>
2023-05-26 07:56:18 -03:00
Ran Benita
af124c7f21 Merge pull request #11026 from bluetech/small-fixes
Small fixes and improvements
2023-05-24 21:44:03 +03:00
Bruno Oliveira
4e6d53fef5 Merge pull request #11033 from jkeifer/patch-1
nonpython example now repr all exceptions
2023-05-24 08:10:42 -03:00
Jarrett Keifer
751d726d21 nonpython example now repr all exceptions
The definition of `repr_failure` on the `YamlItem` subclass only handled the custom `YamlException` class, which hides all other errors from the user. By adding in the `super` call we ensure all other exception types also appropriately handled by `repr_failure`.
2023-05-23 20:06:05 -07:00
github-actions[bot]
9e491f430e [automated] Update plugin list (#11027)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-05-21 10:47:02 -03:00
Ran Benita
63f258f432 python: fix syntax typo 2023-05-20 21:14:29 +03:00
Ran Benita
baaa67dfb9 python: simplify code in Package.collect()
The path of Package is already the `__init__.py` file, and we're already
assured it's a file.
2023-05-20 21:14:29 +03:00
Ran Benita
519f351b4f pathlib: extract scandir utility from visit
Will be used on its in some upcoming changes, but good on its own.
2023-05-20 21:14:29 +03:00
Ran Benita
5d53447a73 fixtures: use isinstance in get_scope_package
No reason for the exact type equality.
2023-05-20 21:13:48 +03:00
Ran Benita
1716d3c9bf fixtures: type annotate get_scope_package 2023-05-20 21:06:24 +03:00
Ran Benita
ac699e7b25 fixtures: add type annotations and docstring to parsefactories 2023-05-20 21:06:13 +03:00
Ran Benita
a5f37199a9 fixtures: inline FixtureRequest._addfinalizer
There are no longer any calls to `_addfinalizer` other than this one
place, so inline it.
2023-05-20 21:06:07 +03:00
Roberto Aldera
9fa82598a9 Use NamedTuple for pytest_report_teststatus return value (#10972)
Closes #10872

---------

Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-05-19 08:24:28 -03:00
Erik Hasse
a2feb6bd00 add a warning about modifying the root logger during tests 2023-05-18 09:26:16 -05:00
Alex Lambson
ba32a3bd87 Handle disabled logging in 'caplog.set_level' and 'caplog.at_level' (#8758)
Forces requested `caplog` logging levels to be enabled if they were disabled via `logging.disable()`

`[attr-defined]` mypy error ignored in `logging.py` because there were existing errors with the imports
and `loggin.Logger.manager` is an attr set at runtime. Since it's in the standard lib I can't really fix that.

Ignored an attr-defined error in `src/_pytest/config/__init__.py` because the re-export is necessary.

Fixes #8711
2023-05-18 10:18:59 -03:00
Ville Skyttä
c8641f879f Include reason in cache path warnings to aid debugging (#11005)
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-05-18 10:11:47 -03:00
Ville Skyttä
6041511fb4 Spelling and grammar fixes (#11014) 2023-05-18 10:10:44 -03:00
Ronny Pfannschmidt
739408b958 Merge pull request #11009 from nicoddemus/reference-status-of-python-versions
Reference "Status of Python Versions" in backwards-compatibility policy
2023-05-17 09:51:30 +02:00
Bruno Oliveira
1636322995 Reference "Status of Python Versions" in backwards-compatibility policy
As suggested in #10981.
2023-05-16 20:24:06 -03:00
pre-commit-ci[bot]
b8edacb8f1 [pre-commit.ci] pre-commit autoupdate (#11007)
updates:
- [github.com/pre-commit/mirrors-mypy: v1.2.0 → v1.3.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.2.0...v1.3.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-05-16 09:19:38 +02:00
github-actions[bot]
612489e2bd [automated] Update plugin list (#11001)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-05-15 08:26:41 -03:00
dependabot[bot]
383774db10 build(deps): Bump actions/stale from 5 to 8 (#11003)
Bumps [actions/stale](https://github.com/actions/stale) from 5 to 8.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v5...v8)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-15 07:29:18 +02:00
Adam J. Stewart
3b5b3cf50e monkeypatch: add support for TypedDict (#11000) 2023-05-14 22:17:00 +03:00
Bruno Oliveira
23e343af60 Fix close stale issues workflow (#10990)
Fixed how the label is configured.
2023-05-14 08:39:45 -03:00
Ronny Pfannschmidt
f9a995b56d Merge pull request #10998 from bluetech/pre-commit-rm-default
pre-commit: remove `default_language_version` setting
2023-05-13 23:27:48 +02:00
Ran Benita
d9d78a8aef pre-commit: remove default_language_version setting
This makes it difficult to run on newer python versions than the one
specified.
2023-05-13 22:24:30 +03:00
Bruno Oliveira
76d15231f5 Merge pull request #10988 from nicoddemus/initial-testpaths-10987
Consider testpaths for initial conftests
2023-05-12 09:58:59 -03:00
Bruno Oliveira
4cc05e7bee Fix trailing whitespace in .github/workflows/stale.yml 2023-05-12 09:34:44 -03:00
Bruno Oliveira
2d57d5c32f Do not break on very long command-line options
`_set_initial_conftests` could break on some systems if a very long
option was passed, because the `Path.exists()` call raises an
`OSError` instead of returning `False`.

Fix #10169
2023-05-12 09:34:15 -03:00
Bruno Oliveira
faeb16146b Consider testpaths for initial conftests
The 'testpaths' option is meant to be identical to execute
pytest passing the 'testpaths' directories explicitly.

Fix #10987
2023-05-12 09:34:15 -03:00
Bruno Oliveira
b241c0b479 Fix defaults for tmp_path_retention_count and tmp_path_retention_policy in docs 2023-05-12 09:34:15 -03:00
Bruno Oliveira
78403237cf Add workflow to close "needs information" labeled issues (#10986)
This introduces a workflow to automatically close issues with the label
`status: needs information` after a number of days of inactivity.

This work has been done manually for a number of years, but I think it is safe
to close issues with this label automatically.

Not tested yet, but it is in `debug-only` mode so we can watch what it does before
deciding to turn it on (however it needs to be in `main` for it to run).
2023-05-11 15:14:50 -03:00
leeyueh
f84fea0888 Update usage.rst (#10974)
Added a note for single quotation used in Windows.
2023-05-10 22:28:52 -03:00
Ran Benita
271bdf6c23 Merge pull request #10979 from bluetech/faulthandler-no-encoding
faulthandler: avoid accessing sys.stderr.encoding
2023-05-10 14:17:54 +03:00
Ran Benita
fd56968f2b Merge pull request #10970 from pytest-dev/dependabot/pip/testing/plugins_integration/django-4.2.1
build(deps): Bump django from 4.2 to 4.2.1 in /testing/plugins_integration
2023-05-10 10:18:17 +03:00
Ran Benita
5b75b0d03f Merge pull request #10978 from bzoracler/fix-pytest-code-import
fix reference to non-existent module
2023-05-10 10:15:20 +03:00
Ran Benita
aac5d5d08b faulthandler: avoid accessing sys.stderr.encoding
Fixes a pytest-xdist regression after
762bb61562 (not yet released).

pytest-xdist patches sys.stderr with an object which doesn't have
`encoding`. Strictly speaking, this should be fixed there (or more
precisely, in execnet), but it will drop support for older versions
which don't want.

But in any case, the fix turns out to simplify the code, using FD
support added in Python 3.5, so it's good anyway!

Refs: https://github.com/pytest-dev/pytest-xdist/pull/900
2023-05-10 09:59:57 +03:00
bzoracler
b1460f3261 fix reference to non-existent module 2023-05-10 10:48:20 +12:00
github-actions[bot]
a88ae8289c [automated] Update plugin list (#10968)
Co-authored-by: pytest bot <pytestbot@users.noreply.github.com>
2023-05-09 19:05:13 -03:00
pre-commit-ci[bot]
62320e4ff7 [pre-commit.ci] pre-commit autoupdate (#10975)
updates:
- https://github.com/asottile/reorder_python_importshttps://github.com/asottile/reorder-python-imports
- [github.com/asottile/pyupgrade: v3.3.2 → v3.4.0](https://github.com/asottile/pyupgrade/compare/v3.3.2...v3.4.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-05-09 11:22:50 +02:00
dependabot[bot]
6514041a35 build(deps): Bump django in /testing/plugins_integration
Bumps [django](https://github.com/django/django) from 4.2 to 4.2.1.
- [Commits](https://github.com/django/django/compare/4.2...4.2.1)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-08 03:56:49 +00:00
Brian Larsen
7d548c38e2 Improve verbose output by wrapping skip/xfail reasons with margin (#10958)
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2023-05-06 12:15:11 -03:00
Bruno Oliveira
07eeeb8dfc Merge pull request #10957 from pytest-dev/update-plugin-list/patch-762bb6156
[automated] Update plugin list
2023-05-02 10:02:58 -04:00
pytest bot
be774667c2 [automated] Update plugin list 2023-04-30 00:23:40 +00:00
Ran Benita
762bb61562 Fix couple of EncodingWarnings (#10954)
* faulthandler: fix an EncodingWarning

* _py/path: tiny change to `ensure` to silence EncodingWarning

We're not supposed to diverge here, but make this change to fix an
unavoidable EncodingWarning that is otherwise raised in pytest's test
suite. The behavior should be exactly the same besides the warning,
hopefully that won't cause confusion.
2023-04-29 11:37:22 +03:00
Sergey Kim
725de3a0d3 add flake8-pytest-style mention to goodpractices (#10939) 2023-04-28 23:47:47 +03:00
Ran Benita
fcada1ea47 nodes: change _prunetraceback to return the new traceback instead of modifying excinfo
This makes it usable as a general function, and just more understandable
in general.
2023-04-28 11:47:45 +03:00
Ran Benita
6f7f89f3c4 code: make TracebackEntry immutable
TracebackEntry being mutable caught me by surprise and makes reasoning
about the exception formatting code harder. Make it a proper value.
2023-04-28 11:47:45 +03:00
Ran Benita
0a20452f78 code: inline Traceback.getcrashentry into ExceptionInfo._getreprcrash
Since `Traceback.getcrashentry` takes the `ExceptionInfo`, it is not
really independent of it and is in the wrong layer. Prevent nonsensical
mistakes by inlining it.
2023-04-28 11:47:45 +03:00
Ran Benita
cc23ec91d0 code: stop storing weakref to ExceptionInfo on Traceback and TracebackEntry
TracebackEntry needs the excinfo for the `__tracebackhide__ = callback`
functionality, where `callback` accepts the excinfo.

Currently it achieves this by storing a weakref to the excinfo which
created it. I think this is not great, mixing layers and bloating the
objects.

Instead, have `ishidden` (and transitively, `Traceback.filter()`) take
the excinfo as a parameter.
2023-04-28 11:47:45 +03:00
Florian Bruhin
a15f544962 doc: Fix 2024 training location (#10947) 2023-04-26 08:13:06 +02:00
pre-commit-ci[bot]
3823ce60dd [pre-commit.ci] pre-commit autoupdate (#10941)
updates:
- [github.com/PyCQA/autoflake: v2.1.0 → v2.1.1](https://github.com/PyCQA/autoflake/compare/v2.1.0...v2.1.1)
- [github.com/asottile/pyupgrade: v3.3.1 → v3.3.2](https://github.com/asottile/pyupgrade/compare/v3.3.1...v3.3.2)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-04-25 10:52:15 +02:00
Miro Hrončok
e03f82c359 Filter new pkg_resources deprecations (#10938)
Fixes https://github.com/pytest-dev/pytest/issues/10815
2023-04-25 10:51:10 +02:00
Bryan Ricker
158f41fdf8 Fix documentation typo (#10942) 2023-04-25 10:49:16 +02:00
Bruno Oliveira
fd6a4507ac Merge pull request #10936 from pytest-dev/update-plugin-list/patch-0860f4e91
[automated] Update plugin list
2023-04-22 22:42:05 -03:00
pytest bot
15156757b6 [automated] Update plugin list 2023-04-23 00:21:26 +00:00
Florian Bruhin
0860f4e916 Add 2024 pytest training (#10933) 2023-04-22 21:22:25 +02:00
Ran Benita
11965d1c27 Merge pull request #10920 from bluetech/testing-no-testdir
testing: remove usages of testdir that sneaked back in
2023-04-18 22:49:23 +03:00
pre-commit-ci[bot]
14be71b234 [pre-commit.ci] pre-commit autoupdate (#10926)
updates:
- [github.com/PyCQA/autoflake: v2.0.2 → v2.1.0](https://github.com/PyCQA/autoflake/compare/v2.0.2...v2.1.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-04-18 07:03:27 +02:00
dependabot[bot]
2d6206b89a build(deps): Bump pytest-sugar in /testing/plugins_integration (#10922)
Bumps [pytest-sugar](https://github.com/Teemu/pytest-sugar) from 0.9.5 to 0.9.7.
- [Release notes](https://github.com/Teemu/pytest-sugar/releases)
- [Changelog](https://github.com/Teemu/pytest-sugar/blob/main/CHANGES.rst)
- [Commits](https://github.com/Teemu/pytest-sugar/commits/v0.9.7)

---
updated-dependencies:
- dependency-name: pytest-sugar
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-17 08:55:36 +02:00
Alex
41f57ef95d Fix pytrace=False and --tb=line reports None (#10905)
Closes #10831.

This fixes a small bug where running tests that contained
`pytest.fail(pytrace=False)` with the `--tb=line` flag set results in
 an output of "None" in the Failures section of the output, and adds
 a test to ensure the behavior is correct.
2023-04-16 20:31:45 +00:00
Ran Benita
4eca6063c8 Merge pull request #10918 from pytest-dev/update-plugin-list/patch-7834b3b07
[automated] Update plugin list
2023-04-16 19:40:51 +03:00
Ran Benita
819f5abd73 testing: remove usages of testdir that sneaked back in 2023-04-16 19:18:50 +03:00
Ran Benita
adf891ab1d Merge pull request #10919 from bluetech/missing-changelog
doc: add missing changelog for #10907
2023-04-16 18:41:45 +03:00
Ran Benita
f08184ba20 doc: add missing changelog for #10907 2023-04-16 18:22:51 +03:00
pytest bot
28783e5d23 [automated] Update plugin list 2023-04-16 00:21:39 +00:00
Bruno Oliveira
7834b3b07f Merge pull request #10914 from nicoddemus/cherry-pick-release-7.3.1
Merge pull request #10913 from pytest-dev/release-7.3.1
2023-04-14 15:19:13 -03:00
Bruno Oliveira
ece756fcb4 Merge pull request #10913 from pytest-dev/release-7.3.1
Prepare release 7.3.1

(cherry picked from commit a1f7a204df)
2023-04-14 15:15:28 -03:00
Bruno Oliveira
d380771065 Fix tmp_path regression introduced in 7.3.0 (#10911)
The problem is that we would loop over all directories of the basetemp directory searching for dead symlinks, for each test, which would compound over the test session run.

Doing the cleanup just once, at the end of the session, fixes the problem.

Fix #10896
2023-04-14 13:24:12 -03:00
Ran Benita
b893d2a0fe Merge pull request #10907 from bluetech/empty-traceback
code: handle repr'ing empty tracebacks gracefully
2023-04-13 19:36:09 +03:00
Ran Benita
e3b1799766 code: handle repr'ing empty tracebacks gracefully
By "empty traceback" I mean a traceback all of whose entries have been
filtered/cut/pruned out.

Currently, if an empty traceback needs to be repr'ed, the last entry
before the filtering is used instead (added in
accd962c9f).

Showing a hidden frame is not so good IMO. This commit does the
following instead:

1. Shows details of the exception.
2. Shows a message about how the full trace can be seen.

Example:

```
_____________ test _____________

E   ZeroDivisionError: division by zero
All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames.
```

Also handles `--tb=native`, though there the `--full-trace` bit is not
shown.

This commit contains some pieces from
431ec6d34e (which has been reverted).

Helps towards fixing issue # 1904.

Co-authored-by: Felix Hofstätter <Felhof1@hotmail.com>
2023-04-13 19:11:37 +03:00
Ran Benita
5d1385320f Merge pull request #10901 from bluetech/exceptioninfo-from-exception
code: add `ExceptionInfo.from_exception`
2023-04-13 16:04:48 +03:00
Ran Benita
eff54aece1 Merge pull request #10904 from bluetech/revert-10772
Revert "Correctly handle tracebackhide for chained exceptions (#10772)"
2023-04-13 14:51:57 +03:00
Ran Benita
bc1fc3f0fc Merge branch 'main' into exceptioninfo-from-exception 2023-04-13 14:51:07 +03:00
Ran Benita
784ffa0fad Merge pull request #10900 from bluetech/exceptioninfo-from_exc_info-exp
code: drop Experimental API label from ExceptionInfo.from_exc_info
2023-04-13 14:48:56 +03:00
Ran Benita
90412827c3 Revert "Correctly handle tracebackhide for chained exceptions (#10772)"
This reverts commit 431ec6d34e.

Fix #10903.
Reopen #1904.
2023-04-12 19:23:25 +03:00
Ran Benita
424c3eebde code: add ExceptionInfo.from_exception
The old-style `sys.exc_info()` triplet is redundant nowadays with
`(type(exc), exc, exc.__traceback__)`, and is beginning to get
soft-deprecated in Python 3.12.

Add a nicer API to ExceptionInfo which takes just the exc instead of the
triplet. There are already a few internal uses which benefit.
2023-04-12 13:16:48 +03:00
Ran Benita
9c2247ec1b code: drop Experimental API label from ExceptionInfo.from_exc_info
This API is OK, I don't think we're going to change something about it
at this point.
2023-04-12 12:46:29 +03:00
Ran Benita
61f7c27ec0 Merge pull request #10893 from bluetech/py312
Python 3.12 alpha fixes
2023-04-11 23:54:47 +03:00
Ran Benita
1b81d636e2 unittest: add addDuration function for Python 3.12 support
Fix #10875

Without this, fails with

```
...
E           AttributeError: 'TestCaseFunction' object has no attribute 'addDuration'
...
E           RuntimeWarning: TestResult has no addDuration method
```
2023-04-11 13:24:32 +03:00
Ran Benita
1b196fbeaf pathlib: fix Python 3.12 rmtree(onerror=...) deprecation
Fixes #10890
Ref: https://docs.python.org/3.12/library/shutil.html#shutil.rmtree
2023-04-11 13:24:32 +03:00
pre-commit-ci[bot]
22524046cf [pre-commit.ci] pre-commit autoupdate (#10891)
updates:
- [github.com/pre-commit/mirrors-mypy: v1.1.1 → v1.2.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.1.1...v1.2.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-04-11 07:08:45 +02:00
Bruno Oliveira
6dcd652d4a Amend changelog note for removal of attrs (#10888)
As discussed in https://github.com/pytest-dev/pytest/pull/10669#issuecomment-1501497729, we should
make the reasoning behind this change more clear, as well as thank the attrs maintainers for the
many years of cooperation and support.

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
2023-04-10 13:04:02 -03:00
dependabot[bot]
be9faa68d8 build(deps): Bump peter-evans/create-pull-request from 4.2.4 to 5.0.0 (#10887)
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 4.2.4 to 5.0.0.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](38e0b6e68b...5b4a9f6a9e)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-10 08:25:35 -03:00
dependabot[bot]
e4e13dd913 build(deps): Bump django in /testing/plugins_integration (#10886)
Bumps [django](https://github.com/django/django) from 4.1.7 to 4.2.
- [Release notes](https://github.com/django/django/releases)
- [Commits](https://github.com/django/django/compare/4.1.7...4.2)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-10 08:21:27 -03:00
Ran Benita
5a399030c1 Merge pull request #10884 from pytest-dev/update-plugin-list/patch-ec8e23951
[automated] Update plugin list
2023-04-09 11:11:02 +03:00
Ran Benita
19c8ef63a4 Merge pull request #10880 from bluetech/regen-rm-dataclasses-dep
tox: remove `dataclasses` dependency from `regen`
2023-04-09 10:46:11 +03:00
pytest bot
22951bba67 [automated] Update plugin list 2023-04-09 00:22:30 +00:00
Ran Benita
ec8e23951d Merge pull request #10883 from bluetech/cherry-pick-release
Cherry pick 7.3.0 release notes
2023-04-09 00:53:52 +03:00
Ran Benita
bf47357511 Merge pull request #10881 from pytest-dev/release-7.3.0
Prepare release 7.3.0

(cherry picked from commit cec5bfe058)
2023-04-09 00:50:37 +03:00
Ran Benita
2d2dc4a2a8 tox: remove dataclasses dependency from regen
This dep is not needed on newer Pythons.
2023-04-09 00:18:07 +03:00
Stefanie Molin
f1c7585184 Update fixture scope in package/directory fixture example. 2023-03-31 10:00:45 -07:00
Thomas Grainger
246ceb84bd Update doc/en/deprecations.rst 2022-10-10 13:58:05 +01:00
Thomas Grainger
2fd160110c Merge branch 'main' into warn-when-a-mark-is-applied-to-a-fixture 2022-10-10 13:55:24 +01:00
Thomas Grainger
2998b596b4 Merge remote-tracking branch 'graingert/warn-when-a-mark-is-applied-to-a-fixture' into warn-when-a-mark-is-applied-to-a-fixture 2022-10-10 13:53:51 +01:00
Thomas Grainger
7f73722c4a add a test for fixture between mark decorators 2022-10-10 13:52:26 +01:00
Thomas Grainger
f7542f6292 move tests into deprecated_test, and test for number of warnings issued 2022-10-10 13:48:26 +01:00
pre-commit-ci[bot]
0de2aa93f0 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2022-10-10 11:30:13 +00:00
Thomas Grainger
7759a9d3c2 Update src/_pytest/deprecated.py
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2022-10-10 12:28:30 +01:00
Thomas Grainger
d86df89a92 Update doc/en/deprecations.rst
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2022-10-10 12:28:22 +01:00
Thomas Grainger
24fd292878 Update changelog/3664.deprecation.rst
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2022-10-10 12:28:14 +01:00
Thomas Grainger
a1b10b552a use getfixturemarker 2022-10-09 20:25:48 +01:00
pre-commit-ci[bot]
aa9cc7e8b4 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2022-10-09 19:11:57 +00:00
Thomas Grainger
5c286d19d8 Update doc/en/deprecations.rst 2022-10-09 20:11:51 +01:00
Thomas Grainger
faac197fcf Merge branch 'main' into warn-when-a-mark-is-applied-to-a-fixture 2022-10-09 20:10:53 +01:00
pre-commit-ci[bot]
bb6155adfa [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2021-10-01 16:07:39 +00:00
Vijay Arora
5fefd7de96 Updated indentation and spaces in logging.py for #9146 2021-10-01 21:36:35 +05:30
Vijay Arora
750ce30392 Update 9146.doc.rst 2021-10-01 21:33:32 +05:30
pre-commit-ci[bot]
de1f378b60 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2021-10-01 14:53:26 +00:00
Vijay Arora
14d5b4ca6c Merge pull request #2 from Vijay-Arora/Vijay-Arora-patch-1
Updated AUTHORS and added changelog file
2021-10-01 20:19:23 +05:30
Vijay Arora
307dbf15c4 Add Myself as Authors 2021-10-01 20:16:10 +05:30
Vijay Arora
a8697601ad Create 9146.doc.rst
Create 9146.doc.rst
2021-10-01 20:10:46 +05:30
Vijay Arora
0ed1b0ac12 Merge pull request #1 from Vijay-Arora/Vijay-Arora-patch-1
Updated logging.py for #9146
2021-10-01 20:04:51 +05:30
Vijay Arora
26b0702b98 Updated logging.py
Updated logging.py for #9146
2021-10-01 19:34:59 +05:30
Thomas Grainger
5227279c15 Update changelog/3664.deprecation.rst 2021-03-19 09:47:19 +00:00
Thomas Grainger
a7e0ae2455 update MARKED_FIXTURE deprecation message 2021-03-19 09:44:39 +00:00
Thomas Grainger
12efc58479 document deprecation in deprecations.rst 2021-03-19 09:43:22 +00:00
Thomas Grainger
3f71680ac0 Warn when a mark is applied to a fixture
Fixes #3664
2021-03-19 09:30:52 +00:00
326 changed files with 18189 additions and 9182 deletions

View File

@@ -23,6 +23,11 @@ afc607cfd81458d4e4f3b1f3cf8cc931b933907e
5f95dce95602921a70bfbc7d8de2f7712c5e4505
# ran pyupgrade-docs again
75d0b899bbb56d6849e9d69d83a9426ed3f43f8b
# move argument parser to own file
c9df77cbd6a365dcb73c39618e4842711817e871
# Replace reorder-python-imports by isort due to black incompatibility (#11896)
8b54596639f41dfac070030ef20394b9001fe63c
# Run blacken-docs with black's 2024's style
4546d5445aaefe6a03957db028c263521dfb5c4b
# Migration to ruff / ruff format
4588653b2497ed25976b7aaff225b889fb476756

View File

@@ -22,7 +22,7 @@ jobs:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: true

View File

@@ -1,60 +1,101 @@
name: deploy
on:
push:
tags:
# These tags are protected, see:
# https://github.com/pytest-dev/pytest/settings/tag_protection
- "[0-9]+.[0-9]+.[0-9]+"
- "[0-9]+.[0-9]+.[0-9]+rc[0-9]+"
workflow_dispatch:
inputs:
version:
description: 'Release version'
required: true
default: '1.2.3'
# Set permissions at the job level.
permissions: {}
jobs:
deploy:
if: github.repository == 'pytest-dev/pytest'
package:
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: write
env:
SETUPTOOLS_SCM_PRETEND_VERSION: ${{ github.event.inputs.version }}
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Build and Check Package
uses: hynek/build-and-inspect-python-package@v1.5
uses: hynek/build-and-inspect-python-package@v2.0.1
deploy:
if: github.repository == 'pytest-dev/pytest'
needs: [package]
runs-on: ubuntu-latest
environment: deploy
timeout-minutes: 30
permissions:
id-token: write
contents: write
steps:
- uses: actions/checkout@v4
- name: Download Package
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: Packages
path: dist
- name: Publish package to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
uses: pypa/gh-action-pypi-publish@v1.8.11
- name: Push tag
run: |
git config user.name "pytest bot"
git config user.email "pytestbot@gmail.com"
git tag --annotate --message=v${{ github.event.inputs.version }} ${{ github.event.inputs.version }} ${{ github.sha }}
git push origin ${{ github.event.inputs.version }}
release-notes:
# todo: generate the content in the build job
# the goal being of using a github action script to push the release data
# after success instead of creating a complete python/tox env
needs: [deploy]
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
password: ${{ secrets.pypi_token }}
fetch-depth: 0
persist-credentials: false
- name: Download Package
uses: actions/download-artifact@v4
with:
name: Packages
path: dist
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.7"
python-version: "3.11"
- name: Install tox
run: |
python -m pip install --upgrade pip
pip install --upgrade tox
- name: Publish GitHub release notes
env:
GH_RELEASE_NOTES_TOKEN: ${{ github.token }}
- name: Generate release notes
run: |
sudo apt-get install pandoc
tox -e publish-gh-release-notes
tox -e generate-gh-release-notes -- ${{ github.event.inputs.version }} scripts/latest-release-notes.md
- name: Publish GitHub Release
uses: softprops/action-gh-release@v1
with:
body_path: scripts/latest-release-notes.md
files: dist/*
tag_name: ${{ github.event.inputs.version }}

View File

@@ -27,12 +27,12 @@ jobs:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.8"

23
.github/workflows/stale.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
name: close needs-information issues
on:
schedule:
- cron: "30 1 * * *"
workflow_dispatch:
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: actions/stale@v9
with:
debug-only: false
days-before-issue-stale: 14
days-before-issue-close: 7
only-labels: "status: needs information"
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for 14 days with no activity."
close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
days-before-pr-stale: -1
days-before-pr-close: -1

View File

@@ -27,7 +27,19 @@ concurrency:
permissions: {}
jobs:
package:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Build and Check Package
uses: hynek/build-and-inspect-python-package@v2.0.1
build:
needs: [package]
runs-on: ${{ matrix.os }}
timeout-minutes: 45
permissions:
@@ -37,46 +49,41 @@ jobs:
fail-fast: false
matrix:
name: [
"windows-py37",
"windows-py37-pluggy",
"windows-py38",
"windows-py38-pluggy",
"windows-py39",
"windows-py310",
"windows-py311",
"windows-py312",
"ubuntu-py37",
"ubuntu-py37-pluggy",
"ubuntu-py37-freeze",
"ubuntu-py38",
"ubuntu-py38-pluggy",
"ubuntu-py38-freeze",
"ubuntu-py39",
"ubuntu-py310",
"ubuntu-py311",
"ubuntu-py312",
"ubuntu-pypy3",
"macos-py37",
"macos-py38",
"macos-py39",
"macos-py310",
"macos-py312",
"docs",
"doctesting",
"plugins",
]
include:
- name: "windows-py37"
python: "3.7"
os: windows-latest
tox_env: "py37-numpy"
- name: "windows-py37-pluggy"
python: "3.7"
os: windows-latest
tox_env: "py37-pluggymain-pylib-xdist"
- name: "windows-py38"
python: "3.8"
os: windows-latest
tox_env: "py38-unittestextras"
use_coverage: true
- name: "windows-py38-pluggy"
python: "3.8"
os: windows-latest
tox_env: "py38-pluggymain-pylib-xdist"
- name: "windows-py39"
python: "3.9"
os: windows-latest
@@ -86,27 +93,27 @@ jobs:
os: windows-latest
tox_env: "py310-xdist"
- name: "windows-py311"
python: "3.11-dev"
python: "3.11"
os: windows-latest
tox_env: "py311"
- name: "windows-py312"
python: "3.12-dev"
os: windows-latest
tox_env: "py312"
- name: "ubuntu-py37"
python: "3.7"
os: ubuntu-latest
tox_env: "py37-lsof-numpy-pexpect"
use_coverage: true
- name: "ubuntu-py37-pluggy"
python: "3.7"
os: ubuntu-latest
tox_env: "py37-pluggymain-pylib-xdist"
- name: "ubuntu-py37-freeze"
python: "3.7"
os: ubuntu-latest
tox_env: "py37-freeze"
- name: "ubuntu-py38"
python: "3.8"
os: ubuntu-latest
tox_env: "py38-xdist"
tox_env: "py38-lsof-numpy-pexpect"
use_coverage: true
- name: "ubuntu-py38-pluggy"
python: "3.8"
os: ubuntu-latest
tox_env: "py38-pluggymain-pylib-xdist"
- name: "ubuntu-py38-freeze"
python: "3.8"
os: ubuntu-latest
tox_env: "py38-freeze"
- name: "ubuntu-py39"
python: "3.9"
os: ubuntu-latest
@@ -116,58 +123,66 @@ jobs:
os: ubuntu-latest
tox_env: "py310-xdist"
- name: "ubuntu-py311"
python: "3.11-dev"
python: "3.11"
os: ubuntu-latest
tox_env: "py311"
use_coverage: true
- name: "ubuntu-py312"
python: "3.12-dev"
os: ubuntu-latest
tox_env: "py312"
use_coverage: true
- name: "ubuntu-pypy3"
python: "pypy-3.7"
python: "pypy-3.8"
os: ubuntu-latest
tox_env: "pypy3-xdist"
- name: "macos-py37"
python: "3.7"
os: macos-latest
tox_env: "py37-xdist"
- name: "macos-py38"
python: "3.8"
os: macos-latest
tox_env: "py38-xdist"
use_coverage: true
- name: "macos-py39"
python: "3.9"
os: macos-latest
tox_env: "py39-xdist"
use_coverage: true
- name: "macos-py310"
python: "3.10"
os: macos-latest
tox_env: "py310-xdist"
- name: "macos-py312"
python: "3.12-dev"
os: macos-latest
tox_env: "py312-xdist"
- name: "plugins"
python: "3.9"
python: "3.12"
os: ubuntu-latest
tox_env: "plugins"
- name: "docs"
python: "3.7"
os: ubuntu-latest
tox_env: "docs"
- name: "doctesting"
python: "3.7"
python: "3.8"
os: ubuntu-latest
tox_env: "doctesting"
use_coverage: true
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Download Package
uses: actions/download-artifact@v4
with:
name: Packages
path: dist
- name: Set up Python ${{ matrix.python }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
check-latest: ${{ endsWith(matrix.python, '-dev') }}
- name: Install dependencies
run: |
@@ -176,11 +191,13 @@ jobs:
- name: Test without coverage
if: "! matrix.use_coverage"
run: "tox -e ${{ matrix.tox_env }}"
shell: bash
run: tox run -e ${{ matrix.tox_env }} --installpkg `find dist/*.tar.gz`
- name: Test with coverage
if: "matrix.use_coverage"
run: "tox -e ${{ matrix.tox_env }}-coverage"
shell: bash
run: tox run -e ${{ matrix.tox_env }}-coverage --installpkg `find dist/*.tar.gz`
- name: Generate coverage report
if: "matrix.use_coverage"
@@ -188,16 +205,9 @@ jobs:
- name: Upload coverage to Codecov
if: "matrix.use_coverage"
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
continue-on-error: true
with:
fail_ci_if_error: true
files: ./coverage.xml
verbose: true
check-package:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build and Check Package
uses: hynek/build-and-inspect-python-package@v1.5

View File

@@ -20,25 +20,33 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: 3.8
python-version: "3.11"
cache: pip
- name: requests-cache
uses: actions/cache@v4
with:
path: ~/.cache/pytest-plugin-list/
key: plugins-http-cache-${{ github.run_id }} # Can use time based key as well
restore-keys: plugins-http-cache-
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install packaging requests tabulate[widechars] tqdm
pip install packaging requests tabulate[widechars] tqdm requests-cache platformdirs
- name: Update Plugin List
run: python scripts/update-plugin-list.py
- name: Create Pull Request
uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54
uses: peter-evans/create-pull-request@b1ddad2c994a25fbc81a28b3ec0e368bb2021c50
with:
commit-message: '[automated] Update plugin list'
author: 'pytest bot <pytestbot@users.noreply.github.com>'

View File

@@ -1,18 +1,12 @@
default_language_version:
python: "3.10"
repos:
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
args: [--safe, --quiet]
- repo: https://github.com/asottile/blacken-docs
rev: 1.13.0
hooks:
- id: blacken-docs
additional_dependencies: [black==23.1.0]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.2.2"
hooks:
- id: ruff
args: ["--fix"]
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@@ -22,56 +16,38 @@ repos:
- id: debug-statements
exclude: _pytest/(debugging|hookspec).py
language_version: python3
- repo: https://github.com/PyCQA/autoflake
rev: v2.0.2
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0
hooks:
- id: autoflake
name: autoflake
args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports"]
language: python
files: \.py$
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
language_version: python3
additional_dependencies:
- flake8-typing-imports==1.12.0
- flake8-docstrings==1.5.0
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.9.0
hooks:
- id: reorder-python-imports
args: ['--application-directories=.:src', --py37-plus]
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/asottile/setup-cfg-fmt
rev: v2.2.0
hooks:
- id: setup-cfg-fmt
args: ["--max-py-version=3.11", "--include-version-classifiers"]
- id: blacken-docs
additional_dependencies: [black==24.1.1]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.1.1
rev: v1.8.0
hooks:
- id: mypy
files: ^(src/|testing/)
files: ^(src/|testing/|scripts/)
args: []
additional_dependencies:
- iniconfig>=1.1.0
- attrs>=19.2.0
- pluggy>=1.4.0
- packaging
- tomli
- types-pkg_resources
- types-tabulate
# for mypy running on python>=3.11 since exceptiongroup is only a dependency
# on <3.11
- exceptiongroup>=1.0.0rc8
- repo: https://github.com/tox-dev/pyproject-fmt
rev: "1.7.0"
hooks:
- id: pyproject-fmt
# https://pyproject-fmt.readthedocs.io/en/latest/#calculating-max-supported-python-version
additional_dependencies: ["tox>=4.9"]
- repo: local
hooks:
- id: rst

View File

@@ -9,6 +9,10 @@ python:
path: .
- requirements: doc/en/requirements.txt
sphinx:
configuration: doc/en/conf.py
fail_on_warning: true
build:
os: ubuntu-20.04
tools:

46
AUTHORS
View File

@@ -8,11 +8,15 @@ Abdeali JK
Abdelrahman Elbehery
Abhijeet Kasurde
Adam Johnson
Adam Stewart
Adam Uhlir
Ahn Ki-Wook
Akhilesh Ramakrishnan
Akiomi Kamakura
Alan Velasco
Alessio Izzo
Alex Jones
Alex Lambson
Alexander Johnson
Alexander King
Alexei Kozlenok
@@ -44,17 +48,23 @@ Ariel Pillemer
Armin Rigo
Aron Coyle
Aron Curzon
Arthur Richard
Ashish Kurmi
Aviral Verma
Aviv Palivoda
Babak Keyvani
Barney Gale
Ben Brown
Ben Gartner
Ben Leith
Ben Webb
Benjamin Peterson
Benjamin Schubert
Bernard Pratz
Bo Wu
Bob Ippolito
Brian Dorsey
Brian Larsen
Brian Maissy
Brian Okken
Brianna Laugher
@@ -68,6 +78,7 @@ Charles Cloud
Charles Machalow
Charnjit SiNGH (CCSJ)
Cheuk Ting Ho
Chris Mahoney
Chris Lamb
Chris NeJame
Chris Rose
@@ -83,6 +94,7 @@ Christopher Dignam
Christopher Gilling
Claire Cecil
Claudio Madotto
Clément M.T. Robert
CrazyMerlyn
Cristian Vera
Cyrus Maden
@@ -116,6 +128,8 @@ Edison Gustavo Muenz
Edoardo Batini
Edson Tadeu M. Manoel
Eduardo Schettino
Edward Haigh
Eero Vaher
Eli Boyarski
Elizaveta Shashkova
Éloi Rivard
@@ -124,16 +138,21 @@ Eric Hunsberger
Eric Liu
Eric Siegerman
Erik Aronesty
Erik Hasse
Erik M. Bray
Evan Kepner
Evgeny Seliverstov
Fabian Sturm
Fabien Zarifian
Fabio Zadrozny
faph
Felix Hofstätter
Felix Nieuwenhuizen
Feng Ma
Florian Bruhin
Florian Dahlitz
Floris Bruynooghe
Fraser Stark
Gabriel Landau
Gabriel Reis
Garvit Shubham
@@ -160,6 +179,8 @@ Ian Bicking
Ian Lesperance
Ilya Konstantinov
Ionuț Turturică
Isaac Virshup
Israel Fruchter
Itxaso Aizpurua
Iwan Briquemont
Jaap Broekhuizen
@@ -175,6 +196,7 @@ Javier Romero
Jeff Rackauckas
Jeff Widman
Jenni Rinker
Jens Tröger
John Eddie Ayson
John Litborn
John Towler
@@ -192,6 +214,7 @@ Justice Ndou
Justyna Janczyszyn
Kale Kundert
Kamran Ahmad
Kenny Y
Karl O. Pinc
Karthikeyan Singaravelan
Katarzyna Jachim
@@ -222,9 +245,11 @@ Maho
Maik Figura
Mandeep Bhutani
Manuel Krebber
Marc Mueller
Marc Schlaich
Marcelo Duarte Trevisani
Marcin Bachry
Marc Bresson
Marco Gorelli
Mark Abramowitz
Mark Dickinson
@@ -249,15 +274,20 @@ Michael Goerz
Michael Krebs
Michael Seifert
Michal Wajszczuk
Michał Górny
Michał Zięba
Mickey Pashov
Mihai Capotă
Mihail Milushev
Mike Hoyle (hoylemd)
Mike Lundy
Milan Lesnek
Miro Hrončok
mrbean-bremen
Nathaniel Compton
Nathaniel Waisbrot
Ned Batchelder
Neil Martin
Neven Mundar
Nicholas Devenish
Nicholas Murphy
@@ -275,6 +305,7 @@ Ondřej Súkup
Oscar Benjamin
Parth Patel
Patrick Hayes
Patrick Lannigan
Paul Müller
Paul Reece
Pauli Virtanen
@@ -303,7 +334,9 @@ Raphael Pierzina
Rafal Semik
Raquel Alegre
Ravi Chandra
Reagan Lee
Robert Holt
Roberto Aldera
Roberto Polli
Roland Puntaier
Romain Dorgueil
@@ -312,25 +345,33 @@ Ronny Pfannschmidt
Ross Lawley
Ruaridh Williamson
Russel Winder
Russell Martin
Ryan Puddephatt
Ryan Wooden
Sadra Barikbin
Saiprasad Kale
Samuel Colvin
Samuel Dion-Girardeau
Samuel Searles-Bryant
Samuel Therrien (Avasam)
Samuele Pedroni
Sanket Duthade
Sankt Petersbug
Saravanan Padmanaban
Sean Malloy
Segev Finer
Serhii Mozghovyi
Seth Junot
Shantanu Jain
Sharad Nair
Shubham Adep
Simon Blanchard
Simon Gomizelj
Simon Holesch
Simon Kerr
Skylar Downes
Srinivas Reddy Thatiparthy
Stefaan Lippens
Stefan Farmbauer
Stefan Scherfke
Stefan Zimmermann
@@ -344,6 +385,7 @@ Tadek Teleżyński
Takafumi Arakaki
Taneli Hukkinen
Tanvi Mehta
Tanya Agarwal
Tarcisio Fischer
Tareq Alayan
Tatiana Ovary
@@ -362,19 +404,23 @@ Tomer Keren
Tony Narlock
Tor Colvin
Trevor Bekolay
Tushar Sadhwani
Tyler Goodlet
Tyler Smart
Tzu-ping Chung
Vasily Kuznetsov
Victor Maryama
Victor Rodriguez
Victor Uriarte
Vidar T. Fauske
Vijay Arora
Virgil Dupras
Vitaly Lashmanov
Vivaan Verma
Vlad Dragos
Vlad Radziuk
Vladyslav Rachek
Volodymyr Kochetkov
Volodymyr Piskun
Wei Lin
Wil Cooley

View File

@@ -50,7 +50,7 @@ Fix bugs
--------
Look through the `GitHub issues for bugs <https://github.com/pytest-dev/pytest/labels/type:%20bug>`_.
See also the `"status: easy" issues <https://github.com/pytest-dev/pytest/labels/status%3A%20easy>`_
See also the `"good first issue" issues <https://github.com/pytest-dev/pytest/labels/good%20first%20issue>`_
that are friendly to new contributors.
:ref:`Talk <contact>` to developers to find out how you can fix specific bugs. To indicate that you are going
@@ -197,11 +197,12 @@ Short version
~~~~~~~~~~~~~
#. Fork the repository.
#. Fetch tags from upstream if necessary (if you cloned only main `git fetch --tags https://github.com/pytest-dev/pytest`).
#. Enable and install `pre-commit <https://pre-commit.com>`_ to ensure style-guides and code checks are followed.
#. Follow **PEP-8** for naming and `black <https://github.com/psf/black>`_ for formatting.
#. Follow `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`_ for naming.
#. Tests are run using ``tox``::
tox -e linting,py37
tox -e linting,py39
The test environments above are usually enough to cover most cases locally.
@@ -236,6 +237,7 @@ Here is a simple overview, with pytest-specific bits:
$ git clone git@github.com:YOUR_GITHUB_USERNAME/pytest.git
$ cd pytest
$ git fetch --tags https://github.com/pytest-dev/pytest
# now, create your own branch off "main":
$ git checkout -b your-bugfix-branch-name main
@@ -272,24 +274,24 @@ Here is a simple overview, with pytest-specific bits:
#. Run all the tests
You need to have Python 3.7 available in your system. Now
You need to have Python 3.8 or later available in your system. Now
running tests is as simple as issuing this command::
$ tox -e linting,py37
$ tox -e linting,py39
This command will run tests via the "tox" tool against Python 3.7
This command will run tests via the "tox" tool against Python 3.9
and also perform "lint" coding-style checks.
#. You can now edit your local working copy and run the tests again as necessary. Please follow PEP-8 for naming.
#. You can now edit your local working copy and run the tests again as necessary. Please follow `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`_ for naming.
You can pass different options to ``tox``. For example, to run tests on Python 3.7 and pass options to pytest
You can pass different options to ``tox``. For example, to run tests on Python 3.9 and pass options to pytest
(e.g. enter pdb on failure) to pytest you can do::
$ tox -e py37 -- --pdb
$ tox -e py39 -- --pdb
Or to only run tests in a particular test module on Python 3.7::
Or to only run tests in a particular test module on Python 3.9::
$ tox -e py37 -- testing/test_config.py
$ tox -e py39 -- testing/test_config.py
When committing, ``pre-commit`` will re-format the files if necessary.

View File

@@ -20,16 +20,13 @@
:target: https://codecov.io/gh/pytest-dev/pytest
:alt: Code coverage Status
.. image:: https://github.com/pytest-dev/pytest/workflows/test/badge.svg
.. image:: https://github.com/pytest-dev/pytest/actions/workflows/test.yml/badge.svg
:target: https://github.com/pytest-dev/pytest/actions?query=workflow%3Atest
.. image:: https://results.pre-commit.ci/badge/github/pytest-dev/pytest/main.svg
:target: https://results.pre-commit.ci/latest/github/pytest-dev/pytest/main
:alt: pre-commit.ci status
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg
:target: https://www.codetriage.com/pytest-dev/pytest
@@ -97,12 +94,12 @@ Features
- `Modular fixtures <https://docs.pytest.org/en/stable/explanation/fixtures.html>`_ for
managing small or parametrized long-lived test resources
- Can run `unittest <https://docs.pytest.org/en/stable/how-to/unittest.html>`_ (or trial),
`nose <https://docs.pytest.org/en/stable/how-to/nose.html>`_ test suites out of the box
- Can run `unittest <https://docs.pytest.org/en/stable/how-to/unittest.html>`_ (or trial)
test suites out of the box
- Python 3.7+ or PyPy3
- Python 3.8+ or PyPy3
- Rich plugin architecture, with over 850+ `external plugins <https://docs.pytest.org/en/latest/reference/plugin_list.html>`_ and thriving community
- Rich plugin architecture, with over 1300+ `external plugins <https://docs.pytest.org/en/latest/reference/plugin_list.html>`_ and thriving community
Documentation

View File

@@ -133,14 +133,12 @@ Releasing
Both automatic and manual processes described above follow the same steps from this point onward.
#. After all tests pass and the PR has been approved, tag the release commit
in the ``release-MAJOR.MINOR.PATCH`` branch and push it. This will publish to PyPI::
#. After all tests pass and the PR has been approved, trigger the ``deploy`` job
in https://github.com/pytest-dev/pytest/actions/workflows/deploy.yml, using the ``release-MAJOR.MINOR.PATCH`` branch
as source.
git fetch upstream
git tag MAJOR.MINOR.PATCH upstream/release-MAJOR.MINOR.PATCH
git push upstream MAJOR.MINOR.PATCH
Wait for the deploy to complete, then make sure it is `available on PyPI <https://pypi.org/project/pytest>`_.
This job will require approval from ``pytest-dev/core``, after which it will publish to PyPI
and tag the repository.
#. Merge the PR. **Make sure it's not squash-merged**, so that the tagged commit ends up in the main branch.

View File

@@ -23,7 +23,6 @@ members of the `contributors team`_ interested in receiving funding.
The current list of contributors receiving funding are:
* `@asottile`_
* `@nicoddemus`_
* `@The-Compiler`_
@@ -55,6 +54,5 @@ funds. Just drop a line to one of the `@pytest-dev/tidelift-admins`_ or use the
.. _`@pytest-dev/tidelift-admins`: https://github.com/orgs/pytest-dev/teams/tidelift-admins/members
.. _`agreement`: https://tidelift.com/docs/lifting/agreement
.. _`@asottile`: https://github.com/asottile
.. _`@nicoddemus`: https://github.com/nicoddemus
.. _`@The-Compiler`: https://github.com/The-Compiler

View File

@@ -1,10 +1,12 @@
import sys
if __name__ == "__main__":
import cProfile
import pytest # NOQA
import pstats
import pytest # noqa: F401
script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"]
cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
p = pstats.Stats("prof")

View File

@@ -4,6 +4,7 @@
# FastFilesCompleter 0.7383 1.0760
import timeit
imports = [
"from argcomplete.completers import FilesCompleter as completer",
"from _pytest._argcomplete import FastFilesCompleter as completer",

View File

@@ -1,5 +1,6 @@
import pytest
SKIP = True

View File

@@ -1,5 +1,6 @@
from unittest import TestCase # noqa: F401
for i in range(15000):
exec(
f"""

View File

@@ -1 +0,0 @@
If multiple errors are raised in teardown, we now re-raise an ``ExceptionGroup`` of them instead of discarding all but the last.

View File

@@ -1 +0,0 @@
Test methods decorated with ``@classmethod`` can now be discovered as tests, following the same rules as normal methods. This fills the gap that static methods were discoverable as tests but not class methods.

View File

@@ -1,3 +0,0 @@
Allow ``-p`` arguments to include spaces (eg: ``-p no:logging`` instead of
``-pno:logging``). Mostly useful in the ``addopts`` section of the configuration
file.

View File

@@ -1 +0,0 @@
pytest no longer depends on the `attrs` package (don't worry, nice diffs for attrs classes are still supported).

View File

@@ -1 +0,0 @@
Added ``start`` and ``stop`` timestamps to ``TestReport`` objects.

View File

@@ -1 +0,0 @@
Split the report header for ``rootdir``, ``config file`` and ``testpaths`` so each has its own line.

View File

@@ -1 +0,0 @@
The assertion rewriting mechanism now works correctly when assertion expressions contain the walrus operator.

View File

@@ -1 +0,0 @@
:confval:`console_output_style` now supports ``progress-even-when-capture-no`` to force the use of the progress output even when capture is disabled. This is useful in large test suites where capture may have significant performance impact.

View File

@@ -1 +0,0 @@
Fixed :fixture:`tmp_path` fixture always raising :class:`OSError` on ``emscripten`` platform due to missing :func:`os.getuid`.

View File

@@ -1 +0,0 @@
Fixed the minimal example in :ref:`goodpractices`: ``pip install -e .`` requires a ``version`` entry in ``pyproject.toml`` to run successfully.

View File

@@ -1 +0,0 @@
pytest should no longer crash on AST with pathological position attributes, for example testing AST produced by `Hylang <https://github.com/hylang/hy>__`.

View File

@@ -1 +0,0 @@
Correctly handle ``__tracebackhide__`` for chained exceptions.

View File

@@ -1,2 +0,0 @@
The full output of a test is no longer truncated if the truncation message would be longer than
the hidden text. The line number shown has also been fixed.

View File

@@ -1 +0,0 @@
``--log-disable`` CLI option added to disable individual loggers.

View File

@@ -1 +0,0 @@
Added :confval:`tmp_path_retention_count` and :confval:`tmp_path_retention_policy` configuration options to control how directories created by the :fixture:`tmp_path` fixture are kept.

View File

@@ -14,7 +14,7 @@ Each file should be named like ``<ISSUE>.<TYPE>.rst``, where
``<ISSUE>`` is an issue number, and ``<TYPE>`` is one of:
* ``feature``: new user facing features, like new command-line options and new behavior.
* ``improvement``: improvement of existing functionality, usually without requiring user intervention (for example, new fields being written in ``--junitxml``, improved colors in terminal, etc).
* ``improvement``: improvement of existing functionality, usually without requiring user intervention (for example, new fields being written in ``--junit-xml``, improved colors in terminal, etc).
* ``bugfix``: fixes a bug.
* ``doc``: documentation improvement, like rewording an entire session or adding missing docs.
* ``deprecation``: feature deprecation.

View File

@@ -5,11 +5,10 @@
<div id="searchbox" style="display: none" role="search">
<div class="searchformwrapper">
<form class="search" action="{{ pathto('search') }}" method="get">
<input type="text" name="q" aria-labelledby="searchlabel"
placeholder="Search"/>
<input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
<input type="submit" value="{{ _('Go') }}" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
<script>document.getElementById('searchbox').style.display = "block"</script>
{%- endif %}

View File

@@ -44,7 +44,7 @@ Partner projects, sign up here! (by 22 March)
What does it mean to "adopt pytest"?
-----------------------------------------
There can be many different definitions of "success". Pytest can run many nose_ and unittest_ tests by default, so using pytest as your testrunner may be possible from day 1. Job done, right?
There can be many different definitions of "success". Pytest can run many unittest_ tests by default, so using pytest as your testrunner may be possible from day 1. Job done, right?
Progressive success might look like:
@@ -62,7 +62,6 @@ Progressive success might look like:
It may be after the month is up, the partner project decides that pytest is not right for it. That's okay - hopefully the pytest team will also learn something about its weaknesses or deficiencies.
.. _nose: nose.html
.. _unittest: unittest.html
.. _assert: assert.html
.. _pycmd: https://bitbucket.org/hpk42/pycmd/overview

View File

@@ -6,6 +6,20 @@ Release announcements
:maxdepth: 2
release-8.1.0
release-8.0.2
release-8.0.1
release-8.0.0
release-8.0.0rc2
release-8.0.0rc1
release-7.4.4
release-7.4.3
release-7.4.2
release-7.4.1
release-7.4.0
release-7.3.2
release-7.3.1
release-7.3.0
release-7.2.2
release-7.2.1
release-7.2.0

View File

@@ -0,0 +1,130 @@
pytest-7.3.0
=======================================
The pytest team is proud to announce the 7.3.0 release!
This release contains new features, improvements, and bug fixes,
the full list of changes is available in the changelog:
https://docs.pytest.org/en/stable/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/stable/
As usual, you can upgrade from PyPI via:
pip install -U pytest
Thanks to all of the contributors to this release:
* Aaron Berdy
* Adam Turner
* Albert Villanova del Moral
* Alessio Izzo
* Alex Hadley
* Alice Purcell
* Anthony Sottile
* Anton Yakutovich
* Ashish Kurmi
* Babak Keyvani
* Billy
* Brandon Chinn
* Bruno Oliveira
* Cal Jacobson
* Chanvin Xiao
* Cheuk Ting Ho
* Chris Wheeler
* Daniel Garcia Moreno
* Daniel Scheffler
* Daniel Valenzuela
* EmptyRabbit
* Ezio Melotti
* Felix Hofstätter
* Florian Best
* Florian Bruhin
* Fredrik Berndtsson
* Gabriel Landau
* Garvit Shubham
* Gergely Kalmár
* HTRafal
* Hugo van Kemenade
* Ilya Konstantinov
* Itxaso Aizpurua
* James Gerity
* Jay
* John Litborn
* Jon Parise
* Jouke Witteveen
* Kadino
* Kevin C
* Kian Eliasi
* Klaus Rettinghaus
* Kodi Arfer
* Mahesh Vashishtha
* Manuel Jacob
* Marko Pacak
* MatthewFlamm
* Miro Hrončok
* Nate Meyvis
* Neil Girdhar
* Nhieuvu1802
* Nipunn Koorapati
* Ofek Lev
* Paul Kehrer
* Paul Müller
* Paul Reece
* Pax
* Pete Baughman
* Peyman Salehi
* Philipp A
* Pierre Sassoulas
* Prerak Patel
* Ramsey
* Ran Benita
* Robert O'Shea
* Ronny Pfannschmidt
* Rowin
* Ruth Comer
* Samuel Colvin
* Samuel Gaist
* Sandro Tosi
* Santiago Castro
* Shantanu
* Simon K
* Stefanie Molin
* Stephen Rosen
* Sviatoslav Sydorenko
* Tatiana Ovary
* Teejay
* Thierry Moisan
* Thomas Grainger
* Tim Hoffmann
* Tobias Diez
* Tony Narlock
* Vivaan Verma
* Wolfremium
* Yannick PÉROUX
* Yusuke Kadowaki
* Zac Hatfield-Dodds
* Zach OBrien
* aizpurua23a
* bitzge
* bluthej
* gresm
* holesch
* itxasos23
* johnkangw
* q0w
* rdb
* s-padmanaban
* skhomuti
* sommersoft
* vin01
* wim glenn
* wodny
* zx.qiu
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,18 @@
pytest-7.3.1
=======================================
pytest 7.3.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,21 @@
pytest-7.3.2
=======================================
pytest 7.3.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Adam J. Stewart
* Alessio Izzo
* Bruno Oliveira
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,49 @@
pytest-7.4.0
=======================================
The pytest team is proud to announce the 7.4.0 release!
This release contains new features, improvements, and bug fixes,
the full list of changes is available in the changelog:
https://docs.pytest.org/en/stable/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/stable/
As usual, you can upgrade from PyPI via:
pip install -U pytest
Thanks to all of the contributors to this release:
* Adam J. Stewart
* Alessio Izzo
* Alex
* Alex Lambson
* Brian Larsen
* Bruno Oliveira
* Bryan Ricker
* Chris Mahoney
* Facundo Batista
* Florian Bruhin
* Jarrett Keifer
* Kenny Y
* Miro Hrončok
* Ran Benita
* Roberto Aldera
* Ronny Pfannschmidt
* Sergey Kim
* Stefanie Molin
* Vijay Arora
* Ville Skyttä
* Zac Hatfield-Dodds
* bzoracler
* leeyueh
* nondescryptid
* theirix
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,20 @@
pytest-7.4.1
=======================================
pytest 7.4.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Bruno Oliveira
* Florian Bruhin
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,18 @@
pytest-7.4.2
=======================================
pytest 7.4.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Bruno Oliveira
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,19 @@
pytest-7.4.3
=======================================
pytest 7.4.3 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Bruno Oliveira
* Marc Mueller
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,20 @@
pytest-7.4.4
=======================================
pytest 7.4.4 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Bruno Oliveira
* Ran Benita
* Zac Hatfield-Dodds
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,26 @@
pytest-8.0.0
=======================================
The pytest team is proud to announce the 8.0.0 release!
This release contains new features, improvements, bug fixes, and breaking changes, so users
are encouraged to take a look at the CHANGELOG carefully:
https://docs.pytest.org/en/stable/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/stable/
As usual, you can upgrade from PyPI via:
pip install -U pytest
Thanks to all of the contributors to this release:
* Bruno Oliveira
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,82 @@
pytest-8.0.0rc1
=======================================
The pytest team is proud to announce the 8.0.0rc1 release!
This release contains new features, improvements, bug fixes, and breaking changes, so users
are encouraged to take a look at the CHANGELOG carefully:
https://docs.pytest.org/en/stable/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/stable/
As usual, you can upgrade from PyPI via:
pip install -U pytest
Thanks to all of the contributors to this release:
* Akhilesh Ramakrishnan
* Aleksandr Brodin
* Anthony Sottile
* Arthur Richard
* Avasam
* Benjamin Schubert
* Bruno Oliveira
* Carsten Grohmann
* Cheukting
* Chris Mahoney
* Christoph Anton Mitterer
* DetachHead
* Erik Hasse
* Florian Bruhin
* Fraser Stark
* Ha Pam
* Hugo van Kemenade
* Isaac Virshup
* Israel Fruchter
* Jens Tröger
* Jon Parise
* Kenny Y
* Lesnek
* Marc Mueller
* Michał Górny
* Mihail Milushev
* Milan Lesnek
* Miro Hrončok
* Patrick Lannigan
* Ran Benita
* Reagan Lee
* Ronny Pfannschmidt
* Sadra Barikbin
* Sean Malloy
* Sean Patrick Malloy
* Sharad Nair
* Simon Blanchard
* Sourabh Beniwal
* Stefaan Lippens
* Tanya Agarwal
* Thomas Grainger
* Tom Mortimer-Jones
* Tushar Sadhwani
* Tyler Smart
* Uday Kumar
* Warren Markham
* WarrenTheRabbit
* Zac Hatfield-Dodds
* Ziad Kermadi
* akhilramkee
* antosikv
* bowugit
* mickeypash
* neilmartin2000
* pomponchik
* ryanpudd
* touilleWoman
* ubaumann
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,32 @@
pytest-8.0.0rc2
=======================================
The pytest team is proud to announce the 8.0.0rc2 prerelease!
This is a prerelease, not intended for production use, but to test the upcoming features and improvements
in order to catch any major problems before the final version is released to the major public.
We appreciate your help testing this out before the final release, making sure to report any
regressions to our issue tracker:
https://github.com/pytest-dev/pytest/issues
When doing so, please include the string ``[prerelease]`` in the title.
You can upgrade from PyPI via:
pip install pytest==8.0.0rc2
Users are encouraged to take a look at the CHANGELOG carefully:
https://docs.pytest.org/en/release-8.0.0rc2/changelog.html
Thanks to all the contributors to this release:
* Ben Brown
* Bruno Oliveira
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,21 @@
pytest-8.0.1
=======================================
pytest 8.0.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Bruno Oliveira
* Clément Robert
* Pierre Sassoulas
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,18 @@
pytest-8.0.2
=======================================
pytest 8.0.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/stable/changelog.html.
Thanks to all of the contributors to this release:
* Ran Benita
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,54 @@
pytest-8.1.0
=======================================
The pytest team is proud to announce the 8.1.0 release!
This release contains new features, improvements, and bug fixes,
the full list of changes is available in the changelog:
https://docs.pytest.org/en/stable/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/stable/
As usual, you can upgrade from PyPI via:
pip install -U pytest
Thanks to all of the contributors to this release:
* Ben Brown
* Ben Leith
* Bruno Oliveira
* Clément Robert
* Dave Hall
* Dương Quốc Khánh
* Eero Vaher
* Eric Larson
* Fabian Sturm
* Faisal Fawad
* Florian Bruhin
* Franck Charras
* Joachim B Haga
* John Litborn
* Loïc Estève
* Marc Bresson
* Patrick Lannigan
* Pierre Sassoulas
* Ran Benita
* Reagan Lee
* Ronny Pfannschmidt
* Russell Martin
* clee2000
* donghui
* faph
* jakkdl
* mrbean-bremen
* robotherapist
* whysage
* woutdenolf
Happy testing,
The pytest Development Team

View File

@@ -22,7 +22,7 @@ b) transitional: the old and new API don't conflict
We will only start the removal of deprecated functionality in major releases (e.g. if we deprecate something in 3.0 we will start to remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9 and 4.0 is the next release, we start to remove it in 5.0, not in 4.0).
A deprecated feature scheduled to be removed in major version X will use the warning class `PytestRemovedInXWarning` (a subclass of :class:`~pytest.PytestDeprecationwarning`).
A deprecated feature scheduled to be removed in major version X will use the warning class `PytestRemovedInXWarning` (a subclass of :class:`~pytest.PytestDeprecationWarning`).
When the deprecation expires (e.g. 4.0 is released), we won't remove the deprecated functionality immediately, but will use the standard warning filters to turn `PytestRemovedInXWarning` (e.g. `PytestRemovedIn4Warning`) into **errors** by default. This approach makes it explicit that removal is imminent, and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealt with in your own time. In the next minor release (e.g. 4.1), the feature will be effectively removed.
@@ -87,8 +87,11 @@ Released pytest versions support all Python versions that are actively maintaine
============== ===================
pytest version min. Python version
============== ===================
8.0+ 3.8+
7.1+ 3.7+
6.2 - 7.0 3.6+
5.0 - 6.1 3.5+
3.3 - 4.6 2.7, 3.4+
============== ===================
`Status of Python Versions <https://devguide.python.org/versions/>`__.

View File

@@ -18,11 +18,11 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
$ pytest --fixtures -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collected 0 items
cache -- .../_pytest/cacheprovider.py:510
cache -- .../_pytest/cacheprovider.py:527
Return a cache object that can persist state between testing sessions.
cache.get(key, default)
@@ -33,7 +33,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
Values can be any object handled by the json stdlib module.
capsysbinary -- .../_pytest/capture.py:1001
capsysbinary -- .../_pytest/capture.py:1008
Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``capsysbinary.readouterr()``
@@ -43,7 +43,6 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
Example:
.. code-block:: python
def test_output(capsysbinary):
@@ -51,7 +50,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
captured = capsysbinary.readouterr()
assert captured.out == b"hello\n"
capfd -- .../_pytest/capture.py:1029
capfd -- .../_pytest/capture.py:1035
Enable text capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``capfd.readouterr()`` method
@@ -61,7 +60,6 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
Example:
.. code-block:: python
def test_system_echo(capfd):
@@ -69,7 +67,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
captured = capfd.readouterr()
assert captured.out == "hello\n"
capfdbinary -- .../_pytest/capture.py:1057
capfdbinary -- .../_pytest/capture.py:1062
Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``capfd.readouterr()`` method
@@ -79,7 +77,6 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
Example:
.. code-block:: python
def test_system_echo(capfdbinary):
@@ -87,7 +84,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
captured = capfdbinary.readouterr()
assert captured.out == b"hello\n"
capsys -- .../_pytest/capture.py:973
capsys -- .../_pytest/capture.py:981
Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``capsys.readouterr()`` method
@@ -97,7 +94,6 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
Example:
.. code-block:: python
def test_output(capsys):
@@ -119,7 +115,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
For more details: :ref:`doctest_namespace`.
pytestconfig [session scope] -- .../_pytest/fixtures.py:1360
pytestconfig [session scope] -- .../_pytest/fixtures.py:1346
Session-scoped fixture that returns the session's :class:`pytest.Config`
object.
@@ -129,7 +125,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
if pytestconfig.getoption("verbose") > 0:
...
record_property -- .../_pytest/junitxml.py:282
record_property -- .../_pytest/junitxml.py:283
Add extra properties to the calling test.
User properties become part of the test report and are available to the
@@ -143,13 +139,13 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
def test_function(record_property):
record_property("example_key", 1)
record_xml_attribute -- .../_pytest/junitxml.py:305
record_xml_attribute -- .../_pytest/junitxml.py:306
Add extra xml attributes to the tag for the calling test.
The fixture is callable with ``name, value``. The value is
automatically XML-encoded.
record_testsuite_property [session scope] -- .../_pytest/junitxml.py:343
record_testsuite_property [session scope] -- .../_pytest/junitxml.py:344
Record a new ``<property>`` tag as child of the root ``<testsuite>``.
This is suitable to writing global information regarding the entire test
@@ -174,18 +170,18 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
`pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See
:issue:`7767` for details.
tmpdir_factory [session scope] -- .../_pytest/legacypath.py:302
tmpdir_factory [session scope] -- .../_pytest/legacypath.py:317
Return a :class:`pytest.TempdirFactory` instance for the test session.
tmpdir -- .../_pytest/legacypath.py:309
tmpdir -- .../_pytest/legacypath.py:324
Return a temporary directory path object which is unique to each test
function invocation, created as a sub directory of the base temporary
directory.
By default, a new base temporary directory is created each test session,
and old bases are removed after 3 sessions, to aid in debugging. If
``--basetemp`` is used then it is cleared each session. See :ref:`base
temporary directory`.
``--basetemp`` is used then it is cleared each session. See
:ref:`temporary directory location and retention`.
The returned object is a `legacy_path`_ object.
@@ -196,7 +192,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
.. _legacy_path: https://py.readthedocs.io/en/latest/path.html
caplog -- .../_pytest/logging.py:498
caplog -- .../_pytest/logging.py:601
Access and control log capturing.
Captured logs are available through the following properties/methods::
@@ -207,7 +203,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
* caplog.record_tuples -> list of (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string
monkeypatch -- .../_pytest/monkeypatch.py:29
monkeypatch -- .../_pytest/monkeypatch.py:32
A convenient fixture for monkey-patching.
The fixture provides these methods to modify objects, dictionaries, or
@@ -231,16 +227,16 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
To undo modifications done by the fixture in a contained scope,
use :meth:`context() <pytest.MonkeyPatch.context>`.
recwarn -- .../_pytest/recwarn.py:30
recwarn -- .../_pytest/recwarn.py:31
Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
on warning categories.
tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:245
tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:241
Return a :class:`pytest.TempPathFactory` instance for the test session.
tmp_path -- .../_pytest/tmpdir.py:260
tmp_path -- .../_pytest/tmpdir.py:256
Return a temporary directory path object which is unique to each test
function invocation, created as a sub directory of the base temporary
directory.
@@ -249,8 +245,8 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
and old bases are removed after 3 sessions, to aid in debugging.
This behavior can be configured with :confval:`tmp_path_retention_count` and
:confval:`tmp_path_retention_policy`.
If ``--basetemp`` is used then it is cleared each session. See :ref:`base
temporary directory`.
If ``--basetemp`` is used then it is cleared each session. See
:ref:`temporary directory location and retention`.
The returned object is a :class:`pathlib.Path` object.

File diff suppressed because it is too large Load Diff

View File

@@ -15,16 +15,15 @@
#
# The full version, including alpha/beta/rc tags.
# The short X.Y version.
import ast
import os
import shutil
import sys
from textwrap import dedent
from typing import List
from typing import TYPE_CHECKING
from _pytest import __version__ as version
if TYPE_CHECKING:
import sphinx.application
@@ -171,6 +170,49 @@ extlinks = {
}
nitpicky = True
nitpick_ignore = [
# TODO (fix in pluggy?)
("py:class", "HookCaller"),
("py:class", "HookspecMarker"),
("py:exc", "PluginValidationError"),
# Might want to expose/TODO (https://github.com/pytest-dev/pytest/issues/7469)
("py:class", "ExceptionRepr"),
("py:class", "Exit"),
("py:class", "SubRequest"),
("py:class", "SubRequest"),
("py:class", "TerminalReporter"),
("py:class", "_pytest._code.code.TerminalRepr"),
("py:class", "_pytest.fixtures.FixtureFunctionMarker"),
("py:class", "_pytest.logging.LogCaptureHandler"),
("py:class", "_pytest.mark.structures.ParameterSet"),
# Intentionally undocumented/private
("py:class", "_pytest._code.code.Traceback"),
("py:class", "_pytest._py.path.LocalPath"),
("py:class", "_pytest.capture.CaptureResult"),
("py:class", "_pytest.compat.NotSetType"),
("py:class", "_pytest.python.PyCollector"),
("py:class", "_pytest.python.PyobjMixin"),
("py:class", "_pytest.python_api.RaisesContext"),
("py:class", "_pytest.recwarn.WarningsChecker"),
("py:class", "_pytest.reports.BaseReport"),
# Undocumented third parties
("py:class", "_tracing.TagTracerSub"),
("py:class", "warnings.WarningMessage"),
# Undocumented type aliases
("py:class", "_PluggyPlugin"),
# TypeVars
("py:class", "_pytest._code.code.E"),
("py:class", "_pytest.fixtures.FixtureFunction"),
("py:class", "_pytest.nodes._NodeType"),
("py:class", "_pytest.python_api.E"),
("py:class", "_pytest.recwarn.T"),
("py:class", "_pytest.runner.TResult"),
("py:obj", "_pytest.fixtures.FixtureValue"),
("py:obj", "_pytest.stash.T"),
]
# -- Options for HTML output ---------------------------------------------------
sys.path.append(os.path.abspath("_themes"))
@@ -341,7 +383,7 @@ epub_copyright = "2013, holger krekel et alii"
# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# The unique identifier of the text. This can be an ISBN number
# or the project homepage.
# epub_identifier = ''
@@ -399,9 +441,10 @@ intersphinx_mapping = {
def configure_logging(app: "sphinx.application.Sphinx") -> None:
"""Configure Sphinx's WarningHandler to handle (expected) missing include."""
import sphinx.util.logging
import logging
import sphinx.util.logging
class WarnLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
"""Ignore warnings about missing include with "only" directive.
@@ -451,25 +494,6 @@ def setup(app: "sphinx.application.Sphinx") -> None:
configure_logging(app)
# Make Sphinx mark classes with "final" when decorated with @final.
# We need this because we import final from pytest._compat, not from
# typing (for Python < 3.8 compat), so Sphinx doesn't detect it.
# To keep things simple we accept any `@final` decorator.
# Ref: https://github.com/pytest-dev/pytest/pull/7780
import sphinx.pycode.ast
import sphinx.pycode.parser
original_is_final = sphinx.pycode.parser.VariableCommentPicker.is_final
def patched_is_final(self, decorators: List[ast.expr]) -> bool:
if original_is_final(self, decorators):
return True
return any(
sphinx.pycode.ast.unparse(decorator) == "final" for decorator in decorators
)
sphinx.pycode.parser.VariableCommentPicker.is_final = patched_is_final
# legacypath.py monkey-patches pytest.Testdir in. Import the file so
# that autodoc can discover references to it.
import _pytest.legacypath # noqa: F401

View File

@@ -44,7 +44,6 @@ How-to guides
how-to/existingtestsuite
how-to/unittest
how-to/nose
how-to/xunit_setup
how-to/bash-completion

View File

@@ -19,170 +19,6 @@ Below is a complete list of all pytest features which are considered deprecated.
:class:`~pytest.PytestWarning` or subclasses, which can be filtered using :ref:`standard warning filters <warnings>`.
.. _nose-deprecation:
Support for tests written for nose
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.2
Support for running tests written for `nose <https://nose.readthedocs.io/en/latest/>`__ is now deprecated.
``nose`` has been in maintenance mode-only for years, and maintaining the plugin is not trivial as it spills
over the code base (see :issue:`9886` for more details).
setup/teardown
^^^^^^^^^^^^^^
One thing that might catch users by surprise is that plain ``setup`` and ``teardown`` methods are not pytest native,
they are in fact part of the ``nose`` support.
.. code-block:: python
class Test:
def setup(self):
self.resource = make_resource()
def teardown(self):
self.resource.close()
def test_foo(self):
...
def test_bar(self):
...
Native pytest support uses ``setup_method`` and ``teardown_method`` (see :ref:`xunit-method-setup`), so the above should be changed to:
.. code-block:: python
class Test:
def setup_method(self):
self.resource = make_resource()
def teardown_method(self):
self.resource.close()
def test_foo(self):
...
def test_bar(self):
...
This is easy to do in an entire code base by doing a simple find/replace.
@with_setup
^^^^^^^^^^^
Code using `@with_setup <with-setup-nose>`_ such as this:
.. code-block:: python
from nose.tools import with_setup
def setup_some_resource():
...
def teardown_some_resource():
...
@with_setup(setup_some_resource, teardown_some_resource)
def test_foo():
...
Will also need to be ported to a supported pytest style. One way to do it is using a fixture:
.. code-block:: python
import pytest
def setup_some_resource():
...
def teardown_some_resource():
...
@pytest.fixture
def some_resource():
setup_some_resource()
yield
teardown_some_resource()
def test_foo(some_resource):
...
.. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup
.. _instance-collector-deprecation:
The ``pytest.Instance`` collector
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionremoved:: 7.0
The ``pytest.Instance`` collector type has been removed.
Previously, Python test methods were collected as :class:`~pytest.Class` -> ``Instance`` -> :class:`~pytest.Function`.
Now :class:`~pytest.Class` collects the test methods directly.
Most plugins which reference ``Instance`` do so in order to ignore or skip it,
using a check such as ``if isinstance(node, Instance): return``.
Such plugins should simply remove consideration of ``Instance`` on pytest>=7.
However, to keep such uses working, a dummy type has been instanted in ``pytest.Instance`` and ``_pytest.python.Instance``,
and importing it emits a deprecation warning. This will be removed in pytest 8.
.. _node-ctor-fspath-deprecation:
``fspath`` argument for Node constructors replaced with ``pathlib.Path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
In order to support the transition from ``py.path.local`` to :mod:`pathlib`,
the ``fspath`` argument to :class:`~_pytest.nodes.Node` constructors like
:func:`pytest.Function.from_parent()` and :func:`pytest.Class.from_parent()`
is now deprecated.
Plugins which construct nodes should pass the ``path`` argument, of type
:class:`pathlib.Path`, instead of the ``fspath`` argument.
Plugins which implement custom items and collectors are encouraged to replace
``fspath`` parameters (``py.path.local``) with ``path`` parameters
(``pathlib.Path``), and drop any other usage of the ``py`` library if possible.
If possible, plugins with custom items should use :ref:`cooperative
constructors <uncooperative-constructors-deprecated>` to avoid hardcoding
arguments they only pass on to the superclass.
.. note::
The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the
new attribute being ``path``) is **the opposite** of the situation for
hooks, :ref:`outlined below <legacy-path-hooks-deprecated>` (the old
argument being ``path``).
This is an unfortunate artifact due to historical reasons, which should be
resolved in future versions as we slowly get rid of the :pypi:`py`
dependency (see :issue:`9283` for a longer discussion).
Due to the ongoing migration of methods like :meth:`~_pytest.Item.reportinfo`
which still is expected to return a ``py.path.local`` object, nodes still have
both ``fspath`` (``py.path.local``) and ``path`` (``pathlib.Path``) attributes,
no matter what argument was used in the constructor. We expect to deprecate the
``fspath`` attribute in a future release.
.. _legacy-path-hooks-deprecated:
Configuring hook specs/impls using markers
@@ -197,13 +33,11 @@ have been available since years and should be used instead.
.. code-block:: python
@pytest.mark.tryfirst
def pytest_runtest_call():
...
def pytest_runtest_call(): ...
# or
def pytest_runtest_call():
...
def pytest_runtest_call(): ...
pytest_runtest_call.tryfirst = True
@@ -213,8 +47,7 @@ should be changed to:
.. code-block:: python
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_call():
...
def pytest_runtest_call(): ...
Changed ``hookimpl`` attributes:
@@ -229,31 +62,6 @@ Changed ``hookwrapper`` attributes:
* ``historic``
``py.path.local`` arguments for hooks replaced with ``pathlib.Path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
In order to support the transition from ``py.path.local`` to :mod:`pathlib`, the following hooks now receive additional arguments:
* :hook:`pytest_ignore_collect(collection_path: pathlib.Path) <pytest_ignore_collect>` as equivalent to ``path``
* :hook:`pytest_collect_file(file_path: pathlib.Path) <pytest_collect_file>` as equivalent to ``path``
* :hook:`pytest_pycollect_makemodule(module_path: pathlib.Path) <pytest_pycollect_makemodule>` as equivalent to ``path``
* :hook:`pytest_report_header(start_path: pathlib.Path) <pytest_report_header>` as equivalent to ``startdir``
* :hook:`pytest_report_collectionfinish(start_path: pathlib.Path) <pytest_report_collectionfinish>` as equivalent to ``startdir``
The accompanying ``py.path.local`` based paths have been deprecated: plugins which manually invoke those hooks should only pass the new ``pathlib.Path`` arguments, and users should change their hook implementations to use the new ``pathlib.Path`` arguments.
.. note::
The name of the :class:`~_pytest.nodes.Node` arguments and attributes,
:ref:`outlined above <node-ctor-fspath-deprecation>` (the new attribute
being ``path``) is **the opposite** of the situation for hooks (the old
argument being ``path``).
This is an unfortunate artifact due to historical reasons, which should be
resolved in future versions as we slowly get rid of the :pypi:`py`
dependency (see :issue:`9283` for a longer discussion).
Directly constructing internal classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -273,62 +81,6 @@ Directly constructing the following classes is now deprecated:
These constructors have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 8.
.. _cmdline-preparse-deprecated:
Passing ``msg=`` to ``pytest.skip``, ``pytest.fail`` or ``pytest.exit``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
Passing the keyword argument ``msg`` to :func:`pytest.skip`, :func:`pytest.fail` or :func:`pytest.exit`
is now deprecated and ``reason`` should be used instead. This change is to bring consistency between these
functions and the ``@pytest.mark.skip`` and ``@pytest.mark.xfail`` markers which already accept a ``reason`` argument.
.. code-block:: python
def test_fail_example():
# old
pytest.fail(msg="foo")
# new
pytest.fail(reason="bar")
def test_skip_example():
# old
pytest.skip(msg="foo")
# new
pytest.skip(reason="bar")
def test_exit_example():
# old
pytest.exit(msg="foo")
# new
pytest.exit(reason="bar")
Implementing the ``pytest_cmdline_preparse`` hook
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
Implementing the :hook:`pytest_cmdline_preparse` hook has been officially deprecated.
Implement the :hook:`pytest_load_initial_conftests` hook instead.
.. code-block:: python
def pytest_cmdline_preparse(config: Config, args: List[str]) -> None:
...
# becomes:
def pytest_load_initial_conftests(
early_config: Config, parser: Parser, args: List[str]
) -> None:
...
.. _diamond-inheritance-deprecated:
Diamond inheritance between :class:`pytest.Collector` and :class:`pytest.Item`
@@ -336,7 +88,7 @@ Diamond inheritance between :class:`pytest.Collector` and :class:`pytest.Item`
.. deprecated:: 7.0
Defining a custom pytest node type which is both an :class:`pytest.Item <Item>` and a :class:`pytest.Collector <Collector>` (e.g. :class:`pytest.File <File>`) now issues a warning.
Defining a custom pytest node type which is both an :class:`~pytest.Item` and a :class:`~pytest.Collector` (e.g. :class:`~pytest.File`) now issues a warning.
It was never sanely supported and triggers hard to debug errors.
Some plugins providing linting/code analysis have been using this as a hack.
@@ -348,8 +100,8 @@ Instead, a separate collector node should be used, which collects the item. See
.. _uncooperative-constructors-deprecated:
Constructors of custom :class:`pytest.Node` subclasses should take ``**kwargs``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Constructors of custom :class:`~_pytest.nodes.Node` subclasses should take ``**kwargs``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
@@ -380,28 +132,22 @@ conflicts (such as :class:`pytest.File` now taking ``path`` instead of
``fspath``, as :ref:`outlined above <node-ctor-fspath-deprecation>`), a
deprecation warning is now raised.
Backward compatibilities in ``Parser.addoption``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Applying a mark to a fixture function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 2.4
.. deprecated:: 7.4
Several behaviors of :meth:`Parser.addoption <pytest.Parser.addoption>` are now
scheduled for removal in pytest 8 (deprecated since pytest 2.4.0):
Applying a mark to a fixture function never had any effect, but it is a common user error.
- ``parser.addoption(..., help=".. %default ..")`` - use ``%(default)s`` instead.
- ``parser.addoption(..., type="int/string/float/complex")`` - use ``type=int`` etc. instead.
.. code-block:: python
@pytest.mark.usefixtures("clean_database")
@pytest.fixture
def user() -> User: ...
Using ``pytest.warns(None)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Users expected in this case that the ``usefixtures`` mark would have its intended effect of using the ``clean_database`` fixture when ``user`` was invoked, when in fact it has no effect at all.
.. deprecated:: 7.0
:func:`pytest.warns(None) <pytest.warns>` is now deprecated because it was frequently misused.
Its correct usage was checking that the code emits at least one warning of any type - like ``pytest.warns()``
or ``pytest.warns(Warning)``.
See :ref:`warns use cases` for examples.
Now pytest will issue a warning when it encounters this problem, and will raise an error in the future versions.
Returning non-None value in test functions
@@ -444,19 +190,6 @@ The proper fix is to change the `return` to an `assert`:
assert foo(a, b) == result
The ``--strict`` command-line option
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 6.2
The ``--strict`` command-line option has been deprecated in favor of ``--strict-markers``, which
better conveys what the option does.
We have plans to maybe in the future to reintroduce ``--strict`` and make it an encompassing
flag for all strictness related options (``--strict-markers`` and ``--strict-config``
at the moment, more might be introduced in the future).
The ``yield_fixture`` function/decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -467,12 +200,415 @@ The ``yield_fixture`` function/decorator
It has been so for a very long time, so can be search/replaced safely.
Removed Features
----------------
Removed Features and Breaking Changes
-------------------------------------
As stated in our :ref:`backwards-compatibility` policy, deprecated features are removed only in major releases after
an appropriate period of deprecation has passed.
Some breaking changes which could not be deprecated are also listed.
.. _node-ctor-fspath-deprecation:
``fspath`` argument for Node constructors replaced with ``pathlib.Path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
In order to support the transition from ``py.path.local`` to :mod:`pathlib`,
the ``fspath`` argument to :class:`~_pytest.nodes.Node` constructors like
:func:`pytest.Function.from_parent()` and :func:`pytest.Class.from_parent()`
is now deprecated.
Plugins which construct nodes should pass the ``path`` argument, of type
:class:`pathlib.Path`, instead of the ``fspath`` argument.
Plugins which implement custom items and collectors are encouraged to replace
``fspath`` parameters (``py.path.local``) with ``path`` parameters
(``pathlib.Path``), and drop any other usage of the ``py`` library if possible.
If possible, plugins with custom items should use :ref:`cooperative
constructors <uncooperative-constructors-deprecated>` to avoid hardcoding
arguments they only pass on to the superclass.
.. note::
The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the
new attribute being ``path``) is **the opposite** of the situation for
hooks, :ref:`outlined below <legacy-path-hooks-deprecated>` (the old
argument being ``path``).
This is an unfortunate artifact due to historical reasons, which should be
resolved in future versions as we slowly get rid of the :pypi:`py`
dependency (see :issue:`9283` for a longer discussion).
Due to the ongoing migration of methods like :meth:`~pytest.Item.reportinfo`
which still is expected to return a ``py.path.local`` object, nodes still have
both ``fspath`` (``py.path.local``) and ``path`` (``pathlib.Path``) attributes,
no matter what argument was used in the constructor. We expect to deprecate the
``fspath`` attribute in a future release.
``py.path.local`` arguments for hooks replaced with ``pathlib.Path``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
.. versionremoved:: 8.0
In order to support the transition from ``py.path.local`` to :mod:`pathlib`, the following hooks now receive additional arguments:
* :hook:`pytest_ignore_collect(collection_path: pathlib.Path) <pytest_ignore_collect>` as equivalent to ``path``
* :hook:`pytest_collect_file(file_path: pathlib.Path) <pytest_collect_file>` as equivalent to ``path``
* :hook:`pytest_pycollect_makemodule(module_path: pathlib.Path) <pytest_pycollect_makemodule>` as equivalent to ``path``
* :hook:`pytest_report_header(start_path: pathlib.Path) <pytest_report_header>` as equivalent to ``startdir``
* :hook:`pytest_report_collectionfinish(start_path: pathlib.Path) <pytest_report_collectionfinish>` as equivalent to ``startdir``
The accompanying ``py.path.local`` based paths have been deprecated: plugins which manually invoke those hooks should only pass the new ``pathlib.Path`` arguments, and users should change their hook implementations to use the new ``pathlib.Path`` arguments.
.. note::
The name of the :class:`~_pytest.nodes.Node` arguments and attributes,
:ref:`outlined above <node-ctor-fspath-deprecation>` (the new attribute
being ``path``) is **the opposite** of the situation for hooks (the old
argument being ``path``).
This is an unfortunate artifact due to historical reasons, which should be
resolved in future versions as we slowly get rid of the :pypi:`py`
dependency (see :issue:`9283` for a longer discussion).
.. _nose-deprecation:
Support for tests written for nose
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.2
.. versionremoved:: 8.0
Support for running tests written for `nose <https://nose.readthedocs.io/en/latest/>`__ is now deprecated.
``nose`` has been in maintenance mode-only for years, and maintaining the plugin is not trivial as it spills
over the code base (see :issue:`9886` for more details).
setup/teardown
^^^^^^^^^^^^^^
One thing that might catch users by surprise is that plain ``setup`` and ``teardown`` methods are not pytest native,
they are in fact part of the ``nose`` support.
.. code-block:: python
class Test:
def setup(self):
self.resource = make_resource()
def teardown(self):
self.resource.close()
def test_foo(self): ...
def test_bar(self): ...
Native pytest support uses ``setup_method`` and ``teardown_method`` (see :ref:`xunit-method-setup`), so the above should be changed to:
.. code-block:: python
class Test:
def setup_method(self):
self.resource = make_resource()
def teardown_method(self):
self.resource.close()
def test_foo(self): ...
def test_bar(self): ...
This is easy to do in an entire code base by doing a simple find/replace.
@with_setup
^^^^^^^^^^^
Code using `@with_setup <with-setup-nose>`_ such as this:
.. code-block:: python
from nose.tools import with_setup
def setup_some_resource(): ...
def teardown_some_resource(): ...
@with_setup(setup_some_resource, teardown_some_resource)
def test_foo(): ...
Will also need to be ported to a supported pytest style. One way to do it is using a fixture:
.. code-block:: python
import pytest
def setup_some_resource(): ...
def teardown_some_resource(): ...
@pytest.fixture
def some_resource():
setup_some_resource()
yield
teardown_some_resource()
def test_foo(some_resource): ...
.. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup
The ``compat_co_firstlineno`` attribute
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Nose inspects this attribute on function objects to allow overriding the function's inferred line number.
Pytest no longer respects this attribute.
Passing ``msg=`` to ``pytest.skip``, ``pytest.fail`` or ``pytest.exit``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
.. versionremoved:: 8.0
Passing the keyword argument ``msg`` to :func:`pytest.skip`, :func:`pytest.fail` or :func:`pytest.exit`
is now deprecated and ``reason`` should be used instead. This change is to bring consistency between these
functions and the ``@pytest.mark.skip`` and ``@pytest.mark.xfail`` markers which already accept a ``reason`` argument.
.. code-block:: python
def test_fail_example():
# old
pytest.fail(msg="foo")
# new
pytest.fail(reason="bar")
def test_skip_example():
# old
pytest.skip(msg="foo")
# new
pytest.skip(reason="bar")
def test_exit_example():
# old
pytest.exit(msg="foo")
# new
pytest.exit(reason="bar")
.. _instance-collector-deprecation:
The ``pytest.Instance`` collector
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionremoved:: 7.0
The ``pytest.Instance`` collector type has been removed.
Previously, Python test methods were collected as :class:`~pytest.Class` -> ``Instance`` -> :class:`~pytest.Function`.
Now :class:`~pytest.Class` collects the test methods directly.
Most plugins which reference ``Instance`` do so in order to ignore or skip it,
using a check such as ``if isinstance(node, Instance): return``.
Such plugins should simply remove consideration of ``Instance`` on pytest>=7.
However, to keep such uses working, a dummy type has been instanted in ``pytest.Instance`` and ``_pytest.python.Instance``,
and importing it emits a deprecation warning. This was removed in pytest 8.
Using ``pytest.warns(None)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
.. versionremoved:: 8.0
:func:`pytest.warns(None) <pytest.warns>` is now deprecated because it was frequently misused.
Its correct usage was checking that the code emits at least one warning of any type - like ``pytest.warns()``
or ``pytest.warns(Warning)``.
See :ref:`warns use cases` for examples.
Backward compatibilities in ``Parser.addoption``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 2.4
.. versionremoved:: 8.0
Several behaviors of :meth:`Parser.addoption <pytest.Parser.addoption>` are now
removed in pytest 8 (deprecated since pytest 2.4.0):
- ``parser.addoption(..., help=".. %default ..")`` - use ``%(default)s`` instead.
- ``parser.addoption(..., type="int/string/float/complex")`` - use ``type=int`` etc. instead.
The ``--strict`` command-line option
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 6.2
.. versionremoved:: 8.0
The ``--strict`` command-line option has been deprecated in favor of ``--strict-markers``, which
better conveys what the option does.
We have plans to maybe in the future to reintroduce ``--strict`` and make it an encompassing
flag for all strictness related options (``--strict-markers`` and ``--strict-config``
at the moment, more might be introduced in the future).
.. _cmdline-preparse-deprecated:
Implementing the ``pytest_cmdline_preparse`` hook
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 7.0
.. versionremoved:: 8.0
Implementing the ``pytest_cmdline_preparse`` hook has been officially deprecated.
Implement the :hook:`pytest_load_initial_conftests` hook instead.
.. code-block:: python
def pytest_cmdline_preparse(config: Config, args: List[str]) -> None: ...
# becomes:
def pytest_load_initial_conftests(
early_config: Config, parser: Parser, args: List[str]
) -> None: ...
Collection changes in pytest 8
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Added a new :class:`pytest.Directory` base collection node, which all collector nodes for filesystem directories are expected to subclass.
This is analogous to the existing :class:`pytest.File` for file nodes.
Changed :class:`pytest.Package` to be a subclass of :class:`pytest.Directory`.
A ``Package`` represents a filesystem directory which is a Python package,
i.e. contains an ``__init__.py`` file.
:class:`pytest.Package` now only collects files in its own directory; previously it collected recursively.
Sub-directories are collected as sub-collector nodes, thus creating a collection tree which mirrors the filesystem hierarchy.
:attr:`session.name <pytest.Session.name>` is now ``""``; previously it was the rootdir directory name.
This matches :attr:`session.nodeid <_pytest.nodes.Node.nodeid>` which has always been `""`.
Added a new :class:`pytest.Dir` concrete collection node, a subclass of :class:`pytest.Directory`.
This node represents a filesystem directory, which is not a :class:`pytest.Package`,
i.e. does not contain an ``__init__.py`` file.
Similarly to ``Package``, it only collects the files in its own directory,
while collecting sub-directories as sub-collector nodes.
Files and directories are now collected in alphabetical order jointly, unless changed by a plugin.
Previously, files were collected before directories.
The collection tree now contains directories/packages up to the :ref:`rootdir <rootdir>`,
for initial arguments that are found within the rootdir.
For files outside the rootdir, only the immediate directory/package is collected --
note however that collecting from outside the rootdir is discouraged.
As an example, given the following filesystem tree::
myroot/
pytest.ini
top/
├── aaa
│ └── test_aaa.py
├── test_a.py
├── test_b
│ ├── __init__.py
│ └── test_b.py
├── test_c.py
└── zzz
├── __init__.py
└── test_zzz.py
the collection tree, as shown by `pytest --collect-only top/` but with the otherwise-hidden :class:`~pytest.Session` node added for clarity,
is now the following::
<Session>
<Dir myroot>
<Dir top>
<Dir aaa>
<Module test_aaa.py>
<Function test_it>
<Module test_a.py>
<Function test_it>
<Package test_b>
<Module test_b.py>
<Function test_it>
<Module test_c.py>
<Function test_it>
<Package zzz>
<Module test_zzz.py>
<Function test_it>
Previously, it was::
<Session>
<Module top/test_a.py>
<Function test_it>
<Module top/test_c.py>
<Function test_it>
<Module top/aaa/test_aaa.py>
<Function test_it>
<Package test_b>
<Module test_b.py>
<Function test_it>
<Package zzz>
<Module test_zzz.py>
<Function test_it>
Code/plugins which rely on a specific shape of the collection tree might need to update.
:class:`pytest.Package` is no longer a :class:`pytest.Module` or :class:`pytest.File`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionchanged:: 8.0
The ``Package`` collector node designates a Python package, that is, a directory with an `__init__.py` file.
Previously ``Package`` was a subtype of ``pytest.Module`` (which represents a single Python module),
the module being the `__init__.py` file.
This has been deemed a design mistake (see :issue:`11137` and :issue:`7777` for details).
The ``path`` property of ``Package`` nodes now points to the package directory instead of the ``__init__.py`` file.
Note that a ``Module`` node for ``__init__.py`` (which is not a ``Package``) may still exist,
if it is picked up during collection (e.g. if you configured :confval:`python_files` to include ``__init__.py`` files).
Collecting ``__init__.py`` files no longer collects package
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionremoved:: 8.0
Running `pytest pkg/__init__.py` now collects the `pkg/__init__.py` file (module) only.
Previously, it collected the entire `pkg` package, including other test files in the directory, but excluding tests in the `__init__.py` file itself
(unless :confval:`python_files` was changed to allow `__init__.py` file).
To collect the entire package, specify just the directory: `pytest pkg`.
The ``pytest.collect`` module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -596,7 +732,7 @@ By using ``legacy`` you will keep using the legacy/xunit1 format when upgrading
pytest 6.0, where the default format will be ``xunit2``.
In order to let users know about the transition, pytest will issue a warning in case
the ``--junitxml`` option is given in the command line but ``junit_family`` is not explicitly
the ``--junit-xml`` option is given in the command line but ``junit_family`` is not explicitly
configured in ``pytest.ini``.
Services known to support the ``xunit2`` format:
@@ -773,8 +909,7 @@ Applying marks to values of a ``pytest.mark.parametrize`` call is now deprecated
(50, 500),
],
)
def test_foo(a, b):
...
def test_foo(a, b): ...
This code applies the ``pytest.mark.xfail(reason="flaky")`` mark to the ``(6, 36)`` value of the above parametrization
call.
@@ -797,8 +932,7 @@ To update the code, use ``pytest.param``:
(50, 500),
],
)
def test_foo(a, b):
...
def test_foo(a, b): ...
.. _pytest_funcarg__ prefix deprecated:
@@ -949,15 +1083,13 @@ This is just a matter of renaming the fixture as the API is the same:
.. code-block:: python
def test_foo(record_xml_property):
...
def test_foo(record_xml_property): ...
Change to:
.. code-block:: python
def test_foo(record_property):
...
def test_foo(record_property): ...
.. _passing command-line string to pytest.main deprecated:
@@ -1119,8 +1251,7 @@ Example of usage:
.. code-block:: python
class MySymbol:
...
class MySymbol: ...
def pytest_namespace():

View File

@@ -172,7 +172,7 @@ class TestRaises:
raise ValueError("demo error")
def test_tupleerror(self):
a, b = [1] # NOQA
a, b = [1] # noqa: F841
def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
items = [1, 2, 3]
@@ -180,7 +180,7 @@ class TestRaises:
a, b = items.pop()
def test_some_error(self):
if namenotexi: # NOQA
if namenotexi: # noqa: F821
pass
def func1(self):

View File

@@ -2,6 +2,7 @@ import os.path
import pytest
mydir = os.path.dirname(__file__)

View File

@@ -1,6 +1,7 @@
import os.path
import shutil
failure_demo = os.path.join(os.path.dirname(__file__), "failure_demo.py")
pytest_plugins = ("pytester",)

View File

@@ -1 +1 @@
collect_ignore = ["nonpython"]
collect_ignore = ["nonpython", "customdirectory"]

View File

@@ -0,0 +1,77 @@
.. _`custom directory collectors`:
Using a custom directory collector
====================================================
By default, pytest collects directories using :class:`pytest.Package`, for directories with ``__init__.py`` files,
and :class:`pytest.Dir` for other directories.
If you want to customize how a directory is collected, you can write your own :class:`pytest.Directory` collector,
and use :hook:`pytest_collect_directory` to hook it up.
.. _`directory manifest plugin`:
A basic example for a directory manifest file
--------------------------------------------------------------
Suppose you want to customize how collection is done on a per-directory basis.
Here is an example ``conftest.py`` plugin that allows directories to contain a ``manifest.json`` file,
which defines how the collection should be done for the directory.
In this example, only a simple list of files is supported,
however you can imagine adding other keys, such as exclusions and globs.
.. include:: customdirectory/conftest.py
:literal:
You can create a ``manifest.json`` file and some test files:
.. include:: customdirectory/tests/manifest.json
:literal:
.. include:: customdirectory/tests/test_first.py
:literal:
.. include:: customdirectory/tests/test_second.py
:literal:
.. include:: customdirectory/tests/test_third.py
:literal:
An you can now execute the test specification:
.. code-block:: pytest
customdirectory $ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/customdirectory
configfile: pytest.ini
collected 2 items
tests/test_first.py . [ 50%]
tests/test_second.py . [100%]
============================ 2 passed in 0.12s =============================
.. regendoc:wipe
Notice how ``test_three.py`` was not executed, because it is not listed in the manifest.
You can verify that your custom collector appears in the collection tree:
.. code-block:: pytest
customdirectory $ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/customdirectory
configfile: pytest.ini
collected 2 items
<Dir customdirectory>
<ManifestDirectory tests>
<Module test_first.py>
<Function test_1>
<Module test_second.py>
<Function test_2>
======================== 2 tests collected in 0.12s ========================

View File

@@ -0,0 +1,28 @@
# content of conftest.py
import json
import pytest
class ManifestDirectory(pytest.Directory):
def collect(self):
# The standard pytest behavior is to loop over all `test_*.py` files and
# call `pytest_collect_file` on each file. This collector instead reads
# the `manifest.json` file and only calls `pytest_collect_file` for the
# files defined there.
manifest_path = self.path / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
ihook = self.ihook
for file in manifest["files"]:
yield from ihook.pytest_collect_file(
file_path=self.path / file, parent=self
)
@pytest.hookimpl
def pytest_collect_directory(path, parent):
# Use our custom collector for directories containing a `mainfest.json` file.
if path.joinpath("manifest.json").is_file():
return ManifestDirectory.from_parent(parent=parent, path=path)
# Otherwise fallback to the standard behavior.
return None

View File

@@ -0,0 +1,6 @@
{
"files": [
"test_first.py",
"test_second.py"
]
}

View File

@@ -0,0 +1,3 @@
# content of test_first.py
def test_1():
pass

View File

@@ -0,0 +1,3 @@
# content of test_second.py
def test_2():
pass

View File

@@ -0,0 +1,3 @@
# content of test_third.py
def test_3():
pass

View File

@@ -18,7 +18,6 @@ For basic examples, see
- :ref:`Fixtures <fixtures>` for basic fixture/setup examples
- :ref:`parametrize` for basic test function parametrization
- :ref:`unittest` for basic unittest integration
- :ref:`noseintegration` for basic nosetests integration
The following examples aim at various use cases you might encounter.
@@ -32,3 +31,4 @@ The following examples aim at various use cases you might encounter.
special
pythoncollection
nonpython
customdirectory

View File

@@ -45,7 +45,7 @@ You can then restrict a test run to only run tests marked with ``webtest``:
$ pytest -v -m webtest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 4 items / 3 deselected / 1 selected
@@ -60,7 +60,7 @@ Or the inverse, running all tests except the webtest ones:
$ pytest -v -m "not webtest"
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 4 items / 1 deselected / 3 selected
@@ -82,7 +82,7 @@ tests based on their module, class, method, or function name:
$ pytest -v test_server.py::TestClass::test_method
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 1 item
@@ -97,7 +97,7 @@ You can also select on the class:
$ pytest -v test_server.py::TestClass
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 1 item
@@ -112,7 +112,7 @@ Or select multiple nodes:
$ pytest -v test_server.py::TestClass test_server.py::test_send_http
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 2 items
@@ -136,7 +136,7 @@ Or select multiple nodes:
Node IDs for failing tests are displayed in the test summary info
when running pytest with the ``-rf`` option. You can also
construct Node IDs from the output of ``pytest --collectonly``.
construct Node IDs from the output of ``pytest --collect-only``.
Using ``-k expr`` to select tests based on their name
-------------------------------------------------------
@@ -156,7 +156,7 @@ The expression matching is now case-insensitive.
$ pytest -v -k http # running with the above defined example module
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 4 items / 3 deselected / 1 selected
@@ -171,7 +171,7 @@ And you can also run all tests except the ones that match the keyword:
$ pytest -k "not send_http" -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 4 items / 1 deselected / 3 selected
@@ -188,7 +188,7 @@ Or to select "http" and "quick" tests:
$ pytest -k "http or quick" -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 4 items / 2 deselected / 2 selected
@@ -397,7 +397,7 @@ the test needs:
$ pytest -E stage2
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -411,7 +411,7 @@ and here is one that specifies exactly the environment needed:
$ pytest -E stage1
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -604,7 +604,7 @@ then you will see two tests skipped and two executed tests as expected:
$ pytest -rs # this option reports skip reasons
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items
@@ -620,7 +620,7 @@ Note that if you specify a platform via the marker-command line option like this
$ pytest -m linux
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items / 3 deselected / 1 selected
@@ -683,7 +683,7 @@ We can now use the ``-m option`` to select one set:
$ pytest -m interface --tb=short
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items / 2 deselected / 2 selected
@@ -709,7 +709,7 @@ or to select both "event" and "interface" tests:
$ pytest -m "interface or event" --tb=short
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items / 1 deselected / 3 selected

View File

@@ -1,14 +1,14 @@
"""
module containing a parametrized tests testing cross-python
serialization via the pickle module.
"""
"""Module containing a parametrized tests testing cross-python serialization
via the pickle module."""
import shutil
import subprocess
import textwrap
import pytest
pythonlist = ["python3.5", "python3.6", "python3.7"]
pythonlist = ["python3.9", "python3.10", "python3.11"]
@pytest.fixture(params=pythonlist)
@@ -33,37 +33,33 @@ class Python:
dumpfile = self.picklefile.with_name("dump.py")
dumpfile.write_text(
textwrap.dedent(
r"""
rf"""
import pickle
f = open({!r}, 'wb')
s = pickle.dump({!r}, f, protocol=2)
f = open({str(self.picklefile)!r}, 'wb')
s = pickle.dump({obj!r}, f, protocol=2)
f.close()
""".format(
str(self.picklefile), obj
)
"""
)
)
subprocess.check_call((self.pythonpath, str(dumpfile)))
subprocess.run((self.pythonpath, str(dumpfile)), check=True)
def load_and_is_true(self, expression):
loadfile = self.picklefile.with_name("load.py")
loadfile.write_text(
textwrap.dedent(
r"""
rf"""
import pickle
f = open({!r}, 'rb')
f = open({str(self.picklefile)!r}, 'rb')
obj = pickle.load(f)
f.close()
res = eval({!r})
res = eval({expression!r})
if not res:
raise SystemExit(1)
""".format(
str(self.picklefile), expression
)
"""
)
)
print(loadfile)
subprocess.check_call((self.pythonpath, str(loadfile)))
subprocess.run((self.pythonpath, str(loadfile)), check=True)
@pytest.mark.parametrize("obj", [42, {}, {1: 3}])

View File

@@ -28,7 +28,7 @@ now execute the test specification:
nonpython $ pytest test_simple.yaml
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/nonpython
collected 2 items
@@ -64,7 +64,7 @@ consulted when reporting in ``verbose`` mode:
nonpython $ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project/nonpython
collecting ... collected 2 items
@@ -90,7 +90,7 @@ interesting to just look at the collection tree:
nonpython $ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/nonpython
collected 2 items

View File

@@ -12,7 +12,7 @@ class YamlFile(pytest.File):
# We need a yaml parser, e.g. PyYAML.
import yaml
raw = yaml.safe_load(self.path.open())
raw = yaml.safe_load(self.path.open(encoding="utf-8"))
for name, spec in sorted(raw.items()):
yield YamlItem.from_parent(self, name=name, spec=spec)
@@ -38,6 +38,7 @@ class YamlItem(pytest.Item):
" no further details known at this point.",
]
)
return super().repr_failure(excinfo)
def reportinfo(self):
return self.path, 0, f"usecase: {self.name}"

View File

@@ -4,8 +4,6 @@
Parametrizing tests
=================================================
.. currentmodule:: _pytest.python
``pytest`` allows to easily parametrize test functions.
For basic docs, see :ref:`parametrize-basics`.
@@ -160,19 +158,20 @@ objects, they are still using the default pytest representation:
$ pytest test_time.py --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 8 items
<Module test_time.py>
<Function test_timedistance_v0[a0-b0-expected0]>
<Function test_timedistance_v0[a1-b1-expected1]>
<Function test_timedistance_v1[forward]>
<Function test_timedistance_v1[backward]>
<Function test_timedistance_v2[20011212-20011211-expected0]>
<Function test_timedistance_v2[20011211-20011212-expected1]>
<Function test_timedistance_v3[forward]>
<Function test_timedistance_v3[backward]>
<Dir parametrize.rst-195>
<Module test_time.py>
<Function test_timedistance_v0[a0-b0-expected0]>
<Function test_timedistance_v0[a1-b1-expected1]>
<Function test_timedistance_v1[forward]>
<Function test_timedistance_v1[backward]>
<Function test_timedistance_v2[20011212-20011211-expected0]>
<Function test_timedistance_v2[20011211-20011212-expected1]>
<Function test_timedistance_v3[forward]>
<Function test_timedistance_v3[backward]>
======================== 8 tests collected in 0.12s ========================
@@ -185,7 +184,7 @@ A quick port of "testscenarios"
Here is a quick port to run tests configured with :pypi:`testscenarios`,
an add-on from Robert Collins for the standard unittest framework. We
only have to work a bit to construct the correct arguments for pytest's
:py:func:`Metafunc.parametrize`:
:py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`:
.. code-block:: python
@@ -222,7 +221,7 @@ this is a fully self-contained example which you can run with:
$ pytest test_scenarios.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items
@@ -236,16 +235,17 @@ If you just collect tests you'll also nicely see 'advanced' and 'basic' as varia
$ pytest --collect-only test_scenarios.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items
<Module test_scenarios.py>
<Class TestSampleWithScenarios>
<Function test_demo1[basic]>
<Function test_demo2[basic]>
<Function test_demo1[advanced]>
<Function test_demo2[advanced]>
<Dir parametrize.rst-195>
<Module test_scenarios.py>
<Class TestSampleWithScenarios>
<Function test_demo1[basic]>
<Function test_demo2[basic]>
<Function test_demo1[advanced]>
<Function test_demo2[advanced]>
======================== 4 tests collected in 0.12s ========================
@@ -314,13 +314,14 @@ Let's first see how it looks like at collection time:
$ pytest test_backends.py --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
<Module test_backends.py>
<Function test_db_initialized[d1]>
<Function test_db_initialized[d2]>
<Dir parametrize.rst-195>
<Module test_backends.py>
<Function test_db_initialized[d1]>
<Function test_db_initialized[d2]>
======================== 2 tests collected in 0.12s ========================
@@ -412,7 +413,7 @@ The result of this test will be successful:
$ pytest -v test_indirect_list.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 1 item
@@ -483,8 +484,8 @@ argument sets to use for each test function. Let's run it:
FAILED test_parametrize.py::TestClass::test_equals[1-2] - assert 1 == 2
1 failed, 2 passed in 0.12s
Indirect parametrization with multiple fixtures
--------------------------------------------------------------
Parametrization with multiple fixtures
--------------------------------------
Here is a stripped down real-life example of using parametrized
testing for testing serialization of objects between different python
@@ -502,11 +503,14 @@ Running it results in some skips if we don't have all the python interpreters in
.. code-block:: pytest
. $ pytest -rs -q multipython.py
........................... [100%]
27 passed in 0.12s
ssssssssssss...ssssssssssss [100%]
========================= short test summary info ==========================
SKIPPED [12] multipython.py:65: 'python3.9' not found
SKIPPED [12] multipython.py:65: 'python3.11' not found
3 passed, 24 skipped in 0.12s
Indirect parametrization of optional implementations/imports
--------------------------------------------------------------------
Parametrization of optional implementations/imports
---------------------------------------------------
If you want to compare the outcomes of several implementations of a given
API, you can write test functions that receive the already imported implementations
@@ -563,7 +567,7 @@ If you run this with reporting for skips enabled:
$ pytest -rs test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
@@ -624,7 +628,7 @@ Then run ``pytest`` with verbose mode and with only the ``basic`` marker:
$ pytest -v -m basic
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 24 items / 21 deselected / 3 selected
@@ -653,13 +657,16 @@ Use :func:`pytest.raises` with the
:ref:`pytest.mark.parametrize ref` decorator to write parametrized tests
in which some tests raise exceptions and others do not.
It may be helpful to use ``nullcontext`` as a complement to ``raises``.
``contextlib.nullcontext`` can be used to test cases that are not expected to
raise exceptions but that should result in some value. The value is given as the
``enter_result`` parameter, which will be available as the ``with`` statements
target (``e`` in the example below).
For example:
.. code-block:: python
from contextlib import nullcontext as does_not_raise
from contextlib import nullcontext
import pytest
@@ -667,16 +674,17 @@ For example:
@pytest.mark.parametrize(
"example_input,expectation",
[
(3, does_not_raise()),
(2, does_not_raise()),
(1, does_not_raise()),
(3, nullcontext(2)),
(2, nullcontext(3)),
(1, nullcontext(6)),
(0, pytest.raises(ZeroDivisionError)),
],
)
def test_division(example_input, expectation):
"""Test how much I know division."""
with expectation:
assert (6 / example_input) is not None
with expectation as e:
assert (6 / example_input) == e
In the example above, the first three test cases should run unexceptionally,
while the fourth should raise ``ZeroDivisionError``.
In the example above, the first three test cases should run without any
exceptions, while the fourth should raise a``ZeroDivisionError`` exception,
which is expected by pytest.

View File

@@ -147,15 +147,16 @@ The test collection would look like this:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
configfile: pytest.ini
collected 2 items
<Module check_myapp.py>
<Class CheckMyApp>
<Function simple_check>
<Function complex_check>
<Dir pythoncollection.rst-196>
<Module check_myapp.py>
<Class CheckMyApp>
<Function simple_check>
<Function complex_check>
======================== 2 tests collected in 0.12s ========================
@@ -209,16 +210,18 @@ You can always peek at the collection tree without running tests like this:
. $ pytest --collect-only pythoncollection.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
configfile: pytest.ini
collected 3 items
<Module CWD/pythoncollection.py>
<Function test_function>
<Class TestClass>
<Function test_method>
<Function test_anothermethod>
<Dir pythoncollection.rst-196>
<Dir CWD>
<Module pythoncollection.py>
<Function test_function>
<Class TestClass>
<Function test_method>
<Function test_anothermethod>
======================== 3 tests collected in 0.12s ========================
@@ -291,7 +294,7 @@ file will be left out:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
configfile: pytest.ini
collected 0 items

View File

@@ -9,7 +9,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
assertion $ pytest failure_demo.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/assertion
collected 44 items
@@ -70,27 +70,29 @@ Here is a nice run of several failures and how ``pytest`` presents things:
> assert not f()
E assert not 42
E + where 42 = <function TestFailing.test_not.<locals>.f at 0xdeadbeef0002>()
E + where 42 = <function TestFailing.test_not.<locals>.f at 0xdeadbeef0006>()
failure_demo.py:39: AssertionError
_________________ TestSpecialisedExplanations.test_eq_text _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0006>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0007>
def test_eq_text(self):
> assert "spam" == "eggs"
E AssertionError: assert 'spam' == 'eggs'
E
E - eggs
E + spam
failure_demo.py:44: AssertionError
_____________ TestSpecialisedExplanations.test_eq_similar_text _____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0007>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0008>
def test_eq_similar_text(self):
> assert "foo 1 bar" == "foo 2 bar"
E AssertionError: assert 'foo 1 bar' == 'foo 2 bar'
E
E - foo 2 bar
E ? ^
E + foo 1 bar
@@ -99,11 +101,12 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:47: AssertionError
____________ TestSpecialisedExplanations.test_eq_multiline_text ____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0008>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0009>
def test_eq_multiline_text(self):
> assert "foo\nspam\nbar" == "foo\neggs\nbar"
E AssertionError: assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
E
E foo
E - eggs
E + spam
@@ -112,13 +115,14 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:50: AssertionError
______________ TestSpecialisedExplanations.test_eq_long_text _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0009>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000a>
def test_eq_long_text(self):
a = "1" * 100 + "a" + "2" * 100
b = "1" * 100 + "b" + "2" * 100
> assert a == b
E AssertionError: assert '111111111111...2222222222222' == '111111111111...2222222222222'
E
E Skipping 90 identical leading characters in diff, use -v to show
E Skipping 91 identical trailing characters in diff, use -v to show
E - 1111111111b222222222
@@ -129,55 +133,58 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:55: AssertionError
_________ TestSpecialisedExplanations.test_eq_long_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000a>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000b>
def test_eq_long_text_multiline(self):
a = "1\n" * 100 + "a" + "2\n" * 100
b = "1\n" * 100 + "b" + "2\n" * 100
> assert a == b
E AssertionError: assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n...n2\n2\n2\n2\n'
E
E Skipping 190 identical leading characters in diff, use -v to show
E Skipping 191 identical trailing characters in diff, use -v to show
E 1
E 1
E 1
E 1
E 1...
E
E ...Full output truncated (6 lines hidden), use '-vv' to show
E ...Full output truncated (7 lines hidden), use '-vv' to show
failure_demo.py:60: AssertionError
_________________ TestSpecialisedExplanations.test_eq_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000b>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000c>
def test_eq_list(self):
> assert [0, 1, 2] == [0, 1, 3]
E assert [0, 1, 2] == [0, 1, 3]
E
E At index 2 diff: 2 != 3
E Use -v to get more diff
failure_demo.py:63: AssertionError
______________ TestSpecialisedExplanations.test_eq_list_long _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000c>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000d>
def test_eq_list_long(self):
a = [0] * 100 + [1] + [3] * 100
b = [0] * 100 + [2] + [3] * 100
> assert a == b
E assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]
E
E At index 100 diff: 1 != 2
E Use -v to get more diff
failure_demo.py:68: AssertionError
_________________ TestSpecialisedExplanations.test_eq_dict _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000d>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000e>
def test_eq_dict(self):
> assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}
E AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
E
E Omitting 1 identical items, use -vv to show
E Differing items:
E {'b': 1} != {'b': 2}
@@ -190,11 +197,12 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:71: AssertionError
_________________ TestSpecialisedExplanations.test_eq_set __________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000e>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000f>
def test_eq_set(self):
> assert {0, 10, 11, 12} == {0, 20, 21}
E assert {0, 10, 11, 12} == {0, 20, 21}
E
E Extra items in the left set:
E 10
E 11
@@ -207,18 +215,19 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:74: AssertionError
_____________ TestSpecialisedExplanations.test_eq_longer_list ______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000f>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0010>
def test_eq_longer_list(self):
> assert [1, 2] == [1, 2, 3]
E assert [1, 2] == [1, 2, 3]
E
E Right contains one more item: 3
E Use -v to get more diff
failure_demo.py:77: AssertionError
_________________ TestSpecialisedExplanations.test_in_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0010>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0011>
def test_in_list(self):
> assert 1 in [0, 2, 3, 4, 5]
@@ -227,12 +236,13 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:80: AssertionError
__________ TestSpecialisedExplanations.test_not_in_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0011>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0012>
def test_not_in_text_multiline(self):
text = "some multiline\ntext\nwhich\nincludes foo\nand a\ntail"
> assert "foo" not in text
E AssertionError: assert 'foo' not in 'some multil...nand a\ntail'
E
E 'foo' is contained here:
E some multiline
E text
@@ -245,12 +255,13 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:84: AssertionError
___________ TestSpecialisedExplanations.test_not_in_text_single ____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0012>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0013>
def test_not_in_text_single(self):
text = "single foo line"
> assert "foo" not in text
E AssertionError: assert 'foo' not in 'single foo line'
E
E 'foo' is contained here:
E single foo line
E ? +++
@@ -258,12 +269,13 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:88: AssertionError
_________ TestSpecialisedExplanations.test_not_in_text_single_long _________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0013>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0014>
def test_not_in_text_single_long(self):
text = "head " * 50 + "foo " + "tail " * 20
> assert "foo" not in text
E AssertionError: assert 'foo' not in 'head head h...l tail tail '
E
E 'foo' is contained here:
E head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
E ? +++
@@ -271,12 +283,13 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:92: AssertionError
______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0014>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0015>
def test_not_in_text_single_long_term(self):
text = "head " * 50 + "f" * 70 + "tail " * 20
> assert "f" * 70 not in text
E AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head h...l tail tail '
E
E 'ffffffffffffffffff...fffffffffffffffffff' is contained here:
E head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
E ? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -284,7 +297,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:96: AssertionError
______________ TestSpecialisedExplanations.test_eq_dataclass _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0015>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0016>
def test_eq_dataclass(self):
from dataclasses import dataclass
@@ -311,7 +324,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:108: AssertionError
________________ TestSpecialisedExplanations.test_eq_attrs _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0016>
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0017>
def test_eq_attrs(self):
import attr
@@ -345,7 +358,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
i = Foo()
> assert i.b == 2
E assert 1 == 2
E + where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef0017>.b
E + where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef0018>.b
failure_demo.py:128: AssertionError
_________________________ test_attribute_instance __________________________
@@ -356,8 +369,8 @@ Here is a nice run of several failures and how ``pytest`` presents things:
> assert Foo().b == 2
E AssertionError: assert 1 == 2
E + where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0018>.b
E + where <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0018> = <class 'failure_demo.test_attribute_instance.<locals>.Foo'>()
E + where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0019>.b
E + where <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0019> = <class 'failure_demo.test_attribute_instance.<locals>.Foo'>()
failure_demo.py:135: AssertionError
__________________________ test_attribute_failure __________________________
@@ -375,7 +388,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:146:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0xdeadbeef0019>
self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0xdeadbeef001a>
def _get_b(self):
> raise Exception("Failed to get attrib")
@@ -393,15 +406,15 @@ Here is a nice run of several failures and how ``pytest`` presents things:
> assert Foo().b == Bar().b
E AssertionError: assert 1 == 2
E + where 1 = <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001a>.b
E + where <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001a> = <class 'failure_demo.test_attribute_multiple.<locals>.Foo'>()
E + and 2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001b>.b
E + where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001b> = <class 'failure_demo.test_attribute_multiple.<locals>.Bar'>()
E + where 1 = <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001b>.b
E + where <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001b> = <class 'failure_demo.test_attribute_multiple.<locals>.Foo'>()
E + and 2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001c>.b
E + where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001c> = <class 'failure_demo.test_attribute_multiple.<locals>.Bar'>()
failure_demo.py:156: AssertionError
__________________________ TestRaises.test_raises __________________________
self = <failure_demo.TestRaises object at 0xdeadbeef001c>
self = <failure_demo.TestRaises object at 0xdeadbeef001d>
def test_raises(self):
s = "qwe"
@@ -411,7 +424,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:166: ValueError
______________________ TestRaises.test_raises_doesnt _______________________
self = <failure_demo.TestRaises object at 0xdeadbeef001d>
self = <failure_demo.TestRaises object at 0xdeadbeef001e>
def test_raises_doesnt(self):
> raises(OSError, int, "3")
@@ -420,7 +433,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:169: Failed
__________________________ TestRaises.test_raise ___________________________
self = <failure_demo.TestRaises object at 0xdeadbeef001e>
self = <failure_demo.TestRaises object at 0xdeadbeef001f>
def test_raise(self):
> raise ValueError("demo error")
@@ -429,16 +442,16 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:172: ValueError
________________________ TestRaises.test_tupleerror ________________________
self = <failure_demo.TestRaises object at 0xdeadbeef001f>
self = <failure_demo.TestRaises object at 0xdeadbeef0020>
def test_tupleerror(self):
> a, b = [1] # NOQA
> a, b = [1] # noqa: F841
E ValueError: not enough values to unpack (expected 2, got 1)
failure_demo.py:175: ValueError
______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______
self = <failure_demo.TestRaises object at 0xdeadbeef0020>
self = <failure_demo.TestRaises object at 0xdeadbeef0021>
def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
items = [1, 2, 3]
@@ -451,10 +464,10 @@ Here is a nice run of several failures and how ``pytest`` presents things:
items is [1, 2, 3]
________________________ TestRaises.test_some_error ________________________
self = <failure_demo.TestRaises object at 0xdeadbeef0021>
self = <failure_demo.TestRaises object at 0xdeadbeef0022>
def test_some_error(self):
> if namenotexi: # NOQA
> if namenotexi: # noqa: F821
E NameError: name 'namenotexi' is not defined
failure_demo.py:183: NameError
@@ -482,7 +495,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
abc-123:2: AssertionError
____________________ TestMoreErrors.test_complex_error _____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0022>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0023>
def test_complex_error(self):
def f():
@@ -508,7 +521,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:6: AssertionError
___________________ TestMoreErrors.test_z1_unpack_error ____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0023>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0024>
def test_z1_unpack_error(self):
items = []
@@ -518,7 +531,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:217: ValueError
____________________ TestMoreErrors.test_z2_type_error _____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0024>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0025>
def test_z2_type_error(self):
items = 3
@@ -528,20 +541,20 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:221: TypeError
______________________ TestMoreErrors.test_startswith ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0025>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0026>
def test_startswith(self):
s = "123"
g = "456"
> assert s.startswith(g)
E AssertionError: assert False
E + where False = <built-in method startswith of str object at 0xdeadbeef0026>('456')
E + where <built-in method startswith of str object at 0xdeadbeef0026> = '123'.startswith
E + where False = <built-in method startswith of str object at 0xdeadbeef0027>('456')
E + where <built-in method startswith of str object at 0xdeadbeef0027> = '123'.startswith
failure_demo.py:226: AssertionError
__________________ TestMoreErrors.test_startswith_nested ___________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0027>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef0028>
def test_startswith_nested(self):
def f():
@@ -552,15 +565,15 @@ Here is a nice run of several failures and how ``pytest`` presents things:
> assert f().startswith(g())
E AssertionError: assert False
E + where False = <built-in method startswith of str object at 0xdeadbeef0026>('456')
E + where <built-in method startswith of str object at 0xdeadbeef0026> = '123'.startswith
E + where '123' = <function TestMoreErrors.test_startswith_nested.<locals>.f at 0xdeadbeef0028>()
E + and '456' = <function TestMoreErrors.test_startswith_nested.<locals>.g at 0xdeadbeef0029>()
E + where False = <built-in method startswith of str object at 0xdeadbeef0027>('456')
E + where <built-in method startswith of str object at 0xdeadbeef0027> = '123'.startswith
E + where '123' = <function TestMoreErrors.test_startswith_nested.<locals>.f at 0xdeadbeef0029>()
E + and '456' = <function TestMoreErrors.test_startswith_nested.<locals>.g at 0xdeadbeef002a>()
failure_demo.py:235: AssertionError
_____________________ TestMoreErrors.test_global_func ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002a>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002b>
def test_global_func(self):
> assert isinstance(globf(42), float)
@@ -571,18 +584,18 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:238: AssertionError
_______________________ TestMoreErrors.test_instance _______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002b>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002c>
def test_instance(self):
self.x = 6 * 7
> assert self.x != 42
E assert 42 != 42
E + where 42 = <failure_demo.TestMoreErrors object at 0xdeadbeef002b>.x
E + where 42 = <failure_demo.TestMoreErrors object at 0xdeadbeef002c>.x
failure_demo.py:242: AssertionError
_______________________ TestMoreErrors.test_compare ________________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002c>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002d>
def test_compare(self):
> assert globf(10) < 5
@@ -592,7 +605,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:245: AssertionError
_____________________ TestMoreErrors.test_try_finally ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002d>
self = <failure_demo.TestMoreErrors object at 0xdeadbeef002e>
def test_try_finally(self):
x = 1
@@ -603,7 +616,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:250: AssertionError
___________________ TestCustomAssertMsg.test_single_line ___________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef002e>
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef002f>
def test_single_line(self):
class A:
@@ -618,7 +631,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:261: AssertionError
____________________ TestCustomAssertMsg.test_multiline ____________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef002f>
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef0030>
def test_multiline(self):
class A:
@@ -637,7 +650,7 @@ Here is a nice run of several failures and how ``pytest`` presents things:
failure_demo.py:268: AssertionError
___________________ TestCustomAssertMsg.test_custom_repr ___________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef0030>
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef0031>
def test_custom_repr(self):
class JSON:

View File

@@ -168,7 +168,7 @@ Now we'll get feedback on a bad argument:
If you need to provide more detailed error messages, you can use the
``type`` parameter and raise ``pytest.UsageError``:
``type`` parameter and raise :exc:`pytest.UsageError`:
.. code-block:: python
@@ -232,7 +232,7 @@ directory with the above conftest.py:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 0 items
@@ -296,7 +296,7 @@ and when running it will see a skipped "slow" test:
$ pytest -rs # "-rs" means report details on the little 's'
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
@@ -312,7 +312,7 @@ Or run it including the ``slow`` marked test:
$ pytest --runslow
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
@@ -456,7 +456,7 @@ which will add the string to the test header accordingly:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
project deps: mylib-1.1
rootdir: /home/sweet/project
collected 0 items
@@ -484,7 +484,7 @@ which will add info only when run with "--v":
$ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
info1: did you know that ...
did you?
@@ -499,7 +499,7 @@ and nothing when run plainly:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 0 items
@@ -538,7 +538,7 @@ Now we can profile which test functions execute the slowest:
$ pytest --durations=3
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items
@@ -644,7 +644,7 @@ If we run this:
$ pytest -rx
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items
@@ -660,6 +660,31 @@ If we run this:
E assert 0
test_step.py:11: AssertionError
================================ XFAILURES =================================
______________________ TestUserHandling.test_deletion ______________________
item = <Function test_deletion>
def pytest_runtest_setup(item):
if "incremental" in item.keywords:
# retrieve the class name of the test
cls_name = str(item.cls)
# check if a previous test has failed for this class
if cls_name in _test_failed_incremental:
# retrieve the index of the test (if parametrize is used in combination with incremental)
parametrize_index = (
tuple(item.callspec.indices.values())
if hasattr(item, "callspec")
else ()
)
# retrieve the name of the first test function to fail for this class name and index
test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
# if name found, test has failed for the combination of class name & test name
if test_name is not None:
> pytest.xfail(f"previous test failed ({test_name})")
E _pytest.outcomes.XFailed: previous test failed (test_modification)
conftest.py:47: XFailed
========================= short test summary info ==========================
XFAIL test_step.py::TestUserHandling::test_deletion - reason: previous test failed (test_modification)
================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================
@@ -691,7 +716,7 @@ Here is an example for making a ``db`` fixture available in a directory:
pass
@pytest.fixture(scope="session")
@pytest.fixture(scope="package")
def db():
return DB()
@@ -726,14 +751,14 @@ We can run this:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 7 items
test_step.py .Fx. [ 57%]
a/test_db.py F [ 71%]
a/test_db2.py F [ 85%]
b/test_error.py E [100%]
a/test_db.py F [ 14%]
a/test_db2.py F [ 28%]
b/test_error.py E [ 42%]
test_step.py .Fx. [100%]
================================== ERRORS ==================================
_______________________ ERROR at setup of test_root ________________________
@@ -745,39 +770,39 @@ We can run this:
/home/sweet/project/b/test_error.py:1
================================= FAILURES =================================
_________________________________ test_a1 __________________________________
db = <conftest.DB object at 0xdeadbeef0002>
def test_a1(db):
> assert 0, db # to show value
E AssertionError: <conftest.DB object at 0xdeadbeef0002>
E assert 0
a/test_db.py:2: AssertionError
_________________________________ test_a2 __________________________________
db = <conftest.DB object at 0xdeadbeef0002>
def test_a2(db):
> assert 0, db # to show value
E AssertionError: <conftest.DB object at 0xdeadbeef0002>
E assert 0
a/test_db2.py:2: AssertionError
____________________ TestUserHandling.test_modification ____________________
self = <test_step.TestUserHandling object at 0xdeadbeef0002>
self = <test_step.TestUserHandling object at 0xdeadbeef0003>
def test_modification(self):
> assert 0
E assert 0
test_step.py:11: AssertionError
_________________________________ test_a1 __________________________________
db = <conftest.DB object at 0xdeadbeef0003>
def test_a1(db):
> assert 0, db # to show value
E AssertionError: <conftest.DB object at 0xdeadbeef0003>
E assert 0
a/test_db.py:2: AssertionError
_________________________________ test_a2 __________________________________
db = <conftest.DB object at 0xdeadbeef0003>
def test_a2(db):
> assert 0, db # to show value
E AssertionError: <conftest.DB object at 0xdeadbeef0003>
E assert 0
a/test_db2.py:2: AssertionError
========================= short test summary info ==========================
FAILED test_step.py::TestUserHandling::test_modification - assert 0
FAILED a/test_db.py::test_a1 - AssertionError: <conftest.DB object at 0x7...
FAILED a/test_db2.py::test_a2 - AssertionError: <conftest.DB object at 0x...
FAILED test_step.py::TestUserHandling::test_modification - assert 0
ERROR b/test_error.py::test_root
============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ==============
@@ -808,16 +833,15 @@ case we just write some information out to a ``failures`` file:
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
rep = yield
# we only look at actual failing test calls, not setup/teardown
if rep.when == "call" and rep.failed:
mode = "a" if os.path.exists("failures") else "w"
with open("failures", mode) as f:
with open("failures", mode, encoding="utf-8") as f:
# let's also access a fixture for the fun of it
if "tmp_path" in item.fixturenames:
extra = " ({})".format(item.funcargs["tmp_path"])
@@ -826,6 +850,8 @@ case we just write some information out to a ``failures`` file:
f.write(rep.nodeid + extra + "\n")
return rep
if you then have failing tests:
@@ -845,7 +871,7 @@ and run them:
$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
@@ -899,16 +925,17 @@ here is a little example implemented via a local plugin:
phase_report_key = StashKey[Dict[str, CollectReport]]()
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()
rep = yield
# store test results for each phase of a call, which can
# be "setup", "call", "teardown"
item.stash.setdefault(phase_report_key, {})[rep.when] = rep
return rep
@pytest.fixture
def something(request):
@@ -953,7 +980,7 @@ and run it:
$ pytest -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items
@@ -1088,4 +1115,4 @@ application with standard ``pytest`` command-line options:
.. code-block:: bash
./app_main --pytest --verbose --tb=long --junitxml=results.xml test-suite/
./app_main --pytest --verbose --tb=long --junit=xml=results.xml test-suite/

View File

@@ -1,5 +1,6 @@
import pytest
xfail = pytest.mark.xfail

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
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
something should be green, we'd say ``assert thing == "green"``.

View File

@@ -85,7 +85,7 @@ style of setup/teardown functions:
In addition, pytest continues to support :ref:`xunitsetup`. You can mix
both styles, moving incrementally from classic to new style, as you
prefer. You can also start out from existing :ref:`unittest.TestCase
style <unittest.TestCase>` or :ref:`nose based <nosestyle>` projects.
style <unittest.TestCase>`.
@@ -162,7 +162,7 @@ A note about fixture cleanup
----------------------------
pytest does not do any special processing for :data:`SIGTERM <signal.SIGTERM>` and
:data:`SIGQUIT <signal.SIGQUIT>` signals (:data:`SIGINT <signal.SIGINT>` is handled naturally
``SIGQUIT`` signals (:data:`SIGINT <signal.SIGINT>` is handled naturally
by the Python runtime via :class:`KeyboardInterrupt`), so fixtures that manage external resources which are important
to be cleared when the Python process is terminated (by those signals) might leak resources.

View File

@@ -60,8 +60,10 @@ Within Python modules, ``pytest`` also discovers tests using the standard
:ref:`unittest.TestCase <unittest.TestCase>` subclassing technique.
Choosing a test layout / import rules
-------------------------------------
.. _`test layout`:
Choosing a test layout
----------------------
``pytest`` supports two common test layouts:
@@ -294,3 +296,20 @@ See also `pypa/setuptools#1684 <https://github.com/pypa/setuptools/issues/1684>`
setuptools intends to
`remove the test command <https://github.com/pypa/setuptools/issues/931>`_.
Checking with flake8-pytest-style
---------------------------------
In order to ensure that pytest is being used correctly in your project,
it can be helpful to use the `flake8-pytest-style <https://github.com/m-burst/flake8-pytest-style>`_ flake8 plugin.
flake8-pytest-style checks for common mistakes and coding style violations in pytest code,
such as incorrect use of fixtures, test function names, and markers.
By using this plugin, you can catch these errors early in the development process
and ensure that your pytest code is consistent and easy to maintain.
A list of the lints detected by flake8-pytest-style can be found on its `PyPI page <https://pypi.org/project/flake8-pytest-style/>`_.
.. note::
flake8-pytest-style is not an official pytest project. Some of the rules enforce certain style choices, such as using `@pytest.fixture()` over `@pytest.fixture`, but you can configure the plugin to fit your preferred style.

View File

@@ -10,19 +10,27 @@ Import modes
pytest as a testing framework needs to import test modules and ``conftest.py`` files for execution.
Importing files in Python (at least until recently) is a non-trivial processes, often requiring
changing :data:`sys.path`. Some aspects of the
Importing files in Python is a non-trivial processes, so aspects of the
import process can be controlled through the ``--import-mode`` command-line flag, which can assume
these values:
* ``prepend`` (default): the directory path containing each module will be inserted into the *beginning*
of :py:data:`sys.path` if not already there, and then imported with the :func:`importlib.import_module <importlib.import_module>` function.
.. _`import-mode-prepend`:
This requires test module names to be unique when the test directory tree is not arranged in
packages, because the modules will put in :py:data:`sys.modules` after importing.
* ``prepend`` (default): the directory path containing each module will be inserted into the *beginning*
of :py:data:`sys.path` if not already there, and then imported with
the :func:`importlib.import_module <importlib.import_module>` function.
It is highly recommended to arrange your test modules as packages by adding ``__init__.py`` files to your directories
containing tests. This will make the tests part of a proper Python package, allowing pytest to resolve their full
name (for example ``tests.core.test_core`` for ``test_core.py`` inside the ``tests.core`` package).
If the test directory tree is not arranged as packages, then each test file needs to have a unique name
compared to the other test files, otherwise pytest will raise an error if it finds two tests with the same name.
This is the classic mechanism, dating back from the time Python 2 was still supported.
.. _`import-mode-append`:
* ``append``: the directory containing each module is appended to the end of :py:data:`sys.path` if not already
there, and imported with :func:`importlib.import_module <importlib.import_module>`.
@@ -38,32 +46,78 @@ these values:
the tests will run against the installed version
of ``pkg_under_test`` when ``--import-mode=append`` is used whereas
with ``prepend`` they would pick up the local version. This kind of confusion is why
we advocate for using :ref:`src <src-layout>` layouts.
we advocate for using :ref:`src-layouts <src-layout>`.
Same as ``prepend``, requires test module names to be unique when the test directory tree is
not arranged in packages, because the modules will put in :py:data:`sys.modules` after importing.
* ``importlib``: new in pytest-6.0, this mode uses more fine control mechanisms provided by :mod:`importlib` to import test modules. This gives full control over the import process, and doesn't require changing :py:data:`sys.path`.
.. _`import-mode-importlib`:
For this reason this doesn't require test module names to be unique.
* ``importlib``: this mode uses more fine control mechanisms provided by :mod:`importlib` to import test modules, without changing :py:data:`sys.path`.
One drawback however is that test modules are non-importable by each other. Also, utility
modules in the tests directories are not automatically importable because the tests directory is no longer
added to :py:data:`sys.path`.
Advantages of this mode:
Initially we intended to make ``importlib`` the default in future releases, however it is clear now that
it has its own set of drawbacks so the default will remain ``prepend`` for the foreseeable future.
* pytest will not change :py:data:`sys.path` at all.
* Test module names do not need to be unique -- pytest will generate a unique name automatically based on the ``rootdir``.
Disadvantages:
* Test modules can't import each other.
* Testing utility modules in the tests directories (for example a ``tests.helpers`` module containing test-related functions/classes)
are not importable. The recommendation in this case it to place testing utility modules together with the application/library
code, for example ``app.testing.helpers``.
Important: by "test utility modules" we mean functions/classes which are imported by
other tests directly; this does not include fixtures, which should be placed in ``conftest.py`` files, along
with the test modules, and are discovered automatically by pytest.
It works like this:
1. Given a certain module path, for example ``tests/core/test_models.py``, derives a canonical name
like ``tests.core.test_models`` and tries to import it.
For non-test modules this will work if they are accessible via :py:data:`sys.path`, so
for example ``.env/lib/site-packages/app/core.py`` will be importable as ``app.core``.
This is happens when plugins import non-test modules (for example doctesting).
If this step succeeds, the module is returned.
For test modules, unless they are reachable from :py:data:`sys.path`, this step will fail.
2. If the previous step fails, we import the module directly using ``importlib`` facilities, which lets us import it without
changing :py:data:`sys.path`.
Because Python requires the module to also be available in :py:data:`sys.modules`, pytest derives a unique name for it based
on its relative location from the ``rootdir``, and adds the module to :py:data:`sys.modules`.
For example, ``tests/core/test_models.py`` will end up being imported as the module ``tests.core.test_models``.
.. versionadded:: 6.0
.. note::
Initially we intended to make ``importlib`` the default in future releases, however it is clear now that
it has its own set of drawbacks so the default will remain ``prepend`` for the foreseeable future.
.. note::
By default, pytest will not attempt to resolve namespace packages automatically, but that can
be changed via the :confval:`consider_namespace_packages` configuration variable.
.. seealso::
The :confval:`pythonpath` configuration variable.
The :confval:`consider_namespace_packages` configuration variable.
:ref:`test layout`.
``prepend`` and ``append`` import modes scenarios
-------------------------------------------------
Here's a list of scenarios when using ``prepend`` or ``append`` import modes where pytest needs to
change ``sys.path`` in order to import test modules or ``conftest.py`` files, and the issues users
change :py:data:`sys.path` in order to import test modules or ``conftest.py`` files, and the issues users
might encounter because of that.
Test modules / ``conftest.py`` files inside packages
@@ -92,7 +146,7 @@ pytest will find ``foo/bar/tests/test_foo.py`` and realize it is part of a packa
there's an ``__init__.py`` file in the same folder. It will then search upwards until it can find the
last folder which still contains an ``__init__.py`` file in order to find the package *root* (in
this case ``foo/``). To load the module, it will insert ``root/`` to the front of
``sys.path`` (if not there already) in order to load
:py:data:`sys.path` (if not there already) in order to load
``test_foo.py`` as the *module* ``foo.bar.tests.test_foo``.
The same logic applies to the ``conftest.py`` file: it will be imported as ``foo.conftest`` module.
@@ -122,8 +176,8 @@ When executing:
pytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that
there's no ``__init__.py`` file in the same folder. It will then add ``root/foo/bar/tests`` to
``sys.path`` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done
with the ``conftest.py`` file by adding ``root/foo`` to ``sys.path`` to import it as ``conftest``.
:py:data:`sys.path` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done
with the ``conftest.py`` file by adding ``root/foo`` to :py:data:`sys.path` to import it as ``conftest``.
For this reason this layout cannot have test modules with the same name, as they all will be
imported in the global import namespace.
@@ -136,7 +190,7 @@ Invoking ``pytest`` versus ``python -m pytest``
-----------------------------------------------
Running pytest with ``pytest [...]`` instead of ``python -m pytest [...]`` yields nearly
equivalent behaviour, except that the latter will add the current directory to ``sys.path``, which
equivalent behaviour, except that the latter will add the current directory to :py:data:`sys.path`, which
is standard ``python`` behavior.
See also :ref:`invoke-python`.

View File

@@ -11,8 +11,6 @@ funcarg mechanism, see :ref:`historical funcargs and pytest.funcargs`.
If you are new to pytest, then you can simply ignore this
section and read the other sections.
.. currentmodule:: _pytest
Shortcomings of the previous ``pytest_funcarg__`` mechanism
--------------------------------------------------------------
@@ -46,7 +44,7 @@ There are several limitations and difficulties with this approach:
2. parametrizing the "db" resource is not straight forward:
you need to apply a "parametrize" decorator or implement a
:py:func:`~hookspec.pytest_generate_tests` hook
:hook:`pytest_generate_tests` hook
calling :py:func:`~pytest.Metafunc.parametrize` which
performs parametrization at the places where the resource
is used. Moreover, you need to modify the factory to use an
@@ -94,15 +92,14 @@ Direct parametrization of funcarg resource factories
Previously, funcarg factories could not directly cause parametrization.
You needed to specify a ``@parametrize`` decorator on your test function
or implement a ``pytest_generate_tests`` hook to perform
or implement a :hook:`pytest_generate_tests` hook to perform
parametrization, i.e. calling a test multiple times with different value
sets. pytest-2.3 introduces a decorator for use on the factory itself:
.. code-block:: python
@pytest.fixture(params=["mysql", "pg"])
def db(request):
... # use request.param
def db(request): ... # use request.param
Here the factory will be invoked twice (with the respective "mysql"
and "pg" values set as ``request.param`` attributes) and all of
@@ -143,8 +140,7 @@ argument:
.. code-block:: python
@pytest.fixture()
def db(request):
...
def db(request): ...
The name under which the funcarg resource can be requested is ``db``.
@@ -153,8 +149,7 @@ aka:
.. code-block:: python
def pytest_funcarg__db(request):
...
def pytest_funcarg__db(request): ...
But it is then not possible to define scoping and parametrization.

View File

@@ -9,7 +9,7 @@ Get Started
Install ``pytest``
----------------------------------------
``pytest`` requires: Python 3.7+ or PyPy3.
``pytest`` requires: Python 3.8+ or PyPy3.
1. Run the following command in your command line:
@@ -22,7 +22,7 @@ Install ``pytest``
.. code-block:: bash
$ pytest --version
pytest 7.2.0.dev534+ga2c84caaa.d20230317
pytest 8.1.0
.. _`simpletest`:
@@ -47,7 +47,7 @@ The test
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -97,6 +97,30 @@ Use the :ref:`raises <assertraises>` helper to assert that some code raises an e
with pytest.raises(SystemExit):
f()
You can also use the context provided by :ref:`raises <assertraises>` to
assert that an expected exception is part of a raised :class:`ExceptionGroup`:
.. code-block:: python
# content of test_exceptiongroup.py
import pytest
def f():
raise ExceptionGroup(
"Group message",
[
RuntimeError(),
],
)
def test_exception_in_group():
with pytest.raises(ExceptionGroup) as excinfo:
f()
assert excinfo.group_contains(RuntimeError)
assert not excinfo.group_contains(TypeError)
Execute the test function with “quiet” reporting mode:
.. code-block:: pytest

View File

@@ -112,7 +112,7 @@ More details can be found in the :pull:`original PR <3317>`.
.. note::
in a future major release of pytest we will introduce class based markers,
at which point markers will no longer be limited to instances of :py:class:`~_pytest.mark.Mark`.
at which point markers will no longer be limited to instances of :py:class:`~pytest.Mark`.
cache plugin integrated into the core
@@ -227,8 +227,7 @@ to use strings:
@pytest.mark.skipif("sys.version_info >= (3,3)")
def test_function():
...
def test_function(): ...
During test function setup the skipif condition is evaluated by calling
``eval('sys.version_info >= (3,0)', namespace)``. The namespace contains
@@ -262,8 +261,7 @@ configuration value which you might have added:
.. code-block:: python
@pytest.mark.skipif("not config.getvalue('db')")
def test_function():
...
def test_function(): ...
The equivalent with "boolean conditions" is:

View File

@@ -29,7 +29,7 @@ you will see the return value of the function call:
$ pytest test_assert1.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -54,14 +54,13 @@ operators. (See :ref:`tbreportdemo`). This allows you to use the
idiomatic python constructs without boilerplate code while not losing
introspection information.
However, if you specify a message with the assertion like this:
If a message is specified with the assertion like this:
.. code-block:: python
assert a % 2 == 0, "value was odd, should be even"
then no assertion introspection takes places at all and the message
will be simply shown in the traceback.
it is printed alongside the assertion introspection in the traceback.
See :ref:`assert-details` for more information on assertion introspection.
@@ -99,6 +98,27 @@ and if you need to have access to the actual exception info you may use:
the actual exception raised. The main attributes of interest are
``.type``, ``.value`` and ``.traceback``.
Note that ``pytest.raises`` will match the exception type or any subclasses (like the standard ``except`` statement).
If you want to check if a block of code is raising an exact exception type, you need to check that explicitly:
.. code-block:: python
def test_foo_not_implemented():
def foo():
raise NotImplementedError
with pytest.raises(RuntimeError) as excinfo:
foo()
assert excinfo.type is RuntimeError
The :func:`pytest.raises` call will succeed, even though the function raises :class:`NotImplementedError`, because
:class:`NotImplementedError` is a subclass of :class:`RuntimeError`; however the following `assert` statement will
catch the problem.
Matching exception messages
~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can pass a ``match`` keyword parameter to the context-manager to test
that a regular expression matches on the string representation of an exception
(similar to the ``TestCase.assertRaisesRegex`` method from ``unittest``):
@@ -116,36 +136,113 @@ that a regular expression matches on the string representation of an exception
with pytest.raises(ValueError, match=r".* 123 .*"):
myfunc()
The regexp parameter of the ``match`` method is matched with the ``re.search``
function, so in the above example ``match='123'`` would have worked as
well.
Notes:
There's an alternate form of the :func:`pytest.raises` function where you pass
a function that will be executed with the given ``*args`` and ``**kwargs`` and
assert that the given exception is raised:
* The ``match`` parameter is matched with the :func:`re.search`
function, so in the above example ``match='123'`` would have worked as well.
* The ``match`` parameter also matches against `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``.
.. _`assert-matching-exception-groups`:
Matching exception groups
~~~~~~~~~~~~~~~~~~~~~~~~~
You can also use the :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>`
method to test for exceptions returned as part of an :class:`ExceptionGroup`:
.. code-block:: python
pytest.raises(ExpectedException, func, *args, **kwargs)
def test_exception_in_group():
with pytest.raises(ExceptionGroup) as excinfo:
raise ExceptionGroup(
"Group message",
[
RuntimeError("Exception 123 raised"),
],
)
assert excinfo.group_contains(RuntimeError, match=r".* 123 .*")
assert not excinfo.group_contains(TypeError)
The optional ``match`` keyword parameter works the same way as for
:func:`pytest.raises`.
By default ``group_contains()`` will recursively search for a matching
exception at any level of nested ``ExceptionGroup`` instances. You can
specify a ``depth`` keyword parameter if you only want to match an
exception at a specific level; exceptions contained directly in the top
``ExceptionGroup`` would match ``depth=1``.
.. code-block:: python
def test_exception_in_group_at_given_depth():
with pytest.raises(ExceptionGroup) as excinfo:
raise ExceptionGroup(
"Group message",
[
RuntimeError(),
ExceptionGroup(
"Nested group",
[
TypeError(),
],
),
],
)
assert excinfo.group_contains(RuntimeError, depth=1)
assert excinfo.group_contains(TypeError, depth=2)
assert not excinfo.group_contains(RuntimeError, depth=2)
assert not excinfo.group_contains(TypeError, depth=1)
Alternate form (legacy)
~~~~~~~~~~~~~~~~~~~~~~~
There is an alternate form where you pass
a function that will be executed, along ``*args`` and ``**kwargs``, and :func:`pytest.raises`
will execute the function with the arguments and assert that the given exception is raised:
.. code-block:: python
def func(x):
if x <= 0:
raise ValueError("x needs to be larger than zero")
pytest.raises(ValueError, func, x=-1)
The reporter will provide you with helpful output in case of failures such as *no
exception* or *wrong exception*.
Note that it is also possible to specify a "raises" argument to
``pytest.mark.xfail``, which checks that the test is failing in a more
This form was the original :func:`pytest.raises` API, developed before the ``with`` statement was
added to the Python language. Nowadays, this form is rarely used, with the context-manager form (using ``with``)
being considered more readable.
Nonetheless, this form is fully supported and not deprecated in any way.
xfail mark and pytest.raises
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is also possible to specify a ``raises`` argument to
:ref:`pytest.mark.xfail <pytest.mark.xfail ref>`, which checks that the test is failing in a more
specific way than just having any exception raised:
.. code-block:: python
def f():
raise IndexError()
@pytest.mark.xfail(raises=IndexError)
def test_f():
f()
Using :func:`pytest.raises` is likely to be better for cases where you are
testing exceptions your own code is deliberately raising, whereas using
``@pytest.mark.xfail`` with a check function is probably better for something
like documenting unfixed bugs (where the test describes what "should" happen)
or bugs in dependencies.
This will only "xfail" if the test fails by raising ``IndexError`` or subclasses.
* Using :ref:`pytest.mark.xfail <pytest.mark.xfail ref>` with the ``raises`` parameter is probably better for something
like documenting unfixed bugs (where the test describes what "should" happen) or bugs in dependencies.
* Using :func:`pytest.raises` is likely to be better for cases where you are
testing exceptions your own code is deliberately raising, which is the majority of cases.
.. _`assertwarns`:
@@ -183,7 +280,7 @@ if you run this module:
$ pytest test_assert2.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -197,6 +294,7 @@ if you run this module:
set2 = set("8035")
> assert set1 == set2
E AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'}
E
E Extra items in the left set:
E '1'
E Extra items in the right set:

View File

@@ -86,7 +86,7 @@ If you then run it with ``--lf``:
$ pytest --lf
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
run-last-failure: rerun previous 2 failures
@@ -132,7 +132,7 @@ of ``FF`` and dots):
$ pytest --ff
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 50 items
run-last-failure: rerun previous 2 failures first
@@ -176,14 +176,21 @@ with more recent files coming first.
Behavior when no tests failed in the last run
---------------------------------------------
When no tests failed in the last run, or when no cached ``lastfailed`` data was
found, ``pytest`` can be configured either to run all of the tests or no tests,
using the ``--last-failed-no-failures`` option, which takes one of the following values:
The ``--lfnf/--last-failed-no-failures`` option governs the behavior of ``--last-failed``.
Determines whether to execute tests when there are no previously (known)
failures or when no cached ``lastfailed`` data was found.
There are two options:
* ``all``: when there are no known test failures, runs all tests (the full test suite). This is the default.
* ``none``: when there are no known test failures, just emits a message stating this and exit successfully.
Example:
.. code-block:: bash
pytest --last-failed --last-failed-no-failures all # run all tests (default behavior)
pytest --last-failed --last-failed-no-failures none # run no tests and exit
pytest --last-failed --last-failed-no-failures all # runs the full test suite (default behavior)
pytest --last-failed --last-failed-no-failures none # runs no tests and exits successfully
The new config.cache object
--------------------------------
@@ -206,12 +213,12 @@ across pytest invocations:
@pytest.fixture
def mydata(request):
val = request.config.cache.get("example/value", None)
def mydata(pytestconfig):
val = pytestconfig.cache.get("example/value", None)
if val is None:
expensive_computation()
val = 42
request.config.cache.set("example/value", val)
pytestconfig.cache.set("example/value", val)
return val
@@ -274,7 +281,7 @@ You can always peek at the content of the cache using the
$ pytest --cache-show
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
cachedir: /home/sweet/project/.pytest_cache
--------------------------- cache values for '*' ---------------------------
@@ -296,7 +303,7 @@ filtering:
$ pytest --cache-show example/*
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
cachedir: /home/sweet/project/.pytest_cache
----------------------- cache values for 'example/*' -----------------------

View File

@@ -83,7 +83,7 @@ of the failing function and hide the other one:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items

View File

@@ -28,7 +28,7 @@ Running pytest now produces this output:
$ pytest test_show_warnings.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -382,8 +382,6 @@ warnings: a WarningsRecorder instance. To view the recorded warnings, you can
iterate over this instance, call ``len`` on it to get the number of recorded
warnings, or index into it to get a particular recorded warning.
.. currentmodule:: _pytest.warnings
Full API: :class:`~_pytest.recwarn.WarningsRecorder`.
.. _`warns use cases`:

View File

@@ -30,7 +30,7 @@ then you can just invoke ``pytest`` directly:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -58,7 +58,7 @@ and functions, including from test modules:
$ pytest --doctest-modules
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items

View File

@@ -4,8 +4,8 @@ How to use pytest with an existing test suite
==============================================
Pytest can be used with most existing test suites, but its
behavior differs from other test runners such as :ref:`nose <noseintegration>` or
Python's default unittest framework.
behavior differs from other test runners such as Python's
default unittest framework.
Before using this section you will want to :ref:`install pytest <getstarted>`.

View File

@@ -135,10 +135,6 @@ Warning about unraisable exceptions and unhandled thread exceptions
.. versionadded:: 6.2
.. note::
These features only work on Python>=3.8.
Unhandled exceptions are exceptions that are raised in a situation in which
they cannot propagate to a caller. The most common case is an exception raised
in a :meth:`__del__ <object.__del__>` implementation.

View File

@@ -433,7 +433,7 @@ marked ``smtp_connection`` fixture function. Running the test looks like this:
$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items
@@ -494,7 +494,7 @@ Fixtures are created when first requested by a test, and are destroyed based on
* ``function``: the default scope, the fixture is destroyed at the end of the test.
* ``class``: the fixture is destroyed during teardown of the last test in the class.
* ``module``: the fixture is destroyed during teardown of the last test in the module.
* ``package``: the fixture is destroyed during teardown of the last test in the package.
* ``package``: the fixture is destroyed during teardown of the last test in the package where the fixture is defined, including sub-packages and sub-directories within it.
* ``session``: the fixture is destroyed at the end of the test session.
.. note::
@@ -771,7 +771,7 @@ For yield fixtures, the first teardown code to run is from the right-most fixtur
$ pytest -s test_finalizers.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -805,7 +805,7 @@ For finalizers, the first fixture to run is last call to `request.addfinalizer`.
$ pytest -s test_finalizers.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -1271,7 +1271,7 @@ configured in multiple ways.
Extending the previous example, we can flag the fixture to create two
``smtp_connection`` fixture instances which will cause all tests using the fixture
to run twice. The fixture function gets access to each parameter
through the special :py:class:`request <FixtureRequest>` object:
through the special :py:class:`request <pytest.FixtureRequest>` object:
.. code-block:: python
@@ -1414,27 +1414,28 @@ Running the above tests results in the following test IDs being used:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 12 items
<Module test_anothersmtp.py>
<Function test_showhelo[smtp.gmail.com]>
<Function test_showhelo[mail.python.org]>
<Module test_emaillib.py>
<Function test_email_received>
<Module test_finalizers.py>
<Function test_bar>
<Module test_ids.py>
<Function test_a[spam]>
<Function test_a[ham]>
<Function test_b[eggs]>
<Function test_b[1]>
<Module test_module.py>
<Function test_ehlo[smtp.gmail.com]>
<Function test_noop[smtp.gmail.com]>
<Function test_ehlo[mail.python.org]>
<Function test_noop[mail.python.org]>
<Dir fixtures.rst-214>
<Module test_anothersmtp.py>
<Function test_showhelo[smtp.gmail.com]>
<Function test_showhelo[mail.python.org]>
<Module test_emaillib.py>
<Function test_email_received>
<Module test_finalizers.py>
<Function test_bar>
<Module test_ids.py>
<Function test_a[spam]>
<Function test_a[ham]>
<Function test_b[eggs]>
<Function test_b[1]>
<Module test_module.py>
<Function test_ehlo[smtp.gmail.com]>
<Function test_noop[smtp.gmail.com]>
<Function test_ehlo[mail.python.org]>
<Function test_noop[mail.python.org]>
======================= 12 tests collected in 0.12s ========================
@@ -1468,7 +1469,7 @@ Running this test will *skip* the invocation of ``data_set`` with value ``2``:
$ pytest test_fixture_marks.py -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 3 items
@@ -1518,7 +1519,7 @@ Here we declare an ``app`` fixture which receives the previously defined
$ pytest -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 2 items
@@ -1598,7 +1599,7 @@ Let's run the tests in verbose mode and with looking at the print-output:
$ pytest -v -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
rootdir: /home/sweet/project
collecting ... collected 8 items
@@ -1698,7 +1699,7 @@ and declare its use in a test module via a ``usefixtures`` marker:
class TestDirectoryInit:
def test_cwd_starts_empty(self):
assert os.listdir(os.getcwd()) == []
with open("myfile", "w") as f:
with open("myfile", "w", encoding="utf-8") as f:
f.write("hello")
def test_cwd_again_starts_empty(self):
@@ -1720,8 +1721,7 @@ You can specify multiple fixtures like this:
.. code-block:: python
@pytest.mark.usefixtures("cleandir", "anotherfixture")
def test():
...
def test(): ...
and you may specify fixture usage at the test module level using :globalvar:`pytestmark`:
@@ -1749,11 +1749,9 @@ into an ini-file:
@pytest.mark.usefixtures("my_other_fixture")
@pytest.fixture
def my_fixture_that_sadly_wont_use_my_other_fixture():
...
def my_fixture_that_sadly_wont_use_my_other_fixture(): ...
Currently this will not generate any error or warning, but this is intended
to be handled by :issue:`3664`.
This generates a deprecation warning, and will become an error in Pytest 8.
.. _`override fixtures`:

View File

@@ -52,7 +52,6 @@ pytest and other test systems
existingtestsuite
unittest
nose
xunit_setup
pytest development environment

View File

@@ -172,6 +172,13 @@ the records for the ``setup`` and ``call`` stages during teardown like so:
The full API is available at :class:`pytest.LogCaptureFixture`.
.. warning::
The ``caplog`` fixture adds a handler to the root logger to capture logs. If the root logger is
modified during a test, for example with ``logging.config.dictConfig``, this handler may be
removed and cause no logs to be captured. To avoid this, ensure that any root logger configuration
only adds to the existing handlers.
.. _live_logs:
@@ -199,8 +206,9 @@ option names are:
* ``log_cli_date_format``
If you need to record the whole test suite logging calls to a file, you can pass
``--log-file=/path/to/log/file``. This log file is opened in write mode which
``--log-file=/path/to/log/file``. This log file is opened in write mode by default which
means that it will be overwritten at each run tests session.
If you'd like the file opened in append mode instead, then you can pass ``--log-file-mode=a``.
Note that relative paths for the log-file location, whether passed on the CLI or declared in a
config file, are always resolved relative to the current working directory.
@@ -216,12 +224,13 @@ All of the log file options can also be set in the configuration INI file. The
option names are:
* ``log_file``
* ``log_file_mode``
* ``log_file_level``
* ``log_file_format``
* ``log_file_date_format``
You can call ``set_log_path()`` to customize the log_file path dynamically. This functionality
is considered **experimental**.
is considered **experimental**. Note that ``set_log_path()`` respects the ``log_file_mode`` option.
.. _log_colors:
@@ -234,7 +243,7 @@ through ``add_color_level()``. Example:
.. code-block:: python
@pytest.hookimpl
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
logging_plugin = config.pluginmanager.get_plugin("logging-plugin")

View File

@@ -1,82 +0,0 @@
.. _`noseintegration`:
How to run tests written for nose
=======================================
``pytest`` has basic support for running tests written for nose_.
.. warning::
This functionality has been deprecated and is likely to be removed in ``pytest 8.x``.
.. _nosestyle:
Usage
-------------
After :ref:`installation` type:
.. code-block:: bash
python setup.py develop # make sure tests can import our package
pytest # instead of 'nosetests'
and you should be able to run your nose style tests and
make use of pytest's capabilities.
Supported nose Idioms
----------------------
* ``setup()`` and ``teardown()`` at module/class/method level: any function or method called ``setup`` will be called during the setup phase for each test, same for ``teardown``.
* ``SkipTest`` exceptions and markers
* setup/teardown decorators
* ``__test__`` attribute on modules/classes/functions
* general usage of nose utilities
Unsupported idioms / known issues
----------------------------------
- unittest-style ``setUp, tearDown, setUpClass, tearDownClass``
are recognized only on ``unittest.TestCase`` classes but not
on plain classes. ``nose`` supports these methods also on plain
classes but pytest deliberately does not. As nose and pytest already
both support ``setup_class, teardown_class, setup_method, teardown_method``
it doesn't seem useful to duplicate the unittest-API like nose does.
If you however rather think pytest should support the unittest-spelling on
plain classes please post to :issue:`377`.
- nose imports test modules with the same import path (e.g.
``tests.test_mode``) but different file system paths
(e.g. ``tests/test_mode.py`` and ``other/tests/test_mode.py``)
by extending sys.path/import semantics. pytest does not do that
but there is discussion in :issue:`268` for adding some support. Note that
`nose2 choose to avoid this sys.path/import hackery <https://nose2.readthedocs.io/en/latest/differences.html#test-discovery-and-loading>`_.
If you place a conftest.py file in the root directory of your project
(as determined by pytest) pytest will run tests "nose style" against
the code below that directory by adding it to your ``sys.path`` instead of
running against your installed code.
You may find yourself wanting to do this if you ran ``python setup.py install``
to set up your project, as opposed to ``python setup.py develop`` or any of
the package manager equivalents. Installing with develop in a
virtual environment like tox is recommended over this pattern.
- nose-style doctests are not collected and executed correctly,
also doctest fixtures don't work.
- no nose-configuration is recognized.
- ``yield``-based methods are unsupported as of pytest 4.1.0. They are
fundamentally incompatible with pytest because they don't support fixtures
properly since collection and test execution are separated.
Migrating from nose to pytest
------------------------------
`nose2pytest <https://github.com/pytest-dev/nose2pytest>`_ is a Python script
and pytest plugin to help convert Nose-based tests into pytest-based tests.
Specifically, the script transforms nose.tools.assert_* function calls into
raw assert statements, while preserving format of original arguments
as much as possible.
.. _nose: https://nose.readthedocs.io/en/latest/

View File

@@ -16,6 +16,12 @@ Examples for modifying traceback printing:
pytest -l # show local variables (shortcut)
pytest --no-showlocals # hide local variables (if addopts enables them)
pytest --capture=fd # default, capture at the file descriptor level
pytest --capture=sys # capture at the sys level
pytest --capture=no # don't capture
pytest -s # don't capture (shortcut)
pytest --capture=tee-sys # capture to logs but also output to sys level streams
pytest --tb=auto # (default) 'long' tracebacks for the first and last
# entry, but 'short' style for the other entries
pytest --tb=long # exhaustive, informative traceback formatting
@@ -36,6 +42,16 @@ option you make sure a trace is shown.
Verbosity
--------------------------------------------------
Examples for modifying printing verbosity:
.. code-block:: bash
pytest --quiet # quiet - less verbose - mode
pytest -q # quiet - less verbose - mode (shortcut)
pytest -v # increase verbosity, display individual test names
pytest -vv # more verbose, display more details from the test output
pytest -vvv # not a standard , but may be used for even more detail in certain setups
The ``-v`` flag controls the verbosity of pytest output in various aspects: test session progress, assertion
details when tests fail, fixtures details with ``--fixtures``, etc.
@@ -84,6 +100,7 @@ Executing pytest normally gives us this output (we are skipping the header to fo
fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
> assert fruits1 == fruits2
E AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']
E
E At index 2 diff: 'grapes' != 'orange'
E Use -v to get more diff
@@ -95,6 +112,7 @@ Executing pytest normally gives us this output (we are skipping the header to fo
number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
> assert number_to_text1 == number_to_text2
E AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}
E
E Omitting 1 identical items, use -vv to show
E Left contains 4 more items:
E {'1': 1, '2': 2, '3': 3, '4': 4}
@@ -146,12 +164,15 @@ Now we can increase pytest's verbosity:
fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
> assert fruits1 == fruits2
E AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']
E
E At index 2 diff: 'grapes' != 'orange'
E
E Full diff:
E - ['banana', 'apple', 'orange', 'melon', 'kiwi']
E ? ^ ^^
E + ['banana', 'apple', 'grapes', 'melon', 'kiwi']
E ? ^ ^ +
E [
E 'banana',
E 'apple',...
E
E ...Full output truncated (7 lines hidden), use '-vv' to show
test_verbosity_example.py:8: AssertionError
____________________________ test_numbers_fail _____________________________
@@ -161,15 +182,15 @@ Now we can increase pytest's verbosity:
number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
> assert number_to_text1 == number_to_text2
E AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}
E
E Omitting 1 identical items, use -vv to show
E Left contains 4 more items:
E {'1': 1, '2': 2, '3': 3, '4': 4}
E Right contains 4 more items:
E {'10': 10, '20': 20, '30': 30, '40': 40}
E Full diff:
E - {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}
E ? - - - - - - - -
E + {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
E ...
E
E ...Full output truncated (16 lines hidden), use '-vv' to show
test_verbosity_example.py:14: AssertionError
___________________________ test_long_text_fail ____________________________
@@ -215,12 +236,20 @@ Now if we increase verbosity even more:
fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
> assert fruits1 == fruits2
E AssertionError: assert ['banana', 'apple', 'grapes', 'melon', 'kiwi'] == ['banana', 'apple', 'orange', 'melon', 'kiwi']
E
E At index 2 diff: 'grapes' != 'orange'
E
E Full diff:
E - ['banana', 'apple', 'orange', 'melon', 'kiwi']
E ? ^ ^^
E + ['banana', 'apple', 'grapes', 'melon', 'kiwi']
E ? ^ ^ +
E [
E 'banana',
E 'apple',
E - 'orange',
E ? ^ ^^
E + 'grapes',
E ? ^ ^ +
E 'melon',
E 'kiwi',
E ]
test_verbosity_example.py:8: AssertionError
____________________________ test_numbers_fail _____________________________
@@ -230,16 +259,30 @@ Now if we increase verbosity even more:
number_to_text2 = {str(x * 10): x * 10 for x in range(5)}
> assert number_to_text1 == number_to_text2
E AssertionError: assert {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4} == {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}
E
E Common items:
E {'0': 0}
E Left contains 4 more items:
E {'1': 1, '2': 2, '3': 3, '4': 4}
E Right contains 4 more items:
E {'10': 10, '20': 20, '30': 30, '40': 40}
E
E Full diff:
E - {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}
E ? - - - - - - - -
E + {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
E {
E '0': 0,
E - '10': 10,
E ? - -
E + '1': 1,
E - '20': 20,
E ? - -
E + '2': 2,
E - '30': 30,
E ? - -
E + '3': 3,
E - '40': 40,
E ? - -
E + '4': 4,
E }
test_verbosity_example.py:14: AssertionError
___________________________ test_long_text_fail ____________________________
@@ -270,6 +313,22 @@ situations, for example you are shown even fixtures that start with ``_`` if you
Using higher verbosity levels (``-vvv``, ``-vvvv``, ...) is supported, but has no effect in pytest itself at the moment,
however some plugins might make use of higher verbosity.
.. _`pytest.fine_grained_verbosity`:
Fine-grained verbosity
~~~~~~~~~~~~~~~~~~~~~~
In addition to specifying the application wide verbosity level, it is possible to control specific aspects independently.
This is done by setting a verbosity level in the configuration file for the specific aspect of the output.
:confval:`verbosity_assertions`: Controls how verbose the assertion output should be when pytest is executed. Running
``pytest --no-header`` with a value of ``2`` would have the same output as the previous example, but each test inside
the file is shown by a single character in the output.
:confval:`verbosity_test_cases`: Controls how verbose the test execution output should be when pytest is executed.
Running ``pytest --no-header`` with a value of ``2`` would have the same output as the first verbosity example, but each
test inside the file gets its own line in the output.
.. _`pytest.detailed_failed_tests_usage`:
Producing a detailed summary report
@@ -324,7 +383,7 @@ Example:
$ pytest -ra
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 6 items
@@ -347,10 +406,19 @@ Example:
E assert 0
test_example.py:14: AssertionError
================================ XFAILURES =================================
________________________________ test_xfail ________________________________
def test_xfail():
> pytest.xfail("xfailing this test")
E _pytest.outcomes.XFailed: xfailing this test
test_example.py:26: XFailed
================================= XPASSES ==================================
========================= short test summary info ==========================
SKIPPED [1] test_example.py:22: skipping this test
XFAIL test_example.py::test_xfail - reason: xfailing this test
XPASS test_example.py::test_xpass always xfail
XPASS test_example.py::test_xpass - always xfail
ERROR test_example.py::test_error - assert 0
FAILED test_example.py::test_fail - assert 0
== 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===
@@ -380,7 +448,7 @@ More than one character can be used, so for example to only see failed and skipp
$ pytest -rfs
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 6 items
@@ -415,7 +483,7 @@ captured output:
$ pytest -rpP
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 6 items
@@ -478,7 +546,7 @@ integration servers, use this invocation:
.. code-block:: bash
pytest --junitxml=path
pytest --junit-xml=path
to create an XML file at ``path``.

View File

@@ -56,7 +56,7 @@ them in turn:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items
@@ -167,7 +167,7 @@ Let's run this:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items

View File

@@ -47,8 +47,7 @@ which may be passed an optional ``reason``:
.. code-block:: python
@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
...
def test_the_unknown(): ...
Alternatively, it is also possible to skip imperatively during test execution or setup
@@ -93,8 +92,7 @@ when run on an interpreter earlier than Python3.10:
@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
def test_function():
...
def test_function(): ...
If the condition evaluates to ``True`` during collection, the test function will be skipped,
with the specified reason appearing in the summary when using ``-rs``.
@@ -112,8 +110,7 @@ You can share ``skipif`` markers between modules. Consider this test module:
@minversion
def test_function():
...
def test_function(): ...
You can import the marker and reuse it in another test module:
@@ -124,8 +121,7 @@ You can import the marker and reuse it in another test module:
@minversion
def test_anotherfunction():
...
def test_anotherfunction(): ...
For larger test suites it's usually a good idea to have one file
where you define the markers which you then consistently apply
@@ -232,8 +228,7 @@ expect a test to fail:
.. code-block:: python
@pytest.mark.xfail
def test_function():
...
def test_function(): ...
This test will run but no traceback will be reported when it fails. Instead, terminal
reporting will list it in the "expected to fail" (``XFAIL``) or "unexpectedly
@@ -275,8 +270,7 @@ that condition as the first parameter:
.. code-block:: python
@pytest.mark.xfail(sys.platform == "win32", reason="bug in a 3rd party library")
def test_function():
...
def test_function(): ...
Note that you have to pass a reason as well (see the parameter description at
:ref:`pytest.mark.xfail ref`).
@@ -289,8 +283,7 @@ You can specify the motive of an expected failure with the ``reason`` parameter:
.. code-block:: python
@pytest.mark.xfail(reason="known parser issue")
def test_function():
...
def test_function(): ...
``raises`` parameter
@@ -302,8 +295,7 @@ a single exception, or a tuple of exceptions, in the ``raises`` argument.
.. code-block:: python
@pytest.mark.xfail(raises=RuntimeError)
def test_function():
...
def test_function(): ...
Then the test will be reported as a regular failure if it fails with an
exception not mentioned in ``raises``.
@@ -317,8 +309,7 @@ even executed, use the ``run`` parameter as ``False``:
.. code-block:: python
@pytest.mark.xfail(run=False)
def test_function():
...
def test_function(): ...
This is specially useful for xfailing tests that are crashing the interpreter and should be
investigated later.
@@ -334,8 +325,7 @@ You can change this by setting the ``strict`` keyword-only parameter to ``True``
.. code-block:: python
@pytest.mark.xfail(strict=True)
def test_function():
...
def test_function(): ...
This will make ``XPASS`` ("unexpectedly passing") results from this test to fail the test suite.

View File

@@ -8,9 +8,8 @@ How to use temporary directories and files in tests
The ``tmp_path`` fixture
------------------------
You can use the ``tmp_path`` fixture which will
provide a temporary directory unique to the test invocation,
created in the `base temporary directory`_.
You can use the ``tmp_path`` fixture which will provide a temporary directory
unique to each test function.
``tmp_path`` is a :class:`pathlib.Path` object. Here is an example test usage:
@@ -24,8 +23,8 @@ created in the `base temporary directory`_.
d = tmp_path / "sub"
d.mkdir()
p = d / "hello.txt"
p.write_text(CONTENT)
assert p.read_text() == CONTENT
p.write_text(CONTENT, encoding="utf-8")
assert p.read_text(encoding="utf-8") == CONTENT
assert len(list(tmp_path.iterdir())) == 1
assert 0
@@ -36,7 +35,7 @@ Running this would result in a passed test except for the last
$ pytest test_tmp_path.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item
@@ -51,8 +50,8 @@ Running this would result in a passed test except for the last
d = tmp_path / "sub"
d.mkdir()
p = d / "hello.txt"
p.write_text(CONTENT)
assert p.read_text() == CONTENT
p.write_text(CONTENT, encoding="utf-8")
assert p.read_text(encoding="utf-8") == CONTENT
assert len(list(tmp_path.iterdir())) == 1
> assert 0
E assert 0
@@ -62,6 +61,11 @@ Running this would result in a passed test except for the last
FAILED test_tmp_path.py::test_create_file - assert 0
============================ 1 failed in 0.12s =============================
By default, ``pytest`` retains the temporary directory for the last 3 ``pytest``
invocations. Concurrent invocations of the same test function are supported by
configuring the base temporary directory to be unique for each concurrent
run. See `temporary directory location and retention`_ for details.
.. _`tmp_path_factory example`:
The ``tmp_path_factory`` fixture
@@ -100,7 +104,7 @@ See :ref:`tmp_path_factory API <tmp_path_factory factory api>` for details.
.. _tmpdir:
The ``tmpdir`` and ``tmpdir_factory`` fixtures
---------------------------------------------------
----------------------------------------------
The ``tmpdir`` and ``tmpdir_factory`` fixtures are similar to ``tmp_path``
and ``tmp_path_factory``, but use/return legacy `py.path.local`_ objects
@@ -124,10 +128,10 @@ See :fixture:`tmpdir <tmpdir>` :fixture:`tmpdir_factory <tmpdir_factory>`
API for details.
.. _`base temporary directory`:
.. _`temporary directory location and retention`:
The default base temporary directory
-----------------------------------------------
Temporary directory location and retention
------------------------------------------
Temporary directories are by default created as sub-directories of
the system temporary directory. The base name will be ``pytest-NUM`` where
@@ -152,7 +156,7 @@ You can override the default temporary directory setting like this:
for that purpose only.
When distributing tests on the local machine using ``pytest-xdist``, care is taken to
automatically configure a basetemp directory for the sub processes such that all temporary
data lands below a single per-test run basetemp directory.
automatically configure a `basetemp` directory for the sub processes such that all temporary
data lands below a single per-test run temporary directory.
.. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html

Some files were not shown because too many files have changed in this diff Show More