982 questions
0
votes
0
answers
36
views
Monkeypatching pandas series to_csv with pytest
I am testing a function, write_query(), in module.py. My test is in test_module.py, which is carried out using pytest. I am using the pytest monkeypatch fixture to monkeypatch Series.to_csv(), in ...
0
votes
1
answer
40
views
Overwrite a property in a used (but not imported) Class
I am using fitz/pymupdf and pdf2docx packages of python to read tables from pdf files so that I can get data out of them and model it appropriately for storage in a data lake.
It seems like Converter ...
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 ...
-1
votes
1
answer
31
views
With pytest, for multi-input function looping, how do i assert the answers that i expect based on the responses?
I have referenced theY4Kman's accepted answer here. https://stackoverflow.com/a/59998012/27327525
How do I give my assertions iteratively so I can test the inputs 1 after another.
This code isn't ...
0
votes
0
answers
16
views
MonkeyPatch on ConfigParser
I have a python script that uses ConfigParser to read the config file as below:
mymodule.py:
import configparser
def read_config():
config_ini = configparser.ConfigParser()
config_ini.read('...
0
votes
0
answers
40
views
How to clone or monkey patch a React Component so one method changes
Let's say we have
class OriginalComponent extends Component {
// various code..
someFunction = () => {
// does stuff
}
}
I want to get the functionality of OriginalComponent but with the ...
3
votes
1
answer
79
views
Do global augmentations need to be imported as a side effect in the consumer?
I have a package called core.error. In this package I have two files
global.d.ts
export {};
declare global {
export interface Error {
foo(): void;
}
}
index.ts
Error.prototype.foo = function ...
1
vote
2
answers
66
views
Monkeypatch Extract step in ETL data pipeline for functional testing
Consider an ETL pipelines repo build like that:
etl_repo
├── app
├── extract
├── extr_a.py
├── extr_b.py
├── transform
├── trans_a.py
├── ...
1
vote
0
answers
37
views
Pytest: Mocking requests.get to Raise RequestException for 400 Error
I’m writing tests for a currency converter application using pytest. I want to test the scenario where the API returns a 400 error. However, my test is failing because the expected requests.exceptions....
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 ...
0
votes
1
answer
44
views
Defining fixtures with variable import paths
I am testing functions from different modules that use an imported helper function from helpers.py. I am monkeypatching this helper function in each module function's test (please see below). I ...
1
vote
2
answers
67
views
Inverse :belongs_to for successful :has_many yields nil
I'm developing a plugin to Foreman (v3.5.1) to add support of CNAME records to the network interface model (Nic::Base): ForemanCnames (WIP). I'll first show you the associations that I want, where the ...
0
votes
1
answer
45
views
Locust Gevent friendly socket
I have the following client listed below to send request to my server using a custom protobuf message. How do I make this gevent friendly so I can make connection in parallel. Right now it seems the ...
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 ...
1
vote
1
answer
80
views
Ruby module is not an ancestor after prepend
I'm developing a plugin to the Rails (6.1.7) project Foreman (v3.5.1; based on the Foreman Plugin Template) and face the issue that one of my modules (DnsInterfaceExtensions) ought to be prepended to ...
0
votes
1
answer
65
views
monkeypatch logging basicConfig with pytest
I have a function that that involves setting up a logger:
app/src/app/pipelines.py:
import logging
def get_log_handlers(filepath):
return [logging.FileHandler(filepath,
...
1
vote
0
answers
25
views
Opposite results between `bool(x)` and `x.__bool__()` after patching
In this simple little test case, I monkey patch the __bool__ method of an instance, but am surprised to see that calling bool(x) and x.__bool__() give opposite results afterwards. What is the ...
0
votes
1
answer
72
views
MonkeyPatching python submodule
I want to monkey patch an external code base to check alternative versions of the same function.
At the moment, the project tree looks like this
.
├── mymodule
│ ├── __init__.py
│ └── myA.py
└── ...
0
votes
0
answers
71
views
typescript: transform property to function call
Here's a minimal example of some typescript code:
// codebase.ts
console.log(document.body.shadowRoot);
console.log(document.body.childNodes);
It is proposed that we add the following functions:
// ...
0
votes
1
answer
128
views
How to remove duplication of loguru logger patching in pytest
I am testing a function which calls loguru.logger.add("file.log") at the start. This causes issues during pytest execution. The file is written to a temp dir and thus is being used by ...
2
votes
1
answer
98
views
Monkey-patching internal classes in Python
I use the function lxml.etree.fromstring(str) that returns an instance of lxml.etree._Element. I want to add a few convenience functions to all lxml.etree._Element objects, but seem unable to do so.
...
0
votes
0
answers
95
views
How to monkey patch `__init__` in a third party module?
I'm trying to monkey patch the __init__ method of a third party module (smbprotocol).
Specifically, the SMBDirectoryIO#_init__ which inherits from SMBRawIO#__init__ (here)
I want to add "a" ...
1
vote
1
answer
92
views
Global fixture in pytest
Question
I want, with as little boilerplate possible, to mock one of my function.
Project Setup
In my (simplified) project, I have the following files/functions:
utils.py, with function get_id(param1,...
0
votes
1
answer
29
views
How to setup an instance method monkeypatch in this PyQt5 code?
Yes, I have seen:
monkey-patching python an instance method
How to call the original method when it is monkey-patched?
... but none of these approaches seem to work in my example:
Basically, this is ...
0
votes
0
answers
35
views
Run JavaScript code directly from a local file on any existing page?
You can open a browser's Dev-Tools on any page and write & run JavaScript-Code in the console.
However I now need to run ("inject" into an existing page) JavaScript code that is about ~5 ...
0
votes
1
answer
117
views
How to monkey-patch np.savez_compressed to add compression level, without editing numpy's source files?
I need to modify the ZIP compressionlevel internally used in np.savez_compressed. There is a feature proposal on Numpy Github, but it is not implemented yet.
I see two options:
modify the source file ...
0
votes
0
answers
39
views
Avoid delayed patching
I'm working on a Python project where I use diskcache.Cache.memoize for caching. I want to write unit tests for my code, and I'm having trouble figuring out how to properly mock diskcache.Cache....
0
votes
0
answers
257
views
How to patch datetime.datetime.now() using pytest and pass isinstance
I'm using pytest to perform testing in a Python project that uses the datetime.datetime class, datetime.datetime.now() function, and isinstance(time, datetime.datetime) check. Where time is a DateTime ...
0
votes
0
answers
61
views
How to patch intermediate layers of a python keras model with monkey patching?
I have a tf.keras model which internally contains a "custom tf.keras.layers.MultiHeadAttention() layer ". That is, I have divided the multihead attention layers into two parts:
(1) a first ...
1
vote
0
answers
36
views
Using patching to add an argument to a method
I am working on a project that makes GET and POST API calls. These are performed using the request.Session package. The API calls are made in many Classes.
I'm writing a test which will execute the ...
0
votes
0
answers
51
views
Handle Dynamic function call during pytest
When main.py is executed, the Python interpreter scans all files and executes any functions that were called at the beginning.
In source/settings.py, there's a function called get_settings(): which ...
0
votes
0
answers
113
views
how to mock a gRPC request in pytest using monkeypatch
I implemented a gRPC client in Python and I have functions that are connecting to a gRPC endpoint, retrieving the response and manipulating it such as:
def get_entities(self):
with grpc....
0
votes
0
answers
30
views
How do python resolve package names when Monkey Patching
I learn that python will make sure to input each package only once by appending the __name__ of each imported (either directly or indirectly ) package to sys.path only once.
I'm currently working ...
0
votes
1
answer
1k
views
Browser extension: monkey patching fetch responses from the actual webpage
I'm working on a browser extension, currently running script under content_scripts.
I'm trying to intercept the response from fetch request from the website my extension is running onto.
I found a lot ...
-1
votes
1
answer
70
views
Need help testing this function using pytest . I try to test is but with every test it keeps altering my csv file . how can i bypass some variables? [duplicate]
This is the function I'm trying to test:
def withdraw():
while 1:
try:
wd = float(input("How much $ would you like to withdraw? :"))
break
except ...
0
votes
0
answers
119
views
Using monkeypatch to set sys.argv when some required arguments can start with "-"
I'm trying to write tests for a piece of data analysis software, which takes some command-line arguments. One problem is that some of the cl arguments can start with a minus sign. For example, I have ...
2
votes
1
answer
102
views
How to mock imported module class in pytest
I have this files.
main.py
util.py
mocking_util.py
test_main.py
I'd like to use mocking_util.py instead of util.py in test code.
I know mocker.patch("util.my_something1", return_value = 1)
...
2
votes
2
answers
239
views
Why does unittest's `mock.patch.start` re-run the function in which the patcher is started?
Let's say we have two files:
to_patch.py
from unittest.mock import patch
def patch_a_function():
print("Patching!")
patcher = patch("to_be_patched.function")
patcher....
0
votes
2
answers
106
views
Python: monkey patch a function used by classes in the same module
I want to modify a function (not a method) in a module, such that the classes within the same module that use that function behave differently.
For the sake of simplicity assume I have a file called ...
0
votes
2
answers
3k
views
how to mock a function in pytest monkeypatch?
I am trying to mock a simple function but I get an AttributeError and have no clue on how to fix it.
def my_function():
return "original"
def mock_my_function():
return "mocked&...
0
votes
2
answers
218
views
How to override (monkeypatch) the document and element specific `querySelector` implementations and how to restore each original functionality again?
I have a local testing environment, where I want to temporary override querySelector. I know that monkeypatching is bad practice, but in this case this code will only be used locally on developer side....
0
votes
0
answers
248
views
Python: Using kwargs with patch() decorator
I can only use positional arguments with a function that uses @patch. Running being_patched(True) works. Running being_patched(arg=True) does not.
The general principle is positional args cannot come ...
1
vote
1
answer
145
views
How to use a refinement to change the output of { now: Time.now }.inspect to be customized?
After years of working with ruby, I finally came across a good need for ruby refinement!
# frozen_string_literal: true
module TimeMongoInspect
refine Time do
def inspect
strftime("...
2
votes
2
answers
73
views
How to modify a behavior of `pathlib.Path`?
I want pathlib.Path to automatically output logs for some destructive commands such as path.rename(new_path).
I made a subclass of pathlib.Path with logging functions, and replaced from pathlib import ...
1
vote
1
answer
427
views
Go Unittest for Telegram Bot
I'm trying to generate a unittest function in order to test the main function in my main.go file but it gets really complex when it comes to mock other functions called in main function function.:
...
0
votes
0
answers
50
views
Monkeypatching C stdin from Python
Is there any way of monkeypatching the C version of stdin in Python?
I’m attempting to write unit tests (pytest) for a Python module written in C. One of the functions in the library tries to read a ...
0
votes
1
answer
52
views
Why doesn't the `nonlocal` keyword propogate the outer-scoped variable to the calling module?
So this involves a maybe unusual chain of things:
A.py
from B import call
def make_call():
print("I'm making a call!")
call(phone_number="867-5309")
B.py
def call(...
1
vote
1
answer
1k
views
Getting Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation when monkey patching fetch
I'm trying to monkey patch window.fetch inside a class to be able to fetch request and response body.
I currently have the following implementation:
export class NetworkService implements Listener {
...
4
votes
0
answers
405
views
eventlet.monkey_patch cause: maximum recursion depth exceeded in ssl.py
In a python 3.10.9 docker container, the app depends on a critical package what uses eventlet.monkey_patch(socket=True). Unfortunatelly this cause RecursionError: maximum recursion depth exceeded when ...
0
votes
2
answers
785
views
How to write Golang tests for functions where complexity is abstracted away
I'm trying to figure out how to write tests for a simple function that calls a function. Now I'm aware that this has been asked before, but none of the answers I've seen so far have shown how one ...