软件:Pycharm2020 Python:python3.7.5 Django:django3.0.8 数据库:mysql5.7.30
github链接 https://github.com/yt-xy/Django-student
对于Mysql数据库,Django会直接用配置的数据库用户和密码创建一个名为test_stu_db的数据库,用于测试。因此,需要保证有建表和建库的权限。 也可以定义测试用的数据库名称,可以通过settings配置
DATABASES = { 'default': { ..., 'TEST': { 'NAME': 'testproject' # 这里配置 }, }, }方法说明: def setUp(self):用来初始化环境,包括创建初始化的数据,或者一些其他准备工作。 def test_xxxx(self):方法后面的xxxx可以是容易东西。以test_开头的方法,会被认为是需要测试的方法,跑测试时会被执行。每个需要被测试的方法是相互独立的。 def tearDown(self):跟setUp相对,用来清理测试环境和测试数据。在Django中,我们可以不关心这个。
Model层测试 models.py
# 这一层的测试主要保证数据的写入和查询是可用的,同时也要保证我们在Model层所提供的方法是符合预期的。 ... @classmethod def get_all(cls): return cls.objects.all() @property def sex_show(self): return dict(self.SEX_ITEMS)[self.sex]test.py
from django.test import TestCase, Client from .models import Student class StudentTestCase(TestCase): def setUp(self): # 创建一条数据用于测试 Student.objects.create( name='Tony', sex=1, email='123@qq.com', profession='程序员', qq='123', phone='123456', ) def test_create_and_sex_show(self): # 用来测试数据创建以及sex字段的正确展示 student = Student.objects.create( name='Alice', sex=1, email='234@qq.com', profession='程序员', qq='234', phone='234567', ) self.assertEqual(student.sex_show, '男', '性别字段内容跟展示不一致!') def test_filter(self): # 测试查询是否可用 Student.objects.create( name='Adobe', sex=1, email='345@qq.com', profession='程序员', qq='345', phone='345678', ) name = 'Tony', students = Student.objects.filter(name=name) self.assertEqual(students.count(), 1, '应该只存在一个名称为{}的记录'.format(name)) def test_get_index(self): # 测试首页的可用性 client = Client() response = client.get('/') self.assertEqual(response.status_code, 200, 'status code must be 200!') def test_post_student(self): # 提交数据->请求首页->检查数据是否存在 client = Client() data = dict( name='test_for_post', sex=1, email='111@qq.com', profession='程序员', qq='111', phone='111111', ) response = client.post('/', data) self.assertEqual(response.status_code, 302, 'status code must be 302!') response = client.get('/') self.assertEqual(b'test_for_post' in response.content, 'response content must contain `test_for_post`')