有没有办法让pytest忽略所有失败的测试,而是我选择的一种异常。
例如,我希望pytest只告诉我有关引发IndexError
的测试,而其他内容则一无所有。
def test_a():
raise IndexError()
def test_b():
1/0 # this test would be ignored
def test_c():
raise KeyError() # this test would also be ignored
请注意,我有3000多个测试,并且我无法编辑每个测试以添加标记。我只想找到那些会产生IndexError的东西。
答案 0 :(得分:2)
请注意,我有3000多个测试,并且我无法编辑每个测试来添加标记。
您可以动态添加标记。示例:在您的conftest.py
中添加以下代码:
# conftest.py
import pytest
def pytest_collection_modifyitems(items):
xfail_exceptions = (IndexError, KeyError)
for item in items:
item.add_marker(pytest.mark.xfail(raises=xfail_exceptions))
现在,所有测试将被自动标记,仅引发xfail_exceptions
中未列出的异常。
您可以进一步扩展它,并在命令行中对异常进行参数化:
import importlib
import pytest
def pytest_addoption(parser):
parser.addoption('--ex', action='append', default=[], help='exception classes to xfail')
def class_from(name):
modname, clsname = name.rsplit('.', 1)
mod = importlib.import_module(modname)
return getattr(mod, clsname)
def pytest_collection_modifyitems(items):
xfail_exceptions = tuple((class_from(name) for name in pytest.config.getoption('--ex')))
if xfail_exceptions:
for item in items:
item.add_marker(pytest.mark.xfail(raises=xfail_exceptions))
用法示例:
$ pytest --ex builtins.KeyError --ex builtins.IndexError -sv
================================== test session starts ====================================
platform darwin -- Python 3.6.4, pytest-3.7.3, py-1.5.4, pluggy-0.7.1
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow, inifile:
plugins: django-3.4.2
collected 3 items
test_spam.py::test_a xfail
test_spam.py::test_b FAILED
test_spam.py::test_c xfail
======================================== FAILURES =========================================
_________________________________________ test_b __________________________________________
def test_b():
> 1/0 # this test would be ignored
E ZeroDivisionError: division by zero
test_spam.py:5: ZeroDivisionError
========================== 1 failed, 2 xfailed in 0.08 seconds ============================
答案 1 :(得分:0)
Pytest可让您添加XFail装饰器,以决定是否要在特定异常下使测试失败:
function App(){
function render(){}
this.run = function() {
render();
}
}
function MainWindow(){
App.call(this);
function render(){
renderFirstController();
renderSecondController();
renderThirdController();
}
this.render = render;
}
function FirstController(){
MainWindow.call(this);
function render(){
console.log("Good");
// renderFirtsBlock();
// renderSecondBlock();
// renderThirdBlock();
}
this.renderFirstController = render;
}
function ready(){
let app = new App();
app.run();
}
document.addEventListener("DOMContentLoaded", ready);
您可以详细了解here
编辑:
您可能还想添加@pytest.mark.xfail(raises= IndexError)
def test_function():
test_here
参数,如下所示:
strict=true
如果未满足此要求,这将使套件失败,也就是测试不会在IndexError上失败(XFail测试的默认值是即使套件未抛出错误也不会使套件失败)
答案 2 :(得分:0)
只需让您的代码查找错误,然后继续执行即可。尝试添加:
except (KeyError, IndexError):
pass
这将处理异常,但不会执行任何操作,您的程序将继续。