pytest断言封装
时间: 2023-09-20 09:13:16 浏览: 96
在pytest中,断言是一种用于测试特定异常的机制。可以使用pytest.raises作为上下文管理器来捕获特定的异常实例。可以将待测试的代码放在with pytest.raises(ExceptionType) as excinfo的代码块中,然后在代码块内部对异常类型和异常值进行断言。
例如,可以使用以下代码封装pytest断言:
import pytest
def assert_zero_division():
with pytest.raises(ZeroDivisionError) as excinfo:
1/0
assert excinfo.type == ZeroDivisionError
assert "division by zero" in str(excinfo.value)
if __name__ == '__main__':
pytest.main()
在这个例子中,使用pytest.raises(ZeroDivisionError)来捕获ZeroDivisionError类型的异常。然后,通过excinfo.type和excinfo.value来断言异常的类型和值。这样,如果断言失败,将会抛出AssertionError异常并显示相关错误信息。
这是一个简单的封装示例,你可以根据实际需求进行修改和扩展。通过封装pytest断言,可以更方便地进行异常测试和断言验证。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [Pytest之断言](https://blog.csdn.net/ZangKang1/article/details/119968621)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *3* [pytest框架之断言](https://blog.csdn.net/Beck_k/article/details/127903890)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文