Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking test in Django not working when running all in TestCase but works well one by one

I'm using python mock for patching some functions and classes when testing views in Django.

If I run each test independently, all test works. But when I run the TestCase, some test dont work (the patch has not effect).

class ViewsTest(TestCase):
    @mock.patch('extras.utils.get_user_category')
    def test_select_test(self, mock_method):        
        mock_method.return_value = Category(id=1, name="Foo")

        response = self.client.post(reverse('select_test', args=['Foo']))

        self.assertEqual(200, self.client.post(reverse('select')).status_code)

    @mock.patch('user_profile.models.Profile.categories')
    def test_category_view(self, mock_related):      
        mock_related.all.return_value = []

        self.assertEqual(200, self.client.post(reverse('category')).status_code)

I have a print int the views to see each mocked method, when it works it prints:

MagicMock name='get_user_category' id='162815756'

And when doesn't works I see:

function get_user_category at 0x8e0fb8c

I tried the patcher start() and stop() but I still have problems.

¿What is the problem?

like image 714
OscarV Avatar asked Nov 28 '13 16:11

OscarV


People also ask

How do I run a test case in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

What is MagicMock Pytest?

The workhorse: MagicMock The basic idea is that MagicMock a placeholder object with placeholder attributes that can be passed into any function. I can. mock a constant, mock an object with attributes, or mock a function, because a function is an object in Python and the attribute in this case is its return value.

What is RequestFactory in Django?

The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.

What order Django tests are run?

Order in which tests are executedAll TestCase subclasses are run first. Then, all other Django-based tests (test cases based on SimpleTestCase , including TransactionTestCase ) are run with no particular ordering guaranteed nor enforced among them. Then any other unittest.


1 Answers

I had the same problem. You're probably pointing the wrong way.

Check this link. It helped me.

like image 127
LAPA Avatar answered Oct 15 '22 07:10

LAPA