我有一个Django管理命令,它将要求命令行输入(y/n),我现在正在为此编写一个测试。
目前,当我运行测试时(就像现在一样),测试将停止并等待y/n输入。但是我如何编写/更新我的测试,以便我可以向call_command函数发送y/n响应?
作为参考,我的管理命令代码是(已删除导入-但完整代码位于: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)
我的测试代码是:
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)
任何帮助非常感谢,如果你需要任何额外的信息/代码,只是让我知道,谢谢。
编辑我尝试了@xyres的建议来添加'interactive=False',但我得到了一个类型错误:
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
然后,我也尝试使用'skip_checks=True',但这仍然使测试挂起等待命令行输入
2条答案
按热度按时间k2arahey1#
我喜欢使用
mock.patch
来处理这类事情。接下来是
TestCase
。我喜欢使用调用 Package 器来整合打补丁的逻辑,并允许测试不同的选项等。ergxz8rk2#
我觉得上面的答案给出了一个太DRY的例子。我喜欢将设置阶段与运行代码分开。您不需要创建单独的 Package 器或使用
side_effect
。毕竟,input
只是一个函数。我的看法是这样的指挥
你可以写