I have a Django management command that will ask for command line input (y/n) and I'm now writing a test for this.
Currently when I run the test (as is now), the test will stop and wait for the y/n input. But how can I write/update my test so that I can send a y/n response to the call_command function?
For info, my management command code is (imports removed - but full code at: https://github.com/DigitalCampus/django-oppia/blob/master/oppia/management/commands/remove_duplicate_trackers.py):
class Command(BaseCommand):
help = _(u"Removes any duplicate trackers based on UUID")
def handle(self, *args, **options):
"""
Remove page/media/quiz trackers with no UUID
"""
result = Tracker.objects.filter(Q(type='page')
| Q(type='quiz')
| Q(type='media'),
uuid=None).delete()
print(_(u"\n\n%d trackers removed that had no UUID\n" % result[0]))
"""
Remove proper duplicate trackers - using min id
"""
trackers = Tracker.objects.filter(Q(type='page')
| Q(type='quiz')
| Q(type='media')) \
.values('uuid') \
.annotate(dcount=Count('uuid')) \
.filter(dcount__gte=2)
for index, tracker in enumerate(trackers):
print("%d/%d" % (index, trackers.count()))
exclude = Tracker.objects.filter(uuid=tracker['uuid']) \
.aggregate(min_id=Min('id'))
deleted = Tracker.objects.filter(uuid=tracker['uuid']) \
.exclude(id=exclude['min_id']).delete()
print(_(u"%d duplicate tracker(s) removed for UUID %s based on \
min id" % (deleted[0], tracker['uuid'])))
"""
Remember to run summary cron from start
"""
if result[0] + trackers.count() > 0:
print(_(u"Since duplicates have been found and removed, you \
should now run `update_summaries` to ensure the \
dashboard graphs are accurate."))
accept = input(_(u"Would you like to run `update_summaries` \
now? [Yes/No]"))
if accept == 'y':
call_command('update_summaries', fromstart=True)
and my test code is:
def test_remove_with_duplicates(self):
Tracker.objects.create(
user_id=1,
course_id = 1,
type = "page",
completed = True,
time_taken = 280,
activity_title = "{\"en\": \"Calculating the uptake of antenatal care services\"}",
section_title = "{\"en\": \"Planning Antenatal Care\"}",
uuid = "835713f3-b85e-4960-9cdf-128f04014178")
out = StringIO()
tracker_count_start = Tracker.objects.all().count()
call_command('remove_duplicate_trackers', stdout=out)
tracker_count_end = Tracker.objects.all().count()
self.assertEqual(tracker_count_start-1, tracker_count_end)
Any help much appreciated, and if you need any extra info/code, just let me know, thanks.
Edit I tried the suggestion from @xyres to add 'interactive=False' but I got a type error with this:
TypeError: Unknown option(s) for remove_duplicate_trackers command: interactive. Valid options are: force_color, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version
I then also tried with 'skip_checks=True' but this still made the test hang awaiting on command line input
I like to use mock.patch
for this sort of thing. Here's a pared-down example loosely based on your command. First, the management command which just prompts for and accepts a single line of input
from django.core.management import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
accept = input("Would you like to run `update_summaries` now? [Yes/No]")
if accept == 'y':
self.stdout.write("Updating Summaries!")
return
self.stdout.write("Not updating Summaries...")
Next, here is the TestCase
. I like to use a call wrapper to consolidate the logic for patching and allow testing different options etc.
from io import StringIO
from unittest import mock
from django.core.management import call_command
from django.test import TestCase
class UpdateTestCase(TestCase):
@mock.patch("my_app.management.commands.update.input")
def _call_wrapper(self, response_value, mock_input=None):
def input_response(message):
return response_value
mock_input.side_effect = input_response
out = StringIO()
call_command('update', stdout=out)
return out.getvalue().rstrip()
def test_yes(self):
"""Test update command with "y" response
"""
self.assertEqual("Updating Summaries!", self._call_wrapper('y'))
def test_no(self):
"""Test update command with "n" response
"""
self.assertEqual("Not updating Summaries...", self._call_wrapper('n'))
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