Commit Graph

3325 Commits

Author SHA1 Message Date
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
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
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 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 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
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
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 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 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
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
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
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 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 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 d220880924
nodes: fix tracebacks from collection errors are not getting pruned (#11711)
Fix #11710.
2023-12-31 10:14:23 +02: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
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 75f292d9df Some minor typing tweaks 2023-12-19 23:29:27 +02: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
Arthur Richard 047ba83dab
Improve pytest.exit docs (#11698)
Fixes #11695
2023-12-14 08:14:36 -03: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 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
Ran Benita 0ae02e2165 nodes,python: mark abstract node classes as ABCs
Fixes #11676
2023-12-07 16:41:07 +02:00
Ran Benita ee91d095f6 doc: fix more broken Sphinx references 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
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 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 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
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
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
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
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
Bruno Oliveira 970d11cf34 Explicitly export error and path from py
Required by mypy 1.7.0
2023-11-14 07:29:40 -03:00
Sharad Nair 7c7bdf4574
Sanitize ini-options default handling #11282 (#11594)
Fixes #11282
2023-11-11 13:08:18 -03:00
Bruno Oliveira 1e02797d15
Improve pytest.raises docs (#11578) 2023-11-04 10:24:57 +00: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
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] 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
ryanpudd 3ab70cd561
Use hyphenated cmdline options in docs (#11490)
Fix #11091
2023-10-10 21:16:24 +00: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
Reagan Lee 9bbfe995ee
Add more comprehensive set assertion rewrites (#11469)
Fixes #10617
2023-10-02 18:37:52 -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 4ae102c003
Merge pull request #11446 from bluetech/pluggy-typing
Improve pluggy-related typing
2023-09-24 15:42:58 +03: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
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
Chris Mahoney 8062743f6b
Change deprecated_call to handle FutureWarning (#11448)
Fixes #11447
2023-09-18 09:34:05 -03: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
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
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