Django 单元测试笔记

  引言

  关于单元测试的基本知识这里不再讲述,简单一句话:单元测试是用一段代码去测试另一段代码。最常用的框架是unittest,这是python的单元测试框架,而django单元测试框架test.TestCase是继承了python的unittest.TestCase。

TestCase也是对unittest.TestCase进行了进一步的封装,省去了很多重复要写的代码,比如定义一个self.client、Email Service提供了方便的邮件发送的方法。

众所周知django模式是MTV模型,其中T是模板也就是HTML文件,对于HTML来说,没有可测的代码,基本上写死,即使有,并不是重要的逻辑代码。所以在进行单元测试的时候,重点针对M和V展开,也就是models和views。

 

  方式

单元测试进行的两种方式:

1.使用django框架自带的tests.py文件进行单元测试;
2.自定义创建test.py文件;
这两种是一样,只是运行时所执行目录不一样。

注:我这里只介绍第一种。

 

  模型测试

首先导入公共使用库:

from django.test import TestCase
from django_web.models import Event,Guest
from django.contrib.auth.models import User
# Create your tests here.
import datetime
get_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

 

测试模型

class DjangoWebModelTest(TestCase):
    """测试模型"""
    def setUp(self) -> None:
        Event.objects.create(id=1,name='小米5',status=True,address='深圳',limit=3,start_time=get_now)
        Guest.objects.create(id=1,event_id=1,realname='老王',phone=15099925893,email='11@qq.com',sign=False)

    def test_event_model(self):
        """测试发布会表"""
        result = Event.objects.get(name='小米5')
        self.assertEqual(result.address,'深圳')
        self.assertTrue(result.status)

    def test_guest_model(self):
        """测试嘉宾表"""
        result = Guest.objects.get(phone='15099925893')
        self.assertEqual(result.realname,'老王')
        self.assertFalse(result.sign)

 

  视图函数测试

class IndexPageTest(TestCase):
    """测试index登录首页"""

    def test_index_page(self):
        """测试index视图"""
        response = self.client.get('/index/')
        self.assertEqual(response.status_code,200)
        self.assertTemplateUsed(response,'index.html')

class LoginAction(TestCase):
    """测试登录动作"""
    def setUp(self) -> None:
        """创建用户数据:两种不同的方式创建用户"""
        User.objects.create(username='admin')
        User.objects.create_user(username='admin2',email='admin@11.com',password='123456')

    def test_add_admin(self):
        """添加用户admin测试"""
        user = User.objects.get(username='admin')
        self.assertEqual(user.username,'admin')

    def test_add_admin2(self):
        """添加用户admin2测试"""
        user = User.objects.get(username='admin2')
        self.assertEqual(user.username,'admin2')
        self.assertEqual(user.email,'admin@11.com')

    def test_login_username_password_null(self):
        """用户名密码为空"""
        test_data = {'username':'','password':''}
        response = self.client.post('/login_action/',data=test_data)
        self.assertEqual(response.status_code,302)

    def test_login_username_password_error(self):
        """用户名密码错误"""
        test_data = {'username':'test','password':'123456'}
        response = self.client.post('/login_action/',data=test_data)
        self.assertEqual(response.status_code,302)

    def test_login_action_success(self):
        """登录成功"""
        test_data = {'username':'admin2','password':'123456'}
        response = self.client.post('/login_action/',data=test_data)
        self.assertEqual(response.status_code,302)


class EventManageTest(TestCase):
    """发布会管理"""

    def setUp(self) -> None:
        #创建用户账号
        User.objects.create_user('admin','admin@qq.com','123456')
        Event.objects.create(name='小米3',limit=3,address='深圳',status=True,start_time=get_now)
        self.login_user = {'username':'admin','password':'123456'}
        #预先登录
        self.client.post('/login_action/', data=self.login_user)

    def test_add_event_data(self):
        """ 测试添加发布会:小米3 """
        event = Event.objects.get(name="小米3")
        self.assertEqual(event.address, "深圳")

    def test_event_success(self):
        """测试发布会:小米3"""
        response = self.client.post('/event_manager/')
        self.assertEqual(response.status_code,200)
        self.assertIn("小米3".encode('utf-8'),response.content)

    def test_event_search_success(self):
        """测试发布会搜索"""
        response = self.client.post('/search_name/')
        self.assertEqual(response.status_code,200)
        self.assertIn('小米3'.encode('UTF-8'),response.content)



class GuestManageTest(TestCase):
    """嘉宾管理"""
    def setUp(self) -> None:
        User.objects.create_user('admin','admin@qq.com','123456')
        Event.objects.create(id=1,name='小米2',limit=3,address='深圳',status=True,start_time=get_now)
        Guest.objects.create(realname='小李子',phone=15099925798,email='11@qq.com',sign=0,event_id=1)
        self.login_user = {'username':'admin','password':'123456'}
        #预先登录
        self.client.post('/login_action/',data=self.login_user)

    def test_add_guest(self):
        """测试添加嘉宾:小李子"""
        guest =Guest.objects.get(realname='小李子')
        self.assertEqual(guest.realname,'小李子')
        self.assertEqual(guest.phone,'15099925798')
        self.assertEqual(guest.email,'11@qq.com')
        self.assertFalse(guest.sign)

    def test_guest_success(self):
        """测试嘉宾列表:小李子"""
        response = self.client.post('/guest_manager/')
        self.assertEqual(response.status_code,200)
        self.assertIn('小李子'.encode('UTF-8'),response.content)
        self.assertIn('15099925798'.encode('utf-8'),response.content)

    def test_guest_search_success(self):
        """测试嘉宾搜索"""
        response = self.client.post('/search_phone/')
        self.assertEqual(response.status_code,200)
        self.assertIn('小李子'.encode('utf-8'),response.content)
        self.assertIn('15099925798'.encode('utf-8'),response.content)


class SignIndexActionTest(TestCase):
    """发布会签到"""
    def setUp(self) -> None:
        User.objects.create_user('admin','admin@qq.com','123456')
        Event.objects.create(id=1, name='小米1', limit=3, address='广州', status=True, start_time=get_now)
        Event.objects.create(id=2, name='小米9', limit=3, address='北京', status=True, start_time=get_now)
        Guest.objects.create(realname='老张', phone=15099925798, email='11@qq.com', sign=0, event_id=1)   #未签到
        Guest.objects.create(realname='老周', phone=15099925700, email='22@qq.com', sign=1, event_id=2)   #未签到
        self.login_user = {'username':'admin','password':'123456'}
        self.client.post('/login_action/',data=self.login_user)

    def test_phone_null(self):
        """测试手机号码为空"""
        response =self.client.post('/sign_index_action/1/',{"phone":""})
        self.assertEqual(response.status_code,200)
        self.assertIn('请输入电话号码.'.encode('utf-8'),response.content)

    def test_phone_error(self):
        """手机号码错误"""
        response = self.client.post('/sign_index_action/2/',{"phone":"15099925732398"})
        self.assertEqual(response.status_code,200)
        self.assertIn("电话号码错误.".encode('UTF-8'),response.content)

    def test_phone_or_eventid_error(self):
        """电话号码所属嘉宾不属于该发布会"""
        response = self.client.post('/sign_index_action/2/',{"phone":"15099925798"})
        self.assertEqual(response.status_code,200)
        self.assertIn("电话号码所属嘉宾不属于该发布会.".encode('UTF-8'),response.content)

    def test_already_sign(self):
        """用户已签到"""
        response = self.client.post('/sign_index_action/2/',{"phone":"15099925700"})
        self.assertEqual(response.status_code,200)
        self.assertIn("您已经签到!.".encode('utf-8'),response.content)

    def test_sign_success(self):
        """签到成功"""
        response = self.client.post('/sign_index_action/1/',{"phone":"15099925798"})
        self.assertEqual(response.status_code,200)
        self.assertIn("签到成功!".encode('utf-8'),response.content)

 

  运行单元测试代码

"""
运行所有用例:
python3 manage.py test

运行django_web应用下的所有用例:
python3 manage.py test django_web

运行sign应用下的tests.py文件用例:
python3 manage.py test django_web.tests

运行django_web应用下的tests.py文件中的 DjangoWebModelTest 测试类:
python3 manage.py test django_web.tests.DjangoWebModelTest

运行django_web应用下DjangoWebModelTest 测试类中的测试方法(用例):
python3 manage.py test django_web.tests.DjangoWebModelTest.test_event_model

模糊匹配测试文件
运行python3 manage.py test django_web -p test*.py 
......

"""

 

  执行结果

D:\my_django_guest>python3 manage.py test django_web
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...................
----------------------------------------------------------------------
Ran 19 tests in 3.080s

OK
Destroying test database for alias 'default'...

  

posted @ 2020-02-18 23:45  全栈测试开发日记  阅读(476)  评论(0编辑  收藏  举报