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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With