我可以选择性地运行test_function_1
,覆盖我的conftest.py
装置中的仪表1
def test_function_1(instrumentation: dict[str, float]) -> None:
assert instrumentation['a'] > instrumentation['b']
def test_function_2(capsys) -> None:
print("Hello, pytest!")
captured = capsys.readouterr()
assert captured.out == "Hello, pytest!\n"
当我尝试调用时test_function_2
,我不知道如何传递capsys
给它2:
import tests
import pytest # <--- doesn't help ...
def test_callee_with_instrumentation():
tests.test_function_1({'a': 110, 'b': 55, 'g': 6000})
def test_callee_with_capsys():
# tests.test_function_2() # <--- TypeError: test_function_2() missing 1 required positional argument: 'capsys'
# tests.test_function_2(capsys) # <--- NameError: name 'capsys' is not defined
# tests.test_function_2(pytest.capsys) # <--- AttributeError: module 'pytest' has no attribute 'capsys'
pass
test_callee_with_instrumentation()
test_callee_with_capsys()
我很确定这些conftest.py
装置是无关紧要的,但为了完整起见:
import pytest
@pytest.fixture(scope='function')
def instrumentation():
return { 'a': 800, 'b': 620, 'c': 44 }
1在我的实际代码中,是众多capsys
参数之一。
2这里有类似的问题。在我看来,这不是重复的,因为我问的是编程运行测试,而不是的正确含义capsys
。
capsys
是一个 PyTest 装置。您可以使用以下方式列出所有装置:
源代码位于
_pytest/capture.py
。(注意:您不应该尝试直接实例化/调用装置。)编写带有参数的函数:
然后运行
pytest your_test_file.py
,PyTest 将自动实例化该装置并将其传递到测试中。如果您不想使用 PyTest 运行测试,那么就不要
capsys
尝试捕获标准输出。如果您确实想使用 PyTest,但不想直接从控制台调用 PyTest,那么请
pytest.main()
从代码中调用:如果想要有选择地只运行某些测试,并且底层文件具有任意名称,则以下
pytest.main
参数调整可能会有所帮助:python
然后当您使用(而不是)运行脚本时pytest
:1来自 databricks 上下文,我仍然很难,因为
__file__
在运行单元格时没有定义......arrggghh......