Mocking test in Django not working when running al

2019-02-19 02:03发布

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-19 02:50

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

Check this link. It helped me.

查看更多
登录 后发表回答