单元测试的优点:
1,当编写新的代码时候,你可以使用测试来验证你的代码是否想预期的一样工作
2,当重构或者修改代码的时候,你可以使用测试来保证你的修改不会影响到应用的运行
pytest是python的第三方测试框架,是基于unittest的扩展框架,比unittest更简洁,更高效。
使用pytest编写用例,必须遵守以下规则(与unittest的区别!):
1,测试文件名必须以“test_”开头(如:test_ab.py)
2,测试方法必须以“test_”开头
3,pytest使用python原生的assert断言(也就是说,需要测试的地方只需要使用断言就行,不用这么麻烦)
4,pytest的fixture比unittest的Setup/teardown更灵活。更自由的定义fixture,任何函数加上@pytest.fixture的装饰器就成了fixture,然后通过fixture装载(3种装载方法)在测试用例中装载fixture。而且,fixture的使用范围可以是function,module,class,session. unittest也可以定义fixture使用范围,用法是将setup/teardown封装到一个class中,然后在其他Test class中继承这个封装好的class
5,基于第二点,pytest基本上就万能了,什么读json文件作为参数,做法:def load_file(json_file) return data. 将load_file加上fixture标签
import json
from pytest import fixture, mark
from rest_framework.status import (
HTTP_200_OK, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND,
)
#每次执行测试函数都会首先执行此函数
@fixture
def password():
return 'Passw0rd@123'
#每次执行测试函数都会首先执行带有@fixture修饰的函数
@fixture
def bill_group():
bill_group = "lico_bill_group"
bill = BillGroup.objects.create(name=bill_group)
return bill
#当创建用户的时候进行测试,mask.django_db 表明我的测试需要数据库访问,并且采取缓存措施
@mark.django_db
def test_create_user_with_error_name(test_user, bill_group,
password, client):
# test UserNameVerifyException
response = client.post('/users/',
data=json.dumps({"username": '123lico',
"os_group": 'group_01',
"bill_group": bill_group.id,
"password": password,
"role": 'admin',
}),
content_type='application/json',
)
#pytest 使用的是python 原生的断言,更加简单与简洁
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.data['errid'] == '2001'
pytest 在项目之中的配置!
1,首先在建立一个 pytest.ini 文件(一般项目根目录)

2,项目位置中所有的 test_ 开头文件都会被测试!直接运行 pytest

