首页 > 解决方案 > 我们可以在 if 语句中使用 assert 吗?

问题描述

我有一个使用assert检查某些条件的测试。我可以在if语句中使用 then 断言吗?如下:

assert 'string 1' in response, "Did not get 'string 1'!"
if assert:
    continue...

标签: pythonpytestassert

解决方案


assert引入了语句,而不是表达式,因此它不能在语法上用作if语句的条件。但是,没有必要这样做,因为声明

assert cond, msg

相当于

if not cond:
    raise AssertionError(msg)

推荐阅读