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其餘的精彩之處我再來分享。

參考文檔

相關文章
相關標籤/搜索