376 questions
0
votes
1
answer
66
views
How to "inject" a local variable when importing a python module?
Is it possible to declare a local variable before it's imported?
For example to get this code to run as expected:
# a.py
# do magic here to make b.foo = "bar"
import b
b.printlocal()
# b....
-1
votes
1
answer
37
views
Python unittest.mock patch fail with F() expressions can only be used to update, not to insert
A minimal working example is available at https://github.com/rgaiacs/django-mwe-magicmock.
When using Django, I use Model.clean() to validate the form submitted by the user. During the validation, ...
0
votes
1
answer
20
views
unittest.AsyncMock: side_effect results in an coroutine instead of raising the Exception
Here's a minimal reproducible example.
This is with python 3.11. Besides pytest, no other dependency.
# minum_reproducible_example.py
from typing import Literal
from unittest.mock import Mock, patch
...
1
vote
0
answers
27
views
unittest.mock patch decorator is not called depending on the pytest target
Running
docker compose -f docker-compose.local.yml run --rm django pytest ./project/app/
the following test passes perfectly, meaning patch method is being used
@patch("project.app....
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) -> ...
0
votes
1
answer
69
views
How to patch function within pandas DataFrame.apply call
I'm trying to write a test for a class which performs a pandas apply. Here's a simplified version:
import pandas as pd
class Foo:
def bar(self, row):
return "BAR"
def apply(...
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 ...
-1
votes
2
answers
48
views
How do I test instantiation outside a function with patching in Python
I have a file that looks roughly like this:
bar.py
from foo import foo # function that returns an int
from dog import Dog
dog_foo = 4 * foo()
my_dog = Dog(dog_foo)
...
I want to test that the ...
0
votes
2
answers
41
views
Assert that unittest Mock has these calls and no others
Mock.assert_has_calls asserts that the specified calls exist, but not that these were the only calls:
from unittest.mock import Mock, call
mock = Mock()
mock("foo")
mock("bar")
...
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
613
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 ...
3
votes
1
answer
52
views
How to mock imported function?
I've tried multiple ways and just can't get the result I'm looking for. It seems like a lot of questions use a different type of mocking with the whole @patch decorators but I've been using this more ...
2
votes
3
answers
520
views
How to test a Pydantic BaseModel with MagicMock spec and wraps
Given this example in Python 3.8, using Pydantic v2:
from pydantic import BaseModel
import pytest
from unittest.mock import MagicMock
class MyClass(BaseModel):
a: str = '123'
# the actual ...
2
votes
1
answer
106
views
Is there a way to mock .strip() for unit testing in Python 2.7's unittest module?
I am using Python 2.7 for a coding project. I'd love to switch to Python 3, but unfortunately I'm writing scripts for a program that only has a python package in 2.7 and even if it had one in 3 our ...
0
votes
1
answer
65
views
How to import and test the target function only without touching other codes in the file?
I'm trying to perform a unit test on each function of a Python file using unittest.
Assuming the file I want to test is called X.py and the file containing the testing code is Y.py.
In file X, there ...
1
vote
1
answer
51
views
How to use unit test's @patch to mock self.attribute.savefig for matplotlib?
I'm trying to figure out how to mock matplotlib's plt.savefig inside a class to test if my GUI's button is actually saving a figure. For simplicity's sake, I will not include the GUI, but only the ...
-1
votes
1
answer
47
views
Function not being mocked unless full path is called
main.py
from path.to.mod import run
def foo(args: str):
run(args)
test.py
@patch("path.to.mod.run")
def verify_args(mock):
foo("bar")
mock.assert_called_once_with(&...
-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
1
answer
48
views
side_effect not iterating on Mock in Pytho
I'm trying to obtain different responses by each call on a Mock by using the side_effect attribute. However, I'm obtaining the first one each time. I would like to ask if I can get any help on it. ...
2
votes
1
answer
43
views
Verifying constructor calling another constructor
I want to verify Foo() calls Bar() without actually calling Bar(). And then I want to verify that obj is assigned with whatever Bar() returns.
I tried the following:
class Bar:
def __init__(self, ...
0
votes
1
answer
21
views
Patch call from another class
I have Processor class:
class Processor:
def __init__(self, session_provider):
self.session_provider = session_provider
def run(self):
...
self.session_provider....
0
votes
0
answers
26
views
Mock testing in Python shows an error "no module found named path.csv"
class TestFilterDF(unittest.TestCase):
@patch('plugins.qa_plugins.preprocessing.read_df')
def test_filter_df(self, read_df_mock):
# Mocking read_df function to return a DataFrame ...
0
votes
0
answers
27
views
python unittest mocking a custom exception and triggering it
I can't get my custom mock exception to trigger
def exist_on_p4(path, p4):
""" Checks to see if file exists on p4 """
try:
p4.run_files('-e', path)
...
0
votes
3
answers
43
views
Python unittest how to mock a passed in class
Trying to unittest a method that receives a class as an argument but unsure how to mock it right
I am trying to unittest this method `
def get_local_path(p4_path, p4):
if p4_path.endswith('...'):
...
0
votes
0
answers
41
views
Python unittest.mock.patch: usage of new and side_effect
I am a little confused about the usage of patch and of its arguments: new and side_effect (although this is not a proper argument of patch but is passed to the created MagicMock).
When should I use or ...
0
votes
1
answer
64
views
How to mock global variable, when the value is coming from a function python unittest
I have to mock the global variable in python, but the variable value is coming from the another function. When i am importing the file, this function is getting run but instead of this, I want the ...
1
vote
0
answers
90
views
Mocking GraphCypherQAChain in Python unit test cases
chain.py
----------------------------------
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI
from langchain_community.graphs import Neo4jGraph
from langchain....
0
votes
1
answer
234
views
how to mock s3 using pytest? Unittest script calls actual function instead of mocking it?
I'm trying to test a function that should mock s3 resource but instead it tries to call the actual function.
Here is my code to test.
import sys
import requests
import json
import pandas as pd
import ...
0
votes
0
answers
25
views
Python patched function mock called_with compares with modified data -- best way to fix?
I have a function (validate.py):
def _validate_data(data: dict[string,Any]):
pass
It's not implemented yet so its a stub. I want to verify that another function calls this one with an empty dict ...
0
votes
0
answers
33
views
Define return value after chained mocks
I am using unittest.mock to test my Django application.
The set-up is the following:
I want to test a function foo
foo uses a method X which is a constructor from an external package
X is called in ...
0
votes
1
answer
44
views
How to mock environment variable that uses equality operator
Given the following code, I am unable to properly patch the os.environ "USE_THING".
I believe this is because USE_THING is a constant created before the test runs, so I cannot reassign the ...
1
vote
0
answers
48
views
Why mock is not applied on a method which called within thread after testcase finishes
I have these two classes:
one.py
class One:
def __init__(self) -> None:
pass
def startS(self):
self._doS()
def _doS(self):
print("Inside doS ...
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
20
views
Testing a function in python without in- and output value
I have the following function in my py-file.
def change_grid():
print("switch grid, current value:", grid_var.get())
global grid
if grid_var.get() == "off":
...
0
votes
2
answers
42
views
Why is my mock not returning True for the following patched function?
In my get_orders.py file I am importing a function called admin_only that exists at the given path (src.lib.authorization). In my test_get_orders.py file I am trying to patch this function, however ...
0
votes
1
answer
44
views
How to send extra parameter to unittest's side_effect in Python?
I'm using side_effect for dynamic mocking in unittest.
This is the code.
// main functionn
from api import get_users_from_api
def get_users(user_ids):
for user_id in user_ids:
res = ...
0
votes
1
answer
305
views
Using AsyncMock with context manager to assert await was called (python)
I am new to using asyncio in Python and I'm having trouble figuring out how to write a test which uses python-websockets (and asyncio). I want to have a client which connects to a websocket and sends ...
0
votes
1
answer
63
views
Dynamic mocking using patch from unittest in Python
I'm going to mock a Python function in unit tests.
This is the main function.
from api import get_users_from_api
def get_users(user_ids):
for user_id in user_ids:
res = get_users_from_api(...
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 ...
1
vote
1
answer
86
views
How to mock a function called in a class attribute in python
I need to mock a function that is called in a class attribute in a python class. I'm able to do it patching the function when the object is initialised, but it does not work when I access it without ...
0
votes
0
answers
53
views
Mock a method called on a mock object (execute method of cursor object generated by a mocked connection)
I want to make a unit test for the following code.
But i can not try to correctly mock the cursor of my mocked connection.
In the unit test, I mock first the connection of my tested code. But the ...
2
votes
1
answer
36
views
What is the role of `Base` class used in the built-in module `unittest.mock`?
While having deep dive into how the built-in unittest.mock was designed, I run into these lines in the official source code of mock.py:
class Base(object):
_mock_return_value = DEFAULT
...
0
votes
1
answer
495
views
How can I assert on mock_open to check a specific filepath has been written to with specific content in python?
I have a program that needs to write different files with different content depending on some logic.
I tried to write a assert_file_written_with_content(filepath: str, content: str) function that ...
0
votes
1
answer
857
views
Python unittests: how to get an AsyncMock to block until a certain point
I have some async Python code I want to test, which include something like
async def task(self):
while True:
await self.thing.change()
...
self.run_callbacks()
In my test ...
1
vote
0
answers
168
views
how to mock a class with metaclass inheritance decorator wrapt_timeout_decorator
In this test it only simulates the call to a class method that in turn calls another class, and both inherit a metaclass that uses the wrapt_timeout_decorator library, so that all methods of a class ...
1
vote
1
answer
90
views
Patching a property of a used class
I'm trying to patch two properties from a class but the mocking is returning a MagicMock instead the expected return value (String).
Client class:
class ClientApi:
def create_path(self):
...
0
votes
1
answer
73
views
Mocking method that calls other methods
I have a class
class X:
def __init__(self, db):
self.db = db
def get_data_from_friend(self):
return None
def get_data_from_db(self):
return self.db.get_my_db_data()
def ...
0
votes
0
answers
48
views
How can I mock an imported dependency from my function file?
I'm attempting to mock a config that is being imported in my security file here:
import aiohttp
from fastapi import Header, HTTPException
from .util.config import config
async def ...
0
votes
1
answer
29
views
How to mock object value in python using unittest library?
The sample API -
@admin_blueprint.route("/test", methods=["GET"])
def test(kwargs):
"""
test API
"""
# Check if cache purge is ...