1. 程式人生 > 其它 >Python測試框架pytest(26)測試報告Allure - 特性

Python測試框架pytest(26)測試報告Allure - 特性

1、Environment

Environment 是環境變數,報告預設是沒有任何變數引數的,是需要自己配置的。

1.1、新增Environment

通過建立 environment.properties 或者 environment.xml 檔案,並把檔案存放到測試結果的資料夾(執行指令碼時,--alluredir 選項後指定的目錄)。

例如:

pytest -n auto --alluredir=allure

存放在allure資料夾裡。

1、新增配置檔案

方式一:environment.properties

檔案內容:

Browser=Chrome
Browser.Version
=89.0.4389.128 Stand=Test ApiUrl=127.0.0.1/login python.Version=3.7.9

方式二:environment.xml

檔案內容:

<environment>
    <parameter>
        <key>Browser</key>
        <value>Chrome</value>
    </parameter>
    <parameter>
        <key>Browser.Version</key
> <value>89.0.4389.128</value> </parameter> <parameter> <key>Stand</key> <value>Test</value> </parameter> <parameter> <key>ApiUrl</key> <value>127.0.0.1/login</value>
</parameter> <parameter> <key>python.Version</key> <value>3.7.9</value> </parameter> </environment>

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

3、報告展示效果:

注:environment.xml 方式,檔案內容含中文時,報告顯示正常。

注:environment.properties 方式,檔案內容含中文時,報告顯示亂碼。

1.2、解決配置檔案被刪的問題

執行 pytest 生成 allure 報告時,有時候需要加引數 --clean-alluredir(清除之前的報告記錄),而配置檔案(environment.properties 或 environment.xml)也會被刪除。

解決方法:

將配置檔案(environment.properties 或 environment.xml)存放於專案根目錄,執行報告之前,拷貝到報告目錄裡即可。

專案目錄結構:

執行命令(配置檔案 environment.properties)

pytest test_case.py --alluredir=allure --clean-alluredir
cp environment.properties ./allure/environment.properties
allure serve allure

執行命令(配置檔案 environment.xml)

pytest test_case.py --alluredir=allure --clean-alluredir
cp environment.xml ./allure/environment.xml
allure serve allure

2、Categories

Categories 是分類(測試用例結果的分類)

預設情況下,有兩類缺陷:

  • Product defects 產品缺陷(測試結果:failed)

  • Test defects 測試缺陷(測試結果:error/broken)

可以建立自定義缺陷分類,將 categories.json 檔案新增到測試結果的目錄即可(和 environment.properties 放同一個目錄)。

categories.json 引數:

  • name:分類名稱。

  • matchedStatuses:測試用例的執行狀態,預設["failed", "broken", "passed", "skipped", "unknown"]。

  • messageRegex:測試用例執行的錯誤資訊,預設是 .* ,是通過正則去匹配的。

  • traceRegex:測試用例執行的錯誤堆疊資訊,預設是.*,是通過正則去匹配的。

categories.json檔案內容:

[
  {
    "name": "Ignored tests",
    "matchedStatuses": ["skipped"]
  },
  {
    "name": "Infrastructure problems",
    "matchedStatuses": ["broken", "failed"],
    "messageRegex": ".*signOut.*"
  },
  {
    "name": "Outdated tests",
    "matchedStatuses": ["broken"],
    "traceRegex": ".*FileNotFoundException.*"
  },
  {
    "name": "Product defects",
    "matchedStatuses": ["failed"]
  },
  {
    "name": "Test defects",
    "matchedStatuses": ["broken"]
  }
]

如圖所示:測試用例報錯時,顯示效果

3、allure.step()

在 allure 報告中新增測試用例步驟有兩種方式:

1、@allure.step() 這種方式會帶上函式的傳參和對應的值。

2、with allure.step() 這種方式程式碼可讀性更好一點,但不會帶上函式裡面的傳參和對應的值。

3.1、@allure.step()方式

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

@allure.step() 只有一個引數,就是 title,輸入標題內容,allure 報告上就會顯示出來。

1、建立test_allure_step.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

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

@allure.step("第二步")
def step_two_with_nested():
    step_three()

@allure.step("第三步")
def step_three():
    step_four_with_arguments(123456, 'AllTests')

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

@allure.step("第五步")
def test_step_five():
    step_one()
    step_two_with_nested()

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

像Python字串一樣,支援位置引數和關鍵字引數

如:第四步{0},{arg2}

3.2、with allure.step()方式

1、建立test_allure_step2.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

def one():
    pass

def two_with_nested():
    three()

def three():
    pass

def four(arg1, arg2):
    pass

def five():
    one()
    two_with_nested()

def test_case():
    with allure.step("第一步"):
        one()

    with allure.step("第二步"):
        two_with_nested()

    with allure.step("第三步"):
        three()

    with allure.step("第四步"):
        four(arg1=123456, arg2='AllTests')

    with allure.step("第五步"):
        five()

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

執行第四步時,報告沒有帶上函式裡面的傳參和對應的值。

4、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:包含檔案路徑的字串。

(其他引數相同)

1、建立test_allure_attach.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest
import allure

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

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

    request.addfinalizer(attach_fixture_two)

def test_attach_fixture(attach_fixture_one):
    print("allure")

def test_attach_fixture_file():
    allure.attach('<head></head><body> a page </body>', 'page demo', allure.attachment_type.HTML)
    allure.attach.file('./demo.html', 'AllTests demo', attachment_type=allure.attachment_type.HTML)

建立demo.html檔案(存放到專案的根目錄上)

檔案內容:

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>軟體測試</title>
  </head>
  <body>
    <h1>AllTests</h1>
  </body>
</html>

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

用例test_attach_fixture

用例test_attach_fixture_file,第一個附件為手寫的HTML,第二個附件是匯入的HTML檔案。

5、@allure.description()

新增足夠詳細的測試用例描述,更加方便檢視測試步驟。

三種方式:

方式一:
@allure.description_html(str):傳一個HTML程式碼組成的字串

方式二:
@allure.description(str)

方式三:
在測試用例函式下方新增 """ """

1、建立test_allure_description.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

# 方式一
@allure.description_html("""
<h1>Test with some complicated html description</h1>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr align="center">
    <td>William</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr align="center">
    <td>Vasya</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
""")
def test_html_description():
    assert True

# 方式二
@allure.description("""
多行測試描述
這是一個@allure.description裝飾器
""")
def test_description_from_decorator():
    assert 42 == int(6 * 7)

# 方式三
def test_unicode_in_docstring_description():
    """
    多行測試描述
    assert斷言
    """
    assert 42 == int(6 * 7)

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

方式一:

方式二:

方式三:

6、@allure.title()

測試用例的標題可以通過特殊的方式變得更易讀,標題支援引數佔位符並支援動態替換。

示例一:

1、建立test_allure_title.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest
import allure

@allure.title("前置操作:登入")
@pytest.fixture
def test_login(request):
    params = request.param
    name = params["username"]
    pwd = params["pwd"]
    allure.attach(f"測試用例傳的引數{params}")
    print(name, pwd, params)
    yield name, pwd

@allure.title("登入成功,測試資料:{test_login}")
@pytest.mark.parametrize("test_login", [{"username": "admin", "pwd": "123456"}, {"username": "root", "pwd": "root"}], indirect=True)
def test_login_success(test_login):
    name, pwd = test_login
    allure.attach(f"賬號:{name},密碼:{pwd}")

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

示例二:

1、建立test_allure_title2.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest
import allure

@allure.title("測試標題引數化: {param1} + {param2}")
@pytest.mark.parametrize('param1,param2,expected', [
    (2, 2, 4),
    (1, 2, 5)
])
def test_with_parameterized_title(param1, param2, expected):
    assert param1 + param2 == expected

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

7、@allure.link()

連結(訪問連結)

裝飾器原始碼:

引數:

  • url:跳轉的連結。

  • name:顯示在 allure 報告的名字,如果不傳就是顯示完整的連結。

類似的裝飾器:

Bug連結:@allure.issue()

測試用例連結:@allure.testcase()

1、建立test_allure_link.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

@allure.link('https://www.baidu.com/')
def test_with_link():
    pass

@allure.link('https://www.baidu.com/', name='百度一下')
def test_with_named_link():
    pass

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

無name引數

有name引數

8、@allure.issue()

連結(Bug連結)

裝飾器原始碼:

呼叫link(),但link_type=LinkType.ISSUE。

引數:

  • url:跳轉的連結。

  • name:顯示在 allure 報告的名字,如果不傳就是顯示完整的連結。

類似的裝飾器:

訪問連結:@allure.link()

測試用例連結:@allure.testcase()

1、建立test_allure_issue.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

@allure.issue('https://www.baidu.com/')
def test_with_issue():
    pass

@allure.issue('https://www.baidu.com/', 'BUG連結')
def test_with_named_issue():
    pass

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

無name引數

有name引數

9、@allure.testcase()

連結(測試用例連結)

裝飾器原始碼:

呼叫link(),但link_type=LinkType.TEST_CASE。

引數:

  • url:跳轉的連結。

  • name:顯示在 allure 報告的名字,如果不傳就是顯示完整的連結。

類似的裝飾器:

訪問連結:@allure.link()

Bug連結:@allure.issue()

1、建立test_allure_testcase.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

@allure.testcase('https://www.baidu.com/')
def test_with_testcase():
    pass

@allure.testcase('https://www.baidu.com/', '測試用例地址')
def test_with_named_testcase():
    pass

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

無name引數

有name引數

10、@allure.epic()/feature()/story()

allure 標記裝飾器(可顯示在測試報告上):

@allure.epic:敏捷裡面的概念,定義史詩,往下是 feature。

@allure.feature:功能點的描述,理解成模組,往下是 story。

@allure.story:故事,往下是 title。

示例一:

1、建立test_allure_epic_feature_story.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

def test_without_any_annotations_that_wont_be_executed():
    pass

@allure.story('story1')
def test_with_story1():
    pass

@allure.story('story2')
def test_with_story2():
    pass

@allure.feature('feature3')
@allure.story('story3')
def test_with_feature3_story3():
    pass

@allure.epic('epic4')
@allure.feature('feature4')
@allure.story('story4')
def test_with_epic4_feature4_story4():
    pass

@allure.epic('epic5')
@allure.feature('feature5')
class TestCase:
    @allure.story('story5_1')
    def test_with_story5_1(self):
        print("執行 test_with_story5_1")

    @allure.story('story5_2')
    def test_with_story5_2(self):
        print("執行 test_with_story5_2")

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

首頁FEATURES BY STORIES區域顯示所設定的標記

Behaviors欄目下,帶有標記的測試用例顯示的標記層次順序

示例二:命令列執行,指定執行某個標記(epic、feature、story)

命令列引數:

  • --allure-epics

  • --allure-features

  • --allure-stories

1、建立test_allure_epic_feature_story2.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest
import allure
import os

@pytest.fixture(scope="session")
def login_fixture():
    print("===前置操作-登陸===")

@allure.step("步驟1")
def step1():
    print("===操作步驟1===")

@allure.step("步驟2")
def step2():
    print("===操作步驟2===")

@allure.step("步驟3")
def step3():
    print("===操作步驟3===")

@allure.epic("總體描述1")
@allure.feature("測試模組1")
class TestCaseAll1:
    @allure.testcase("https://www.baidu.com/", "測試用例")
    @allure.issue("https://www.baidu.com/", "Bug連結")
    @allure.title("用例標題")
    @allure.story("story1")
    @allure.severity("critical")
    def test_case1(self, login_fixture):
        print("===測試用例1===")
        step1()
        step2()

    @allure.story("story2")
    def test_case2(self, login_fixture):
        print("===測試用例2===")
        step1()
        step3()

@allure.epic("總體描述2")
@allure.feature("測試模組2")
class TestCaseAll2:
    @allure.story("story3")
    def test_case3(self, login_fixture):
        print("===測試用例3===")
        step1()

    @allure.story("story4")
    def test_case4(self, login_fixture):
        print("===測試用例4===")
        step3()

if __name__ == '__main__':
    pytest.main(['-s', '-q', '--alluredir', './allure'])
    os.system('allure -c ./allure')
    os.system('allure serve ./allure')

2、執行結果:

(1)執行全部:

執行完成後,自動開啟瀏覽器載入測試報告

(2)命令列指定執行:

1)、只執行epic名為“總體描述1”的測試用例

pytest --alluredir ./allure --allure-epics=總體描述1
allure serve allure

執行結果:

2)、只執行feature名為“測試模組2”的測試用例

pytest --alluredir ./allure --allure-features=測試模組2
allure serve allure

執行結果:

3)、只執行story1、story3的測試用例(可以不用=號 空格也可以)

pytest --alluredir ./allure test_allure_epic_feature_story2.py --allure-stories story1,story3
allure serve allure

執行結果:

4)執行指定的feature+story的測試用例(可以不用=號 空格也可以)

pytest --alluredir ./allure test_allure_epic_feature_story2.py --allure-features 測試模組2 --allure-stories story2
allure serve allure

執行結果:

11、@allure.severity()

用來標記用例級別。

Allure 提供的用例等級:

  • BLOCKER = 'blocker' 阻塞缺陷(功能未實現,無法下一步)

  • CRITICAL = 'critical' 嚴重缺陷(功能點缺失)

  • NORMAL = 'normal' 一般缺陷(邊界情況,格式錯誤)

  • MINOR = 'minor' 次要缺陷(介面錯誤與UI需求不符)

  • TRIVIAL = 'trivial 輕微缺陷(必須項無提示,或者提示不規範等)

一、示例:

1、建立test_allure_severity.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import allure

def test_with_no_severity():
    pass

@allure.severity(allure.severity_level.BLOCKER)
def test_with_blocker_severity():
    pass

@allure.severity(allure.severity_level.CRITICAL)
def test_with_critical_severity():
    pass

@allure.severity(allure.severity_level.MINOR)
def test_with_minor_severity():
    pass

@allure.severity(allure.severity_level.TRIVIAL)
def test_with_trivial_severity():
    pass

@allure.severity(allure.severity_level.NORMAL)
def test_with_normal_severity():
    pass

@allure.severity(allure.severity_level.NORMAL)
class TestClassWithNormalSeverity(object):

    def test_inside_the_normal_severity_test_class(self):
        """
        測試類優先順序 normal
        """
        print("測試類優先順序 normal")

    @allure.severity(allure.severity_level.CRITICAL)
    def test_inside_the_normal_severity_test_class_with_overriding_critical_severity(self):
        """
        測試類優先順序 normal
        測試用例優先順序 critical
        """
        print("測試類優先順序 normal;測試用例優先順序 critical")

@allure.severity("normal")
def test_case_1():
    """ normal 級別測試用例 """
    print("normal 級別測試用例")

@allure.severity("critical")
def test_case_2():
    """ critical 級別測試用例 """
    print("critical 級別測試用例")

@allure.severity("blocker")
def test_case_3():
    """ blocker 級別測試用例 """
    print("blocker 級別測試用例")

@allure.severity("minor")
def test_case_4():
    """ minor 級別測試用例 """
    print("minor 級別測試用例")

@allure.severity("trivial")
def test_case_5():
    """ trivial 級別測試用例 """
    print("trivial 級別測試用例")

def test_case_6():
    """ 未標記 severity 的用例預設為 normal """
    print("未標記 severity 的用例預設為 normal")

@allure.severity("normal")
def test_case_7():
    """ normal 級別測試用例 """
    assert (1 == 2)

@allure.severity("critical")
def test_case_8():
    """ critical 級別測試用例 """
    assert (1 == 2)

@allure.severity("blocker")
def test_case_9():
    """ blocker 級別測試用例 """
    assert (1 == 2)

2、輸入命令執行:

pytest -n auto --alluredir=allure
allure serve allure

執行結果:

Severity欄位標記用例級別

圖表裡統計用例優先順序

二、命令列引數執行:

根據優先順序選擇需要執行的測試用例

引數:

--allure-severities

例如:只執行severity=blocker、critical的測試用例,命令列輸入

寫法一:

pytest test_allure_severity.py -sq --alluredir=allure --allure-severities=blocker,critical

寫法二:

pytest test_allure_severity.py -sq --alluredir=allure --allure-severities blocker,critical

執行結果:

按照需要執行的用例級別,運行了7條測試用例。


本文來自部落格園,作者:AllTests軟體測試,轉載請註明原文連結:https://www.cnblogs.com/alltests/p/15503009.html