天天看點

pytest文檔79 - 内置 fixtures 之 cache 寫入和讀取緩存資料

前言

pytest測試用例之間的參數如何傳遞?如在前置操作中生成了一個資料id,在測試用例需要引用,或者用例執行完成後需要在後置操作中删除。

還有很多同學經常問到的case1 生成了資料a,在case2中引用這個值。這些在用例執行過程中生成的資料可以用cache緩存來解決。

内置cache fixture

cache 是一個可以在測試會話之間保持狀态的緩存對象。

@pytest.fixture
def cache(request):
    """
    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.
    """
    return request.config.cache
           

cache是Cache類的一個執行個體對象

  • mkdir 建立一個檔案夾
  • set(key: str, value: object) 設定一個cache值
  • get(key: str, default) 得到key對應的值
pytest文檔79 - 内置 fixtures 之 cache 寫入和讀取緩存資料

cache的使用場景

場景1:目前置操作生成一個id值,在用例中擷取這個id

import pytest


@pytest.fixture()
def create_id(cache):
    """取值生成一個id"""
    id = "yoyo_10086"
    cache.set("id", id)
    yield id


def test_1(cache, create_id):
    # 方式1: cache擷取
    get_id = cache.get("id", None)
    print("擷取到的id: {}".format(get_id))
    # 方式2:直接通過create_id 擷取傳回值
    print("create_id fixture return: {}".format(create_id))
           

場景2:執行用例後生成一個sp_id,後置操作需要清理資料

import pytest


@pytest.fixture()
def delete_sp(cache):
    """後置處理"""
    yield
    # 先擷取用例執行後得到的sp_id
    sp_id = cache.get("sp_id", None)
    print("後置處理得到值: {}".format(sp_id))


def test_2(cache, delete_sp):
    # 執行用例後生成sp_id
    sp_id = "yy_10086"
    cache.set("sp_id", sp_id)
           

用例之間的資料關聯

很多同學喜歡把用例當步驟去執行,執行a用例得到id參數,後面的用例需要前面得到的值,用cache也可以實作

import pytest


def test_1(cache):
    x = "yoyo_123"
    cache.set("id", x)
    print("case 1 create id : {}".format(x))


def test_2(cache):
    a = cache.get("id", None)
    print("case2 get id: {}".format(a))

           

這種用例之間存在依賴的,必須要保證用例1在用例2前面先執行

.pytest_cache 緩存檔案

在pycharm中右鍵執行,不會生成.pytest_cache 緩存檔案。

使用 pytest 指令行執行,會在項目目錄生成.pytest_cache 緩存檔案

> pytest
           

v目錄下的id檔案就是cache設定的緩存檔案,裡面寫的對應的value值

pytest文檔79 - 内置 fixtures 之 cache 寫入和讀取緩存資料

繼續閱讀