foreword
When writing test cases, one use case may have multiple assertion results. Of course, this problem will also be encountered in automated test cases. Once our ordinary assertion results fail, an error will appear. How to proceed more What about an assertion? The pytest plugin pytest-assume can solve this problem.
pytest-assume
pytest-assume belongs to a plug-in of pytest. This plug-in means that multiple assertion methods can be used. When the assertion method fails, it does not affect the execution of the code behind the assertion.
Install: pip install pytest-assume
github:
Instructions
The basic similarity between the usage method and assert is to compare the result with the expected or True and False
import pytest
class Test_01:
def test_01(self):
print('---用例01---')
pytest.assume('anjing' in 'test_anjing')
pytest.assume(1==2)
print('执行完成!')
def test_02(self):
print('---用例02---')
def test_03(self):
print('---用例03---')
if __name__ == '__main__':
pytest.main(['-vs'])
Through the execution results, two assertions were found, one of which failed, and then the execution was completed. And output the detailed error message
Through the use of with
We can also write assertion methods through the method of with+assert
import pytest
from pytest import assume
class Test_01:
def test_01(self):
print('---用例01---')
with assume: assert 'anjing' in 'test_anjing'
with assume: assert 1==2
print('执行完成!')
def test_02(self):
print('---用例02---')
def test_03(self):
print('---用例03---')
if __name__ == '__main__':
pytest.main(['-vs'])
Through execution, it is found that the assertion execution is the same, the first one passed, the second one reported an error, and detailed error information was printed
There must be friends who will say that the code pays attention to indirection. Can you extract the with assume and write it all together. In fact, this can be executed, but there should be no errors in the assertion. If there is an error, the subsequent assertion It doesn't work anymore.
import pytest
from pytest import assume
class Test_01:
def test_01(self):
print('---用例01---')
with assume:
assert 'anjing' in 'test_anjing'
assert 1==2
assert 1==1
print('执行完成!')
def test_02(self):
print('---用例02---')
def test_03(self):
print('---用例03---')
if __name__ == '__main__':
pytest.main(['-vs'])
After execution, it is found that such a method can also be executed, but careful friends will find that when the second use case is executed, the third assertion basically has no effect, that is, it is not executed
Therefore, for the sake of insurance, it is recommended to build with assume method