前言
什么是元數據?元數據是關於數據的描述,存儲着關於數據的信息,為人們更方便地檢索信息提供了幫助。
pytest 框架里面的元數據可以使用 pytest-metadata 插件實現。文檔地址https://pypi.org/project/pytest-metadata/
pytest-metadata 環境准備
使用 pip 安裝 pytest-metadata
pip install pytest-metadata
查看 pytest 元數據
使用pytest 執行用例的時候加上 -v 參數(或--verbose),在控制台輸出報告的頭部就會輸出元數據(metadata)
>pytest --verbose
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.5.4, pluggy-0.13.1 -- e:\python36\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.6.0', 'Platform': 'Windows-10-10.0.17134-SP0', 'Packages': {'pytest': '4.5.0', 'py': '1.5.4', 'pluggy': '0.13.1'}, 'Plugins': {'allure-pytest': '2.8.6', 'PyTestReport': '0.1.9.3', 'assume': '2.2.1', 'forked': '0.2', 'html': '1.19.0', 'metadata': '1.7.0', 'ordering': '0.6', 'repeat': '0.7.0', 'rerunfailures': '8.0', 'xdist': '1.23.2'}, 'JAVA_HOME': 'D:\\java\\jdk1.8'}
rootdir: D:\soft\code\pytest_api_2020_03
plugins: allure-pytest-2.8.6
可以獲取到的元數據
| Key | Description | Example |
|---|---|---|
| Python | Python 版本 | '3.6.0' |
| Platform | 運行平台 | 'Windows-10-10.0.17134-SP0' |
| Packages | pytest 包相關信息 | {'pytest': '4.5.0', 'py': '1.5.4', 'pluggy': '0.13.1'} |
| Plugins | pytest 插件 | {'allure-pytest': '2.8.6', 'PyTestReport': '0.1.9.3'} |
| JAVA_HOME | JAVA環境變量 | 'D:\java\jdk1.8' |
元數據是以鍵值對(key-value)方式存儲的
添加 metadata
我們可以在命令行用 --metadata 參數添加鍵值對(key, value)的元數據。
比如當我們完成了一個項目,需要添加作者信息,於是就可以添加元數據
pytest --metadata auther yoyo
如果需要添加多個元數據,可以使用多次 --metadata 參數添加
pytest --metadata auther yoyo --metadata version v1.0
從文檔上看可以支持json格式,一次性傳多組元數據,使用--metadata-from-json,但我自己試了下,並不支持這個參數,這種方式可以忽略!
pytest --metadata-from-json '{"cat_says": "bring the cat nip", "human_says": "yes kitty"}'
pytest_metadata hook函數
在代碼里面也可以新增/修改/刪除 元數據,我們可以使用 pytest_metadata hook函數
import pytest
@pytest.mark.optionalhook
def pytest_metadata(metadata):
metadata.pop("password", None)
我們可以使用 metadata fixture,用於測試用例或fixture 訪問元數據(metadata)
def test_metadata(metadata):
assert 'metadata' in metadata['Plugins']
在插件里面訪問 metadata,可以在config對象使用 _metadata 屬性來新增/修改/刪除 元數據
def pytest_configure(config):
if hasattr(config, '_metadata'):
config._metadata['foo'] = 'bar'
插件集成
下面是一個方便的插件列表,這些插件要么讀取元數據,要么對元數據有貢獻:
- pytest-base-url - Adds the base URL to the metadata.
- pytest-html - Displays the metadata at the start of each report.
- pytest-selenium - Adds the driver, capabilities, and remote server to the metadata.
pytest.ini 管理元數據
如果新增的元數據較多,在命令行輸入不太方便,可以在pytest.ini配置里面配置你的項目元數據
# pytest.ini
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
[pytest]
addopts = -v
--html=report.html
--self-contained-html
--metadata auther yoyo
--metadata version v1.0
