![](/img/trans.png)
[英]How can I parametrize tests to run with different fixtures in pytest?
[英]Can tests with pytest fixtures be run interactively?
我有一些使用 pytest 和夾具編寫的測試,例如:
class TestThing:
@pytest.fixture()
def temp_dir(self, request):
my_temp_dir = tempfile.mkdtemp()
def fin():
shutil.rmtree(my_temp_dir)
request.addfinalizer(fin)
return my_temp_dir
def test_something(self, temp_dir)
with open(os.path.join(temp_dir, 'test.txt'), 'w') as f:
f.write('test')
當從 shell 調用測試時,這可以正常工作,例如
$ py.test
但我不知道如何在 python/ipython 會話中運行它們; 嘗試例如
tt = TestThing()
tt.test_something(tt.temp_dir())
失敗,因為temp_dir
需要傳遞request
對象。 那么,如何使用注入的request
對象調用夾具呢?
是的。 您不必手動組裝任何測試夾具或類似的東西。 一切都像在項目目錄中調用pytest
一樣運行。
這是最好的方法,因為如果您的測試失敗,它可以讓您訪問調試器
在ipython
shell 中使用:
**ipython**> run -m pytest prj/
這將運行prj/tests
目錄中的所有prj/tests
。
這將使您能夠訪問調試器,或者如果您有import ipdb; ipdb.set_trace()
則允許您設置breakpoints
import ipdb; ipdb.set_trace()
import ipdb; ipdb.set_trace()
在您的程序中( https://docs.pytest.org/en/latest/usage.html#setting-breakpoints )。
在測試目錄中使用!pytest
。 這不會讓您訪問調試器。 但是,如果您使用
**ipython**> !pytest --pdb
如果您的測試失敗,它會將您放入調試器(子shell),因此您可以運行事后分析( https://docs.pytest.org/en/latest/usage.html#dropping-to- pdb-python-debugger-on-failures )
使用這些方法,您甚至可以使用( https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests )在ipython
運行單個模塊/test_fuctions/TestClasses
**ipython**> run -m pytest prj/tests/test_module1.py::TestClass1::test_function1
您可以繞過 pytest.fixture 裝飾器,直接調用包裝好的測試函數。
tmp = tt.temp_dir.__pytest_wrapped__.obj(request=...)
訪問內部結構,這很糟糕,但是當您需要時...
我擁有的最好的方法遠非理想,只是 %run 測試文件,然后手動組裝夾具,然后簡單地調用測試。 這樣做的問題是跟蹤定義了默認裝置的模塊,然后按照它們的依賴順序調用它們。
您可以為此使用兩個單元格:
第一的:
def test_something():
assert True
第二:
from tempfile import mktemp
test_file = mktemp('.py', 'test_')
open(test_file, 'wb').write(_i) # write last cell input
!pytest $test_file
您也可以在這樣的一個單元格上執行此操作,但不會突出顯示代碼:
from tempfile import mktemp
test_code = """
def test_something():
assert True
"""
test_file = mktemp('.py', 'test_')
open(test_file, 'wb').write(test_code)
!pytest $test_file
簡單的答案是您不想從 python 交互式運行 py.test 。 大多數人設置了一些與他們的文本編輯器或 IDE 的集成來運行 py.test 並解析它的輸出。 但實際上它是一個命令行工具,應該如何使用它。
作為側節點,您可能想查看內置的tmpdir
固定裝置: http ://pytest.org/latest/tmpdir.html 因為您似乎正在重新發明它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.