Master Pytest Assert Function called

The pytest is a common framework used for testing scripts. It has a wide variety of assert functions. pytest assert function called has several related attributes that have been discussed in this blog. Read to know more!

Why are we required to assert functions?

The mock module helps in checking the function calls. Assume you have made a script to assess whether your function works properly or not. The mock module consists of plenty of assertions that are responsible for the verification part. They will tell you whether your script is actually working or not.

Benefits of Mock module’s assertions

The mock module holds great importance in the code-testing phase. Let us see in which ways it proves to be of great use to developers. The assert functions hold the following benefits:

  • Improved code quality
  • Early error detection
  • Enhanced code readability
  • Simplified testing

Types of Mock module’s assertions

This module under the pytest framework provides a great number of assertions. These assertions can be used with a mock object. Such objects are representative of real-time functions and are used for testing purposes. These assertions are:

  • assert_called() – function call at least once.
  • assert_called_once() – function call exactly once.
  • assert_called_with() – function call with specific arguments.
  • assert_has_calls() – if the function call has specific arguments.
  • assert_not_called() – if a function has not been called at all.

Working of assert functions

The following sections elaborate on the functioning of all these assert functions, namely:

Using assert_called()

This function will let you know whether it has been called at least once. If there is no response, it means that you need to make changes to your original script. It uses a decorator to function because you can make changes to the function once, as decorators don’t modify the entire code but just the function part that you will make a call to.

import unittest
from unittest.mock import patch

def my_function(x, y):
    return x + y

class MyTest(unittest.TestCase):

    @patch('my_module.my_function')
    def test_my_function(self, mock_my_function):
        my_function(1, 2)
        my_function(3, 4)

        mock_my_function.assert_called()

Using assert_called_once()

This function lets you check whether you have called the function exactly one time or not. Once this has been ensured, we can be clear of the fact that the mock object works one time. In other words, it has been asserted once only.

import unittest
from unittest.mock import patch

def my_function(x, y):
    return x + y

class MyTest(unittest.TestCase):

    @patch('my_module.my_function')
    def test_my_function(self, mock_my_function):
        my_function(1, 2)

        mock_my_function.assert_called_once()

Using assert_called_with()

In this type of assert function call, the user can specify mock arguments as per his choice. In the example given below, my_function() the function has the arguments 1 and 2. Once this is successful, it means that the mock object has been asserted correctly.

import unittest
from unittest.mock import patch

def my_function(x, y):
    return x + y

class MyTest(unittest.TestCase):

    @patch('my_module.my_function')
    def test_my_function(self, mock_my_function):
        my_function(1, 2)

        mock_my_function.assert_called_with(1, 2)

Using assert_not_called()

In this function type, the test case makes no function call. We have the pass keyword instead. Thus, if this executes correctly, assert_not_called() confirms that the code has no issues else you need to check the code again.

import unittest
from unittest.mock import patch

def my_function(x, y):
    return x + y

class MyTest(unittest.TestCase):

    @patch('my_module.my_function')
    def test_my_function(self, mock_my_function):
        pass

        mock_my_function.assert_not_called()

Using assert_has_calls()

The assert_has_calls() function creates a mock object with arguments specified by the developer to see if the function asserts anything or not. The mock object for this function includes 5 and 3 as the arguments.

import unittest
from unittest.mock import patch

def add_numbers(x, y):
    return x + y

class MyTest(unittest.TestCase):
    @patch('my_module.add_numbers')
    def test_add_numbers(self, mock_add_numbers):
        result = add_numbers(5, 3)

        mock_add_numbers.assert_has_calls([
            mock.call(5, 3),
        ])

Recommend Reading | Python Unittest Vs Pytest: Choose the Best

pytest assert function called n times

In pytest, you can check the number of times you have made a function call. This can be done through the call_count attribute of the mock object. You can verify how many times the function call has been made. The example given below explains this. You need to use the patch function of the unittest.mock module to carry out this operation. The decorator replaces the real function with the mock function.

from unittest.mock import patch

@patch('my_module.my_function')
def test_my_function(self, mock_function):
    # Call the function under test
    my_function(1, 2)
    my_function(3, 4)

    # Assert that the function was called twice
    assert mock_function.call_count == 2

Pytest assert function called without mock

You can try calling the assert function without creating a mock object. This works when you are working with the pytest-mock plugin. Consider the example given below. It uses a mocker fixture instead of a mock directly. The mocker fixture lets you access a mock object for any function or class. It then uses the assert_called_once method to check whether the function call is made once or not. You can specify the arguments you want in the placeholder (...). The mocker fixture lets you create a mock object for the required function. You can be a bit more specific with the module.function by specifying the actual path to the mocked function.

import pytest

@pytest.mark.parametrize(...)
def test_function_called(mocker):
  mock_function = mocker.patch('module.function')
  # Code that calls the function
  assert mock_function.called_once()

Other tips while working with assert functions

You need to keep certain tips in mind while working with assert functions of the pytest module. These are:

  • Don’t load your code with assert functions. This will make it unreadable.
  • The function can use decorators to be simple and clear.
  • Try working on assert functions with mock objects.
  • See which assert function works the best as per your use case.

FAQs

Should I use assert functions to control program flow?

No, you should use these functions for code testing.

Conclusion

This article elaborates on the pytest assert function and other functions in the mock module under the pytest framework. It explains some commonly used assert functions that are efficient in code testing.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments