我正在使用Python的unittest
和pytest
集成测试库与第三方API。
某些API调用暂时返回错误,这会在我的代码中引发特定异常。这种行为在代码中很好。
但是,我宁愿跳过这些临时错误,而不是让测试失败。
我有超过150个测试。而不是像这样重写每一个测试:
class TestMyLibrary(unittest.TestCase):
def test_some_test(self):
try:
// run the test as normal
// assert the normal behaviour
except SomeException:
// skip the test
def test_some_other_test(self):
try:
// run the test as normal
// assert the normal behaviour
except SomeException:
// skip the test
我是否可以在课堂上以某种方式将它们全部包装起来?
如果你期望这个例外,为什么不检查它应该在什么时候提出?您可以使用 :
pytest.raises(Exceptiontype, Foo())
这可以通过装饰器来完成。例如:
def handle_lastfm_exceptions(f):
def wrapper(*args, **kw):
try:
return f(*args, **kw)
except pylast.WSError as e:
if (str(e) == "Invalid Method - "
"No method with that name in this package"):
msg = "Ignore broken Last.fm API: " + str(e)
print(msg)
pytest.skip(msg)
else:
raise(e)
return wrapper
然后装饰有问题的功能:
class TestMyLibrary(unittest.TestCase):
@handle_lastfm_exceptions
def test_some_bad_test(self):
// run the test as normal
// assert the normal behaviour
def test_some_good_test(self):
// run the test as normal
// assert the normal behaviour
有同样的问题(不稳定的第三方库,等待修复......)。结果是这样的:
def pytest_runtest_makereport(item, call):
from _pytest.runner import pytest_runtest_makereport as orig_pytest_runtest_makereport
tr = orig_pytest_runtest_makereport(item, call)
if call.excinfo is not None:
if call.excinfo.type == SomeExceptionFromLibrary:
tr.outcome = 'skipped'
tr.wasxfail = "reason: SomeExceptionFromLibrary. shame on them..."
return tr
奇迹般有效