Django单元测试之Client

本文介绍了Django的测试客户端(Client)的使用,通过实例展示了如何进行GET和POST请求,以及如何处理返回的JSON数据。此外,文章还提到了assert系列方法在测试中的应用。
摘要由CSDN通过智能技术生成

首先上一个简单的测试用例(添加用户,然后利用此用户登陆测试并添加一个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/')
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值