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

查看:24
本文介绍了如何直接从测试驱动程序调用自定义 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.

但是如果您由于某种原因无法解耦逻辑表单命令,您可以使用 call_command 方法如下:

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

from django.core.management import call_command

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

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

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