Fixture
以下命令可以列出所有可用的fixture,包括内置的、插件中的、以及当前项目定义的。
pytest --fixtures
-
fixture作为函数参数
测试用例可以接受一个fixture
函数作为参数(函数命名),fixture
函数的注册通过@pytest. fixture
来标记,下面看一个简单的例子:
# test_sample.pyimport pytest @pytest.fixture def data(): return [1, 2, 3] def test_equal(data): print data[0] assert data[0] == 1
test_equal
需要data
的值,pytest
将会查找并调用@pytest. fixture
标记的data
函数,运行将会看到如下结果:
-
共享fixture函数
上面的一个例子fixture函数只运用于单个py
文件,如果想要共享数据函数怎么办呢?只需要将这些fixture
函数放入到conftest.py
文件中即可(名称不可变);在当前路径创建conftest.py
文件,输入以下代码:
# conftest.pyimport pytest @pytest.fixture def data(): return [1, 2, 3]
test_sample.py
更新代码:# test_sample.py
import pytest def test_equal(data): print data[0] assert data[0] == 1
运行代码将会得到同样的结果;如果此时在
test_sample.py
文件中也包含fixture标记过的data函数(返回数据改变),那么将会重载该数据(即会调用当前文件中的data) -
pytest.fixture
特性实现pytest
中的setup/teardown
经典的xunit风格的setUp、tearDown参考:上篇博客和官网介绍。
pytest.fixture
特性实现:
这里的scope支持 function, class, module, package or session四种,默认情况下的scope是function。- function作用于函数(类中或模块中)
- class开始于类的始末
- module开始于模块的始末
- package/session开始于测试用例的始末(整个包)
默认使用return的时候是没有tearDown的,但是可以使用yield 、addfinalizer函数来实现tearDown功能。
具体请参考:tests │-- conftest.py │-- test_sample.py │-- test_sample1.py
conftest.py
代码:import pytest pytest.fixture(scope="module") def try_module(): print "#######################module begin####################" yield [6, 7, 8] print "#######################module end####################" @pytest.fixture() # 不加(scope="function")默认scope就是function def try_function(): print "#######################function begin####################" yield "just a test about function scope" print "#######################function end####################" @pytest.fixture(scope="class") def try_class(request): print "#######################class begin####################" def end(): print "#######################class end####################" request.addfinalizer(end) return "just a test about class scope" @pytest.fixture(scope="package") # session == package def try_session(request): print "#######################session begin####################" def end(): print "#######################session end####################" request.addfinalizer(end) return "just a test about session scope"
test_sample.py
代码:class TestAdd(object): def test1(self, try_session): print "test1 something" assert 4 == 4 def test2(self, try_module): print "test2 something" assert 5 == 5 def test3(self, try_class): print "test3 something" assert 5 == 5 def test4(self, try_function): print "test4 something" assert 5 == 5 def test5(self): print "test5 something" assert 5 == 5
test_sample1.py
代码:def test_file2_1(try_module): print "test_file2_1 something" assert 2 == 2 def test_file2_2(try_function): print "test_file2_2 something" assert "a"*3 == "aaa" def test_file2_3(try_session):