下面的subject模块包含两个函数,其中一个处理全局变量。
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_
函数进行最少更改的情况下实现它?上面的玩具示例说明了我在较大的代码库和许多测试中遇到的问题。
发布于 2019-03-19 04:07:35
这是意料之中的,因为通过pytest运行的所有测试都在单个进程中运行,并且您的第一个测试通过将x
添加到全局名称空间来改变全局状态。
您有几个选择。
pytest-xdist
(请参阅Run py.test test in different process)这样的框架来确保您的测试在不同的进程中运行。在第二个测试之前添加一个装置,这将显式地取消全局变量x
.的设置
https://stackoverflow.com/questions/55229163
复制相似问题