【问题标题】:Run Python/Django Management Command from a UnitTest/WebTest从 UnitTest/WebTest 运行 Python/Django 管理命令
【发布时间】:2012-03-21 07:39:17
【问题描述】:

我们的 Django 站点中有一堆命令,一些是管理命令,一些是在我不知道如何测试的 cron 作业上运行的。它们几乎看起来像这样:

# Saved in file /app/management/commands/some_command.py
# Usage: python manage.py some_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
    def handle_noargs(self, **options):
         # Do something useful

我有一些测试,看起来像这样:

import unittest
from django.test import TestCase
from django_webtest import WebTest

class SomeTest(WebTest):
    fixtures = ['testdata.json']

    def setUp(self):
        self.open_in_browser = False
        # Set up some objects

    def test_registration(self):
        response = self.client.get('/register/')
        self.assertEqual(response.status_code, 200)
        form = self.app.get('/register/').forms[1]
        # Set up the form
        response = form.submit()
        self.assertContains(response, 'You are Registered.')
        if self.open_in_browser:
            response.showbrowser()

        # Here I'd like to run some_command to see the how it affects my new user.

在我的测试中(我有评论)我想运行我的 NoArgsCommand 来看看我的新用户会发生什么。我找不到任何有关如何完成此操作的文档或示例。另请注意,我的测试环境是我在内存中从头开始创建的 SQLlite 数据库,将一些固定装置和对象加载到并运行我的测试,所以我想在真实数据库中设置数据,然后运行我的从命令行命令,我不能,这太耗时了。任何想法将不胜感激。

【问题讨论】:

    标签: python django unit-testing webtest


    【解决方案1】:

    Django documentation on management commands 可能会有所帮助,它描述了如何从 python 代码中调用它们。

    基本上你需要这样的东西:

    from django.core import management
    management.call_command( ... )
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    相关资源
    最近更新 更多