All Questions
Tagged with python-unittest.mock mocking
77 questions
0
votes
1
answer
60
views
Python mock not asserting call when target method is called inside another method
I do not manage to do some basic assert_called() in a class where some methods are internally calling other methods.
Example code:
from unittest.mock import Mock
class Foo:
def print1(self) -> ...
1
vote
1
answer
59
views
When writing unit tests in python, why are mocks in subsequent tests not overwriting mocks made in previous tests?
I am trying to write unit tests that involve mocking several libraries in different ways for each test. When I run each test individually, they all pass, but when I run them all together, many of them ...
0
votes
2
answers
63
views
Assert that two files have been written correctly
How would I assert that this function wrote to those files in tests?
def write() -> None:
with open('./foo', 'w') as f:
f.write('fooo')
with open('./bar', 'w') as f:
f.write(...
1
vote
2
answers
614
views
How to Mock a Function Within a FastAPI Route Using Pytest
I'm working on a FastAPI application and am trying to write some tests for one of my routes. My testing environment cannot make calls to external services. My goal is just to test the parsing of the ...
-1
votes
2
answers
76
views
How to run a function multiple times with different return values?
I have a test that intermittently fails during automated builds so I want to add some retries to my tool. However, I'm not sure how to force the tool to fail and verify that it has retried before I ...
0
votes
1
answer
45
views
Python unit testing: function patch does not get applied to consumer that runs in a separate thread
I am trying to test a consumer that consumes messages of a queue and creates the corresponding object in salesforce.
To test the consumer I have to start it in a new thread because, it is an infinite ...
0
votes
0
answers
123
views
how to mock default_factory in pydantic model [duplicate]
I have a simple pydantic model with a default value field:
import pydantic
from uuid import UUID, uuid4
class User(pydantic.BaseModel):
id: UUID = pydantic.Field(default_factory=uuid4)
email:...
0
votes
0
answers
135
views
TypeError: 'Mock' object is not iterable when mocking Boto3 paginator in unit test
I'm attempting to write unit tests for a Python function that downloads a directory from S3 using Boto3. However, I'm facing a TypeError: 'Mock' object is not iterable issue when trying to simulate ...
0
votes
0
answers
31
views
Mock function appends instead of replacing return values
I'm writing a script that uses spotipy to just list albums of a specific artist. I'm trying to create a test for my script, by mocking the artist_albums function that should return a dict.
This is my ...
1
vote
2
answers
122
views
Python mock and call assertion
I am trying to write a python unit test to assert that a scoped_session .commit() is called.
main.py
from database import DBSession
def deactivate_user(user_id):
db_session = DBSession()
user ...
0
votes
1
answer
232
views
How to mock read and write a single file after updating its contents using mock_open in Python
def simple_read_write():
with open("file", "r") as f:
data = json.load(f)
data["change"] = "some content"
with open("file", &...
-1
votes
2
answers
176
views
how to mock in python API testing [closed]
I'm trying to mock a sample function below. Somehow I'm getting error.
For example,
I've a class as below myclass.py:
import os, requests
class MyClass:
def __init__(self, login_url):
...
1
vote
3
answers
206
views
Python mock: replace function with another function if sys.argv argument is set
I have a snippet of code that looks like this:
if args.module == 'omega':
with mock.patch.object(quantum_entangler, 'sort_by_dirac', sort_by_heisenberg):
quantum_entangler.main(atom_no)
...
-1
votes
1
answer
77
views
Which method is the best way to mock classes used in the `__init__` of a class being tested?
I was hoping that someone could give me guidance on some of the approaches I've tried for mocking. I'm really trying to understand what the best method is for this general case (I think general enough)...
0
votes
1
answer
1k
views
python - mock - class method mocked but not reported as being called
learning python mocks here. I need some helps to understand how the patch work when mocking a class.
In the code below, I mocked a class. the function under tests receives the mock and calls a ...
1
vote
1
answer
646
views
Why is an autospecced mock of Enum not iterable (has no __iter__ method)?
Why is an autospecced mock of Enum not iterable (has no __iter__ method)?
from unittest.mock import create_autospec
from enum import IntEnum
class IE(IntEnum):
Q = 1
W = 2
m = ...
1
vote
0
answers
897
views
How do I use a pytest fixture to mock a child class's inherited methods with classes as properties while maintaining the API contract using autospec?
How it started
I'm testing a class, ClassToTest, that makes API calls using atlassian-python-api. The tests are going to ensure that ClassToTest performs correctly with the data it gets back from the ...
0
votes
1
answer
680
views
How to mock a function which gets executed during the import time?
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__(), ...
0
votes
1
answer
946
views
Python unittest returns MagicMock object instead of value
I have a program like this:
class SomeClass:
_attribute = None
def __init__(self, attribute):
self._attribute = attribute
@property
def ...
1
vote
0
answers
392
views
How do I assert_called_once when using a context manager for unittest.mock?
I am relatively new to python and exploring mocking in unit tests. I have the following method to test, calc_scores so I want to mock the response to get_score_json:
def calc_scores(
score_id: str,...
2
votes
1
answer
1k
views
Python unit test case for mocking directory and generating test files
Can we mock test directory and couple of files in python unit test case?
scan.py:
import re
from pathlib import Path
class Scan():
def scan_files(self, dir_path, filter_regex=None):
for ...
1
vote
2
answers
2k
views
Python mock patch not mocking the object
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....
1
vote
1
answer
1k
views
Python Mocking - How to store function arguments to a mocked function in the mock that is returned?
Consider two explicit MagicMocks, such that one is used to create new mock instances by calling a method with arguments, and these mocks in turn are passed to the other mock's method as arguments:
In [...
0
votes
0
answers
41
views
Check if a mocked function is being called from within a class method
I have the following files -
summer.py
def sum(a, b):
return a+b
base.py
class Base():
def work(self, a, b):
self.add(a, b)
calculator.py
from summer import sum
from base import Base
...
4
votes
0
answers
2k
views
mock assert_called_with treat argument as unordered list
I have some mocked function and I try to test that the arguments I pass there are correct.
One of the arguments is a list generated based on DB queryset, lets say [{"id": 1}, {"id":...
2
votes
1
answer
4k
views
Mock a function with parameters that is indirectly called with a mock function instead
I have been trying to test a function that calls another function with some parameters. I am trying to mock the latest so that it won't actually run and instead executes a mock function that returns ...
0
votes
1
answer
2k
views
Using mock patch decorator twice with autospec=True
How do I create two different mocked objects with the same spec using the patch decorator?
I have a test that needs two mocked selenium WebElements. I could just use two patch decorators:
@mock.patch(&...
3
votes
0
answers
456
views
unittest - Mock a class instance return is impossible?
I've been trying for days to mock the instance of a certain class. I've tried dozens of approaches... I'm starting to think that this is not possible. 😓
The code below is the only one, so far, that I'...
1
vote
1
answer
1k
views
Patching over local JSON file in unit testing
I have some Python code that loads in a local JSON file:
with open("/path/to/file.json") as f:
json_str = f.read()
# Now do stuff with this JSON string
In testing, I want to patch ...
1
vote
0
answers
1k
views
Mocking - Can a mock patch be toggled on/off selectively using start() stop()
I'm charged with adding a unit test to an existing TestCase object. The setup method instantiates and starts several unittest.patch objects on functions that I need to test unmocked. Is calling stop() ...
1
vote
1
answer
2k
views
MagicMock's reset_mock not properly resetting sub-mock's side_effect
I have a long-lived patch on a class, whose made instance undergoes multiple batches of assertions. Please see the below code snippet for the scenario.
It exposes (what I think is annoying) behavior ...
0
votes
1
answer
1k
views
How to employ a MagicMock spec_set or spec on a method?
I am trying to use a method as a spec_set on a MagicMock.
https://stackoverflow.com/a/25323517/11163122 provides a nice example of an unexpected call signature resulting in an Exception. ...
7
votes
1
answer
4k
views
Python unittest mock pyspark chain
I'd like to write some unit tests for simple methods which have pyspark code.
def do_stuff(self, df1: DataFrame, df2_path: str, df1_key: str, df2_key: str) -> DataFrame:
df2 = self.spark.read....
1
vote
1
answer
479
views
ModuleNotFoundError when using mock.patch()
I want to mock a response from the Python Kubernetes client. Below code of my Kubernetes service:
import os
from kubernetes.client.rest import ApiException
from kubernetes import client
from ...
0
votes
1
answer
393
views
How to mock mongodb with unites Flask
I want to mock mongo in order to make some unit test with unittest for Flask. The doc about this is so huge and I don't really understand how to make it.
I want to test a POST method with the ...
4
votes
0
answers
627
views
Python unittest returns MagicMock object instead of return value
I have a python which has a class A. Class A object has a method that takes a list as input and sends a post request to a client endpoint to create new sources in the database and returns a tuple of ...
1
vote
1
answer
1k
views
How to mock a class in one script from another test script running the first
I have a class SQLES in a separate script, sqles.py, which is imported in main.py and comprises methods to read SQL data and set the results in the class instance.
I am now writing a test script, ...
3
votes
1
answer
706
views
How do I patch mock multiple calls from os in python?
I have a method that does the following:
import os
...
if not os.path.exists(dirpath):
os.makedirs(dirpath)
I'm trying to mock the makedirs and path.exists but when I do this ...
0
votes
0
answers
1k
views
Mocking a class method in Python
Say I have the following:
# maincode.py
from othermodule import do_something
class Myclass():
@staticmethod
def return_array():
array_result = do_something()
return array_result
...
7
votes
3
answers
8k
views
Python mock - mocking class method that modifies class attributes
I currently have the following basic Python class that I want to test:
class Example:
def run_steps(self):
self.steps = 0
while self.steps < 4:
self.step()
...
0
votes
1
answer
721
views
Raise error when calling a non-existent method of a mocked method of a mock created from `spec`
from unittest import mock
class A:
def f(self): pass
m = mock.MagicMock(spec_set=A)
m.f.called_once() # I want this to fail
Out[42]: <MagicMock name='mock.f.called_once()' id='140326790593792'&...
0
votes
1
answer
207
views
Using a generator with Python mock to replicate server responses
I would like to use a list (converted into a generator) to serve as a mock for my API calls (using unittest.mock). My function is:
def monitor_order(order_id)
order_info = client.get_order_status(...
-1
votes
3
answers
326
views
Override 'is' operator for mocked object
Simplified code: I have a function that expects either a number or None, and returns True if it's None, and False if it's a number, like:
def function(var):
return var is None
I want to pass a ...
0
votes
1
answer
135
views
Cannot mock subprocess.check_call
I want to write a test for this function while mocking check_call (I don't want it to be called):
from subprocess import check_call
def foo_method():
check_call(["ls"])
print("...
1
vote
0
answers
2k
views
Python how to patch entire object with patch.object
Python's unittest.mock built-in library provides patch.object, which let's you:
patch the named member (attribute) on an object (target) with a mock object.
With regular patch, you can easily ...
6
votes
1
answer
2k
views
Using unittest.mock's patch in same module, getting "does not have the attribute" when patching via "__main__.imported_obj"
I have what should've been a simple task, and it has stumped me for a while. I am trying to patch an object imported into the current module.
Per the answers to Mock patching from/import statement in ...
0
votes
1
answer
1k
views
How to mock and test decorator?
How to test the following decorator which calls 3rd party library?
import third_party_lib
import functools
class MyDecorator:
def __init__(self, ....):
self.third_party_lib = ...
0
votes
1
answer
222
views
Is there a built-in mock object to pass in to Python unit test?
I commonly instantiate a Mock object during unit tests. I am sick of:
Having to type from unittest.mock import Mock
And then instantiate a Mock object via mock = Mock()
I am wondering, does pytest, ...
0
votes
1
answer
2k
views
Python mock.patch is not mocking my function?
So I wrote a pretty simple test case and function. I can't seem to figure out the problem. Anyone have an idea? I feel like it should work.
import pandas
import unittest
from unittest import mock
...
0
votes
0
answers
795
views
How to mock a function called inside a class attribute?
I have a class with an attribute that calls a function:
users.mixins.py:
from django.contrib import messages
from ..utils.services import redirect_to_previous
class AdminRightsMixin:
def ...