前言
最近通过群友了解到了allure这个报告,开始还不以为然,但还是逃不过真香定律。
经过试用之后,发现这个报告真的很好,很适合自动化测试结果的展示。下面说说我的探索历程吧。
- 选用的项目为
Selenium自动化测试Pytest框架实战 ,在这个项目的基础上说allure报告。
allure安装
-
首先安装python的allure-pytest包
1pip install allure-pytest -
然后安装allure的command命令行程序
在GitHub下载安装程序https://github.com/allure-framework/allure2/releases
但是由于GitHub访问太慢,我已经下载好并放在了
群文件 里面,QQ群:299524235。
下载完成后解压放到一个文件夹。我的路径是
然后配置环境变量: 在系统变量
打开cmd,输入allure,如果结果显示如下则表示成功了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 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初体验
改造一下之前的测试用例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys sys.path.append('.') __author__ = '[email protected]' 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') |
然后运行一下:
1 2 3 4 5 6 7 8 9 10 11 12 | *** ------------------------------- 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 |
命令行会出现如上提示,接着浏览器会自动打开:
点击左下角
是不是很清爽很友好,比pytest-html更舒服。
allure装饰器介绍
报告的生成和展示
刚才的两个命令:
- 生成allure原始报告到report/allure目录下,生成的全部为json或txt文件。
1 | pytest TestCase/test_search.py --alluredir ./report/allure |
- 在一个临时文件中生成报告并启动浏览器打开
1 | allure serve report/allure |
但是在关闭浏览器之后这个报告就再也打不开了。不建议使用这种。
所以我们必须使用其他的命令,让allure可以指定生成的报告目录。
我们现在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys sys.path.append('.') __author__ = '[email protected]' import sys sys.path.append('.') import os from selenium.webdriver.common.by import By +++ # allure报告目录 ALLURE_REPORT = os.path.join(BASE_DIR, 'allure-report') # allure原始数据 ALLURE_RESULTS = os.path.join(BASE_DIR, 'allure-results') +++ |
我们在项目根目录新建一个文件:
-
Windows系统创建
run_win.sh 文件。 -
MacOS或Linux系统
run_mac.sh 文件。
输入以下内容
1 2 3 4 5 | pytest --alluredir allure-results allure generate allure-results -c -o allure-report allure open allure-report |
命令释义:
1、使用pytest生成原始报告,里面大多数是一些原始的json数据
1 | pytest --alluredir allure-results |
2、使用generate命令导出HTML报告到新的目录
1 | allure generate allure-results -o allure-report |
- -c 在生成报告之前先清理之前的报告目录
- -o 指定生成报告的文件夹
3、使用open命令在浏览器中打开HTML报告
1 | allure open allure-report |
好了我们执行一下该脚本命令。
1 2 3 4 5 6 | 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 |
可以看到运行成功了。
在项目中的allure-report文件夹也生成了相应的报告。
allure发生错误截图
上面的用例全是运行成功的,没有错误和失败的,那么发生了错误怎么样在allure报告中生成错误截图呢,我们一起来看看。
首先我们先在
1 2 3 4 5 6 | +++ # 截图目录 SCREENSHOT_DIR = os.path.join(BASE_DIR, 'screen_capture') +++ |
然后我们修改项目目录中的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys sys.path.append('.') __author__ = '[email protected]' 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;" ' \ 'οnclick="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() |
来看看我们修改了什么:
1、首先我们修改了_capture_screenshot函数
在里面我们使用了webdriver截图生成文件,并使用allure.attach.file方法将文件添加到了allure测试报告中。
并且我们还返回了图片的base64编码,这样可以让pytest-html的错误截图和allure都能生效。
运行一次得到两份报告,一份是简单的一份是好看内容丰富的。
2、接着我们修改了hook函数pytest_runtest_makereport
更新了原来的判断逻辑。
现在我们在测试用例中构建一个预期的错误测试一个我们的这个代码。
修改test_002测试用例
1 | assert not all(["selenium" in i for i in search.imagine]) |
运行一下:
可以看到allure报告中已经有了这个错误的信息。
再来看看pytest-html中生成的报告:
可以看到两份生成的报告都附带了错误的截图,真是鱼和熊掌可以兼得呢。
allure历史的原始数据清除
当我们继续用上面的命令执行生成allure好几次后,就会发现
而且在报告总显示的用例数和用例也有一些混乱,原因就是
我们在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys sys.path.append('.') import os import shutil from config.conf import ALLURE_RESULTS def clear_allure_results(): var = True for i in os.listdir(ALLURE_RESULTS): new_path = os.path.join(ALLURE_RESULTS, i) if os.path.isfile(new_path): os.remove(new_path) print("删除{}成功!".format(new_path)) var = False if var: print("没有数据可清理!") if __name__ == "__main__": clear_allure_results() |
这个就实现了历史数据的清理,我们把它的执行加载到脚本中。
1 2 3 4 5 6 7 | python tools/clear_log.py pytest --alluredir allure-results allure generate allure-results -c -o allure-report allure open allure-report |
我们把它放在第一行,确保不在生成报告后,才进行删除。
我们多执行几次,是不是
allure本地趋势图生成
在Jenkins持续集成中可以看到多次生成报告的趋势图,官方文档说明:
1 2 3 | 13.2.4。历史档案 从版本2开始,Allure支持报告[有关历史记录插件的更多信息]中的测试历史记录。在构建过程中生成每个报告时,Jenkins Allure插件都将尝试访问先前构建的工作目录,并将`allure-report\history`文件夹内容复制到当前报告内容。目前,测试用例的历史记录条目存储有关多达5个先前结果的信息。 |
但是在本地是不可以的,因为allure不会自动记录你的每次生成报告的历史数据,所以我们必须通过代码的改动让allure也能强制显示趋势图。至于为什么生成趋势图,别问,问就是为了好看。
一起来试试吧。
在本地生成历史记录的方法就是把上一次的历史放在本次的原始报告中进行生成报告。
图一箭头所指的文件夹放在,下图所指的文件夹中。好了,我们来实现吧。
在项目
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys sys.path.append('.') import os import shutil from config.conf import ALLURE_REPORT, ALLURE_RESULTS def copy_history(): start_path = os.path.join(ALLURE_REPORT, 'history') end_path = os.path.join(ALLURE_RESULTS, 'history') if os.path.exists(end_path): shutil.rmtree(end_path) print("复制上一运行结果成功!") try: shutil.copytree(start_path, end_path) except FileNotFoundError: print("allure没有历史数据可复制!") if __name__ == "__main__": copy_history() |
新建了一个copy_history函数,在这个里面我们实现了复制上次运行的history文件夹到allure本地目录。
方法说明:
1、当allure-report中已经有history文件夹时复制history目录会报错,所以我们先进行判断,存在则删除该文件夹
3、通过shutil中的copytree方法来复制整个文件夹
4、如果上一次历史不存在做了异常捕捉,避免引发程序错误
好了,代码加好了,我们来运行一下吧
添加到执行脚本中并继续执行脚本。
1 2 3 4 5 6 7 8 9 | python tools/clear_log.py python tools/copy_history.py pytest --alluredir allure-results allure generate allure-results -c -o allure-report allure open allure-report |
多尝试几次不同的。
分别进行了三次测试,第一次:2 passed 第二次: 1 passed 1failed 第三次:1passed 1skiped
可以看到趋势图中三次的情况全部记录在案。
好了,到这里可以说allure的报告就先到这里了,以后发现allure其他的精彩之处我再来分享。
参考文档
- 《allure官方文档》