【问题标题】:Django Nose how to write this test?Django Nose 怎么写这个测试?
【发布时间】:2013-06-18 10:30:18
【问题描述】:

我对 Django 中的 测试 完全陌生。我已经开始安装 noseselenium,现在我想测试以下代码 (如下) 它会发送一条 SMS 消息。

这是实际代码:

views.py

@login_required
def process_all(request):
    """
    I process the sending for a single or bulk message(s) to a group or single contact.
    :param request:
    """
    #If we had a POST then get the request post values.
    if request.method == 'POST':
        batches = Batch.objects.for_user_pending(request.user)
        for batch in batches:
            ProcessRequests.delay(batch)
            batch.complete_update()

    return HttpResponseRedirect('/reports/messages/')

那么我从哪里开始呢?这就是我到目前为止所做的......

1) 创建了一个名为 tests 的文件夹并添加了 init.py。

2) 创建了一个名为 test_views.py 的新 python 文件(我假设这是正确的)。

现在,我该如何编写这个测试?

谁能告诉我如何为上面的视图编写测试的示例?

谢谢你:)

【问题讨论】:

标签: python django unit-testing testing nose


【解决方案1】:

首先,您不需要selenium 来测试视图。 Selenium 是一种用于高级浏览器内测试的工具 - 当您编写模拟真实用户的 UI 测试时,它非常有用。

Nose 是一个工具,makes testing easier 通过提供自动测试发现等功能,提供许多辅助功能等。将nose 与您的django 项目集成的最佳方法是使用django_nose 包。您所要做的就是:

  1. django_nose 添加到INSTALLED_APPS
  2. 定义TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

然后,每次你运行python manage.py test <project_name>nose 都会被用来运行你的测试。


所以,说到测试这个特定的视图,你应该测试:

  • login_required 装饰器工作 - 换句话说,未经身份验证的用户将被重定向到登录页面
  • 如果request.method 不是POST,则不发送消息+ 重定向到/reports/messages
  • 使用POST方式发送短信+重定向到/reports/messages

测试前两个语句非常简单,但为了测试最后一个语句,您需要提供更多关于BatchProcessRequests 及其工作原理的详细信息。我的意思是,您可能不想在测试期间发送真正的 SMS 消息 - 这就是 mocking 将提供帮助的地方。基本上,您需要模拟(即时替换为您自己的实现)BatchProcessRequests 对象。这是您应该在test_views.py 中拥有的示例:

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import Client
from django.test import TestCase


class ProcessAllTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

    def test_login_required(self):
        response = self.client.get(reverse('process_all'))
        self.assertRedirects(response, '/login')

    def test_get_method(self):
        self.client.login(username='john', password='johnpassword')
        response = self.client.get(reverse('process_all'))
        self.assertRedirects(response, '/reports/messages')

        # assert no messages were sent

    def test_post_method(self):
        self.client.login(username='john', password='johnpassword')

        # add pending messages, mock sms sending?

        response = self.client.post(reverse('process_all'))
        self.assertRedirects(response, '/reports/messages')

        # assert that sms messages were sent

另见:

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多