如何直接从测试驱动程序调用自定义Django manage.py命令? [英] How can I call a custom Django manage.py command directly from a test driver?

查看:182
本文介绍了如何直接从测试驱动程序调用自定义Django manage.py命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为Django manage.py命令编写一个单元测试,该命令对数据库表执行后端操作。我如何直接从代码调用管理命令?

I want to write a unit test for a Django manage.py command that does a backend operation on a database table. How would I invoke the management command directly from code?

我不想在tests.py上执行操作系统shell的命令,因为我无法使用使用manage.py test设置的测试环境测试数据库,测试虚拟电子邮件发件箱等)

I don't want to execute the command on the Operating System's shell from tests.py because I can't use the test environment set up using manage.py test (test database, test dummy email outbox, etc...)

推荐答案

测试这样的东西的最好方法 - 从命令本身独立的功能或类。它有助于从命令执行的东西中抽象出来,并在没有附加要求的情况下编写测试。

The best way to test such things - extract needed functionality from command itself to standalone function or class. It helps to abstract from "command execution stuff" and write test without additional requirements.

但是,如果由于某种原因无法解除逻辑格式命令,您可以从任何代码像这样:

But if you by some reason cannot decouple logic form command you can call it from any code like this:

from django.core.management import call_command

call_command('my_command', 'foo', bar='baz')

这篇关于如何直接从测试驱动程序调用自定义Django manage.py命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆