Pytest series-detailed use of assert assertions (4)

Introduction

  • In terms of assertions, the pytest framework is more concise and easier to use than other similar frameworks (such as unittest). I think this is one of the reasons for choosing pytest as one of the automated testing frameworks.
  • Pytest's assert keyword supports the use of python's built-in assert expression. It can be understood that the assertion of pytest is to directly use the assert keyword that comes with python.
  • The assert keyword can be followed by an expression. As long as the final result of the expression is True, the assertion passes and the use case executes successfully. Otherwise, the use case fails.

Assert Common assertions

The assertion in pytest is actually the assert assertion method in python. The following are commonly used

  • assert xx: determine whether xx is true
  • assert not xx: judge that xx is not true
  • assert a in b: determine whether b contains a
  • assert a == b: Determine whether a is equal to b
  • assert a != b: Determine whether a is not equal to b

Function: Determine whether the expected result is equal to the actual result. At the same time, some prompt information can be output after an exception is thrown. After execution, it is convenient to check the reason.

Exception assertionExcepiton

In addition to supporting assertions about the normal operation of the code, Pytest can also assert about Exceptions and Warnings to determine that certain exceptions or warnings will occur under certain conditions. In functional testing and integration testing, these two types of assertions are not used much. Here is a brief introduction.

You can use with pytest.raises (exception type) as a context manager. When an exception is thrown, you can get the corresponding exception instance.

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

Assertion scenario: Assert whether the exception it throws is expected.
Code execution: 1/0
Expected result: The exception thrown is ZeroDivisionError: division by zero
How to assert: Usually the type and value of the exception are asserted.
The specific method: here 1 The exception type of /0 is ZeroDivisionError, and the value of the exception is divisionby zero

import pytest

def test_zero_division():
    """断言异常"""
    with pytest.raises(ZeroDivisionError) as excinfo:
        1 / 0

    # 断言异常类型type
    assert excinfo.type == ZeroDivisionError
    # 断言异常value值
    assert "division by zero" in str(excinfo.value)

Execution result:
Insert image description here
excinfo: is an exception information instance.
Main attributes: .type, .value, .traceback
Notice: When asserting the type, the exception type does not need to be quoted. When asserting the value, you need to transfer the
test case str. It is asserted that the content of excinfo.value contains the string division by zero. This requires asserting the specific Very useful for exception information.

For more Exception and Warning assertions, please refer to Pytest’s official documentation:
[Exception and Warning assertions Pytest’s official documentation]

Optimize assertion prompt information

You can enter in the terminal: pytest -s assertion file name.py

Expansion 1: match

Keyword arguments can be matchpassed to the context manager to test whether a regular expression matches a string representation of an exception
Notice: This method can only assert value, not type.

# 自定义消息
def test_zero_division_long():
    with pytest.raises(ZeroDivisionError, match=".*zero.*") as excinfo:
        1 / 0

The regexp parameter of the match method matches the re.search function, so in the above example match='zero' will also work

# 自定义消息
def test_zero_division_long():
    with pytest.raises(ZeroDivisionError, match=".*zero.*") as excinfo:
        1 / 0

def test_zero_division_long2():
    with pytest.raises(ZeroDivisionError, match="zero") as excinfo:
        1 / 0

Insert image description here

Extension 2: Check the assertion decorator

# 断言装饰器
@pytest.mark.xfail(raises=ZeroDivisionError)
def test_f():
    1 / 0

Execution results
Insert image description here
knowledge points

  • The code throws an exception, but it matches the exception class specified by raises, so it does not assert failure.
  • It is equivalent to a checked exception decorator, function: check whether there is an exception, not sure whether there is an exception
  • with pytest.raise(ZeroDivisionError)For cases where you are intentionally testing unusual code, it may be better to use
  • While @pytest.mark.xfail(raises=ZeroDivisionError)for checking for unfixed errors (i.e., exceptions may occur), it may be better to use checked assertions

Reference article address

Guess you like

Origin blog.csdn.net/m0_62091240/article/details/132815930