Python monkey patch private function

2024/10/11 22:25:42

I have a module with a function (call it a()) that calls another function defined in the same module (call it __b()). __b() is a function which speaks to a website via urllib2 and gets some data back. Now I'm trying to test a(), but of course would rather not have my unit tests speak to the public internet. Thus, I'm thinking if I can monkey patch __b() with a function which returns canned data, then I can write the tests for a().

To be more concrete, my module looks kinda like:

def a():return __b("someval")def __b(args):return something_complex_with_args

So now I want to test a(), but I need to monkey patch out __b. The problem is that A) the vast majority of information on monkey patching applies to methods of a class, not to functions in a module, and B) the function I want to monkey patch is private. I am willing to change __b to be non-private if it makes the process more feasible, but would rather not.

Suggestions?

Edit: as it stands the test class looks like:

from unittest import TestCaseimport mymoduledef newfn(args):return {"a" : "b"}mymodule._b = newfnclass TestMyModule(TestCase):def test_basic(self):print(mymodule.a('somearg'))

And when I run this, I see the output if the monkey patching had not been done at all, rather than seeing {'a': 'b'} get printed out.

Answer

I can't seem to reproduce your issue (I've tweaked your example a bit, since it doesn't run at all as-is). Did you just mistype something (like mymodule._b instead of mymodule.__b)?

mymodule.py:

def a(x):return __b("someval")def __b(args):return "complex_thingy: {}".format(args)

mytest.py:

from unittest import TestCaseimport mymoduledef newfn(args):return {"a" : "b"}mymodule.__b = newfnclass TestMyModule(TestCase):def test_basic(self):print(mymodule.a('somearg'))

Output:

C:\TEMP>python -m unittest mytest
{'a': 'b'}
.
----------------------------------------------------------------------
Ran 1 test in 0.001sOKC:\TEMP>

Seems to work fine.


Or outside of unittest:

mytest2.py:

import mymoduledef newfn(args):return {"a" : "b"}mymodule.__b = newfnprint(mymodule.a('somearg'))

Output:

C:\TEMP>python mytest2.py
{'a': 'b'}C:\TEMP>
https://en.xdnf.cn/q/69723.html

Related Q&A

How to interleave numpy.ndarrays?

I am currently looking for method in which i can interleave 2 numpy.ndarray. such that>>> a = np.random.rand(5,5) >>> print a [[ 0.83367208 0.29507876 0.41849799 0.58342521 0.818…

Object is not subscripable networkx

import itertools import copy import networkx as nx import pandas as pd import matplotlib.pyplot as plt #-- edgelist = pd.read_csv(https://gist.githubusercontent.com/brooksandrew /e570c38bcc72a8d1024…

WTForms : How to add autofocus attribute to a StringField

I am rather new to WTForms, Flask-WTF. I cant figure out how to simply add the HTML5 attribute "autofocus" to one of the form field, from the form definition. I would like to do that in the P…

Image rotation in Pillow

I have an image and I want to transpose it by 30 degrees. Is it possible to do by using something like the following?spinPicture003 = Picture003.transpose(Image.Rotate_30)

Python code to calculate angle between three points (lat long coordinates)

Can anybody suggest how to calculate angle between three points (lat long coordinates)A : (12.92473, 77.6183) B : (12.92512, 77.61923) C : (12.92541, 77.61985)

z3: solve the Eight Queens puzzle

Im using Z3 to solve the Eight Queens puzzle. I know that each queen can be represented by a single integer in this problem. But, when I represent a queen by two integers as following:from z3 import *X…

Image skewness kurtosis in python

Is there a python package that will provide me a way to clacluate Skewness and Kurtosis of an image?. Any example will be great.Thanks a lot.

Python: Getting all the items out of a `threading.local`

I have a threading.local object. When debugging, I want to get all the objects it contains for all threads, while I am only on one of those threads. How can I do that?

Why tuple is not mutable in Python? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:Why are python strings and tuples are made immutable? What lower-level design makes tuple not mutable in Python? Why th…

Display Django form fields on the same line

I would like to display two form fields on the same line and not each one after the other one.For the moment, I get:Choice a theme :. Datasystems. CamerounBut I would like to display this form like:Cho…