I want to do the following. In my project a
I have a factory class Fac
with instance fac=Fac()
, where certain classes register to. These classes reside in a subpackage ab
.
If I do a plain import a
, the subpackage ab
is not imported, no classes are registered, and thus fac.registered_classes
is an empty list.
After an import of subpackage b
fac.registered_classes
gets filled with the classes in subpackage b
.
To not confuse the user, I added the line
import .b
in the __init__.py
of package a
.
Now, I'd like to write a test with pytest
that basically passes, if the fac.registered_classes
is not empty; so noone accidentally erases that line in my __init__.py
. Lets call that test test_import_b
Different tests of course also test functionality of subpackage b
, thus importing b
themselves explicitly.
However, it seems that all imports during test runs are available for all tests. While just running the single test test_import_b
fails if the import line is removed in __init__.py
, it does not anymore if all tests are ran simultaneously.
What am I supposed to do, to make my test setup work?
This is correct py.test and Python behavior. Module body level code is run when to module is imported. Python virtual machine maintains imported modules per-process.
I do not believe there is a good solution to achieve the behavior you want. Two strategies come to my mind
Do not ever register anything implicitly on module import only - make registering everything explicit through a function call like having your init()
In the tests that explicitly need to import and have register run, import it at the beginning of the test or make a fixture that does the import
Eg
def test_boohoo():
import a.b
# Test goes here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.