正如其文檔所說,pytest 接受夾具作為函數(shù)參數(shù)。然而,這與幾乎所有語言中參數(shù)名稱不應(yīng)影響函數(shù)行為的約定有些矛盾。例如:這有效:import pytest@pytest.fixture()def name(): return 'foo'def test_me(name): assert name == 'foo'但這不會:import pytest@pytest.fixture()def name(): return 'foo'def test_me(nam): assert nam == 'foo'我認(rèn)為這里必須有一些內(nèi)省,需要測試函數(shù)參數(shù)是有效的裝置。我在這方面正確嗎?除了fixtures,還有其他神奇的參數(shù)名稱讓我感到困惑。其中之一是request:import pytest@pytest.fixture(params=['foo', 'bar'])def name(request): return request.paramdef test_me(name): assert name == 'foo'無需閱讀其文檔,您似乎可以重命名request為另一個名稱,例如req:import pytest@pytest.fixture(params=['foo', 'bar'])def name(req): return req.paramdef test_me(name): assert name == 'foo'但是然后運行測試會抱怨req找不到夾具。這讓我更加困惑,因為列出的可用裝置不包括request. 我不確定request在這里調(diào)用夾具是否合適,但錯誤消息自相矛盾:未找到 E 夾具“req”> 可用設(shè)備:緩存、capfd、capfdbinary、caplog、capsys、capsysbinary、doctest_namespace、monkeypatch、名稱、pytestconfig、record_xml_attribute、record_xml_property、recwarn、tmpdir、tmpdir_factory、worker_id> 使用 'pytest --fixtures [testpath]' 尋求幫助。那么在使用 pytest 時我必須注意多少這樣的魔法名稱才不會陷入陷阱?
1 回答

慕哥6287543
TA貢獻(xiàn)1831條經(jīng)驗 獲得超10個贊
是的,Py.test 注入了一點參數(shù)名稱自省魔法來保持你的測試用例簡潔。
除了您可用的任何裝置(正如您發(fā)現(xiàn)的那樣pytest --fixtures
)之外,我確實認(rèn)為這request
是唯一的附加魔術(shù)參數(shù)(當(dāng)然,除非您使用,例如@pytest.mark.parametrize('foo', (...))
,在這種情況下foo
是標(biāo)記的測試用例或裝置的魔術(shù)參數(shù), 等等。)。
順便說一句,我認(rèn)為最好不要將 Py.testtest_
函數(shù)視為常規(guī)的舊函數(shù),因為 Py.test 不會直接調(diào)用它們。
添加回答
舉報
0/150
提交
取消