Django 單元測試筆記

  引言

  關於單元測試的基本知識這裏再也不講述,簡單一句話:單元測試是用一段代碼去測試另外一段代碼。最經常使用的框架是unittest,這是python的單元測試框架,而django單元測試框架test.TestCase是繼承了python的unittest.TestCase。html

TestCase也是對unittest.TestCase進行了進一步的封裝,省去了不少重複要寫的代碼,好比定義一個self.client、Email Service提供了方便的郵件發送的方法。python

衆所周知django模式是MTV模型,其中T是模板也就是HTML文件,對於HTML來講,沒有可測的代碼,基本上寫死,即便有,並非重要的邏輯代碼。因此在進行單元測試的時候,重點針對M和V展開,也就是models和views。web

 

  方式

單元測試進行的兩種方式:

1.使用django框架自帶的tests.py文件進行單元測試;
2.自定義建立test.py文件;
這兩種是同樣,只是運行時所執行目錄不同。django

注:我這裏只介紹第一種。框架

 

  模型測試

首先導入公共使用庫:

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'...
相關文章
相關標籤/搜索