我想為類內pytest的tenth_standard方法執行HighSchool:
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. 有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
您的expected夾具不是從其他夾具中獲取引數,而只是夾具功能,這當然不是您想要的。您可以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夾具已經獲得了正確的值。
附帶說明:在測驗中復制應用程式邏輯通常不是一個好主意,就像這里所做的那樣。這樣,錯誤可以很容易地傳播到測驗中而不會被發現。
(雖然在這種情況下它可能只是由于一個愚蠢的例子)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/449488.html
下一篇:Mocha:事后如何斷言?
