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 运行该命令

Original: https://blog.csdn.net/zangba9624/article/details/114533356
Author: 迷茫小渣渣
Title: pytest——01 入门

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/776861/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球