Lou*_*uis 7 python unit-testing pytest
我有一些单元测试,但我正在寻找一种方法来标记一些特定的单元测试以跳过它们,除非你在调用测试时声明一个选项.
示例:如果我打电话pytest test_reports.py,我想要一些特定的单元测试不能运行.
但如果我打电话pytest -<something> test_reports,那么我希望我的所有测试都能运行.
我查看了@pytest.mark.skipif(condition)标签,但无法弄清楚,所以不确定我是否在正确的轨道上.这里的任何指导都会很棒!
Man*_* CJ 15
该pytest文件提供了关于如何跳过测试标有“慢”在默认情况下,只有一个运行它们很好的例子--runslow选项:
# conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption(
"--runslow", action="store_true", default=False, help="run slow tests"
)
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")
def pytest_collection_modifyitems(config, items):
if config.getoption("--runslow"):
# --runslow given in cli: do not skip slow tests
return
skip_slow = pytest.mark.skip(reason="need --runslow option to run")
for item in items:
if "slow" in item.keywords:
item.add_marker(skip_slow)
Run Code Online (Sandbox Code Playgroud)
我们现在可以通过以下方式标记我们的测试:
# test_module.py
from time import sleep
import pytest
def test_func_fast():
sleep(0.1)
@pytest.mark.slow
def test_func_slow():
sleep(10)
Run Code Online (Sandbox Code Playgroud)
测试test_func_fast总是被执行(调用 eg pytest)。test_func_slow然而,“慢”函数只会在调用时执行pytest --runslow。
小智 10
我们在conftest.py中使用带有addoption的标记
测试用例:
@pytest.mark.no_cmd
def test_skip_if_no_command_line():
assert True
Run Code Online (Sandbox Code Playgroud)
conftest.py: 在功能上
def pytest_addoption(parser):
parser.addoption("--no_cmd", action="store_true",
help="run the tests only in case of that command line (marked with marker @no_cmd)")
Run Code Online (Sandbox Code Playgroud)
在功能上
def pytest_runtest_setup(item):
if 'no_cmd' in item.keywords and not item.config.getoption("--no_cmd"):
pytest.skip("need --no_cmd option to run this test")
Run Code Online (Sandbox Code Playgroud)
pytest通话:
py.test test_the_marker
-> test will be skipped
py.test test_the_marker --no_cmd
-> test will run
Run Code Online (Sandbox Code Playgroud)
有两种方法可以做到这一点:
第一种方法是使用装饰器标记函数@pytest.mark,并使用选项单独运行/跳过标记的函数-m。
@pytest.mark.anytag
def test_calc_add():
assert True
@pytest.mark.anytag
def test_calc_multiply():
assert True
def test_calc_divide():
assert True
Run Code Online (Sandbox Code Playgroud)
运行脚本 aspy.test -m anytag test_script.py将仅运行前两个函数。
或者运行 aspy.test -m "not anytag" test_script.py将仅运行第三个函数并跳过前两个函数。
这里“anytag”是标签的名称。它可以是任何东西。
第二种方法是使用选项运行名称中包含公共子字符串的函数-k。
def test_calc_add():
assert True
def test_calc_multiply():
assert True
def test_divide():
assert True
Run Code Online (Sandbox Code Playgroud)
运行脚本 aspy.test -k calc test_script.py将运行函数并跳过最后一个。
请注意,“calc”是函数名称中存在的公共子字符串,名称中包含“calc”的任何其他函数(如“calculate”)也将运行。
| 归档时间: |
|
| 查看次数: |
2241 次 |
| 最近记录: |