All Questions
3,128 questions
0
votes
1
answer
43
views
How to mock properly recv method in python and use settimeout
I'm trying to use and test sockets in python (I have to use 3.5 version).
Consider this code:
import socket
def send_recv(xml_message):
try:
address = ('127.0.0.1', 12000)
...
0
votes
0
answers
25
views
Mocking a class with arguments, but getting NameError: name 'my_position' is not defined
I am trying to mock out a class that is being called/initialised in a function.
def example_function():
example_class = SomeClass(my_position, num_list, suit_list)
@mock.patch('.../SomeClass')
...
0
votes
2
answers
46
views
Why is python mock assert_any_call not matching
Given the doc for assert_any_call
I have a log statement I want to assert against
...
logger.warning('Backup quantity is 0, supplied uuids %s, matched machines: %s', uuids, machines)
...
see the ...
0
votes
1
answer
39
views
Asserting that a function that is mocked is called_once but running into ValueError: not enough values to unpack (expected 2, got 0)
I am trying to unit test that a function is called within another function.
def run_this_function(something):
'FOLD', {}
def go_to_the_right_street(action):
if street_we_are_on == '...
1
vote
0
answers
55
views
How to mock an Enum in pytest globally
I have a trading bot project, let's call it trading_bot. I am using python-binance. I have an enum
class CoinName(str, Enum):
USDT = "USDT"
BTC = "BTC"
ETH = "ETH&...
0
votes
0
answers
14
views
Unittest asyncio patch object mock with nested coros
I want to mock the client of an async database client in unittest.
The functioncall of the client is like:
test.client.json().set(argumentsforquery)
The test looks like this:
@pytest.mark.asyncio
...
0
votes
0
answers
20
views
How to check the result of a mocked function without relying on calling convention [duplicate]
In Python,
can check the parameters of a mocked function using parameter names in a test without relying on the way the function was called (either with args or with kwargs)?
Concrete example
I'd like ...
0
votes
1
answer
35
views
Problems testing with pytest with mock in a subclass
I'm having problems trying to mock a class called into another class.
I have three modules:
tree.py
from branch import Branch
class Tree:
type_of_tree = None
branches = None
def ...
1
vote
0
answers
52
views
Mocking boto3 client response
I am trying to build unit tests for my calls to dynamodb. I need to specify exactly what the client instance will respond with - to replicate a failure response from AWS. I can force failure responses ...
0
votes
1
answer
34
views
Patching server-side function in python-socket.io and testing client-side call
I'm trying to test a socket.io call.
I have a socket.io server mounted as app into FastAPI, which is up and running and communication is working.
Whenever I call foo(), that calls bar() directly in ...
0
votes
0
answers
21
views
Mock patching a callable upload_to in a Django ImageField
In Django I have a model and a test similar to the following, both in a photos module (Django app).
models.py
def get_user_photo_path(instance, filename):
return str(uuid.uuid4())
class UserPhoto(...
5
votes
2
answers
126
views
Give side effect to only first call of Pytest patched function
I have a function that renders HTML templates. In case exception is thrown during rendering of a given template, a default template will be rendered (simplified version of the function below):
def ...
0
votes
2
answers
144
views
Is my integration test well structured and why is it returning import error
I am learning mock and trying it on a personal project.
This is my project structure:
project/
│
├── src/
│ └── My_app/
│ ├── __init__.py
│ ├── application/
│ │ └── main_code.py
│...
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
85
views
Unable to replace python function definition with mock and unitest
I am trying to write integration test for the following python code:
import xx.settings.config as stg
from xx.infrastructure.utils import csvReader, dataframeWriter
from pyspark.sql import ...
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
vote
1
answer
48
views
How can I dynamically swap out Python’s built-in functions in an imported module for testing purposes, without altering the source code?
I am working on testing a legacy Python module that relies heavily on built-in functions like print(), len(), and others, but I don’t want to modify the module's source code directly. The goal is to ...
0
votes
0
answers
23
views
mock paramiko.SSHClient.exec_command() with side_effects [duplicate]
I need mock execution of some remote command via ssh.exec_command() It returns tuple (stdin, stdout, stderr) as paramiko.ChanelFile object.
I know I can use mock.MagicMock() and that is what I have ...
0
votes
1
answer
47
views
Mocking a class in Python, works in namespace package, but doesn't for regular package
Context
I'm writing unit tests for my application.
I have a module in configuration/connections.py with configuration (usually defined by environment variables):
from typing import Literal
from ...
1
vote
1
answer
86
views
Mocking pytest test with @patch unittest.mock decorator
Issue with Mocking send_request() in Unit Tests
I'm having trouble with mocking the send_request() function in my tests. Despite using patch, the original send_request() function is being called, and ...
0
votes
1
answer
162
views
How to unit-test / mock code with beanie queries
So my concrete problem is that I am trying to create a unit test for something like this:
from mongo_models import Record
async def do_something(record_id: str):
record = await Record.find_one(...
0
votes
1
answer
64
views
How to patch a function with pytest-mock regardless of path/namespace used to call it?
I am trying to mock a function regardless of how it is imported in the code.
I can't find info on how to do it.
Here is an example, the first assert works as expected but the second fails because path:...
1
vote
1
answer
53
views
Can't mock a AWS S3 Client
I am trying to mock a call to the get_paginator function on the Python AWS S3 Client. Here my production code:
handler.py
import boto3
class RealClass:
def __init__(self):
self.s3_client =...
0
votes
1
answer
41
views
unable to mock out functions for testing
I'm somewhat new to mocking for unit tests.
I have some code like this:
In foo/bar/baz.py I have 2 functions I want to mock, one calls the other:
def function1_to_mock():
.
.
.
def ...
0
votes
1
answer
49
views
Mock instantiated class in class attribute
I'm working on a project that uses a class called Deck to fetch data from an API. This class is instantiated inside another class called Game Manager through its __init__ (it's a blackjack game btw) ...
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(...
0
votes
0
answers
144
views
FastAPI Integration Testing with Keycloak User Authentication
I'm desperately trying to write integration tests for my fastapi project for the last 5 days. For security reasons my endpoints are secured via keycloak (python-keycloak module). An example:
# ...
1
vote
0
answers
25
views
mocking a function in a process started with multiprocessing.Process
Is it possible to mock out a function in a process started with multiprocessing.Process? AI tells me it is, but I have not gotten it to work.
The use case is that I have a server I want to write tests ...
0
votes
1
answer
36
views
python mock library - Replacing original side_effect with an exception fails unexpectedly
I want to use a mock.patch decorator over a class with many test with a default side_effect, and then in some specific tests replace that side_effect with some other behavior. When I try to replace ...
0
votes
1
answer
46
views
Is there any way to disguise a mock object as an acceptable PyQt object in Qt method parameters?
This is an MRE. You need to have pytest installed... and in fact pytest-qt won't do any harm.
import sys, pytest
from PyQt5 import QtWidgets
from unittest import mock
class MyLineEdit(QtWidgets....
0
votes
0
answers
27
views
Mocking Modules with Pdoc3
NOTE: Based on the things I have found, I am tempted to assume that this issue continues to be unresolved, but I'll try to ask here anyway just in case.
I work using a program that supports Python ...
0
votes
0
answers
42
views
How to capture call inside a with block?
I have some code with a testcase for it. It works fine.
import pysftp
from unittest import mock
remote_file_name = 'remote_file_name'
local_path = 'local/path/to/file'
def open_sftp_connection(...
0
votes
1
answer
49
views
Mocking or monkey patching a slow loading resource that loads on import
I have 1 file which loads a particular resource ( from a file ) that takes a while to load.
I have a function in another file which uses that resource by importing it first. When that resource is ...
0
votes
0
answers
35
views
Pytest patch not returning expected value
I am using Pytest to mock a function whose return value is defined in another function.
This is my original function which reads all the files from Azure Data Lake that I would like to mock
class ...
0
votes
0
answers
29
views
Mocking throws iterable issue but not suggesting to resolve
This is the main python class and its methods
class ParserManner():
def __init__(self, **kwargs):
self.file_path = kwargs.get(‘file_path’, None)
self.soup = kwargs.get(‘soup’, None)...
1
vote
0
answers
28
views
mocking out imported objects in Python
Lets say there is a module headache that defines an object that is then imported and used by code I want to test:
# defined in headache/__init__.py
problem = Problem()
then it's imported by Foo:
# ...
0
votes
0
answers
52
views
How to avoid import issues when Sphinx docs are generated from a different directory to parent app
I want to autogenerate documentation for a python project. I managed to get a barebones pipeline working with sphinx, but the output is not very pretty and I would appreciate some guidance on how to ...
2
votes
1
answer
64
views
python mock patch call_args_list type
Looking into patch call_args_list feature, I have found something strange.
The execution of the code below, returns different types for the list call_args_list.kwargs with Python3.7 and python3.11 ...
0
votes
1
answer
75
views
Mocking a http.get function isnt working in pytest
The test file contains the test file is in status_update_job/tests and sync_mdl_status.py is in status_update/lib/ folders
from lib.sync_mdl_status import update_mdl_status
class ...
0
votes
0
answers
183
views
Using AWS Moto with Python mock to write unit tests
I am working with a codebase that doesn't have any tests setup. I am trying to add some tests and currently have the below test class test_main.py
from unittest import TestCase
from moto import ...
1
vote
1
answer
69
views
Mocking a function in pytest with Patch doesnt work
I have written the test file status_update/tests/test_status_update.py which has the following content:
from lib.sync_mdl_status import update_mdl_status
@patch('scripts.aws_secrets....
1
vote
1
answer
26
views
Cannot mock the method in dependency module correctly in Python
Here is my project structure
|-- project
|-- util.py
|-- main.py
|-- tests
|-- test_main.py
In the main.py file I reference the function in util.py
from util import rename
def ...
0
votes
0
answers
48
views
Mocking Airflow ImapHook class
I wrote an Airflow Dag that uses the ImapHook to log into an email account and retrieve some mails. I'm trying to write unit tests for this dag, but I'm having issues on mocking the ImapHook class.
...
0
votes
0
answers
34
views
pytest: Mocked value is not returned
My code is the following:
def get_inspection_details(insp_id: int) -> dict:
db = get_session()
inspection_details = (
db.query(
# some fields here
)
....
0
votes
0
answers
44
views
Why python testing always import the file in another module implicitly
Current I have two files in the same folder, in the source file I import the dlt module
# File: pipeline.py
import dlt
Another is a test file which import nothing from the source file yet:
import ...
0
votes
0
answers
109
views
How to mock a function which is not part of a class in Pytest?
I have a dependency in my target code called target/dep.py which should return "PATCHED" when I mock in the Pytest function. But after research, I can't seem to find how to patch a stand ...
0
votes
1
answer
44
views
How to ensure subprocess sees mock patched variable?
I have unit tests that look like the following:
with patch('my_module.file_in_module.SOME_GLOBAL_VARIABLE', new=mocked_var):
subprocess.check_call([
# CLI omitted
])
If I print ...
0
votes
0
answers
96
views
Trouble mocking SFTP client for unit testing in Python
I'm trying to write unit tests for a FastAPI application that interacts with an SFTP server. Specifically, I'm having trouble mocking the SFTP client object to test the get_folder_structure function. ...
-1
votes
2
answers
66
views
Can't send json reponse in requests mock
I'm looking for a way to test a function called fetch_options that basically renders a returned JSONResponse from an internal API. My approach to this test is to mock requests because the internal API ...
1
vote
1
answer
137
views
How to mock file presence in the file server to test FastAPI Static Files?
I am using FastAPI Static Files class to download files from the server. Everything works fine and I can easily download files using URL.
Now, I need to write a test case for file download and I do ...