我想为HighSchool
类中的tenth_standard
方法执行pytest
:
Class HighSchool():
...
def tenth_standard(self):
return f"I-am-studying-in-{self.school}-at-{self.country}"
我想使用@pytest.fixture
和@pytest.mark.parametrize
来执行pytest,我的代码如下:
@pytest.fixture(scope="function")
def expected(request):
return f"I-am-studying-in-{school}-at-{country}"
@pytest.fixture(scope="function")
def school(request):
return request.param
@pytest.fixture(scope="function")
def country(request):
return request.param
@pytest.mark.parametrize("school", ["abcd", "efgh"], indirect=True)
@pytest.mark.parametrize("country", ["India", "Japan"], indirect=True)
def test_tenthstandard(school, country, expected):
b = HighSchool(school=school, country=country)
assert expected == b.tenth_standard()
当我运行这个程序时,我会得到一个AssertionError
,如下所示:
AssertionError: assert ('I-am-studying-in-<function school at 0x7f6b858a63a0>-at-<function country at '0x7f6b858a6280>) == 'I-am-studying-in-abcd-at-India'
我想修复expected fixture
以返回值,而不是function at XXX location
。有人能帮我怎么修吗?
您的expected
fixture并没有从其他fixture中获取参数,而是只获取fixture函数,这当然不是您想要的。你可以";导出";expected
夹具与其他夹具不同,因此它将使用相同的参数自动参数化:
@pytest.fixture
def school(request):
return request.param
@pytest.fixture
def country(request):
return request.param
@pytest.fixture
def expected(school, country):
return f"I-am-studying-in-{school}-at-{country}"
@pytest.mark.parametrize("school", ["abcd", "efgh"])
@pytest.mark.parametrize("country", ["India", "Japan"])
def test_tenthstandard(school, country, expected):
b = HighSchool(school=school, country=country)
assert expected == b.tenth_standard()
请注意,在这种情况下,您甚至可以跳过indirect=True
部分,因为expected
夹具已经获得了正确的值。
附带说明:在测试中复制应用程序逻辑通常不是一个好主意,就像这里所做的那样。通过这种方式,错误可以很容易地传播到测试中,而不会被发现
(尽管在这种情况下,这可能只是由于一个愚蠢的例子(