383 questions
1
vote
0
answers
62
views
unit testing in DRF, Error mock.patch transaction.atomic with unittest.mock.patch
@transaction.atomic
def deposit(user: User, account_number: str, amount: float) -> None:
account = get_object_or_404(
Account.objects.select_for_update(), account_number=account_number, ...
0
votes
1
answer
115
views
How to `assert_called_with` an object instance?
I want to do a unittest with pytest for this method:
class UserService:
@classmethod
async def get_user_by_login(cls, session: SessionDep, login: str) -> Optional[User]:
sql = ...
2
votes
2
answers
122
views
How to correctly patch an async function for unit tests in pytest
I am coding a FastAPI app with async functions. My issue is, I can't properly mock async function with the mocker.patch from pytest-mock nor with AsyncMock from unittest.
The issue is, I can't test ...
0
votes
1
answer
82
views
Difference between mock.patch.dict as function decorator and context manager in Python unittest
I have a configuration module, config with data config.data where I want to add a value for testing.
Ideally, I want to use mock.patch.dict as a context manager because the value is a class attribute ...
1
vote
1
answer
64
views
How can I apply side effects to a function of an instance that is created in a function that is tested?
I have a custom class in the file MyClass.py
class MyClass:
def __init__(self):
self.fetched_data = False
def get_data(self):
self.fetched_data = True
...
1
vote
1
answer
107
views
Unexpected failed assert when changing order of python mocks when mocking function that imports other mocked function
I am implementing a test for a function func1a() in module1.py using mocks.
The function func1a() calls:
one function from module2.py: func2a()
one function from module1.py: func1b()
It appears that ...
2
votes
1
answer
44
views
Test that unittest.Mock was called with some specified and some unspecified arguments [duplicate]
We can check if a unittest.mock.Mock has any call with some specified arguments.
I now want to test that some of the arguments are correct, while I do not know about the other ones.
Is there some ...
0
votes
1
answer
115
views
How can we mock an Object instantiation in python?
I have a scenario where I create a git.repo.base.Repo object in a "someFile.py":
def someFunction():
//some part of code
repo = Repo(path)
repo.head.reference = repo.commit(...
0
votes
0
answers
30
views
Using unittest.Mock in Odoo 17
In odoo 17 I need to use unitest.mock to mock the return value of a function
The function is called cfdi_cancel.
It is located in mymodulename module, inside that module is the 'models' folder, inside ...
0
votes
1
answer
70
views
Why did my mock test work with just a method instead of a full class?
I always thought that you could mock a method on a class only when the class it is coming from is not instantiated in the code under test. And if it is you have to mock the class (just as you have to ...
1
vote
1
answer
46
views
Can you use pytest.fixture and unittest.mock decorators together?
I am trying to call four decorators on my unit tests to easily allow code to be refactored: pytest.fixture, unittest.mock.patch, pytest.mark.parameterize, pytest.mark.asyncio.
I currently am calling ...
0
votes
1
answer
35
views
Working with python unit tests, tring to patch a class but is not working
I have code with below functionality
src/client.py
class Client1(object):
def foo(self, t):
return f"foo-{t}"
def get_foo(self, type):
return self.foo(type)
src/...
1
vote
1
answer
107
views
How to patch a 3rd party lib in a unit test with FastAPI client
I have an app/main.py for FastAPI which does:
import qdrant_client as QdrantClient
...
qdrant_client = QdrantClient(url=...)
qdrant_client.create_collection(...)
...
app = FastAPI()
...
@app.get(&...
0
votes
1
answer
135
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
70
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
235
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
36
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
70
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
195
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
91
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
58
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
111
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
80
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
3k
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
57
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 ...
3
votes
3
answers
3k
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
130
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
86
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
113
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
68
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
86
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
54
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
80
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
51
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
22
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
28
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
3
answers
64
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
1
answer
67
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
135
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
336
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
44
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
72
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
52
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
2
answers
50
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
52
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
610
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
81
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(...
1
vote
1
answer
107
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
63
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
41
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
...