1. Add test case code in the tests.py file in your app
The code structure of this example is as follows:
Since I have many apps, and for the convenience of management, I put the apps in the apps directory. To achieve this effect, just add the following code to the settings.py configuration file
...
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # 整合app统一到apps目录内的必要配置
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0b($)a_$n$!grvsj!pob$5z4(q+u3fo_)aoz!g)3^=pk@7g770sdfgertgsdf'
...
The desired test effect in this example is: test /test/ interface, and display the test results
In this example, write tests.py under the user directory, and add the code as follows:
from django.test import TestCase
from django.test import Client
# Create your tests here.
class TestSubtract(TestCase):
def test_test(self):
"""
未传参数
:return:
"""
# self.client 是 django TestCase提供的一个可以在django运行时使用http客户端,用于发送请求得到响应
res = self.client.get('/test/') # 这传入的参数是path,该path是你项目中存在的路径
status_code = res.status_code
res_data = res.json()
self.assertEqual(status_code, 200)
self.assertEqual(res_data.get('errorCode'), 0)
def test_test_params(self):
"""
传入相关参数
:return:
"""
res = self.client.get('/test/', {
'page': 1, 'page_size': 10}) # 这传入的参数是path和params
status_code = res.status_code
res_data = res.json()
self.assertEqual(status_code, 200)
self.assertEqual(res_data.get('errorCode'), 0)
2. Edit the configuration file and configure the database used for unit testing
Modify the settings.py configuration file
...
# 使用mysql数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'base-api', # 实际数据库
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
'TEST': {
'NAME': 'test_api', # 配置单元测试时使用的测试数据库,会自动创建,因此 USER 用户需要有相关权限
'CHARSET': 'utf8mb4', # 配置测试数据库的字符集,注意:根据需求修改,不然容易出问题
},
'OPTIONS': {
"init_command": "SET foreign_key_checks = 0;", # 去除强制外键约束
'charset': 'utf8mb4',
'sql_mode': 'traditional'
}
},
}
....
3. Start the unit test
You need to specify the app when running the command
$ python manage.py test user
The test results of this example are as follows: