pytest+Allure+jenkins

目錄

1、Allure簡介

2、Pytest框架集成Allure

2.1 環境配置

2.2 生成html報告

2.3 定製報告

2.3.1 Features、Story定製詳解

2.3.2 用例標題和用例描述定製詳解

2.3.3  Severity定製詳解

2.3.4 Step定製詳解

2.3.5 Issue和TestCase定製詳解

2.3.6 Environment定製詳解

2.3.7  attach定製詳解

3、持續集成 Jenkins 構建 Allure Report

3.1 安裝插件 allure-jenkins-plugin

3.2  構建配置

3.3  查看報告

 4、問題總結

1  Jenkins 集成時打包本地python 環境

2  Jenkins中執行python命令,出現python不是內部命令的問題

3  allure-result 不存在,allure報告數據爲空


1、Allure簡介

Allure是一款非常輕量級並且非常靈活的開源測試報告生成框架。 它支持絕大多數測試框架, 例如TestNG、Pytest、JUint等。它簡單易用,易於集成。下面就Pytest如何與Allure集成做詳細介紹。

2、Pytest框架集成Allure

Pytest是Python的單元測試框架,非常方便和易用。強烈推薦對於用Python進行測試工作的小夥伴使用這個測試框架,相比與Python自帶的UnitTest好用太多太多。今天我們主要是介紹如何將測試報告生成工具Allure集成到Pytest中。目前現在已經有allure2了,我們要使用的就是這個allure2。

2.1 環境配置

a、因爲allure2需要在java的環境下,並且要求必須是jdk1.8級以上,所以要首先保證這一點。

b、安裝allure-pytest,他用來在pytest執行測試結束後生成allure所需要的配置信息。安裝使用pip命令即可:

安裝Python依賴庫:
pip3 install allure-pytest

注意:我看到許多教程是讓安裝 pytest-allure-adaptor 的,我剛開始也是安裝的它,但是使用的時候出了錯。查瞭解決方法就是卸掉pytest-allure-adaptor,安裝allure-pytest。後來瞭解到官方已經放棄維護pytest-allure-adaptor~

c、下載allure2:https://github.com/allure-framework/allure2/releases,我們下載的是allure-2.8.0版本;下載後解壓,放在某個位置(建議放在C:\python35\Lib\site-packages下);配置環境變量:環境變量path中加上解壓好的文件夾下的bin目錄下的allure.bat文件的路徑(這裏是:C:\python35\Lib\site-packages\allure-2.8.0\bin)

2.2 生成html報告

if __name__=="__main__":
    pytest.main(['-s','-q','--alluredir','report/result','test_Pytest.py'])
    os.system("C:/python35/Lib/site-packages/allure-2.8.0/bin/allure.bat "
              "generate "
              "F:/pycharm_workspace/FirstApplication/testPytest/report/result "
              "-o "
              "F:/pycharm_workspace/FirstApplication/testPytest/report/html")

2.2.1 pytest命令基礎上加--alluredir,生成測試數據

pytest命令基礎上加--alluredir,生成測試數據。(測試腳本中添加了Allure特性之後,在執行測試的時候需要先生成Allure報告所需要的測試結果數據。在py.test執行測試的時候,指定–alluredir選項及測試數據保存的目錄即可)

pytest -s -q --alluredir [xml_report_path]
//[xml_report_path]根據自己需要定義文件夾,作者定義爲:/report/result

例子:

#test_Pytest.py文件
#coding=utf-8

import pytest
import os

class Test_Pytest():

        def test_one(self):
                print("test_one方法執行" )
                assert 1==1

        def test_two(self):
                print("test_two方法執行" )
                assert "s" in "love"

        def test_three(self):
                print("test_three方法執行" )
                assert 3-2==1

if __name__=="__main__":
    pytest.main(['-s','-q','--alluredir','report/result','test_Pytest.py'])

運行結果: 

æ§è¡ç»æå¾1

2.2.2 命令行方式

第一步:用命令行或os模塊運行allure命令,來生成html格式的報告(通過下面的命令將./result/目錄下的測試數據生成測試報告
命令如下:(因爲我們已經將allure.bat放在環境變量中,所以在哪裏打開cmd窗口都可以找到allure/allure.bat)

allure generate 配置信息的路徑 -o 生成報告的路徑

allure generate ./result/ -o ./report/html --clean

這樣在./report/目錄下就生成了Allure的測試報告了。–clean目的是先清空測試報告目錄,再生成新的測試報告

第二步:打開/report/html,下面的index.html

æ§è¡ç»æå¾3

第三步:通過下面的命令打開測試報告:

$ allure open -h 127.0.0.1 -p 8083 ./report/

解釋:127.0.0.1:是IP,可以替換成本機IP,這樣就可以遠程打開網頁了,8083是端口號,用一個不常用的就行

本機的瀏覽器將打開http://127.0.0.1:8083/index.html網頁,展示測試報告。

或者參考下面方式,打開HTML,但是一般用上面的方面簡單:

第二種方式,打開HTML,參考https://blog.csdn.net/baozi_xiaoge/article/details/103380307

2.3 定製報告

@allure.feature # 用於定義被測試的功能,被測產品的需求點
@allure.story # 用於定義被測功能的用戶場景,即子功能點
with allure.step # 用於將一個測試用例,分成幾個步驟在報告中輸出
allure.attach # 用於向測試報告中輸入一些附加的信息,通常是一些測試數據信息
@pytest.allure.step # 用於將一些通用的函數作爲測試步驟輸出到報告,調用此函數的地方會向報告中輸出步驟

2.3.1 Features、Story定製詳解

# -*- coding: utf-8 -*-
# @Time    : 2018/8/17 上午10:10
# @Author  : WangJuan
# @File    : test_case.py
import allure
import pytest


@allure.feature('test_module_01')
@allure.story('test_story_01')
def test_case_01():
    """
    用例描述:Test case 01
    """
    assert 0

@allure.feature('test_module_01')
@allure.story('test_story_02')
def test_case_02():
    """
    用例描述:Test case 02
    """
    assert 0 == 0


if __name__ == '__main__':
    pytest.main(['-s', '-q', '--alluredir', './report/xml'])

$ py.test test/ --allure_features='test_module_01' --allure_stories='test_story_01'

2.3.2 用例標題和用例描述定製詳解

# -*- coding: utf-8 -*-
# @Time    : 2018/8/17 上午10:10
# @Author  : WangJuan
# @File    : test_case.py
import allure
import pytest

@allure.feature('test_module_01')
@allure.story('test_story_01')
#test_case_01爲用例title
def test_case_01():
    """
    用例描述:這是用例描述,Test case 01,描述本人
    """
    #註釋爲用例描述
    assert 0

if __name__ == '__main__':
    pytest.main(['-s', '-q', '--alluredir', './report/xml'])

2.3.3  Severity定製詳解

Allure中對嚴重級別的定義:
1、 Blocker級別:中斷缺陷(客戶端程序無響應,無法執行下一步操作)
2、 Critical級別:臨界缺陷( 功能點缺失)
3、 Normal級別:普通缺陷(數值計算錯誤)
4、 Minor級別:次要缺陷(界面錯誤與UI需求不符)
5、 Trivial級別:輕微缺陷(必輸項無提示,或者提示不規範)

# -*- coding: utf-8 -*-
# @Time    : 2018/8/17 上午10:10
# @Author  : WangJuan
# @File    : test_case.py
import allure
import pytest


@allure.feature('test_module_01')
@allure.story('test_story_01')
@allure.severity('blocker')
def test_case_01():
    """
    用例描述:Test case 01
    """
    assert 0

@allure.feature('test_module_01')
@allure.story('test_story_01')
@allure.severity('critical')
def test_case_02():
    """
    用例描述:Test case 02
    """
    assert 0 == 0

@allure.feature('test_module_01')
@allure.story('test_story_02')
@allure.severity('normal')
def test_case_03():
    """
    用例描述:Test case 03
    """
    assert 0

@allure.feature('test_module_01')
@allure.story('test_story_02')
@allure.severity('minor')
def test_case_04():
    """
    用例描述:Test case 04
    """
    assert 0 == 0


if __name__ == '__main__':
    pytest.main(['-s', '-q', '--alluredir', './report/xml'])

2.3.4 Step定製詳解

#!/usr/bin/env python
# coding=utf-8

import pytest
import allure


@allure.feature('購物車功能')  # feature定義功能
class TestShoppingTrolley(object):
    @allure.story('加入購物車')  # story定義用戶場景
    def test_add_shopping_trolley(self):
        login('劉春明', '密碼')  # 調用“步驟函數”
        with allure.step("瀏覽商品"):  # 將一個測試用例分成幾個步驟,將步驟打印到測試報告中,步驟2
            allure.attach('商品1', '劉春明')  # attach可以打印一些附加信息
            allure.attach('商品2', 'liuchunming')
        with allure.step("點擊商品"):  # 將一個測試用例分成幾個步驟,將步驟打印到測試報告中,步驟3
            pass
        with allure.step("校驗結果"):
            allure.attach('期望結果', '添加購物車成功')
            allure.attach('實際結果', '添加購物車失敗')
            assert 'success' == 'failed'

    @allure.story('修改購物車')
    def test_edit_shopping_trolley(self):
        pass

    @pytest.mark.skipif(reason='本次不執行')
    @allure.story('刪除購物車')
    def test_delete_shopping_trolley(self):
        pass


@allure.step('用戶登錄')  # 還可以將一個函數作爲一個步驟,調用此函數時,報告中輸出一個步驟,步驟名字通常是函數名,我把這樣的函數叫“步驟函數”
def login(user, pwd):
    print(user, pwd)

2.3.5 Issue和TestCase定製詳解

#-*- coding: utf-8 -*-
#@Time    : 2018/8/17 上午10:10
#@Author  : WangJuan
#@File    : test_case.py
import allure
import pytest

@allure.step("字符串相加:{0},{1}")     
#測試步驟,可通過format機制自動獲取函數參數
def str_add(str1, str2):
    print('hello')
    if not isinstance(str1, str):
        return "%s is not a string" % str1
    if not isinstance(str2, str):
        return "%s is not a string" % str2
    return str1 + str2

@allure.feature('test_module_01')
@allure.story('test_story_01')
@allure.severity('blocker')
@allure.issue("http://www.baidu.com")
@allure.testcase("http://www.testlink.com")
def test_case():
    str1 = 'hello'
    str2 = 'world'
    assert str_add(str1, str2) == 'helloworld'


if __name__ == '__main__':
    pytest.main(['-s', '-q', '--alluredir', './report/xml'])

2.3.6 Environment定製詳解

# 具體Environment參數可自行設置
allure.environment(app_package='com.mobile.fm')
allure.environment(app_activity='com.mobile.fm.activity')
allure.environment(device_name='aad464')
allure.environment(platform_name='Android')

2.3.7  attach定製詳解

file = open('../test.png', 'rb').read()
allure.attach('test_img', file, allure.attach_type.PNG)

在報告中增加附件:allure.attach(’arg1’,’arg2’,’arg3’):
arg1:是在報告中顯示的附件名稱 
arg2:表示添加附件的內容 
arg3:表示添加的類型(支持:HTML,JPG,PNG,JSON,OTHER,TEXTXML)

3、持續集成 Jenkins 構建 Allure Report

3.1 安裝插件 allure-jenkins-plugin

  1. 進入系統管理 - 管理插件 
  2. 搜索Allure,並進行安裝,重啓Jenkins
  3. 進入系統管理 - 全局工具配置 - Allure Commandline
  4. 點擊 Allure Commandline安裝,如下圖:其中name可隨便定義,作爲標識用。

è¿éåå¾çæè¿°

點擊後,彈出下面的頁面,輸入Allure的命令別名和版本後,點擊Apply 和Save。(或者不勾選自動安裝,使用你已經下載好的包,把包的路徑複製到這裏就行,如下圖:)

è¿éåå¾çæè¿°

 

3.2  構建配置

  1. General - 參數化構建過程 處增加參數ALLURE_HOME,參數值填寫存放allure results的默認路徑。
  2. 構建 - Execute shell 處增加命令:--alluredir ${ALLURE_HOME}   如:pytest src\testcase\ -s -q --alluredir report\result
  3. 構建後操作 - Allure Report ,Results Path處設置${ALLURE_HOME}

注意:一定要在jenkins添加shell命令生成result(生成報告的數據源),在腳本里面寫的生成的數據源生不成HTML報告(血淚史)

  1. è¿éåå¾çæè¿°

3.3  查看報告

構建已配置好的工程,即可查看Allure Report,有多處入口,點擊任意入口即可查看Report,見下圖

 

 4、問題總結

1  jenkins 集成時打包本地python 環境

在本地執行:pip freeze > requirements.txt

安裝有jenkins的服務上面執行:pip install -r requirements.txt,,,,將上面打包的環境導入到新環境中,新環境的python 環境將於之前的環境一樣,這樣所使用的包就不用手動一個一個的導入了

2  Jenkins中執行python命令,出現python不是內部命令的問題

問題描述:已安裝python安裝包,但是還是提示python 不是內部命令

定位原因:python.exe 不在jenkins執行用戶的PATH裏面

解決:構建的時候Python命令加上python.exe的路徑

3  allure-result 不存在,allure報告數據爲空

就是生成allure htlm的數據源不存在

問題描述:

 我出現的問題是,在腳本中已經執行命令: pytest src\testcase\ -s -q --alluredir report\result,生成了數據,但是Jenkins中構建成功,生成allure-HTML時,還是提示allure htlm的數據源不存在,生成的報告數據爲空

解決:

a .一定要在jenkins添加shell命令生成result(生成報告的數據源),如下:

b. 下面2處地址一定要一致

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章