You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
2.2 KiB

# Create your tests here.
from django.test import TestCase, Client, RequestFactory
from django.urls import reverse
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.auth.models import AnonymousUser
from .views import secondpage
from .models import user, student
class SecondPageViewTest(TestCase):
def setUp(self):
#模拟数据
self.client = Client()#模拟客户端对象,用来发送 HTTP 请求
self.factory = RequestFactory()#模拟HTTP的请求对象
self.user = user.objects.create(username='testuser')#模拟用户对象
self.student = student.objects.create(student_name='teststudent', teather_id=self.user.id)#模拟学生对象
def test_secondpage_logged_in(self):#检查已登录用户能否正确响应
session = self.client.session
session['info'] = 'testuser' #设置用户的session信息
session.save()
response = self.client.get(reverse('user:second'))#向对象发送请求secondpage页面的路径类似于发送/second/
self.assertEqual(response.status_code, 200)#检查返回的状态码
self.assertTemplateUsed(response, 'secondpage.html')#检查返回的是否为secondpage.html
self.assertContains(response, 'teststudent')#检查返回是否有学生数据
def test_secondpage_not_logged_in(self):#检查未登录用户能否正确响应
response = self.client.get(reverse('user:second'))#向对象请求secondpage页面
self.assertEqual(response.status_code, 200)#检查返回的状态码
self.assertTemplateUsed(response, 'login.html')#检查返回的是否为login.html
def test_secondpage_empty_student_list(self):#检查学生列表为空的secondpage能否正确响应
# 清空学生列表
student.objects.all().delete()
# 模拟已登录用户
session = self.client.session
session['info'] = 'testuser'
session.save()
response = self.client.get(reverse('user:second'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'secondpage.html')