前言

python 接入 Allure

引用的库

from allure_commons import plugin_manager
from allure_commons.logger import AllureFileLogger
from allure_commons.model2 import TestResultContainer, TestResult, TestStepResult, Label, Status, StatusDetails
from allure_commons.reporter import AllureReporter
from allure_commons.types import LabelType, AttachmentType
from allure_commons import utils as utils

初始化

class Reporter(object):
    def __init__(self, report_path, uuid):
        self.allure_reporter = AllureReporter()
        plugin_manager.register(AllureFileLogger(report_path, True))
        self.group = TestResultContainer(uuid=uuid, name=uuid, start=now())
        self.allure_reporter.start_group(self.group.uuid, self.group)

用例开始

def schedule_test(self, test_uuid, name) -> TestResult:
    test_result = TestResult(uuid=test_uuid, name=name, historyId=test_uuid, start=utils.now())
    self.allure_reporter.schedule_test(test_result.uuid, test_result)
    self.allure_reporter.update_group(self.group.uuid, children=test_result.uuid)
    return test_result

步骤开始

def start_step(self, test_uuid, name) -> TestStepResult:
    test_step_result = TestStepResult(name=name, start=utils.now())
    self.allure_reporter.start_step(test_uuid, test_step_result.id, test_step_result)
    return test_step_result

添加分类

def add_label(self, test_uuid, value):
    test_result = self.allure_reporter.get_test(test_uuid)
    test_result.labels.append(Label(name=LabelType.SUITE, value=value))

添加额外 log

def attach_file(self, attach_uuid, result_uuid, source):
    self.allure_reporter.attach_file(uuid=attach_uuid, source=source, name='log', attachment_type=AttachmentType.TEXT, parent_uuid=result_uuid)

设置测试结果

def set_status(self, uuid, status):
    self.allure_reporter.get_item(uuid).status = getattr(Status, status.upper())

设置测试结果详情

def set_status_details(self, uuid, exception_type, exception, exception_traceback):
    message = utils.escape_non_unicode_symbols(utils.format_exception(exception_type, exception))
    trace = utils.escape_non_unicode_symbols(utils.format_traceback(exception_traceback))
    self.allure_reporter.get_item(uuid).statusDetails = StatusDetails(message=message, trace=trace) if message or trace else None

步骤结束

def stop_step(self, step_id):
    self.allure_reporter.stop_step(step_id, stop=utils.now())

用例结束

def close_test(self, test_uuid):
    test_result = self.allure_reporter.get_test(test_uuid)
    test_result.stop = utils.now()
    self.allure_reporter.close_test(test_result.uuid)

测试结束

def stop_group(self):
    self.allure_reporter.stop_group(self.group.uuid, stop=utils.now())

效果

总结

以上就是 python 接入 Allure 的过程,也支持其他编程语言,抛砖引玉。


↙↙↙阅读原文可查看相关链接,并与作者交流