django项目中使用 test_plus 写测试用例
安装 pip install django-test-plus
在项目中创建test文件夹
注意 文件夹名称 不能是tests 否则使用 python manage.py test 运行测试用例的时候会报错
django DRF 接口测试
from django.test import Client
from test_plus import TestCase
from rest_framework.test import APIClient
class APITestCase(TestCase):
client_class = APIClient
class MyAPITestCase(APITestCase):
def setUp(self):
self.user = self.make_user()
self.client = Client()
def test_login(self):
data = {'username': "testuser","password":"password"}
res = self.post("/u/login/",data=data,extra={'format': 'json'})
self.response_201()
print(res)
# todo 上下这两种方式都可以
response = self.client.post("/u/login/",data=data,extra={'format': 'json'})
print(response.status_code)
print(response.data)
assert response.status_code == 201
跑测试用例
在项目文件夹中 python manage.py test
生成html 测试报告 nose
pip install nose
pip install django-nose
pip install nose-htmloutput
django项目的setting.py中添加:
INSTALLED_APPS = [
...
'django_nose'
]
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
项目文件夹中运行 t.html 是我要生成的出报告文件(可以自定义生成到自己定义的文件夹中)
(fk) F:\django\dj3>python manage.py test --with-html --html-file=t.html
1指定只测试某个文件下的测试用例
python manage.py test users.test.test_view
生成报告 python manage.py test users.test.test_view --with-html --html-file=t1.html
2指定只测试某个文件下的某个测试用例
python manage.py test users.test.test_view:MyAPITestCase.test_login
生成报告 python manage.py test users.test.test_view:MyAPITestCase.test_login --with-html --html-file=t1.html
生成测试报告 打开t.html 看到
直接用nose测试django项目。不用python manager.py test命令,而用nosetests加载tests.py进行测试。测试需要django环境,所以在tests.py开头加上:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
import django
django.setup()
运行命令 nosetests --with-html --html-file=/path/to/htmlfile
nosetests --with-coverage --with-xunit --cover-erase && coverage xml