vin*_*one 14 python unit-testing pytest
我有一堆使用pytest编写的测试.目录下都有dir
.例如:
dir/test_base.py
dir/test_something.py
dir/test_something2.py
...
Run Code Online (Sandbox Code Playgroud)
其中代码的简化版本如下:
test_base.py
import pytest
class TestBase:
def setup_module(module):
assert False
def teardown_module(module):
assert False
Run Code Online (Sandbox Code Playgroud)
test_something.py
import pytest
from test_base import TestBase
class TestSomething(TestBase):
def test_dummy():
pass
Run Code Online (Sandbox Code Playgroud)
test_something2.py
import pytest
from test_base import TestBase
class TestSomethingElse(TestBase):
def test_dummy2():
pass
Run Code Online (Sandbox Code Playgroud)
我的所有test_something*.py
文件都扩展了基类test_base.py
.现在我写了setup_module(module)
和teardown_module(module)
方法test_base.py
.我期望为所有测试调用一次setup_module,并teardown_module()
在完成所有测试后在最后调用.
但这些功能似乎没有被调用?我需要一些装饰器吗?
Ste*_*rta 13
OP 的要求是设置和拆卸每个只执行一次,而不是每个模块一次。这可以通过conftest.py
文件的组合来完成,@pytest.fixture(scope="session")
并将夹具名称传递给每个测试函数。
这些在Pytest 装置文档中进行了描述
下面是一个例子:
conftest.py
import pytest
@pytest.fixture(scope="session")
def my_setup(request):
print '\nDoing setup'
def fin():
print ("\nDoing teardown")
request.addfinalizer(fin)
Run Code Online (Sandbox Code Playgroud)
test_something.py
def test_dummy(my_setup):
print '\ntest_dummy'
Run Code Online (Sandbox Code Playgroud)
test_something2.py
def test_dummy2(my_setup):
print '\ntest_dummy2'
def test_dummy3(my_setup):
print '\ntest_dummy3'
Run Code Online (Sandbox Code Playgroud)
运行 py.test -s 时的输出:
collected 3 items
test_something.py
Doing setup
test_dummy
.
test_something2.py
test_dummy2
.
test_dummy3
.
Doing teardown
Run Code Online (Sandbox Code Playgroud)
名称很conftest.py
重要:你不能给这个文件一个不同的名字,并期望 Pytest 找到它作为夹具的来源。
设置scope="session"
很重要。否则,每个测试模块都将重复设置和拆卸。
如果您不想将夹具名称my_setup作为参数传递给每个测试函数,您可以将测试函数放在一个类中并将pytest.mark.usefixtures
装饰器应用于该类。
把setup_module
和teardown_module
在模块级一类的外面。然后将您的课程添加到您的测试中。
def setup_module(module):
"""..."""
def teardown_module(module):
"""..."""
class TestSomething:
def test_dummy(self):
"""do some tests"""
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅本文。
Gia*_*oli -1
首先,将所有测试放在名为“tests”的模块中是一个很好的做法:
<product>
...
tests/
__init__.py
test_something.py
Run Code Online (Sandbox Code Playgroud)
其次,我认为您应该在基类中使用 setup_class/teardown_class 方法:
import unittest
class MyBase(unittest.TestCase):
@classmethod
def setup_class(cls):
...
@classmethod
def teardown_class(cls):
...
Run Code Online (Sandbox Code Playgroud)
更多信息:http://pytest.org/latest/xunit_setup.html