Questions tagged [python-unittest.mock]

mock object library (part of the Python Standard Library)

unittest.mock allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

It provides a core Mock class removing the need to create a host of stubs throughout your test suite.

330 questions
78
votes
2 answers

Python mock call_args_list unpacking tuples for assertion on arguments

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…
nackjicholson
  • 4,557
  • 4
  • 37
  • 35
25
votes
3 answers

Python - How can I assert a mock object was not called with specific arguments?

I realize unittest.mock objects now have an assert_not_called method available, but what I'm looking for is an assert_not_called_with. Is there anything like that? I looked on Google and didn't see anything, and when I tried just using…
Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
23
votes
1 answer

What happens when a python mock has both a return value and a list of side effects?

I'm having trouble understanding what's happening in some test code. It looks like this: import pytest from unittest.mock import MagicMock from my_module import MyClass confusing_mock = MagicMock( return_value=b"", side_effect=[ …
tessafyi
  • 2,273
  • 2
  • 19
  • 28
17
votes
1 answer

python mock assert_called_with

I'm trying to understand the assert_called_with within mock but the code I wrote throws some error. import os import twitter URL = "http://test.com" def tweet(api, message): if len(message) > 40: message = message.strip("?.,.,.") …
user1050619
  • 19,822
  • 85
  • 237
  • 413
17
votes
3 answers

Python Unit Test : How to unit test the module which contains database operations?

I am using pymysql client library to connect to the real database. I have a function in module, where I connect to the database using pymysql and do only database insert operations.How to unit test this function in python without hitting the real…
15
votes
2 answers

Python: patching function defined in same module of tested function

I have been working with Python's unittest.mock library quite a bit, but right now I'm struggling with a use case that may not be approached correctly. Consider a file mymodule/code.py containing the following snippet: def sum(): pass def mul(): …
13
votes
2 answers

Python SQLAlchemy mocking

this is a method that I made chained DB query calls. import math def get_all_keys(): db_session = DBSession() keys = db_session.query(SomeClass).all() I should mock DBSession().query(SomeClass).all(). I tried some but nothing worked. Here…
13
votes
1 answer

Avoid type warnings when mocking objects in unit tests?

Assuming I have a function that takes a complex object and does something with it: def foo(bar: SomeComplexObject): ... In unit tests bar will be replaced by a mock object, but that of courses now raises type warnings. Should I simply ignore or…
gmolau
  • 2,815
  • 1
  • 22
  • 45
12
votes
4 answers

Python asyncio: how to mock __aiter__() method?

I have a code which is listening to messages on WebSocket using aiohttp. It looks like: async for msg in ws: await self._ws_msg_handler.handle_message(ws, msg, _services) Where ws is an instance of aiohttp.web.WebSocketResponse() (original…
11
votes
4 answers

Python unit test mock. ValueError: The truth value of a DataFrame is ambiguous

I am writing a unit test case for one of my python 2.7 methods. In my test method, there is a method call that takes a dictionary with string key and panadas dataframe as the value for that key. I want to write an interaction test for this method to…
Hary
  • 1,127
  • 4
  • 24
  • 51
10
votes
1 answer

Unittest and mocks, how to reset them?

I am testing a class that needs a mock in the constructor, so I usually do this: class TestActionManager(unittest.TestCase): @patch('actionlib.SimpleActionClient', return_value=create_autospec(actionlib.SimpleActionClient)) def setUp(self,…
Bernat
  • 379
  • 1
  • 2
  • 12
10
votes
3 answers

How to mock data as request.Response type in python

I would like to write some testcase to exercise object_check in isinstance(obj, requests.Response) logic. After I create Mock data as return value for requests.post. The type for mock data is always be Mock class. In that way, how can I rewrite mock…
jacobcan118
  • 7,797
  • 12
  • 50
  • 95
10
votes
1 answer

check unittest.mock call arguments agnostically w.r.t. whether they have been passed as positional arguments or keyword arguments

When a unittest.mock.Mock object has been called, I can check for the argument values with the exact signature of the call: from unittest.mock import Mock m = Mock() # creation of mock m('foo', bar='baz') # call to the…
das-g
  • 9,718
  • 4
  • 38
  • 80
9
votes
1 answer

What is the difference between using mock.Mock() vs mock.patch(), and when to use one over the other?

What is the difference between using mock.Mock() vs mock.patch()? When to use mock.Mock() and when to use mock.patch() I've read that Mock is used to replace something that is used in the current scope, vs, patch is used to replace something that…
0x5929
  • 400
  • 1
  • 4
  • 16
9
votes
2 answers

Patch method only in one module

For example, I have some module(foo.py) with next code: import requests def get_ip(): return requests.get('http://jsonip.com/').content And module bar.py with similiar code: import requests def get_fb(): return…
1
2 3
21 22