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對應的值

cache的使用場景

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

import pytest
"""
作者:上海-悠悠
python QQ交流群:730246532
聯系微信/QQ: 283340479
"""

@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+yaml 框架使用與開發》https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
報名咨詢wx:283340479 (已報名的同學學習過程中有問題,都可以協助解決)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM