【发布时间】:2019-08-09 06:45:39
【问题描述】:
以下主题模块包含两个函数,其中一个操作全局变量。
mod.py:
def global_setter():
global x
x = 123
print("setter x:", x)
def global_getter():
print("getter x:", x)
每个函数都有一个测试文件。
test_1.py
import pytest
import mod
def test_set_x():
mod.global_setter()
assert mod.x == 123
test_2.py
import pytest
import mod
def test_get_x():
with pytest.raises(NameError):
mod.global_getter()
如果单独运行,这些测试通过
$ pytest -s -v test_1.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 1 item
test_1.py::test_set_x setter x: 123
PASSED
-
======================= 1 passed in 0.03 seconds ========================
$ pytest -s -v test_2.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 1 item
test_2.py::test_get_x PASSED
======================= 1 passed in 0.02 seconds ========================
如果一起运行,第二个测试失败。
$ pytest -s -v test_1.py test_2.py
========================== test session starts ==========================
platform linux -- Python 3.6.7, pytest-4.3.1, py-1.8.0, pluggy-0.9.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /mnt/temp/test, inifile:
collected 2 items
test_1.py::test_set_x setter x: 123
PASSED
test_2.py::test_get_x getter x: 123
FAILED
=============================== FAILURES ================================
______________________________ test_get_x _______________________________
def test_get_x():
with pytest.raises(NameError):
> mod.global_getter()
E Failed: DID NOT RAISE <class 'NameError'>
test_2.py:8: Failed
================== 1 failed, 1 passed in 0.08 seconds ===================
似乎导入模块的状态在测试和测试文件之间存在差异。
为什么会发生这种情况,有没有办法告诉 pytest 为每个测试文件独立导入模块?如果是这样,有什么方法可以通过对 test_ 函数的最小更改来完成它?上面的玩具示例说明了一个问题,即我在具有大量测试的较大代码库中遇到的问题。
【问题讨论】:
-
这是包的预期行为,您应该查看
monkeypatching,它将为您优雅地处理此问题
标签: python pytest python-import