此发布会签到系统是我跟着虫师的《Web接口开发与自动化测试》做的项目。此项目基于django框架,使用到了python、HTML语言并涉及到非常多的技术。
一、django.test.Client类
充当一个虚拟的网络浏览器,可以测试视图(view)与django的应用程序以编程方式交互。该类可做的事情如下:
- 模拟get和post请求,观察响应结果;
- 检查重定向链,再每一步检查URL和status code;
- 用一个包括特定值的模板context来测试一个request被django模板渲染。
D:\Python37\Scripts\guestProject>python manage.py shell
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> c = Client()
>>> response = c.get('/index/')
>>> response.status_code
200
二、举例
from django.test import TestCase
from sign.models import Event,Guest
from django.contrib.auth.models import User
# Create your tests here.
class IndexPageTest(TestCase):
'''测试index登录首页'''
def test_index_page_renders_index_template(self):
'''测试index视图'''
response = self.client.get('/index/')
self.assertEqual(response.status_code,200)
self.assertTemplateUsed(response,'index.html')
class LoginActionTest(TestCase):
'''测试登录动作'''
def setUp(self):
User.objects.create_user('admin','admin@mail.com','admin123456')
def test_add_admin(self):
'''添加用户测试'''
user = User.objects.get(username='admin')
self.assertEqual(user.username,"admin")
self.assertEqual(user.email,"admin@mail.com")
def test_login_action_username_password_null(self):
'''用户名密码为空'''
test_data = {'username':'','password':''}
respongse = self.client.post('/login_action/', data=test_data)
self.assertEqual(respongse.status_code,200)
self.assertIn(b"user or password error!",respongse.content)
def test_login_action_username_password_error(self):
'''用户名密码错误'''
test_data = {'username':'abc','password':'123'}
response = self.client.post('/login_action/', data=test_data)
self.assertEqual(response.status_code,200)
self.assertIn(b"user or password error!",response.content)
def test_login_action_success(self):
'''登录成功'''
test_data = {'username': 'admin', 'password': 'admin123456'}
response = self.client.post('/login_action/', data=test_data)
self.assertEqual(response.status_code,302)
执行结果:
D:\Python37\Scripts\guestProject>python manage.py test
Creating test database for alias 'default'...
......
----------------------------------------------------------------------
Ran 5 tests in 0.500s
OK
Destroying test database for alias 'default'...