Pytest插件pytest-assume多重断言
背景
import pytest
def test_assume1():
assert 1 == 2
print('hello')
assert 2 == 3
if __name__ == '__main__':
pytest.main(['-sv', __file__])
- 这样的代码运行的时候并不会打印hello
- 同样后面的assert 2==3也不会去操作
- 而实际测试的时候我们经常性的会遇到要去多重断言的情况
安装
pip install pytest-assume
pip install git+https://github.com/astraw38/pytest-assume.git
介绍
https://github.com/astraw38/pytest-assume github上也就讲了几句
- A pytest plugin that allows multiple failures per test
用法一、assume
import pytest
def test_assume2():
pytest.assume( 1 == 2 )
print('hello')
pytest.assume( 2 == 3)
if __name__ == '__main__':
pytest.main(['-sv', __file__])
- 输出
demo_assume.py::test_assume2 hello
FAILED
...
E demo_assume.py:16: AssumptionFailure
E >> pytest.assume( 1 == 2 )
E AssertionError: assert False
E
E demo_assume.py:18: AssumptionFailure
E >> pytest.assume( 2 == 3)
E AssertionError: assert False
- 可以看到
- hello 也输出了
- assume也断言了第二种
用法二、上下文管理器(推荐)
-
在用法一种隐含了一个小的瑕疵
import pytest def test_assume3(): a = 1 b = 2 pytest.assume( a == b ) if __name__ == '__main__': pytest.main(['-sv', __file__])
-
它的输出是
E demo_assume.py:18: AssumptionFailure E >> pytest.assume( a == b ) E AssertionError: assert False
-
你可以看到,变量的真正的值并没有看到,当然你有很多其他的方法来处理,但能看到显然是更利于你便捷的去定位的
-
这个时候可以用另外一种做法:上下文管理器
import pytest def test_assume4(): a = 1 b = 2 with pytest.assume: assert a==b if __name__ == '__main__': pytest.main(['-sv', __file__])
-
输出
E demo_assume.py:18: AssumptionFailure E >> with pytest.assume: assert a==b E AssertionError: assert 1 == 2
- 你可以清晰的看到变量的值了
-
注意,在这种写法中,你要写assert,而第一种写法中你不需要用到assert的
-
在with的写法中,你可以在一个块中assert多个断言内容,但这样是不推荐的
import pytest def test_assume5(): a = 1 b = 2 with pytest.assume: assert a==b assert 1==2 assert 3==3 if __name__ == '__main__': pytest.main(['-sv', __file__])
-
输出:最终你就看到了第二个错误的信息,a==b的断言被你忽略掉了
E demo_assume.py:21: AssumptionFailure E >> assert 3==3 E AssertionError: assert 1 == 2
-
你应该这样写
import pytest def test_assume6(): a = 1 b = 2 with pytest.assume: assert a == b with pytest.assume: assert 1 == 2 with pytest.assume: assert 3 == 3 if __name__ == '__main__': pytest.main(['-sv', __file__])
-
输出
with pytest.assume: assert a == b > with pytest.assume: assert 1 == 2 E pytest_assume.plugin.FailedAssumption: E 2 Failed Assumptions: E E demo_assume.py:18: AssumptionFailure E >> with pytest.assume: assert a == b E AssertionError: assert 1 == 2 E E demo_assume.py:19: AssumptionFailure E >> with pytest.assume: assert 1 == 2 E AssertionError: assert 1 == 2