pytest入门

一、pytest入门?

pytest框架使编写小型测试变得容易,但可以扩展以支持应用程序和库的复杂功能测试。

特点:

  • 失败的assert语句的详细信息
  • 自动发现测试模块和方法

二、使用步骤

1.引入库

代码如下(示例):

'''
只执行pytest,会查找当前目录及子目录下test_*.py和*_test.py文件
如果想只执行某个文件,可以pytest start.py
加上-q就是显示简单的结果pytest -q start.py
'''
def func(x):
    return x+1
def test_answer():
    assert func(3) == 5

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x
    def test_two(self):
        x = 'hello'
        assert hasattr(x,"check")
        

##2.断言引发的异常判断

import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

以“安静”报告模式执行测试功能:

pytest -q test_sysexit.py,

输出为:

.                                                                                         [100%]
1 passed in 0.01s

2.pytest执行标准

python测试发现的约定:

  • 如果没有指定参数,集合从testpaths或者当前目录执行。或者,命令行参数可以用于目录、文件名或节点ID的任意组合。
  • 递归到目录中,除非匹配norecursedirs
  • 目录中搜索tets_.py或者_test.py文件 ,由其导入test package name
  • 从文件中收集测试项
  • test在类外加前缀的测试函数或者方法,test内置前缀测试函数或方法Test带前缀的测试类(不包含__init__方法)

一个类中的多个测试分组

def func(x):
    return x+1
def test_answer():
    assert func(3) == 5

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x
    def test_two(self):
        x = 'hello'
        assert hasattr(x,"check")

测试:

pytest -q test_class.py

输出结果:

D:\pytest\exe\test\learn>pytest -q test_class.py
F.F                                                                                       [100%]
==========================================
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值