pytest使用allure測試報告


前言

最近通過群友了解到了allure這個報告,開始還不以為然,但還是逃不過真香定律。

經過試用之后,發現這個報告真的很好,很適合自動化測試結果的展示。下面說說我的探索歷程吧。

  • 選用的項目為Selenium自動化測試Pytest框架實戰,在這個項目的基礎上說allure報告。

allure安裝

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

MacOS直接使用homebrew工具執行 brew install allure 即可安裝,不用配置下載包和配置環境

在GitHub下載安裝程序https://github.com/allure-framework/allure2/releases

但是由於GitHub訪問太慢,我已經下載好並放在了群文件里面

下載完成后解壓放到一個文件夾。我的路徑是D:\Program Files\allure-2.13.3

然后配置環境變量: 在系統變量path中添加D:\Program Files\allure-2.13.3\bin,然后確定保存。

打開cmd,輸入allure,如果結果顯示如下則表示成功了:

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初體驗

改造一下之前的測試用例代碼

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import re
import pytest
import allure
from utils.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', './allure'])
    os.system('allure serve allure')

然后運行一下:

注意:如果你使用的是pycharm編輯器,請跳過該運行方式,直接使用.bat.sh的方式運行

***


------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\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

命令行會出現如上提示,接着瀏覽器會自動打開:

QQ截圖20200618225326.png

點擊左下角En即可選擇切換為中文。

QQ截圖20200618225554.png

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

allure裝飾器介紹

image

報告的生成和展示

剛才的兩個命令:

  • 生成allure原始報告到report/allure目錄下,生成的全部為json或txt文件。
pytest TestCase/test_search.py --alluredir ./allure
  • 在一個臨時文件中生成報告並啟動瀏覽器打開
allure serve allure

但是在關閉瀏覽器之后這個報告就再也打不開了。不建議使用這種。

所以我們必須使用其他的命令,讓allure可以指定生成的報告目錄。

我們在項目的根目錄中創建run_case.py文件,內容如下:

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

WIN = sys.platform.startswith('win')


def main():
   """主函數"""
   steps = [
       "venv\\Script\\activate" if WIN else "source venv/bin/activate",
       "pytest --alluredir allure-results --clean-alluredir",
       "allure generate allure-results -c -o allure-report",
       "allure open allure-report"
   ]
   for step in steps:
       subprocess.run("call " + step if WIN else step, shell=True)


if __name__ == "__main__":
   main()

命令釋義:

1、使用pytest生成原始報告,里面大多數是一些原始的json數據,加入--clean-alluredir參數清除allure-results歷史數據。

pytest --alluredir allure-results --clean-alluredir
  • --clean-alluredir 清除allure-results歷史數據

2、使用generate命令導出HTML報告到新的目錄

allure generate allure-results -o allure-report
  • -c 在生成報告之前先清理之前的報告目錄
  • -o 指定生成報告的文件夾

3、使用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文件中添加一個截圖目錄和截圖文件的配置。

+++

class ConfigManager(object):

		...
    
    @property
    def screen_path(self):
        """截圖目錄"""
        screenshot_dir = os.path.join(self.BASE_DIR, 'screen_capture')
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
        now_time = dt_strftime("%Y%m%d%H%M%S")
        screen_file = os.path.join(screenshot_dir, "{}.png".format(now_time))
        return now_time, screen_file
	
  	...
+++

然后我們修改項目目錄中的conftest.py

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import base64
import pytest
import allure
from py.xml import html
from selenium import webdriver

from config.conf import cm
from common.readconfig import ini
from utils.times import timestamp
from utils.send_mail import send_report

driver = None


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

    def fn():
        driver.quit()

    request.addfinalizer(fn)
    return driver


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    """
    當測試失敗的時候,自動截圖,展示到html報告中
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)
    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


def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('用例名稱'))
    cells.insert(2, html.th('Test_nodeid'))
    cells.pop(2)


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)


def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('通過的用例未捕獲日志輸出.', class_='empty log'))


def pytest_html_report_title(report):
    report.title = "pytest示例項目測試報告"


def pytest_configure(config):
    config._metadata.clear()
    config._metadata['測試項目'] = "測試百度官網搜索"
    config._metadata['測試地址'] = ini.url


def pytest_html_results_summary(prefix, summary, postfix):
    # prefix.clear() # 清空summary中的內容
    prefix.extend([html.p("所屬部門: XX公司測試部")])
    prefix.extend([html.p("測試執行人: 隨風揮手")])


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """收集測試結果"""
    result = {
        "total": terminalreporter._numcollected,
        'passed': len(terminalreporter.stats.get('passed', [])),
        'failed': len(terminalreporter.stats.get('failed', [])),
        'error': len(terminalreporter.stats.get('error', [])),
        'skipped': len(terminalreporter.stats.get('skipped', [])),
        # terminalreporter._sessionstarttime 會話開始時間
        'total times': timestamp() - terminalreporter._sessionstarttime
    }
    print(result)
    if result['failed'] or result['error']:
        send_report()


def _capture_screenshot():
    """截圖保存為base64"""
    now_time, screen_file = cm.screen_path
    driver.save_screenshot(screen_file)
    allure.attach.file(screen_file,
                       "失敗截圖{}".format(now_time),
                       allure.attachment_type.PNG)
    with open(screen_file, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()

來看看我們修改了什么:

  • 我們修改了_capture_screenshot函數

在里面我們使用了webdriver截圖生成文件,並使用allure.attach.file方法將文件添加到了allure測試報告中。

並且我們還返回了圖片的base64編碼,這樣可以讓pytest-html的錯誤截圖和allure都能生效。

運行一次得到兩份報告,一份是簡單的一份是好看內容豐富的。

現在我們在測試用例中構建一個預期的錯誤測試一個我們的這個代碼。


修改test_002測試用例

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

運行一下:

QQ截圖20200618234740.png

可以看到allure報告中已經有了這個錯誤的信息。

再來看看pytest-html中生成的報告:

image-20201201164954431

可以看到兩份生成的報告都附帶了錯誤的截圖,真是魚和熊掌可以兼得呢。

好了,到這里可以說allure的報告就先到這里了,以后發現allure其他的精彩之處我再來分享。

參考文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM