我的Python代码中有函数可以响应某些条件引发异常,并且希望确认它们在pytest脚本中的行为符合预期。
目前我有
IReadOnlyCollection<T>
但这似乎很麻烦(并且需要针对每种情况重复)。
有没有办法使用Python测试异常和错误,或者这样做的首选模式?
def test_something():
try:
my_func(good_args)
assert True
except MyError as e:
assert False
try:
my_func(bad_args)
assert False
except MyError as e:
assert e.message == "My expected message for bad args"
不起作用(即使我用def test_something():
with pytest.raises(TypeError) as e:
my_func(bad_args)
assert e.message == "My expected message for bad args"
替换断言,它也会通过。)
答案 0 :(得分:8)
这样:
with pytest.raises(<YourException>) as exc_info:
<your code that should raise YourException>
exception_raised = exc_info.value
<do asserts here>