但是,我不知道如何在标准 django 测试中测试它
问问题
22037 次
6 回答
117
如果您正在使用一些覆盖工具,最好从代码中调用它:
from django.core.management import call_command
from django.test import TestCase
class CommandsTestCase(TestCase):
def test_mycommand(self):
" Test my custom command."
args = []
opts = {}
call_command('mycommand', *args, **opts)
# Some Asserts.
可以使用 call_command() 函数测试管理命令。输出可以重定向到 StringIO 实例
于 2011-06-28T21:37:37.337 回答
22
您应该使您的实际命令脚本尽可能少,以便它只在其他地方调用一个函数。然后可以像往常一样通过单元测试或文档测试来测试该功能。
于 2009-08-17T14:37:52.733 回答
16
您可以在 github.com 示例中 看到,请参见此处
def test_command_style(self):
out = StringIO()
management.call_command('dance', style='Jive', stdout=out)
self.assertEquals(out.getvalue(),
"I don't feel like dancing Jive.")
于 2015-01-22T06:48:04.860 回答
2
添加到这里已经发布的内容。如果您的 django-admin 命令将文件作为参数传递,您可以执行以下操作:
from django.test import TestCase
from django.core.management import call_command
from io import StringIO
import os
class CommandTestCase(TestCase):
def test_command_import(self):
out = StringIO()
call_command(
'my_command', os.path.join('path/to/file', 'my_file.txt'),
stdout=out
)
self.assertIn(
'Expected Value',
out.getvalue()
)
当您的 django-command 以如下方式使用时,此方法有效:
$ python manage.py my_command my_file.txt
于 2020-02-21T22:58:17.247 回答
-1
解析标准输出的一个简单替代方法是在管理命令未成功运行时以错误代码退出,例如使用 sys.exit(1)。
您可以通过以下方式在测试中捕捉到这一点:
with self.assertRaises(SystemExit):
call_command('mycommand')
于 2018-08-04T11:39:01.623 回答
-3
我同意 Daniel 的观点,即实际的命令脚本应该尽可能少,但您也可以直接在 Django 单元测试中使用os.popen4
.
在您的单元测试中,您可以使用类似的命令
fin, fout = os.popen4('python manage.py yourcommand')
result = fout.read()
然后您可以分析结果的内容以测试您的 Django 命令是否成功。
于 2010-01-09T00:49:16.100 回答