Commit Graph

269 Commits

Author SHA1 Message Date
karlicoss c02465cee0
Support PEP420 (implicit namespace packages) as `--pyargs` target. (#13426)
Previously, when running `--pyargs pkg`, if you didn't have `pkg/__init__.py`, pytest would fail with `ERROR: module or package not found: pkg (missing __init__.py?)`.

If used in conjunction with `consider_namespace_packages` in config, pytest discovers the package and tests inside it correctly.

If used in conjunction with `consider_namespace_packages` in config, test
modules get correct `__package__` and `__name__` attributes as well.

In addition, remove `"namespace"` origin handling -- this value isn't used since python 3.8.
See:
- https://github.com/python/cpython/pull/5481
- https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.submodule_search_locations

Fixes #478
Fixes #2371
Fixes #10569
2025-07-12 08:03:22 -03:00
Florian Bruhin 2861de3293 Avoid using private _addoption
The only differences between the two is that:

- `addoption` checks for conflicts, but `_addoption` does not
- `addoption` complains if a lower-case short option is given,
  `_addoption` does not

Yet it looks like using the latter has been inconsistently cargo-culted with
newer options.
2025-02-15 16:03:27 +01:00
Florian Bruhin 71ae4d1df4 Move --config-file / --rootdir options
"test session [...] configuration" seems more fitting than "general"
2025-02-15 16:03:27 +01:00
Florian Bruhin d7176e25f7 Move collection options to correct section
Moves --continue-on-collection-errors to "collection:"
2025-02-15 16:03:27 +01:00
Florian Bruhin 60173b59fd Move CLI options to correct help section
Before:

    pytest-warnings:
      -W, --pythonwarnings PYTHONWARNINGS
                            Set which warnings to report, see -W option of Python itself
      --maxfail=num         Exit after first num failures or errors
      --strict-config       Any warnings encountered while parsing the `pytest` section of the configuration file raise errors
      --strict-markers      Markers not registered in the `markers` section of the configuration file raise errors
      --strict              (Deprecated) alias to --strict-markers
      -c, --config-file FILE
                            Load configuration from `FILE` instead of trying to locate one of the implicit configuration files.
      --continue-on-collection-errors
                            Force test execution even if collection errors occur
      --rootdir=ROOTDIR     Define root directory for tests. Can be relative path: 'root_dir', './root_dir', 'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: '$HOME/root_dir'.

But other than -W, those options aren't related to pytest-warnings at all.

This is a regression in 19e99ab413, which added
`group = parser.getgroup("pytest-warnings")` in the middle of those "general"
options, thus moving the help section for some of them.
2025-02-15 16:03:27 +01:00
Zac Hatfield-Dodds 9d4f36d87d
Merge pull request #12810 from FreerGit/dont-auto-discover-feat
Add `discover_imports` in conf, don't collect imported classes named Test* closes #12749`
2024-12-01 13:13:41 -08:00
Pierre Sassoulas 17c5bbbdae [Fix UP031] Manually, keeping some required %r specifiers
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2024-11-30 14:57:44 +01:00
Pierre Sassoulas 66fc31f05f Fix 'typing.AbstractSet' is deprecated, use 'collections.abc.Set' 2024-11-25 20:11:19 +01:00
Pierre Sassoulas 05ed0d0f94 Enable pylint's python 3.8 typing checks (deprecated-typing-alias) 2024-11-25 20:11:19 +01:00
Pierre Sassoulas a4cb74e864 Upgrade doc and CI after dropping python 3.8 2024-11-25 20:11:18 +01:00
sven 935c06de09 WIP: don't collect instead of filtering out 2024-11-04 02:02:18 +01:00
sven eb8592c526 update default and add docs 2024-10-01 18:41:30 +02:00
sven 68ac4a12e3 `collect_imported_tests` option 2024-09-24 14:28:10 +02:00
sven 222457d7d9 Add `discover_imports` in conf
- Allows a user to define whether or not pytest should treat imported (but not in testpaths) as test classes.
- Imagine a class is called TestFoo defined in src/ dir, when discover_imports is disabled, TestFoo is not treated as a test class.
2024-09-12 19:33:16 +02:00
Bruno Oliveira 419bc7a7c3
Use oldest supported Python in mypy pre-commit checks (#12747)
Follow up to #12744, this ensures type checking works at the oldest Python version supported by pytest.
2024-08-29 17:51:54 -03:00
pre-commit-ci[bot] 1f7c917f07 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2024-07-24 05:51:11 +00:00
Ronny Pfannschmidt fa915f6aa8
Apply suggestions from code review
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2024-07-24 07:48:58 +02:00
Ronny Pfannschmidt d0f7884a1d explicitly detect conda envs - fixes #12652
initially we accidentially detected conda environmnts by just testing too many files
after steamlining we no longer detected conda environments
now we explicitly detect conda environments and test for support
2024-07-23 23:57:07 +02:00
Zach Snicker 0adcc21f48
Support venv detection on Windows with mingw Python (#12545)
Closes #12544
2024-06-29 00:30:51 +03:00
Ronny Pfannschmidt 5e1649f59a resolve most sphinx lookup errors
add the extra sphinx annotations to refer to Path instances

add Path to nitpicky ignore
2024-06-20 11:04:33 +02:00
Ronny Pfannschmidt 9295f9ffff RFC: from __future__ import annotations + migrate 2024-06-20 11:03:03 +02:00
Ran Benita c07bbdfa5b Avoid some TYPE_CHECKING
It's better not to use it when possible.
2024-06-07 09:36:55 +03:00
pre-commit-ci[bot] c0532dda18
[pre-commit.ci] pre-commit autoupdate (#12115)
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: Ran Benita <ran@unusedvar.com>
2024-03-13 15:30:18 +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 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
Bruno Oliveira 111c0d910e Add consider_namespace_packages ini option
Fix #11475
2024-03-02 16:13:48 -03: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
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 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
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
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
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
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 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
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 f43a8db618 Improve pluggy-related typing 2023-09-17 21:32:55 +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
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 a21fb87a90 python: change `Package` to no longer be a `Module`/`File`
Fix #11137.
2023-07-28 22:49:24 +03:00