SoFunction
Updated on 2024-11-12

Specific use of Pytest assertions

Pytest uses assert, which is a built-in Python assert. python assert is used to judge an expression and trigger an exception if the expression condition is false. That is, pytest test results for False assertion for assertion failure that test case execution failure, and vice versa for assertion success that test case execution success.

Assertion of usage scenarios:

  • Assertions for test results
  • Adding explanatory information to the result of an assertion that does not pass
  • Assertion of Expected Anomalies
  • Customized message for failure assertions

assert assertion method

The assert keyword is followed by an expression, and the common methods for asserting assertions are as follows.

  • Determine if xx is true: assert xx
  • Determine that xx is not true: assert not xx
  • Determine that b contains a: assert a in b
  • Determine that b does not contain a: assert a not in b
  • Determine that a is equal to b: assert a == b
  • Determine that a is not equal to b: assert a ! = b

Example:

# Assertions for test results
 
import pytest
from func import *
 
class TestFunc:
 def test_add_by_class(self):
  assert add(2,3) == 5
# Add explanatory information to the results of failed assertions
 
def test_login():
    # Use python's built-in assertions
    # "1 is not equal to 2" is a customized message that is output when an assertion fails and an exception is thrown.
    assert 1 == 2, "One is not equal to two."
    
test_login()
 
# Run results:
AssertionError: 1is not equal to2(used form a nominal expression)

Exception assertion Excepiton

An exception assertion is an assertion that the exception thrown was an expected exception and that the test case executed was successful.

Use () as a context manager. When an exception is thrown, the corresponding exception instance can be fetched, and then assert that the exception it threw is the expected one. When code throws an exception that matches the exception class specified by raises, the assertion will not fail.

Official Documentation:How to write and report assertions in tests — pytest documentation

with () at the end of the execution will generate an instance of ExceptionInfo object, the object contains type , value, traceback attributes.

The # variable stores all the information about the exception
with (TypeError) as variant: 
    # Get all the attributes of the variable, i.e. type, value, traceback
    print(variant.__dict__)

Note: When asserting type, the exception type is not quoted. The value attribute can be used as a description of the exception.

Examples are shown below:

import pytest
 
def test_zero_division_long():
    with (ZeroDivisionError) as excinfo:
        1 / 0
 
    # Assertion exception type type
    assert  == ZeroDivisionError
    # assertion exception value value
    assert "division by zero" in str()

with (ZeroDivisionError) is used in the case of intentional testing of exception code (known exceptions), the assertion passes that the use case execution was successful showing passed, and fails to pass will show FAILED.

Examples are shown below:

# Complete example of assertion for expected exceptions, execution case True
 
# ./
def add(a,b):
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('Data type error')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
 
 # Normal test cases
 def test_add_by_class(self):
    assert add(2,3) == 5
 
 # Exception test case where the expected result is that a TypeError exception is thrown
 def test_add_by_func_aaa(self,*args, **kwargs):
    with (TypeError) as E:
        add('3',4)
    print()
    print()
    print()  
 
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 (['-v'])
# There are no examples where the expected exception is thrown, and the execution case is False.
 
# ./
def add(a,b):
 # Specify an exception to be thrown directly from here.
    raise NameError("Wrong name.")
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('Data type error')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
    # Exception test case with the expected result of a TypeError exception being thrown.
    def test_add_by_func_aaa(self,*args, **kwargs):
        with (TypeError):
            add('3',4)
  
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 (['-v'])

The match keyword argument can be passed to the context manager() to test whether the regular expression matches the message expression of the exception. the match method is equivalent to the function.

Note: This method can only assert value, not type.

Examples are shown below:

import pytest
 
def test_zero_division_long():
    with (ZeroDivisionError, match=".*zero.*") as excinfo:
        1 / 0
 
# match method is the functional equivalent, i.e. match="zero" is also allowed
def test_zero_division_long():
    with (ZeroDivisionError, match="zero") as excinfo:
        1 / 0

The pytest. raised() function also has another form, where you pass a function that will execute with the given *args and **kwargs and assert that the given exception was raised. In the absence of an exception or error exception, the reporter will provide you with useful output.

(ExpectedException, func, *args, **kwargs)

Asserts the solution to the possibility of multiple different expected exceptions in a given test case:

Passing an argument to an exception type in with () changes from passing an exception type to passing a tuple consisting of exception types. Again, just passing in a single argument.

Examples are shown below:

# ./
def add(a,b):
    raise NameError('Wrong name')
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('Data type error')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
    # Exception test case with the expected result of a TypeError exception being thrown.
    def test_add_by_func_aaa(self,*args, **kwargs):
    # Form a tuple of expected multiple error messages
        with ((TypeError,NameError),match=r'. *Error . *$') as E:
            add('3',4)
 
 
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 (['-v'])

Check Assertion Decorator

CheckException Decorator @(): used for for checking for unfixed errors, i.e. exceptions that may occur. Assertion passes that the use case execution was successful will show xfailed, and fails to show failed.

Role: Check for anomalies, not sure if there are any.

Examples are shown below:

# Assertion of decorator use on single exception
 
@(raises=ZeroDivisionError)
def test_f():
    1 / 0
# Assertion decorator use on multiple exceptions
@(raises=(TypeError, NameError))
def test_add_by_func_aaa2():
    add("3", 4)

This article on the specific use of Pytest assertion is introduced to this article, more related Pytest assertion content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!