pytest文档43-元数据使用(pytest-metadata)

时间:2022-07-22
本文章向大家介绍pytest文档43-元数据使用(pytest-metadata),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

什么是元数据?元数据是关于数据的描述,存储着关于数据的信息,为人们更方便地检索信息提供了帮助。 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:python36python.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:softcodepytest_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:javajdk1.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