不想在测试代码里加标签,想通过yaml文件加标签实现类似的功能

如果你希望通过yaml文件中的标签来选择性运行测试用例,而不在测试代码中加标签,可以通过自定义pytest插件来实现。下面是一个简单的步骤指南:

  1. 创建一个pytest插件,例如"pytest_custom_plugin.py",代码示例如下:
import pytest
import yaml

def pytest_addoption(parser):
    parser.addoption("--tagfile", action="store", help="path to the tag file")

def pytest_collection_modifyitems(config, items):
    tag_file = config.getoption("--tagfile")
    with open(tag_file, 'r') as file:
        tags = yaml.safe_load(file)
    selected_tags = tags.get('tags', [])

    deselected_items = []
    for item in items:
        item_tags = set(item.keywords.keys())
        if not item_tags.intersection(selected_tags):
            deselected_items.append(item)
    
    for item in deselected_items:
        items.remove(item)

  1. 在test_tags.yaml文件中定义要选择的标签,例如:
tags:
  - smoke
  1. 运行pytest命令时,指定自定义的插件和标签文件,例如:
pytest --tagfile test_tags.yaml

这样就可以根据yaml文件中定义的标签选择性地运行测试用例了。这种方法避免了在测试代码中加标签,使得逻辑更加清晰。希望以上信息对你有所帮助,如果还有其他问题,请随时提出。