pytest-mock

Mock a library method response using pytest

Mock a library method response using pytest Question: I am new to pytest, i want to create a test for a method called inside a library. So following is my sample usecase. I have a python library called core: Inside core there is a folder called p_core. Inside p_core there is python file common.py In …

Total answers: 1

Mocking datetime.now using pytest-mock

Mocking datetime.now using pytest-mock Question: I have a function func_to_mock in module module_to_mock.py. My unit test is located in test_func_to_mock.py I am trying to mock datetime.datetime.now, however, I am struggling. I get the error TypeError: cannot set ‘now’ attribute of immutable type ‘datetime.datetime’. What am I missing here? module_to_mock.py: # module_to_mock.py import datetime def func_to_mock() …

Total answers: 1

Pytest mocker failing to find Path

Pytest mocker failing to find Path Question: I am working with someone else’s testing code, and they make extensive use of mocker. The problem is that I changed the underlying code so it tests for the existence of a file using Path ().is_file. Now I need to mock Path ().is_file so it returns True. I …

Total answers: 1

How can we mock several exception in Pytest, Mock_Response?

How can we mock several exception in Pytest, Mock_Response? Question: We’re revising our pytest script, according to parent ‘executor’ method revision — added retry logic, to retry 3 times until get response and raise error on 4th.attempt. Used to be, we test to raise socket error exception as follows, now we need to raise that …

Total answers: 2

Pytest @patch return different values like @parametrize

Pytest @patch return different values like @parametrize Question: I’m currently writing some tests for my python program and I have a scenario where I need to patch a method but want to run the test multiple times with different return values. For example. Below is the basic use case. There is a method that is …

Total answers: 1

unittest.mock vs mock vs mocker vs pytest-mock

unittest.mock vs mock vs mocker vs pytest-mock Question: I am new to Python development, I am writing test cases using pytest where I need to mock some behavior. Googling best mocking library for pytest, has only confused me. I have seen unittest.mock, mock, mocker and pytest-mock. Not really sure which one to use.Can someone please …

Total answers: 2

session scope with pytest-mock

session scope with pytest-mock Question: I’m looking for example of how to use the session-scoped "session-mocker" fixture of the pytest-mock plugin. It’s fairly clear how to modify the example the docs provide to use it in a particular test: def test_foo(session_mocker): session_mocker.patch(‘os.remove’) etc… But I’m baffled as to where and how this global fixture should …

Total answers: 1