[英]pytest: test for import of subpackage
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.在我的项目中
a
我有一个带有实例fac=Fac()
的工厂类Fac
,其中某些类注册到。 These classes reside in a subpackage ab
.这些类驻留在子包
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.如果我执行普通
import a
,则不会导入子包ab
也不会注册任何类,因此fac.registered_classes
是一个空列表。
After an import of subpackage b
fac.registered_classes
gets filled with the classes in subpackage b
.导入子包
b
fac.registered_classes
将填充子包b
的类。
To not confuse the user, I added the line为了不混淆用户,我添加了这一行
import .b
in the __init__.py
of package a
.在包
a
的__init__.py
中import .b
。
Now, I'd like to write a test with pytest
that basically passes, if the fac.registered_classes
is not empty;现在,如果
fac.registered_classes
不为空,我想用pytest
编写一个基本通过的测试; so noone accidentally erases that line in my __init__.py
.所以没有人不小心删除了我的
__init__.py
那一行。 Lets call that test test_import_b
让我们称之为测试
test_import_b
Different tests of course also test functionality of subpackage b
, thus importing b
themselves explicitly.不同的测试当然也会测试子包
b
功能,从而显式地导入b
本身。
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.如果在
__init__.py
删除导入行,则仅运行单个测试test_import_b
失败,但如果同时运行所有测试,则不会再运行。
What am I supposed to do, to make my test setup work?我该怎么做才能使我的测试设置正常工作?
This is correct py.test and Python behavior.这是正确的 py.test 和 Python 行为。 Module body level code is run when to module is imported.
模块主体级代码在导入模块时运行。 Python virtual machine maintains imported modules per-process.
Python 虚拟机为每个进程维护导入的模块。
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()
永远不要仅在模块导入时隐式注册任何内容 - 通过函数调用显式注册所有内容,例如使用
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在明确需要导入并运行 register 的测试中,在测试开始时导入它或制作一个执行导入的夹具
Eg例如
def test_boohoo():
import a.b
# Test goes here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.