我目前正在使用py.test
处理一些单元测试用例和测试装置我有一些执行此操作的代码:
# my py.test file
import pytest
@pytest.fixture
def fixture_1():
f = open("file_one.txt", 'rb')
f_str = f.read()
yield f_str
f.close()
def test_function_1(fixture_1):
assert fixture_1.startswith("some_test_data") # example test
这一切都很好,效果很好。
现在让我们说我编写了另一个测试函数,该函数可以与存储在另一个文件中的输入配合使用(假设file_two.txt
,我的函数是这样的:
# in same py file as above
def test_function_2(fixture_1):
#some test with data from file_two.txt
assert something_for_fun
在上面的test_function_2
中,我希望fixture_1
进行与以前相同的操作,但要在file_two.txt
而不是file_one.txt
上进行。
EDIT :我也玩过parametrizing fixtures,但是它调用我的test_function_ *的次数是灯具的自变量的数量,这是无效的,因为test_functions特定于来自文件的输入。
我了解了request固定装置,但不确定如何使用它来检查测试函数的上下文。
如果有人知道了,请告诉我。同时,我将在我开始运作后立即发布!
编辑2:我也了解inspect
和introspect
,但我正在寻找一种更简洁的方法来进行此操作,最好使用一些pytest
魔术〜
谢谢!
答案 0 :(得分:1)
您可以根据测试参数化灯具,并通过request.param
读取传递的参数:
import pytest
@pytest.fixture
def fixture_1(request):
filename = request.param
with open(filename) as f:
f_str = f.read()
yield f_str
@pytest.mark.parametrize('fixture_1', ['file_one.txt'], indirect=True)
def test_function_1(fixture_1):
assert fixture_1.startswith("some_test_data") # example test
@pytest.mark.parametrize('fixture_1', ['file_two.txt'], indirect=True)
def test_function_2(fixture_1):
assert something_for_fun
试运行应该产生:
test_module.py::test_function_1[file_one.txt] PASSED
test_module.py::test_function_2[file_two.txt] PASSED
您还可以根据需要为文件名和参数设置默认的固定值:
@pytest.fixture
def fixture_1(request):
filename = getattr(request, 'param', 'file_one.txt')
with open(filename) as f:
f_str = f.read()
yield f_str
def test_function_1(fixture_1):
assert fixture_1.startswith("some_test_data") # example test
@pytest.mark.parametrize('fixture_1', ['file_two.txt'], indirect=True)
def test_function_2(fixture_1):
assert fixture_1.startswith('bar')
现在test_function_1
保持未参数化:
test_module.py::test_function_1 PASSED
test_module.py::test_function_2[file_two.txt] PASSED