Skip to main content

All Questions

Tagged with
Filter by
Sorted by
Tagged with
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) ...
smark's user avatar
  • 17
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') ...
killerbee88's user avatar
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 ...
James Lin's user avatar
  • 26.4k
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 == '...
killerbee88's user avatar
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&...
nontrivial's user avatar
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 ...
nico's user avatar
  • 67
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 ...
DarkTrick's user avatar
  • 3,351
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 ...
Rubén Pozo's user avatar
  • 1,083
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 ...
Kottok Motors's user avatar
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 ...
aknott's user avatar
  • 220
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(...
Goluxas's user avatar
  • 177
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 ...
matetam's user avatar
  • 135
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 │...
Haha's user avatar
  • 1,007
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) -> ...
Manu's user avatar
  • 70
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 ...
Haha's user avatar
  • 1,007
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 ...
Disciple153's user avatar
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 ...
uskudu's user avatar
  • 11
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 ...
rashi's user avatar
  • 3
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 ...
Marco Bresson's user avatar
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 ...
user3565923's user avatar
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(...
Nordico's user avatar
  • 1,307
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:...
Hugo Zaragoza's user avatar
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 =...
NeoFahrenheit's user avatar
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 ...
Norman Robins's user avatar
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) ...
wavesinaroom's user avatar
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(...
sezanzeb's user avatar
  • 1,124
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: # ...
Georg Manthei's user avatar
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 ...
Norman Robins's user avatar
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 ...
Nahuel Aguilar's user avatar
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....
mike rodent's user avatar
  • 15.5k
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 ...
TheParable's user avatar
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(...
Kashyap's user avatar
  • 17k
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 ...
Sam's user avatar
  • 309
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 ...
Vishnukk's user avatar
  • 564
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)...
Tes's user avatar
  • 167
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: # ...
solyd's user avatar
  • 792
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 ...
KBriggs's user avatar
  • 1,402
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 ...
eddie's user avatar
  • 190
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 ...
Sagar Ghanwat's user avatar
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 ...
Justin S's user avatar
  • 1,459
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....
Sagar Ghanwat's user avatar
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 ...
hh54188's user avatar
  • 15.6k
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. ...
Lays Rodrigues's user avatar
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 ) ....
Niko's user avatar
  • 790
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 ...
hh54188's user avatar
  • 15.6k
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 ...
engineer-x's user avatar
  • 3,111
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 ...
roulette01's user avatar
  • 2,432
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. ...
daniel guo's user avatar
-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 ...
wavesinaroom's user avatar
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 ...
Aidos Kenessov's user avatar

1
2 3 4 5
63