Pytest笔记:安装&简介

安装


通过 pip 安装 pytest

$ pip install -U pytest

检查是否安装成功

$ pytest --version

编辑测试文件

# test_sample.py
def func(x):
    return x + 1

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

执行测试文件

pytest test_sample.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 1 item

test_sample.py F

================================== FAILURES ===================================
_________________________________ test_answer _________________________________

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

test_sample.py:7: AssertionError
========================== 1 failed in 0.18 seconds ===========================

到这里 pytest 环境安装完成,正如上面你看到的,我们可以随时使用 assert 来进行测试的断言

简介


运行多个测试

pytest 默认会执行当前目录和子目录下的所有 test_*.py 或 *_test.py 测试文件

可使用 raises 断言特定 Exception

编辑测试代码

# test_sysexit.py
import pytest

def f():
    raise SystemExit(1)

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

执行测试代码

pytest test_sysexit.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 1 item

test_sysexit.py .

========================== 1 passed in 0.03 seconds ===========================

通过Class组合测试用例

该方式可用于测试一个模块或逻辑相关联的不同模块,编写实例测试代码

# 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 test_class.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: E:\test, inifile:
collected 2 items

test_class.py .F

================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________

self = <test_class.TestClass object at 0x03DFA6D0>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

test_class.py:9: AssertionError
===================== 1 failed, 1 passed in 0.18 seconds ======================

请求一个唯一的临时目录

功能测试中,我们往往需要创建一些临时文件或目录,用于程序的测试,pytest 提供一个内置的 fixtures/function 参数来请求一些随机的资源,例如一个临时目录,下面我们看一个测试用例代码

# test_tmpdir.py
def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0  # 报错中断

上面的代码中我们使用了参数 tmpdir,pytest 会注意到这个参数,并调用一个 fixture factory 来创建需要的这个临时目录资源

pytest -q test_tmpdir.py
F
================================== FAILURES ===================================
_______________________________ test_needsfiles _______________________________

tmpdir = local('C:\\Users\\test\\AppData\\Local\\Temp\\pytest-of-test\\pytest-0\\test_needsfiles0')

    def test_needsfiles(tmpdir):
        print(tmpdir)
>       assert 0  
E       assert 0

test_tmpdir.py:4: AssertionError
---------------------------- Captured stdout call -----------------------------
C:\Users\test\AppData\Local\Temp\pytest-of-test\pytest-0\test_needsfiles0
1 failed in 0.12 seconds

通过查看执行结果,pytest 为我们穿件了临时目录 test_needsfiles0

查看全部预置的 pytest fixtures: explicit, modular, scalable

pytest --fixtures
============================= test session starts =============================
cache
    Return a cache object that can persist state between testing sessions.

    cache.get(key, default)
    cache.set(key, value)

    Keys must be a ``/`` separated value, where the first part is usually the
    name of your plugin or application to avoid clashes with other cache users.

    Values can be any object handled by the json stdlib module.
capsys
    Enable capturing of writes to sys.stdout/sys.stderr and make
    captured output available via ``capsys.readouterr()`` method calls
    which return a ``(out, err)`` tuple.
capfd
    Enable capturing of writes to file descriptors 1 and 2 and make
    captured output available via ``capfd.readouterr()`` method calls
    which return a ``(out, err)`` tuple.
doctest_namespace
    Inject names into the doctest namespace.
pytestconfig
    the pytest config object with access to command line opts.
record_xml_property
    Add extra xml properties to the tag for the calling test.
    The fixture is callable with ``(name, value)``, with value being automatically
    xml-encoded.
monkeypatch
    The returned ``monkeypatch`` fixture provides these
    helper methods to modify objects, dictionaries or os.environ::

        monkeypatch.setattr(obj, name, value, raising=True)
        monkeypatch.delattr(obj, name, raising=True)
        monkeypatch.setitem(mapping, name, value)
        monkeypatch.delitem(obj, name, raising=True)
        monkeypatch.setenv(name, value, prepend=False)
        monkeypatch.delenv(name, value, raising=True)
        monkeypatch.syspath_prepend(path)
        monkeypatch.chdir(path)

    All modifications will be undone after the requesting
    test function or fixture has finished. The ``raising``
    parameter determines if a KeyError or AttributeError
    will be raised if the set/deletion operation has no target.
recwarn
    Return a WarningsRecorder instance that provides these methods:

    * ``pop(category=None)``: return last warning matching the category.
    * ``clear()``: clear list of warnings

    See http://docs.python.org/library/warnings.html for information
    on warning categories.
tmpdir_factory
    Return a TempdirFactory instance for the test session.
tmpdir
    返回一个临时目录路径对象,这个对象在每个方法调用时都是唯一的,
    该目录作为临时目录根目录下的子目录,返回的对象是 `py.path.local`_
    path 对象

======================== no tests ran in 0.13 seconds =========================
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,238评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,998评论 6 342
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,257评论 2 33
  • 我在等待着光明 却又无法什么都不做 于是 你便瞧见了在黑暗中跌跌撞撞、寻寻觅觅的我
    耄耋小生阅读 289评论 2 2
  • 文章概要:免费公交车将市民表面的出行成本降到0,对于一般市民来说是难得的好事。但这篇文章的读者们,你们的时间和注意...
    御小灵阅读 884评论 0 2