Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a method gets called twice with different arguments in Python unittest

Say I have a method that looks like this:

from otherModule import B
def A():
    for pair in [[1, 2], [3, 4]]:
        B(*pair)

and I have a test that looks like:

class TestA(unittest.TestCase):
    @patch("moduleA.B")
    def test_A(self, mockB):
        A()
        mockB.assert_has_calls([
            call(1, 2),
            call(3, 4)
        ])

For some reason I get an AssertionError: Calls not found. because it only registers teh call with 3,4 twice. Does what I'm doing look right?

like image 577
Jwan622 Avatar asked Feb 01 '26 18:02

Jwan622


1 Answers

It works fine, can't reproduce the error.

E.g.

moduleA.py:

from otherModule import B


def A():
    for pair in [[1, 2], [3, 4]]:
        B(*pair)

otherModule.py:

def B(x, y):
    print(x, y)

test_moduleA.py:

import unittest
from unittest.mock import patch, call
from moduleA import A


class TestA(unittest.TestCase):
    @patch("moduleA.B")
    def test_A(self, mockB):
        A()
        mockB.assert_has_calls([
            call(1, 2),
            call(3, 4)
        ])


if __name__ == '__main__':
    unittest.main()

unit test results with coverage report:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/59179990/moduleA.py            4      0   100%
src/stackoverflow/59179990/otherModule.py        2      1    50%   2
src/stackoverflow/59179990/test_moduleA.py       9      0   100%
--------------------------------------------------------------------------
TOTAL                                           15      1    93%

Python version: Python 3.7.5

like image 195
slideshowp2 Avatar answered Feb 03 '26 07:02

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!