以下主题模块包含两个函数,其中之一操作全局变量。
mod.py:
def global_setter():
global x
x = 123
print("setter x:", x)
def global_getter():
print("getter x:", x)
每个功能都有一个测试文件。
测试_1.py
import pytest
import mod
def test_set_x():
mod.global_setter()
assert mod.x == 123
测试_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_
功能?上面的玩具示例说明了我在使用具有许多测试的较大代码库时遇到的问题。