mocking a function within a class method

2024/10/6 22:26:38

I want to mock a function which is called within a class method while testing the class method in a Django project. Consider the following structure:

app/utils.py

def func():...return resp  # outcome is a HTTPResponse object

app/models.py

from app.utils import funcclass MyModel(models.Model):# fieldsdef call_func(self):...func()...

app/tests/test_my_model.py

from django.test import TestCase
import mock    from app.models import MyModelclass MyModelTestCase(TestCase):fixtures = ['my_model_fixtures.json']def setUp(self):my_model = MyModel.objects.get(id=1)@mock.patch('app.utils.func')def fake_func(self):return mock.MagicMock(headers={'content-type': 'text/html'},status_code=2000, content="Fake 200 Response"))def test_my_model(self):my_model.call_func()...  # and asserting the parameters returned by func

When I run the test the mock function fake_func() is avoided and the real func() is called instead. I guess the scope in the mock.patch decorator might be wrong, but I couldn't find a way to make it work. What should I do?

Answer

There are three problems with your code:

1) As Daniel Roseman mentioned, you need to patch the module where the function is called, not where it is defined.

2) In addition, you need to decorate the test method that will actually be executing the code that calls the mocked function.

3) Finally, you also need to pass the mocked version in as a parameter to your test method, probably something like this:

fake_response = mock.MagicMock(headers={'content-type': 'text/html'},status_code=2000, content="Fake 200 Response"))class MyModelTestCase(TestCase):fixtures = ['my_model_fixtures.json']def setUp(self):my_model = MyModel.objects.get(id=1)@mock.patch('app.models.func', return_value=fake_response)def test_my_model(self, fake_response):  # the mock goes in as a param or else you get number of arguments error!my_model.call_func()self.assertTrue(fake_response.called)
https://en.xdnf.cn/q/70320.html

Related Q&A

After resizing an image with cv2, how to get the new bounding box coordinate

I have an image of size 720 x 1280, and I can resize it to 256 x 256 like thisimport cv2 img = cv2.imread(sample_img.jpg) img_small = cv2.resize(img, (256, 256), interpolation=cv2.INTER_CUBIC)Say I hav…

convert a tsv file to xls/xlsx using python

I want to convert a file in tsv format to xls/xlsx..I tried usingos.rename("sample.tsv","sample.xlsx")But the file getting converted is corrupted. Is there any other method of doing…

How do you edit cells in a sparse matrix using scipy?

Im trying to manipulate some data in a sparse matrix. Once Ive created one, how do I add / alter / update values in it? This seems very basic, but I cant find it in the documentation for the sparse ma…

AttributeError: DataFrame object has no attribute _data

Azure Databricks execution error while parallelizing on pandas dataframe. The code is able to create RDD but breaks at the time of performing .collect() setup: import pandas as pd # initialize list of …

Python: Problem with overloaded constructors

WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!I have written the following code, however I get the following exception: Message FileName Li…

Validate inlines before saving model

Lets say I have these two models:class Distribution(models.Model):name = models.CharField(max_length=32)class Component(models.Model):distribution = models.ForeignKey(Distribution)percentage = models.I…

Grouping and comparing groups using pandas

I have data that looks like:Identifier Category1 Category2 Category3 Category4 Category5 1000 foo bat 678 a.x ld 1000 foo bat 78 l.o …

Transform a 3-column dataframe into a matrix

I have a dataframe df, for example:A = [["John", "Sunday", 6], ["John", "Monday", 3], ["John", "Tuesday", 2], ["Mary", "Sunday…

python multiline regex

Im having an issue compiling the correct regular expression for a multiline match. Can someone point out what Im doing wrong. Im looping through a basic dhcpd.conf file with hundreds of entries such as…

OpenCV Python Bindings for GrabCut Algorithm

Ive been trying to use the OpenCV implementation of the grab cut method via the Python bindings. I have tried using the version in both cv and cv2 but I am having trouble finding out the correct param…