Python Patch/Mock class method but still call original method

2024/11/18 23:27:05

I want to use patch to record all function calls made to a function in a class for a unittest, but need the original function to still run as expected. I created a dummy code example below:

from mock import patchclass A(object):def __init__(self):self._a = 1class B(A):def __init__(self):super(B, self).__init__() # TypeError: super() argument 1 must be type, not MagicMockself._b = 11def bar(self, b):self._b = self._b + 1 + bdef foo(self, b):self.bar(b)class MockB(B):def foo(self, b):super(MockB, self).foo(self, b)@patch('main.B')
def main(b_class):b_class.side_effect = MockBb = B()print b._b # 11b.foo(0)print b._b # 12main()

In my case, the instance of the class b = B() is not actually in the main function but in another module, so I can't Mock the instance. I need it to generically be a decorator for all instances of B.

Summary: I am not sure how to individually mock the class method on it's own, but still call the original method. After, I want to use something like call_args_list where I can see all calls made to foo().

Answer

I think you are looking for the wraps Mock parameter. Search the official documentation for wraps. Accessing attributes returns a mock object. Calling methods gives the real method result instead, if a return value is not configured for the mock.

https://en.xdnf.cn/q/26504.html

Related Q&A

Daemon vs Upstart for python script

I have written a module in Python and want it to run continuously once started and need to stop it when I need to update other modules. I will likely be using monit to restart it, if module has crashed…

Comparison of Python modes for Emacs

So I have Emacs 24.3 and with it comes a quite recent python.el file providing a Python mode for editing.But I keep reading that there is a python-mode.el on Launchpad, and comparing the two files it j…

Python best formatting practice for lists, dictionary, etc

I have been looking over the Python documentation for code formatting best practice for large lists and dictionaries, for example,something = {foo : bar, foo2 : bar2, foo3 : bar3..... 200 chars wide, e…

TypeError: string indices must be integers, not str // working with dict [duplicate]

This question already has answers here:Why am I seeing "TypeError: string indices must be integers"?(10 answers)Closed 28 days ago.I am trying to define a procedure, involved(courses, person…

Pandas: create dataframe from list of namedtuple

Im new to pandas, therefore perhaps Im asking a very stupid question. Normally initialization of data frame in pandas would be column-wise, where I put in dict with key of column names and values of li…

Closest equivalent of a factor variable in Python Pandas

What is the closest equivalent to an R Factor variable in Python pandas?

Temporarily Disabling Django Caching

How do you disable Django caching on a per checkout basis?Back before Django 1.3, I could disable caching for my local development checkout by specifying CACHE_BACKEND = None, in a settings_local.py i…

How to get a complete exception stack trace in Python

The following snippet:import tracebackdef a():b()def b():try:c()except:traceback.print_exc()def c():assert Falsea()Produces this output:Traceback (most recent call last):File "test.py", line …

python - should I use static methods or top-level functions

I come from a Java background and Im new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated …

Draw graph in NetworkX

Im trying to draw any graph in NetworkX, but get nothing, not even errors:import networkx as nx import matplotlib.pyplot as plt g1=nx.petersen_graph() nx.draw(g1)