tests unitaires Django (fin)

annuaire

1, Introduction
2, essais effectués de deux façons unitaires
3, de test du modèle
4, vue de tester la fonction
5, code de test en cours d' exécution unité
6, les résultats de

connaissances de base sur les tests unitaires ne sont plus ici, simplement: tests unitaires est un morceau de code pour tester un autre morceau de code. Le cadre le plus couramment utilisé est unittest, qui est le cadre de tests unitaires python, django framework de test unitaire test.TestCase hérité unittest.TestCase du python.

Unittest.TestCase TestCase est également effectué plus emballage, ce qui élimine le besoin d'écrire beaucoup de répétitions de code, comme la définition d'un self.client, E-Mail Service fournit une méthode pratique pour l'envoi du courrier.

modèle Django est bien connu modèle MTV, où T est le modèle est les fichiers HTML, pour HTML, il n'y a pas de code mesurable, essentiellement pour écrire les morts, même s'il n'y a pas un code logique importante. Ainsi, lors de l'essai d'unité de temps, en se concentrant sur l'expansion M et V, qui, modèles et points de vue.

Les tests unitaires effectués de deux façons:

1. Cadre de django vient documents tests unitaires tests.py;
2. personnalisé créé test.py fichier, les
deux sont les mêmes, mais l'exécution n'est pas le même répertoire d' exécution.

test Modèle :

Commencez par importer l'utilisation des bibliothèques publiques:
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='[email protected]',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)

Voir le test de la fonction:

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='[email protected]',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,'[email protected]')

    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','[email protected]','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','[email protected]','123456')
        Event.objects.create(id=1,name='小米2',limit=3,address='深圳',status=True,start_time=get_now)
        Guest.objects.create(realname='小李子',phone=15099925798,email='[email protected]',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,'[email protected]')
        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','[email protected]','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='[email protected]', sign=0, event_id=1)   #未签到
        Guest.objects.create(realname='老周', phone=15099925700, email='[email protected]', 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)

Exécutez le code de test unitaire:

"""
运行所有用例:
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 
......

"""

Les résultats:

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'...

Ceci complète la logique de code de test unitaire.

Publié 82 articles originaux · louange gagné 43 · vues 180 000 +

Je suppose que tu aimes

Origine blog.csdn.net/liudinglong1989/article/details/104384865
conseillé
Classement