Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Django Commands with Mock

I have a command that I would like to test. It hits external services and I would like to mock out the function calls that hit these external services, only check that they were called with the proper 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 however I keep getting AssertionError: Expected to be called once. Called 0 times. I assume this is because I am not actually calling the module within the context, I am calling it in call_command('djangocommand', my_option=True), but shouldn't all calls to this module be mocked out while the context is active? If not, does anyone have suggestions for how such a test could be conducted?

like image 315
djds23 Avatar asked Sep 30 '22 20:09

djds23


1 Answers

The reference you need to patch is the 'module' attribute reference in django.core.management. Attempting to mock the package reference in the test file doesn't change the reference in django.core.management.

You'll 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)
like image 185
Silfheed Avatar answered Oct 03 '22 01:10

Silfheed