Closed ee-4-me closed 1 year ago
pytest does not guarantee the order of imports, doing so will be too restrictive. You mentioned that you've found other ways to solve your problem (I can recommend the pythonpath option), instead of relying on import-time side-effects, which is the way to go.
Just in case you're curious why the behavior you're seeing happens, it's because pytest needs to look into the file to figure out what Test_Opp
means in order to collect it, and this happens before importing the files looking for tests. But this is all subject to change.
Pytest
7.4.0
OS
Windows 10 Enterprise
Overview
Issue where test files are not run in order when using test class/method notation in CLI. This issue arose when creating a test setup file to make test setup easier (as opposed to other methods).
Example Setup
Folder structure:
add.py:
opp.py
test_opp.py
When executing
python -m pytest ./test/test_opp.py
, I get the following:Okay, makes sense, there is an error with the import paths.
To simplify adding the import path to
sys.path
for my test file (in actuality, dozens of test files), I create the followingtest_setup.py
:test_setup.py
Now, when running
python -m pytest ./test/test_setup.py ./test/test_opp.py
, the test runs and works:Wonderful, this is working great, I am taking advantage of naming my setup file test_ so that it runs in pytest, and I can add the import before all of the other test files run (among any other things, without refactoring my dozens of test files).
Bug
The bug, however, is if I want to run a test "class" or test "method" with this setup.
For example, running
python -m pytest ./test/test_setup.py ./test/test_opp.py::Test_Opp
It appears that by adding the class option,
::Test_Opp
, thetest_opp.py
file was run (or pre-run / compiled / pytest magic-ed) beforetest_setup.py
This appears to be a bug, that the order of file execution changes when adding a class option,
::
, to a test in the CLI args.I would think that
python -m pytest ./test/test_setup.py ./test/test_opp.py::Test_Opp
should run./test/test_setup.py
before./test/test_opp.py::Test_Opp
.This particular example may not make the strongest case for this change (as there are other ways to solve the path import issue for the test files), however, I think it points out an unexpected outcome with the test order in the CLI.
Workaround
On a side note, I can workaround this issue if I wrap the functionality in
test_setup
with a "test class":test_setup.py
And then run the tests using both class options
python -m pytest ./test/test_setup.py::Test_Setup ./test/test_opp.py::Test_Opp
:The tests execute as expected.
Appendix
pip list
: