2021-10-25 Pytest-html Allure pytest_cov详解

pytest_html 测试报告

import pytest
"""
 使用pytest编写用例,必须遵守以下规则:
    (1)测试文件名必须以"test_"开头或者"_test"结尾(如:test_ab.py)
  (2)测试方法必须以"test_"开头。
  (3)测试类命名以"Test"开头。
"""

"""
@pytest.fixture(scope='')
    function:每个test都运行,默认是function的scope
    class:每个class的所有test只运行一次
    module:每个module的所有test只运行一次
    session:每个session只运行一次
"""

@pytest.fixture(scope='function')
def setup_function(request):
    def teardown_function():
        print("teardown_function called.")
    request.addfinalizer(teardown_function)
    print('setup_function called.')

@pytest.mark.website
def test_1(setup_function):
    print('Test_1 called.')

@pytest.fixture(scope='module')
def setup_module(request):
    def teardown_module():
        print("teardown_module called.")
    request.addfinalizer(teardown_module)
    print('setup_module called.')

def test_2(setup_module):
    print('Test_2 called.')

def test_3(setup_module):
    print('Test_3 called.')
    assert 2==1+1
if __name__ == '__main__':
"""
    Console参数介绍
        -v 用于显示每个测试函数的执行结果
        -q 只显示整体测试结果
        -s 用于显示测试函数中print()函数输出
        -x, --exitfirst, exit instantly on first error or failed test
        -h 帮助
"""
"""
    报告参数 _report.html   ./_report.html   ./report/_report.html    ../report/_report.html    #./当前文件夹,../上个文件夹
        --resultlog=./log.txt
        --junitxml=./log.xml
        --pastebin=all
        --html=./report.html
"""

"""
    生成allure报告(路径/严格按找下面)
    os.system('pytest testCase/demo1.py --alluredir=htmlallure/')   #生成allure文件
    os.system('allure serve htmlallure/')  #生成在线报告
    os.system('allure generate htmlallure/ -o htmlallure/html') #生成离线报告

    os.system('pytest testCase/demo1.py --alluredir=report/htmlallure/')   #生成allure文件
    os.system('allure serve report/htmlallure/')  #生成在线报告
    os.system('allure generate report/htmlallure/ -o report/htmlallure/html') #生成离线报告
"""

pytest_allure 测试报告配置

0. allure 命令行参数

allure 命令的语法格式
allure [options][command][command options]
options列表

  Options:
    --help 命令行帮助文档
    -q, --quiet
      切换至安静模式
      Default: false
    -v, --verbose
      切换至冗长模式
      Default: false
    --version
      版本信息
      Default: false

command列表

generate
serve
open
plugin
  • generate 命令行参数
    作用:生成allure的html报告
    语法格式: generate [options] allure 结果目录
    注:allure 结果目录就是运行 pytest 命令,–alluredir 跟的那个目录
    pytest -sq --alluredir= ./allure
    命令选项选项描述-c, –clean删除 allure 报告生成的目录 就是 -o 跟的目录–configallure 命令行配置路径,如指定会覆盖 –profile 和 –configDirectory–configDirectoryallure 命令行配置目录–profileallure 命令行配置文件-o, –report-dir, –output1. 生成allure报告目录 2. 默认 执行命令当前目录下的 allure-report 3. 没有目录自动生成
  • open 命令行参数
    作用 打开生成的 allure 报告,就是打开 generate 命令生成的报告
    语法格式 open [options] allure报告目录注:allure 报告目录就是运行 allure generate 命令,-o 跟的那个目录 allure generate -o ./allure-report
    命令选项选项描述-h, –host该 host 将用于启动报告的web服务器-p, –port该 port 将用于启动报告的web服务器
  • serve 命令行参数
    作用 启动 allure 服务,打开 allure 报告
    语法格式 serve [options] allure 结果目录
    注:allure 结果目录就是运行 pytest 命令,–alluredir 跟的那个目录 pytest -sq --alluredir= ./allure
    命令选项选项描述–configallure 命令行配置路径,如指定会覆盖 –profile 和 –configDirectory–configDirectoryallure 命令行配置目录–profileallure 命令行配置文件-h, –host该 host 将用于启动报告的web服务器-p, –port该 port 将用于启动报告的web服务器

浏览器打开 allure 报告的两种方式

  • allure serve标准写法

pytest -sq --alluredir=./allure

allure serve ./allure

  • allure generate + allure open标准写法

pytest -sq --alluredir=./allure

allure generate -c -o ./allure-report ./allure

allure open ./allure-report

1. Allure 测试报告装饰器

使用方法参数值参数说明@allure.epic()epic描述定义项目、当有多个项目是使用。往下是feature@allure.feature()模块名称用例按照模块区分,有多个模块时给每个起名字@allure.story()用例名称一个用例的描述@allure.title(用例的标题)用例标题一个用例标题@allure.testcase()测试用例的连接地址自动化用例对应的功能用例存放系统的地址@allure.issue()缺陷地址对应缺陷管理系统里边的缺陷地址@allure.description()用例描述对测试用例的详细描述@allure.step()操作步骤测试用例的操作步骤@allure.severity()用例等级blocker 、critical 、normal 、minor 、trivial@allure.link()定义连接用于定义一个需要在测试报告中展示的连接@allure.attachment()附件添加测试报告附件

2. 为 Allure 测试报告添加 Environment

默认情况下,Allure 生成的报告是不带 Environment 信息的

2021-10-25 Pytest-html Allure pytest_cov详解
首先,执行完测试用例后,创建文件 environment.properties,其内容格式如下:
Browser=Chrome

Browser.Version=86.0.4240

Environment=QA

注意:这里为 key=value 的格式。可以通过编写相关函数动态获取每次执行时的真实值,然后写入 environment.properties 文件

然后,把文件 environment.properties 拷贝到你在执行测试用例时设置的 allure 报告目录下最后,执行如下命令: allure serve ${allure_results_filePath}

3. 为 Allure 测试报告增加错误类型

在默认情况下,Allure 仅仅会列出以下两种类型的 Categories。

  • Product Defects(failed tests)表示真正的测试执行失败,如果 Categories 里出现这个错误,通常表明测试用例最后的输出跟期望不符合,有 Bug 出现。
  • Test Defects(broken tests)表示测试用例本身有问题导致的错误,如果 Categories 里出现这个错误,通常表明测试用例在执行过程中出错了,需要我们进一步调查原因。

首先,创建名称为 categories.json 的文件,内容如下:

[
    {
        "name": "Ignored tests",
        "matchedStatuses": [
            "skipped"
        ]
    },
    {
        "name": "Infrastructure problems",
        "matchedStatuses": [
            "broken",
            "failed"
        ],
        "messageRegex": ".*bye-bye.*"
    },
    {
        "name": "Outdated tests",
        "matchedStatuses": [
            "broken"
        ],
        "traceRegex": ".*FileNotFoundException.*"
    },
    {
        "name": "Product defects",
        "matchedStatuses": [
            "failed"
        ]
    },
    {
        "name": "Test defects",
        "matchedStatuses": [
            "broken"
        ]
    }
]

然后,把文件 categories.json 拷贝到你在执行测试用例时设置的 allure 报告目录下 最后,执行如下命令: allure serve ${allure_results_filePath}

Categories 里出现了我们刚刚配置的值 Ignored tests:

4. 显示历次运行的 trends

默认生成的 Allure 报告不包括历次运行信息 Trends,如果想添加历次运行信息到Trends,步骤如下。

执行完测试后,不要执行 allure serve 命令,转而执行 allure generate。
allure generate ${allure_results_filePath}

这个操作会生成一个新的文件夹,名为 allure-report。拷贝 allure-report 文件夹下的 history 文件夹,及其子文件夹到 allure_results 这个目录中。

在新的一次测试执行后执行 allure serve,即可把历史记录带到 Allure 报告中。

allure serve ${allure_results_filePath}

执行完后,打开 Allure 测试报告,你将看到 Trend 的内容

5. 为 Allure 测试报告添加执行人

默认的 Allure 测试报告也不显示 Executor,这是因为 Executor 通常是由 Builder 自动生成的,比如通过 Jenkins pluginAllure Jenkins Plugin 来生成。

关于如何使用 Allure Jenkins Plugin 配置 Allure,当然你也可以自己生成, 首先创建名称为executor.json 的文件,内容如下:

{
  "name": "iTesting",
  "type": "jenkins",
  "url": "http://helloqa.com",
  "buildOrder": 3,
  "buildName": "allure-report_deploy#1",
  "buildUrl": "http://helloqa.com#1",
  "reportUrl": "http://helloqa.com#1/AllureReport",
  "reportName": "iTesting Allure Report"
}

然后,拷贝 executor.json 到 allure_results 这个目录中去。

最后, 执行如下命令即可: allure serve ${allure_results_filePath}

执行完后,打开 Allure 测试报告,你将看到 Executor 的信息:

6. Allure 测试报告实现错误自动截图

使用 Allure 自动实现错误截图,可以参考 定义的如下函数:

@pytest.hookimpl(tryfirst=True, hookwrapper=True)

def pytest_runtest_makereport(item, call):

"""

      本hook用于制作测试报告

      :param item:测试用例对象

      :param call:测试用例的测试步骤

              执行完常规钩子函数返回的report报告有个属性叫report.when

                when='setup' 代表返回setup 的执行结果

                when='call' 代表返回call 的执行结果

      :return:

"""

    outcome = yield

    rep = outcome.get_result()

    if (rep.when == "call" or rep.when == 'setup') and (rep.failed or rep.skipped):

        try:

            if "initial_browser" in item.fixturenames:

                web_driver = item.funcargs['initial_browser']

            else:

                return

            allure.attach(web_driver.get_screenshot_as_png(), name="wrong picture",

                          attachment_type=allure.attachment_type.PNG)

        except Exception as e:

            print("failed to take screenshot".format(e))

首先,通过如下命令运行所有测试:

pytest -s -v --alluredir=./allure_results --flag --browser chrome

执行成功后,通过如下命令打开测试报告:

allure serve ./allure_results

2021-10-25 Pytest-html Allure pytest_cov详解

pytest_cov 覆盖率配置

case目录下新建 .coveragerc

[run]
branch = True
omit =

    */test_*.py
    */*_test.py

[report]

precision = 2

exclude_lines =

    if __name__ == .__main__.:

[html]

directory = coverage_html_report

'''输出,测试文件目录,报告样式, 配置筛选文件路径'''
pytest.main(['-sq', '--cov=./', '--cov-report=html:./reports/coverage', '--cov-report=xml:reports/coverage.xml', '--cov-config=./cov/coveragerc'])
pytest.main(['-sq','./xdist/','--html=_report.html','-n 3'])

Original: https://blog.csdn.net/qq_37497758/article/details/120951846
Author: 测试的菜鸟
Title: 2021-10-25 Pytest-html Allure pytest_cov详解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/774442/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球