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

執(zhí)行測試文件

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 環(huán)境安裝完成,正如上面你看到的,我們可以隨時(shí)使用 assert 來進(jìn)行測試的斷言

簡介


運(yùn)行多個測試

pytest 默認(rèn)會執(zhí)行當(dāng)前目錄和子目錄下的所有 test_*.py 或 *_test.py 測試文件

可使用 raises 斷言特定 Exception

編輯測試代碼

# test_sysexit.py
import pytest

def f():
    raise SystemExit(1)

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

執(zhí)行測試代碼

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組合測試用例

該方式可用于測試一個模塊或邏輯相關(guān)聯(lián)的不同模塊,編寫實(shí)例測試代碼

# 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')

執(zhí)行測試

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 ======================

請求一個唯一的臨時(shí)目錄

功能測試中,我們往往需要創(chuàng)建一些臨時(shí)文件或目錄,用于程序的測試,pytest 提供一個內(nèi)置的 fixtures/function 參數(shù)來請求一些隨機(jī)的資源,例如一個臨時(shí)目錄,下面我們看一個測試用例代碼

# test_tmpdir.py
def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0  # 報(bào)錯中斷

上面的代碼中我們使用了參數(shù) tmpdir,pytest 會注意到這個參數(shù),并調(diào)用一個 fixture factory 來創(chuàng)建需要的這個臨時(shí)目錄資源

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

通過查看執(zhí)行結(jié)果,pytest 為我們穿件了臨時(shí)目錄 test_needsfiles0

查看全部預(yù)置的 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
    返回一個臨時(shí)目錄路徑對象,這個對象在每個方法調(diào)用時(shí)都是唯一的,
    該目錄作為臨時(shí)目錄根目錄下的子目錄,返回的對象是 `py.path.local`_
    path 對象

======================== no tests ran in 0.13 seconds =========================
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評論 6 342
  • linux資料總章2.1 1.0寫的不好抱歉 但是2.0已經(jīng)改了很多 但是錯誤還是無法避免 以后資料會慢慢更新 大...
    數(shù)據(jù)革命閱讀 13,236評論 2 33
  • 我在等待著光明 卻又無法什么都不做 于是 你便瞧見了在黑暗中跌跌撞撞、尋尋覓覓的我
    耄耋小生閱讀 307評論 2 2
  • 文章概要:免費(fèi)公交車將市民表面的出行成本降到0,對于一般市民來說是難得的好事。但這篇文章的讀者們,你們的時(shí)間和注意...
    御小靈閱讀 968評論 0 2

友情鏈接更多精彩內(nèi)容