1. 程式人生 > >Pytest系列(20)- allure結合pytest,allure.step()、allure.attach的詳細使用

Pytest系列(20)- allure結合pytest,allure.step()、allure.attach的詳細使用

如果你還想從頭學起Pytest,可以看看這個系列的文章哦!

https://www.cnblogs.com/poloyy/category/1690628.html

 

前言

allure除了支援pytest自帶的特性之外(fixture、parametrize、xfail、skip),自己本身也有強大的特性可以在pytest中使用

 

@allure.step 

  • allure報告最重要的一點是,它允許對每個測試用例進行非常詳細的步驟說明
  • 通過 @allure.step() 裝飾器,可以讓測試用例在allure報告中顯示更詳細的測試過程

 

示例程式碼

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__title__  =
__Time__   = 2020-04-08 21:24
__Author__ = 小菠蘿測試筆記
__Blog__   = https://www.cnblogs.com/poloyy/
"""
import allure


@allure.step("第一步")
def passing_step():
    pass


@allure.step("第二步")
def step_with_nested_steps():
    nested_step()


@allure.step("第三步")
def nested_step():
    nested_step_with_arguments(1, 'abc')


@allure.step("第四步{0},{arg2}")
def nested_step_with_arguments(arg1, arg2):
    pass


@allure.step("第五步")
def test_with_nested_steps():
    passing_step()
    step_with_nested_steps()

 

測試用例在allure上的顯示

知識點

  •  step() 只有一個引數,就是title,你傳什麼,在allure上就顯示什麼
  • 可以像python字串一樣,支援位置引數和關鍵字引數 {0},{arg2},可看第四步那裡,如果函式的引數沒有匹配成功就會報錯哦
  •  step() 的使用場景,給我感覺就是,當方法之間巢狀會比較有用,否則的話只會顯示一個步驟,類似下面圖

 

allure.attach(挺有用的)

作用:allure報告還支援顯示許多不同型別的附件,可以補充測試結果;自己想輸出啥就輸出啥,挺好的

語法: allure.attach(body, name, attachment_type, extension) 

引數列表

  • body:要顯示的內容(附件)
  • name:附件名字
  • attachment_type:附件型別,是 allure.attachment_type 裡面的其中一種
  • extension:附件的副檔名(比較少用)

 

allure.attachment_type提供了哪些附件型別?

 

語法二: allure.attach.file(source, name, attachment_type, extension) 

source:檔案路徑,相當於傳一個檔案

其他引數和上面的一致

 

其中一個測試用例的程式碼栗子

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__title__  =
__Time__   = 2020-04-08 21:24
__Author__ = 小菠蘿測試筆記
__Blog__   = https://www.cnblogs.com/poloyy/
"""
import allure
import pytest


@pytest.fixture
def attach_file_in_module_scope_fixture_with_finalizer(request):
    allure.attach('在fixture前置操作裡面新增一個附件txt', 'fixture前置附件', allure.attachment_type.TEXT)

    def finalizer_module_scope_fixture():
        allure.attach('在fixture後置操作裡面新增一個附件txt', 'fixture後置附件',
                      allure.attachment_type.TEXT)

    request.addfinalizer(finalizer_module_scope_fixture)


def test_with_attacments_in_fixture_and_finalizer(attach_file_in_module_scope_fixture_with_finalizer):
    pass


def test_multiple_attachments():
    allure.attach('<head></head><body> 一個HTML頁面 </body>', 'Attach with HTML type', allure.attachment_type.HTML)
    allure.attach.file('./reports.html', attachment_type=allure.attachment_type.HTML)

 

執行之後看結果

這是一個txt附件

 

 

這是一個用了 allure.attach() 來插入一段自己寫的HTML和 allure.attach.file() 來匯入一個已存在的HTML檔案(pytest-html報告)

&n