UiAutomator 解决 uiautomator2 附加截图至 allure 失败问题

FyueC · 2019年11月20日 · 1413 次阅读

1.使用 uiautomator2 产生截图

file = d.screenshot(failname)

2.使用 allure 附加截图方法将截图附加进去

allure.attach(file, 'fail screenshot', attachment_type=allure.attachment_type.PNG)

3.问题出现,如图,测试报告中无法显示图片:

查看源码后发现,attach 最终调用的是如下方法:

def _attach(self, uuid, name=None, attachment_type=None, extension=None):
    mime_type = attachment_type
    extension = extension if extension else 'attach'

    if type(attachment_type) is AttachmentType:
        extension = attachment_type.extension
        mime_type = attachment_type.mime_type

    file_name = ATTACHMENT_PATTERN.format(prefix=uuid, ext=extension)
    attachment = Attachment(source=file_name, name=name, type=mime_type)
    last_uuid = self._last_executable()
    self._items[last_uuid].attachments.append(attachment)

    return file_name

看到第一个参数为 UUID,而不是文件,于是想到使用 uuid 模块给文件做一个 uuid 传入

muuid=uuid.uuid5(uuid.NAMESPACE_DNS, failname)
allure.attach(muuid, 'fail screenshot', attachment_type=allure.attachment_type.PNG)

运行如图:

4.原因

根据上方异常 a bytes-like object is required, not 'UUID',attach 方法接收参数需要为 bytes,需要装文件转换成 byte

5.解决方法

使用二进制读取图片,然后将二进制数据传入 attach

filebayes= ''

with open(self.d.screenshot(filepath),'rb') as file:
    filebayes = file.read()

    allure.attach(filebayes,
                  'fail scrennshot',
                  attachment_type=allure.attachment_type.PNG) 

运行后可成功在测试报告中查看图片

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册