python-unittest.mock

Python unittest case expected not matching with the actual

Python unittest case expected not matching with the actual Question: I am trying to mock the secrets manager client. Earlier the variables weren’t in the class so I was able to mock the client directly using a patch like below: @patch(‘my_repo.rc.client’) and now since I am using an instance method, I need to mock the …

Total answers: 1

How to mock a function which gets executed during the import time?

How to mock a function which gets executed during the import time? Question: Here the ABC() and obj.print_1() get called during the import time and it prints "making object" and "printed 1" respectively. How can we mock all the three functions, __init__(), print_1(), and print_2()? xyz.py from abc import ABC obj = ABC() obj.print_1() def …

Total answers: 1

Mock class in Python with decorator patch

Mock class in Python with decorator patch Question: I would like to patch a class in Python in unit testing. The main code is this (mymath.py): class MyMath: def my_add(self, a, b): return a + b def add_three_and_two(): my_math = MyMath() return my_math.my_add(3, 2) The test class is this: import unittest from unittest.mock import patch …

Total answers: 2

Python Mock: mock calls counted by call_count

Python Mock: mock calls counted by call_count Question: Is there a way to get the mock calls counted by call_count in this example: from mock import MagicMock mock = MagicMock() mock.get_query(arg=1).execute() mock.get_query(arg=2).execute() print(‘count:’, mock.get_query.call_count) print(‘calls:’, mock.get_query.mock_calls) Actual result: count: 2 calls: [call(arg=1), call().execute(), call(arg=2), call().execute()] Desired result: count: 2 calls: [call(arg=1), call(arg=2)] I understand mock_calls. …

Total answers: 1

Python mock patch not mocking the object

Python mock patch not mocking the object Question: I am using the python mocking library and I am not sure why I get this result. Why only the second one got mocked and not the first one? What’s the best way to do it? import unittest from unittest.mock import patch, Mock import requests from requests …

Total answers: 1

Python mock call_args_list unpacking tuples for assertion on arguments

Python mock call_args_list unpacking tuples for assertion on arguments Question: I’m having some trouble dealing with the nested tuple which Mock.call_args_list returns. def test_foo(self): def foo(fn): fn(‘PASS and some other stuff’) f = Mock() foo(f) foo(f) foo(f) for call in f.call_args_list: for args in call: for arg in args: self.assertTrue(arg.startswith(‘PASS’)) I would like to know …

Total answers: 2