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 =========================
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容

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