Commit Graph

3325 Commits

Author SHA1 Message Date
Bruno Oliveira 2ccc73be9a
Merge pull request #12087 from nicoddemus/revert-path-deprecations
Revert legacy path removals
2024-03-08 20:06:47 -03:00
Ran Benita ff551b7685 fixtures: simplify a bit of code 2024-03-09 00:02:06 +02:00
Ran Benita f5de111357 fixtures: check scope mismatch in `getfixturevalue` already-cached case
This makes sure the scope is always compatible, and also allows using
`getfixturevalue` in `pytest_fixture_setup` so less internal magic.
2024-03-09 00:02:06 +02:00
Ran Benita 71671f60b5 fixtures: improve fixture scope mismatch message
- Separate the requesting from the requested.

- Avoid the term "factory", I think most people don't distinguish
  between "fixture" and "fixture function" (i.e. "factory") and would
  find the term "factory" unfamiliar.
2024-03-09 00:02:06 +02:00
Ran Benita a9d1f55a0f fixtures: simplify scope checking
There are two non-optimal things in the current way scope checking is
done:

- It runs on `SubRequest`, but doesn't use the `SubRequest's scope,
  which is confusing. Instead it takes `invoking_scope` and
  `requested_scope`.

- Because `_check_scope` is only defined on `SubRequest` and not
  `TopRequest`, `_compute_fixture_value` first creates the `SubRequest`
  only then checks the scope (hence the need for the previous point).

Instead, also define `_check_scope` on `TopRequest` (always valid), and
remove `invoking_scope`, using `self._scope` instead.
2024-03-09 00:02:06 +02:00
Ran Benita 1a5e0eb71d unittest: make `obj` work more like `Function`/`Class`
Previously, the `obj` of a `TestCaseFunction` (the unittest plugin item
type) was the unbound method. This is unlike regular `Class` where the
`obj` is a bound method to a fresh instance.

This difference necessitated several special cases in in places outside
of the unittest plugin, such as `FixtureDef` and `FixtureRequest`, and
made things a bit harder to understand.

Instead, match how the python plugin does it, including collecting
fixtures from a fresh instance.

The downside is that now this instance for fixture-collection is kept
around in memory, but it's the same as `Class` so nothing new. Users
should only initialize stuff in `setUp`/`setUpClass` and similar
methods, and not in `__init__` which is generally off-limits in
`TestCase` subclasses.

I am not sure why there was a difference in the first place, though I
will say the previous unittest approach is probably the preferable one,
but first let's get consistency.
2024-03-08 14:03:26 +02:00
Bruno Oliveira dacee1f11d Revert "Remove deprecated py.path hook arguments"
This reverts commit a98f02d423.
2024-03-07 19:50:33 -03:00
Bruno Oliveira 303cd0d48a Revert "Remove deprecated py.path (`fspath`) node constructor arguments"
This reverts commit 6c89f9261c.
2024-03-07 19:50:33 -03:00
Bruno Oliveira 03e54712dd
Do not import duplicated modules with --importmode=importlib (#12074)
Regression brought up by #11475.
2024-03-04 12:44:56 -03: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
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 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 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
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 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
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
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
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
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
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 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 9f13d41d7b code: fix `IndexError` crash in `getstatementrange_ast`
Fix #11953.
2024-02-17 18:43:55 +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
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 288201b8f5 recwarn: let base exceptions propagate through `pytest.warns` again
Fix #11907.
2024-02-16 12:07:56 +02: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
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
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 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
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 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
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 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 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
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
Pierre Sassoulas 233ab89f13 [ruff] Fix all consider [*cats, garfield] instead of cats + [garfield] 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 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
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
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
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
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
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 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
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
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 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
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
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
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
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
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