首先上一个简单的测试用例(添加用户,然后利用此用户登陆测试并添加一个Q到系统中)
...
from myapp.models import Question,User
from django.test import TestCase
...
class QATest(TestCase):
def setUp(self):
User.objects.create(username="goood", password=hashlib.md5("Lockey23").hexdigest(), first_name="Young",
last_name="Cheng", department="SRS", email="xxx@xxx.com", member_of="SRS-BI",
team="SRS-BI", role="admin")
self.client.post('/account/login/', {
'username': 'goood', 'password': 'Lockey23'})
user = User.objects.get(nt_id="goood")
Question.objects.create(create_nt_id=user, question_text="test question")
The test client is a Python class that acts as a dummy Web browser, allowing you to test your views and interact with your Django-powered application programmatically.
上面的例子中已经使用了两个最常用的方法GET和POST(PUT和DELETE与POST基本格式相同),请记住请求方式以及数据格式!
然后下面介绍一个clent的特性:
The test client is stateful. If a response returns a cookie, then that cookie will be stored in the test client and sent with all subsequent get() and post() requests.
意思client是状态保持的,所以如果我们需要测试登陆系统中的多个API的话只需要登陆一次然后就可以顺畅的去测试其他的接口了;所以一般对于需要登陆之后才能操作的接口我们会将登陆操作放到setUp函数中去执行,这样后面的所有测试方法都可以使用这一次的登录状态来进行接口测试了
>>> res = c.get('/account/uprofile/')