Python接口自动化测试和性能测试《Django By Example》

Django单元测试(指定MySQL测试数据库)

2019-06-13  本文已影响55人  梨花菜

1.配置测试数据库,在setting.py文件DATABASES中增加TEST字段

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'fast',  # 新建数据库名
        'USER': 'root',  # 数据库登录名
        'PASSWORD': 'root',  # 数据库登录密码
        # 单元测试数据库
        'TEST': {
            'NAME': 'test',  # 测试过程中会生成名字为test的数据库,测试结束后Django会自动删除该数据库
        }
    }
}

2.编写单元测试用例test.py(一定要以test开头)

from django.test import TestCase
from fastuser import models

class ModelTest(TestCase):
    def setUp(self):
        """
        注册:{
            "username": "demo"
            "password": "1321"
            "email": "1@1.com"
        }
        """
        models.UserInfo.objects.create(username='rikasai', password='mypassword', email='lihuacai168@gmail.com')
     # 函数名必须是test开头
    def test_user_register(self):
        res = models.UserInfo.objects.get(username='rikasai')
        self.assertEqual(res.email,"lihuacai168@gmail.com")
class UserInfo(BaseTable):
    """
    用户注册信息表
    """

    class Meta:
        verbose_name = "用户信息"
        db_table = "UserInfo"

    username = models.CharField('用户名', max_length=20, unique=True, null=False)
    password = models.CharField('登陆密码', max_length=100, null=False)
    email = models.EmailField('用户邮箱', unique=True, null=False)

3.执行单元测试命令

# 执行fastrunner这个app下面的test.py测试用例
# 
python manage.py test fastrunner.test 

# 执行fastrunner这个app下面的test*.py测试用例
python manage.py test fastrunner

# 执行所有的app下面的test*.py测试用例
python manage.py test

4.测试结果

(FastRunner) D:\rikasai\Code\FasterRunner>python manage.py test fastrunner.test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.006s

OK
Destroying test database for alias 'default'...
(FastRunner) D:\rikasai\Code\FasterRunner>python manage.py test fastrunner.test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_user_register (fastrunner.test.ModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\rikasai\Code\FasterRunner\fastrunner\test.py", line 27, in test_user_register
    self.assertEqual(res.email,"lihuacai168@gmail.com_false")
AssertionError: 'lihuacai168@gmail.com' != 'lihuacai168@gmail.com_false'
- lihuacai168@gmail.com
+ lihuacai168@gmail.com_false
?                      ++++++


----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (failures=1)
Destroying test database for alias 'default'...
上一篇下一篇

猜你喜欢

热点阅读