在Django中,django.test.Client类充当一个虚拟的网络浏览器,可以测试视图(views)与Django的应用程序以编程方式交互。
django.test.Client类可以做的事情如下:
模拟“GET”和“POST”请求,观察响应结果,从HTTP(headers、status code)到页面内容。
检查重定向链(如果有的话),再每一步检查URL和status code.
用一个包括特定值的模版context来测试一个request被Django模版渲染。
进入Django Shell 模式
Python 3.5.2(v3.5.2:4def2a2901a5,Jun 25 2016,22:18:55)[MSC V.1900 64 bit (AMD64)] on win32
Type "help" ,"copyright","credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.utils import setup_test_environment
>>> setup_test_enviroment()
setup_test_environment()用于测试初始化测试环境。
>>> from django.test import Client
>>> c = Client()
>>> response = c.get('/index')
>>> response.status_code
200
测试index视图。Client类提供了get()和post()方法模拟GET/POST请求。通过get()请求“/index/”路径,即为登录页面,打印HTTP返回的状态码为200,表示请求成功。
测试首页
打开.../sign/test.py文件,编写index视图的测试用例。
from django.test import TestCase
class IndexPageTest(TestCase)
```测试index登录首页```
def test_index_page_renders_index_template(self):
```测试index视图```
response = self.client.get('/index/')
self.assertEqual(response.status_code,200)
self.assertTemplateUsed(response,'index.html')
虽然这里没有导入django.test.Client类,但self.client最终调用的依然是django.test.Client类的问题,通过client.get()方法请求“/index/”路径。status_code获取HTTP返回的状态码,使用assertEqual()断言状态码是否为200。assertTemplateUsed()断言服务器是否用给定的是index.html模版响应。