【Django】 Day5-测试

Django 测试

一.unittest框架

这里之前接触过,就贴上虫师的两个文档吧

  • count.py
'''
虫师原创----http://fnng.cnblogs.com
Describe:实现简单计算器:+、-、*、/、
'''
class Calculator():
    '''实现两个数的加、减、乘、除'''
    def __init__(self, a, b):
        self.a = int(a)
        self.b = int(b)
    
    # 加法
    def add(self):
        return self.a + self.b
    # 减法
    def sub(self):
        return self.a - self.b
    # 乘法
    def mul(self):
        return self.a * self.b
    # 除法
    def div(self):
        return self.a / self.b
  • testCount.py
import unittest
from com.pyCoreEditor.section01.part02.count import Calculator
class CountTest(unittest.TestCase):
    def setUp(self):
        self.cal = Calculator(8, 4)

    def tearDown(self):
        pass

    def test_add(self):
        result = self.cal.add()
        self.assertEqual(result, 12)

    def test_sub(self):
        result = self.cal.sub()
        self.assertEqual(result, 4)

    def test_mul(self):
        result = self.cal.mul()
        self.assertEqual(result, 32)

    def test_div(self):
        result = self.cal.div()
        self.assertEqual(result, 2)

if __name__ == "__main__":
    unittest.main()
    # 构造测试集
    suite = unittest.TestSuite()
    suite.addTest(CountTest("test_add"))
    suite.addTest(CountTest("test_sub"))
    suite.addTest(CountTest("test_mul"))
    suite.addTest(CountTest("test_div"))
    # 执行测试
    runner = unittest.TextTestRunner()
    runner.run(suite)

二.Testing in Django

1.A simple example

对于每一个应用,其中的test文件就是用来单元测试的

  • tests.py
from django.test import TestCase
from blog.models import Event,Guest

# Create your tests here.

class ModelTest(TestCase):
    def setUp(self):
        Event.objects.create(id=1, name="oneplus 3 event", status=True, limit=2000,address='shenzhen', start_time='2016-08-31 02:18:22')
        Guest.objects.create(id=1,event_id=1,realname='alen',phone='13711001101',email='[email protected]', sign=False)

    def test_event_models(self):
        result = Event.objects.get(name="oneplus 3 event")
        self.assertEqual(result.address, "shenzhen")
        self.assertTrue(result.status)

    def test_guest_models(self):
        result = Guest.objects.get(phone='13711001101')
        self.assertEqual(result.realname, "alen")
        self.assertFalse(result.sign)

  • 在shell文件中应用
python manage.py test

Django 在执行setUp()方法中的数据库初始化时,并非真正的向数据库表中插入了数据。所以,数据库并不会因为运行测试而产生测试数据。

2.Run test case

然后是执行测试用例,这里使用unitest里面指定运行程序的功能

# 运行sign模块所有测试用例
python manage.py test sign

# 运行sign模块中的tests测试类
python manage.py test sign.tests

# 运行sign 应用tests.py 测试文件下的ModelTest 测试类:
python manage.py test sign.tests.ModelTest

三.The test views

1.初始化测试环境

  • 初始化测试环境
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
  • 使用Client()测试类,测试登录视图
    这里使用Client测试类模式GET/POST请求,通过get()请求“/index/”路径,即为登录页面,得到的返回码为200,表示成功。
>>> from django.test import Client
>>> c = Client()
>>> response = c.get('/index/')
>>> response.status_code
200

2.Test Index页面

继续在test.py文件中编写测试用例

#python manage.py test blog.tests.IndexPageTest
class IndexPageTest(TestCase):
    ''' 测试index 登录首页'''

    def test_index_page_renders_index_template(self):
        ''' 测试index 视图'''
        response = self.client.get('/index/')
        #断言index返回接口200,断言模板是index.html
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index.html')

3.Test Login action页面

#python manage.py test blog.tests.LoginActionTest
class LoginActionTest(TestCase):
    '''测试登录函数'''
    def setUp(self):
        User.objects.create_user('cat','[email protected]','cat123456')
        self.c = Client()

    def test_login_action_username_password_null(self):
        ''' 用户名密码为空'''
        test_data = {'username': '', 'password': ''}
        response = self.c.post(path='/login_action/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"username or password error!", response.content)


    def test_login_action_username_password_error(self):
        ''' 用户名密码错误'''
        test_data = {'username': 'abc', 'password': '123'}
        response = self.c.post(path='/login_action/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"username or password error!", response.content)

    def test_login_action_success(self):
        ''' 登录成功'''
        test_data = {'username': 'cat', 'password': 'cat123456'}
        response = self.c.post(path='/login_action/', data=test_data)
        self.assertEqual(response.status_code, 302)

这里的/login_action/是用户登录的路径,然后提交登录数据,对返回结果进行验证

4.Test Event Manage页面

from datetime import datetime

#python manage.py test blog.tests.EventManageTest
class EventManageTest(TestCase):
    '''发布会管理'''

    def setUp(self):
        Event.objects.create(id=10,name='xiaomi5',limit=2000,status=True,address='beijing',start_time=datetime(2016,8,10,14,0,0))
        self.c = Client()

    def test_event_manage_success(self):
        ''' 测试发布会:xiaomi5 '''
        response = self.c.post(path='/event_manage/')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"xiaomi5", response.content)
        self.assertIn(b"beijing", response.content)

    def test_event_manage_search_success(self):
        ''' 测试发布会搜索'''
        response = self.c.post(path='/search_name/', data={"name": "xiaomi5"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"xiaomi5", response.content)
        self.assertIn(b"beijing", response.content)

此用例要想运行通过, 需要在views.py 视图文件中将event_manage() 和search_name() 函数的@login_required 装饰器去掉,因为这两个函数依赖于登录,然而,Client()所提供的get()和post()方法并没有验证登录的参数。

5.Test Guest Manage页面

#python manage.py test blog.tests.GuestManageTest
class GuestManageTest(TestCase):
    ''' 嘉宾管理'''
    def setUp(self):
        Event.objects.create(id=1,name="xiaomi5",limit=2000,
        address='beijing',status=1,start_time=datetime(2016,8,10,14,0,0))
        Guest.objects.create(realname="alen",phone=18611001100,
        email='[email protected]',sign=0,event_id=1)
        self.c = Client()

    def test_event_manage_success(self):
        ''' 测试嘉宾信息: alen '''
        response = self.c.post(path='/guest_manage/')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"alen", response.content)
        self.assertIn(b"18611001100", response.content)

    def test_guest_manage_search_success(self):
        ''' 测试嘉宾搜索'''
        response = self.c.post(path='/search_guest/',data={"name":"alen"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"alen", response.content)
        self.assertIn(b"18611001100", response.content)

嘉宾这个和发布会的类似,也要去除装饰器

6.Test User Sign页面


#python manage.py test blog.tests.SignIndexActionTest
class SignIndexActionTest(TestCase):
    ''' 发布会签到'''
    def setUp(self):
        Event.objects.create(id=1,name="xiaomi5",limit=2000,address='beijing',status=1,start_time='2017-8-10 12:30:00')
        Event.objects.create(id=2,name="oneplus4",limit=2000,address='shenzhen',status=1,start_time='2017-6-10 12:30:00')
        Guest.objects.create(realname="alen",phone=18611001100,email='[email protected]',sign=0,event_id=1)
        Guest.objects.create(realname="una",phone=18611001101,email='[email protected]',sign=1,event_id=2)
        self.c = Client()

    def test_sign_index_action_phone_null(self):
        ''' 手机号为空'''
        response = self.c.post(path='/sign_index_action/1/', data={"phone": ""})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"phone error.", response.content)

    def test_sign_index_action_phone_or_event_id_error(self):
        ''' 手机号或发布会id 错误'''
        response = self.c.post(path='/sign_index_action/2/', data={"phone": "18611001100"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"event id or phone error.", response.content)

    def test_sign_index_action_user_sign_has(self):
        ''' 用户已签到'''
        response = self.c.post(path='/sign_index_action/2/', data={"phone": "18611001101"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"user has sign in.", response.content)

    def test_sign_index_action_sign_success(self):
        ''' 签到成功'''
        response = self.c.post(path='/sign_index_action/1/', data={"phone": "18611001100"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"sign in success!", response.content)

同样需要去除登录限制

你可能感兴趣的:(编程代码学习)