junit 如何在PyTest生成的XML中指定自定义测试用例名称

dfty9e19  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(105)

我正在使用Python运行一个测试用例并生成一个XML输出。我想在XML输出中为testcase元素指定一个自定义名称,而不是使用默认名称(即测试用例的函数名称)。我如何在Python中做到这一点,实现它的正确方法是什么
示例:

def test_case_blalbla():
    assert True

生成以下XML:

<?xml version="1.0" encoding="utf-8"?>

<testsuites>
<testsuite name="pytest" errors="0" failures="0" skipped="0" tests="1" time="0.041"
           timestamp="2022-12-29T17:20:24.662571" hostname="my_hostname">
    <testcase classname="my_classname" name="test_case_balbla"
              time="0.021"/>
</testsuite>

我想要

<testcase classname="my_classname" name="test_case_blabla"
              time="0.021"/>

成为

<testcase classname="my_classname" name="My test case blalbla"
              time="0.021"/>
3npbholx

3npbholx1#

您可以尝试使用以下代码在测试收集阶段修改节点ID的名称:

def pytest_collection_modifyitems(items):
    for item in items:
        path = item.nodeid.split("::")[0]
        initial_name = item.nodeid.split("::")[1].replace("test_", "")
        name = initial_name.capitalize().replace("_", " ") # You can name this however you like
        item._nodeid = f"{path}::{name}"
  • 但要小心,因为这可能会带来意想不到的副作用。在我的情况下,它工作得很好。*
    编辑-更好的选择

来自pytest文档:有一个名为record_xml_attribute的内置fixture,可用于更改/覆盖XML标记的 attributes。通过这种方式,您可以更改“name”属性并实现您的目标。例如:

@pytest.fixture()
def change_testcase_name(record_xml_attribute):
    record_xml_attribute("name", "My new test case name")

如果你想在一个钩子中使用这个fixture,你可以这样调用它(钩子需要访问request对象或任何相关的东西):

record_xml_attribute = request.getfixturevalue("record_xml_attribute")
record_xml_attribute("name", "My new test case name")

相关问题