Testing Django Commands with Mock

I have a team that I would like to test. It hits external services, and I would like to mock the function calls that fall into those external services, but only check that they are called with appropriate arguments. The code looks like this:

import mock
from django.core.management import call_command
from myapp.models import User

class TestCommands(TestCase):

    def test_mytest(self):
        import package

        users = User.objects.filter(can_user_service=True)

        with mock.patch.object(package, 'module'):
            call_command('djangocommand', my_option=True)
            package.module.assert_called_once_with(users)

      

When I run it, I still get AssertionError: Expected to be called once. Called 0 times.

I am assuming that this is because I am not actually calling the module in the context, I am calling it in call_command('djangocommand', my_option=True)

, but not all calls to this module will be mocked if the context is active? If not, does anyone have any suggestions on how such a test could be done?

+3


source to share


1 answer


The link to fix is ​​the link to the 'module' attribute in django.core.management. Trying to mock a package reference in a test file does not change the reference in django.core.management.

You need to do something like



import mock
from django.core.management import call_command
import django.core.management
from myapp.models import User

class TestCommands(TestCase):

    def test_mytest(self):

        users = User.objects.filter(can_user_service=True)

        with mock.patch.object(django.core.management, 'module'):
            call_command('djangocommand', my_option=True)
            django.core.management.module.assert_called_once_with(users)

      

+3


source







All Articles