pytest使用allure测试报告

前言

最近经过群友了解到了allure这个报告,开始还不觉得然,但仍是逃不过真香定律。html

通过试用以后,发现这个报告真的很好,很适合自动化测试结果的展现。下面说说个人探索历程吧。node

  • 选用的项目为Selenium自动化测试Pytest框架实战,在这个项目的基础上说allure报告。

allure安装

  • 首先安装python的allure-pytest包
pip install allure-pytest
  • 而后安装allure的command命令行程序

在GitHub下载安装程序https://github.com/allure-framework/allure2/releasespython

可是因为GitHub访问太慢,我已经下载好并放在了群文件里面,请右上角扫描二维码加QQ群下载。git

下载完成后解压放到一个文件夹。个人路径是D:\Program Files\allure-2.13.3github

而后配置环境变量: 在系统变量path中添加D:\Program Files\allure-2.13.3\bin,而后肯定保存。web

打开cmd,输入allure,若是结果显示以下则表示成功了:shell

C:\Users\hoou>allure
Usage: allure [options] [command] [command options]
  Options:
    --help
      Print commandline help.
    -q, --quiet
      Switch on the quiet mode.
      Default: false
    -v, --verbose
      Switch on the verbose mode.
      Default: false
    --version
      Print commandline version.
      Default: false
  Commands:
    generate      Generate the report
      Usage: generate [options] The directories with allure results
        Options:
          -c, --clean
            Clean Allure report directory before generating a new one.
            Default: false
          --config
            Allure commandline config path. If specified overrides values from
            --profile and --configDirectory.
          --configDirectory
            Allure commandline configurations directory. By default uses
            ALLURE_HOME directory.
          --profile
            Allure commandline configuration profile.
          -o, --report-dir, --output
            The directory to generate Allure report into.
            Default: allure-report

    serve      Serve the report
      Usage: serve [options] The directories with allure results
        Options:
          --config
            Allure commandline config path. If specified overrides values from
            --profile and --configDirectory.
          --configDirectory
            Allure commandline configurations directory. By default uses
            ALLURE_HOME directory.
          -h, --host
            This host will be used to start web server for the report.
          -p, --port
            This port will be used to start web server for the report.
            Default: 0
          --profile
            Allure commandline configuration profile.

    open      Open generated report
      Usage: open [options] The report directory
        Options:
          -h, --host
            This host will be used to start web server for the report.
          -p, --port
            This port will be used to start web server for the report.
            Default: 0

    plugin      Generate the report
      Usage: plugin [options]
        Options:
          --config
            Allure commandline config path. If specified overrides values from
            --profile and --configDirectory.
          --configDirectory
            Allure commandline configurations directory. By default uses
            ALLURE_HOME directory.
          --profile
            Allure commandline configuration profile.

allure初体验

改造一下以前的测试用例代码json

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys

sys.path.append('.')
__author__ = '1084502012@qq.com'

import os
import re
import pytest
import allure
from tools.logger import log
from common.readconfig import ini
from page_object.searchpage import SearchPage


@allure.feature("测试百度模块")
class TestSearch:
    @pytest.fixture(scope='function', autouse=True)
    def open_baidu(self, drivers):
        """打开百度"""
        search = SearchPage(drivers)
        search.get_url(ini.url)

    @allure.story("搜索selenium结果用例")
    def test_001(self, drivers):
        """搜索"""
        search = SearchPage(drivers)
        search.input_search("selenium")
        search.click_search()
        result = re.search(r'selenium', search.get_source)
        log.info(result)
        assert result

    @allure.story("测试搜索候选用例")
    def test_002(self, drivers):
        """测试搜索候选"""
        search = SearchPage(drivers)
        search.input_search("selenium")
        log.info(list(search.imagine))
        assert all(["selenium" in i for i in search.imagine])


if __name__ == '__main__':
    pytest.main(['TestCase/test_search.py', '--alluredir', './report/allure'])
    os.system('allure serve report/allure')

而后运行一下:浏览器

***


------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\report\report.html -------------------------------- 

Results (12.97s):
       2 passed
Generating report to temp directory...
Report successfully generated to C:\Users\hoou\AppData\Local\Temp\112346119265936111\allure-report
Starting web server...
2020-06-18 22:52:44.500:INFO::main: Logging initialized @1958ms to org.eclipse.jetty.util.log.StdErrLog
Server started at <http://172.18.47.241:6202/>. Press <Ctrl+C> to exit

命令行会出现如上提示,接着浏览器会自动打开:session

QQ截图20200618225326.png

点击左下角En便可选择切换为中文。

QQ截图20200618225554.png

是否是很清爽很友好,比pytest-html更舒服。

allure装饰器介绍

image

报告的生成和展现

刚才的两个命令:

  • 生成allure原始报告到report/allure目录下,生成的所有为json或txt文件。
pytest TestCase/test_search.py --alluredir ./report/allure
  • 在一个临时文件中生成报告并启动浏览器打开
allure serve report/allure

可是在关闭浏览器以后这个报告就再也打不开了。不建议使用这种。

因此咱们必须使用其余的命令,让allure能够指定生成的报告目录。

咱们在项目根目录新建一个文件:

  • Windows系统建立run_win.sh文件。

  • MacOS或Linux系统run_mac.sh文件。

输入如下内容

pytest --alluredir allure-results --clean-alluredir

allure generate allure-results -c -o allure-report

allure open allure-report

命令释义:

一、使用pytest生成原始报告,里面大多数是一些原始的json数据,加入--clean-alluredir参数清除allure-results历史数据。

pytest --alluredir allure-results --clean-alluredir

二、使用generate命令导出HTML报告到新的目录

allure generate allure-results -o allure-report
  • -c 在生成报告以前先清理以前的报告目录
  • -o 指定生成报告的文件夹

三、使用open命令在浏览器中打开HTML报告

allure open allure-report

好了咱们执行一下该脚本命令。

Results (12.85s):
       2 passed
Report successfully generated to c:\Users\hoou\PycharmProjects\web-demotest\allure-report
Starting web server...
2020-06-18 23:30:24.122:INFO::main: Logging initialized @260ms to org.eclipse.jetty.util.log.StdErrLog
Server started at <http://172.18.47.241:7932/>. Press <Ctrl+C> to exit

QQ截图20200618233119.png

能够看到运行成功了。

在项目中的allure-report文件夹也生成了相应的报告。

QQ截图20200618233214.png

allure发生错误截图

上面的用例全是运行成功的,没有错误和失败的,那么发生了错误怎么样在allure报告中生成错误截图呢,咱们一块儿来看看。

首先咱们先在config/conf.py文件中添加一个截图目录配置。

+++

# 截图目录
SCREENSHOT_DIR = os.path.join(BASE_DIR, 'screen_capture')

+++

而后咱们修改项目目录中的conftest.py

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys

sys.path.append('.')
__author__ = '1084502012@qq.com'

import os
import base64
import pytest
import allure
from py._xmlgen import html
from selenium import webdriver
from config.conf import SCREENSHOT_DIR
from tools.times import datetime_strftime
from common.inspect import inspect_element
driver = None


@pytest.fixture(scope='session', autouse=True)
def drivers(request):
    global driver
    if driver is None:
        driver = webdriver.Chrome()
        driver.maximize_window()
    inspect_element()

    def fn():
        driver.quit()

    request.addfinalizer(fn)
    return driver


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候,自动截图,展现到html报告中
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            screen_img = _capture_screenshot()
            if screen_img:
                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra
        report.description = str(item.function.__doc__)
        report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('用例名称'))
    cells.insert(2, html.th('Test_nodeid'))
    cells.pop(2)


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(1, html.td(report.description))
    cells.insert(2, html.td(report.nodeid))
    cells.pop(2)


@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('经过的用例未捕获日志输出.', class_='empty log'))


def _capture_screenshot():
    '''
    截图保存为base64
    '''
    now_time = datetime_strftime("%Y%m%d%H%M%S")
    if not os.path.exists(SCREENSHOT_DIR):
        os.makedirs(SCREENSHOT_DIR)
    screen_path = os.path.join(SCREENSHOT_DIR, "{}.png".format(now_time))
    driver.save_screenshot(screen_path)
    allure.attach.file(screen_path, "测试失败截图...{}".format(
        now_time), allure.attachment_type.PNG)
    with open(screen_path, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()

来看看咱们修改了什么:

一、首先咱们修改了_capture_screenshot函数

在里面咱们使用了webdriver截图生成文件,并使用allure.attach.file方法将文件添加到了allure测试报告中。

而且咱们还返回了图片的base64编码,这样可让pytest-html的错误截图和allure都能生效。

运行一次获得两份报告,一份是简单的一份是好看内容丰富的。

二、接着咱们修改了hook函数pytest_runtest_makereport

更新了原来的判断逻辑。

如今咱们在测试用例中构建一个预期的错误测试一个咱们的这个代码。

修改test_002测试用例

assert not all(["selenium" in i for i in search.imagine])

运行一下:

QQ截图20200618234740.png

能够看到allure报告中已经有了这个错误的信息。

再来看看pytest-html中生成的报告:

QQ截图20200618234916.png

能够看到两份生成的报告都附带了错误的截图,真是鱼和熊掌能够兼得呢。

好了,到这里能够说allure的报告就先到这里了,之后发现allure其余的精彩之处我再来分享。

参考文档

相关文章
相关标签/搜索