Mocking Django Model and save ()

I have the following script:

in my models.py

class FooBar(models.Model): description = models.CharField(max_length=20) 

in my utils.py file.

 from models import FooBar def save_foobar(value): '''acts like a helper method that does a bunch of stuff, but creates a FooBar object and saves it''' f = FooBar(description=value) f.save() 

in tests.py

 from utils import save_foobar @patch('utils.FooBar') def test_save_foobar(self, mock_foobar_class): save_mock = Mock(return_value=None) mock_foobar_class.save = save_mock save_foobar('some value') #make sure class was created self.assertEqual(mock_foobar_class.call_count, 1) #this passes!!! #now make sure save was called once self.assertEqual(save_mock.call_count, 1) #this fails with 0 != 1 !!! 

This is a simplified version of what I'm trying to do ... so please don't get stuck on why I have a utils file and a helper function for this (in real life, it does a few things). Also, note that while this is simplified, this is an actual working example of my problem. The first call to check call_count returns 1 and passes. However, the second returns 0. Thus, it seems to me that my patch is working and receiving a call.

How can I verify that not only an instance of FooBar is being created, but also that the save method on it is called?

+6
source share
1 answer

Here is your problem: you have:

 mock_foobar_class.save = save_mock 

since mock_foobar_class is a cool class object, and the save method is called on an instance of this class (not the class itself), you need to claim that save is called on the return value of the class (as an instance).

Try the following:

 mock_foobar_class.return_value.save = save_mock 

I hope this helps!

+7
source

Source: https://habr.com/ru/post/915466/


All Articles