django 单元测试错误总结

TestCase

django自带有一个TestCase模块来进行测试,我们可以参考官网 来写单元测试的代码。我这里主要是总结一些错误。

用户无法登陆

我们有些api登录后才可以进行测试,所以我们可以在setUp 方法里面先登录用户后再进行操作,那今天我遇到的问题就是,登陆不上,authenticate返回的是None,明明有正确的用户名密码的呀。后来我定睛一看,发现执行 python manage.py test gray_switch后,第一行出现这 Creating test database for alias 'default'... ,说明是临时创建了一个数据库以及相关的表结构,那么对应的用户表应该是空表,没有数据所以 登录失败了。所以我们在登录之前,先创建用户。

from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User

# Create your tests here.
# 测试单元

class policy_operation_test(TestCase):

    def setUp(self):
        print("begin to test the policy operation's api ")
        User.objects.create_user('test',"[email protected]",'xxx')   #创建用户,大胆的创建吧,反正是测试数据是保存在临时库里的。

        self.c = Client()
        response = self.c.login(username="test",password="xxx")
        print("login status:",response)  

这回可以登录成功了。

猜你喜欢

转载自www.cnblogs.com/liaojiafa/p/9037017.html