pytest——01 入门

安装及入门

Python支持版本: Python 2.6,2.7,3.3,3.4,3.5,Jython,PyPy-2.3

支持的平台: Unix/Posix and Windows

PyPI包名: pytest

依赖项: py,colorama (Windows)

创建你的第一个测试用例

只需要4行代码即可创建一个简单的测试用例:

# test_sample.py文件内容
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

现在你可以执行一下这个测试用例:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y,pytest-3.x.y,py-1.x.y,pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR,inifile:
collected 1 item

test_sample.py F                                                     [100%]

================================= FAILURES =================================
_______________________________ test_answer ________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================

执行多条测试用例

pytest命令会执行当前目录及子目录下所有test_*.py*_test.py格式的文件。一般来说,用例需要遵循标准的测试发现规则。

断言抛出了指定异常

使用raise可以在相应代码的抛出的指定异常:

# test_sysexit.py文件内容
import pytest
def f():
    raise SystemExit(1)

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

使用类组织多条测试用例

# test_class.py文件内容
class TestClass(object):
    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  运行该命令

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值