2013-06-21 58 views
7

我完全陌生,在Django的测试。我已经开始安装鼻子现在我想测试下面的代码(如下)它发送一条短信。Django鼻子如何写这个测试?

这是实际的代码:

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)创建了一个名为测试的文件夹并添加了init .py。

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

现在,我该怎么写这个测试?

有人能告诉我一个如何为上面的视图编写测试的例子吗?

谢谢:)

+0

https://docs.djangoproject.com/en/1.5/topics/testing/&https://docs.djangoproject.com/en/1.5/topics/testing/overview/ –

回答

14

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

鼻子是一个工具,makes testing easier通过提供自动测试发现等功能,提供一些辅助功能等。鼻子与您的Django项目集成的最佳方式是使用django_nose包。所有您需要做的是:

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

然后,每次运行python manage.py test <project_name>鼻子会被用来运行测试的时间。


所以,谈到测试此特定视图,您应该测试:

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

测试前两条语句非常简单,但为了测试最后一条语句,您需要提供关于BatchProcessRequests以及它是如何工作的更多详细信息。我的意思是,您可能不想在测试过程中发送真正的SMS消息 - 这是mocking将提供帮助的地方。基本上,你需要模拟(用你自己的实现来替换)Batch,ProcessRequests对象。下面是你应该在什么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', '[email protected]', '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 

另见:

希望有所帮助。