pytest 在django项目之中的配置与使用(其三)

单元测试的优点:
  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

 
 
 

转载于:https://www.cnblogs.com/shi-qi/articles/9475652.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值