天天看點

【Python系列】pytest自動化測試架構

‍目錄

一、前言

二、pytest簡介

三、pytest入門

四、總結

一、前言

這兩天學習了pytest測試架構,下面我就來簡單分享下學習成果。

二、pytest簡介

pytest是Python的測試架構,特點就是靈活、簡單、易上手。

pytest有豐富的第三方插件,比較好用的如

pytest-selenium(內建selenium)、

pytest-html(完美html測試報告生成)、

pytest-rerunfailures(失敗case重複執行)、

pytest-xdist(多CPU分發)等。

三、pytest入門

3.1、pytest安裝

# 安裝pytest
pip install -U pytest

# 檢視pytest版本
pytest --version           

複制

3.2、pytest規則

  • 測試檔案以test_開頭(以_test結尾也可)
  • 測試類以Test開頭,注意,Test首字母要大寫
  • 測試類名稱後面直接跟冒号,而不能有()
  • 測試類不能帶有 __init__ 方法
  • 測試類裡的每個函數都必須有參數(self)
  • 測試函數以test_開頭,注意,這時首字母要小寫
  • 斷言使用基本的assert即可

3.3、pytest入門demo

建立一個python檔案pytest_demo.py。

import pytest

def add(a, b):
    return a + b

@pytest.mark.parametrize('a,b,expect', [
    [1, 1, 2],
    [2, 2, 4],
    [3, 3, 6],
    [4, 4, 8],
    [5, 5, 10]
])
def test_add_list(a, b, expect):
    assert add(a, b) == expect
                            
# 執行方式一
# "-s": 顯示程式中的print/logging輸出
# "-v": 豐富資訊模式, 輸出更詳細的用例執行資訊               
if __name__ == '__main__':
    pytest.main(["-s", "-v", "pytest_demo.py"])

# 執行方式二
#在Terminal或者cmd執行:python -m pytest pytest_demo.py           

複制

執行結果:

【Python系列】pytest自動化測試架構

3.4、pytest參數分離

3.4.1、excel參數化

為了更靈活的設計自動化測試用例,可以将測試用例寫到excel或者json,再進行讀取。

建立python檔案pytest_excel.py。

import pytest
import requests
import xlrd
import json


def readExcel():
    data = list()
    book = xlrd.open_workbook('../testdata/excel_data.xls')
    sheet = book.sheet_by_index(0)
    for item in range(1, sheet.nrows):
        data.append(sheet.row_values(item))
    return data


@pytest.mark.parametrize('data', readExcel())
def test_excel(data):
    r = requests.post(
        url=data[0],
        json=json.loads(data[1]))
    assert r.json() == json.loads(data[2])


if __name__ == '__main__':
    pytest.main(["-s", "-v", "pytest_excel.py"])           

複制

準備excel_data.xls内容如下:

url body expect
http://localhost:9999/demo/update {"id":"111","username": "pyauto1","password": "123456"} true
http://localhost:9999/demo/update {"id":"222","username": "pyauto2","password": "123456"} true

3.4.2、json參數化

建立python檔案pytest_json.py。

import pytest
import requests
import json


def readJson():
    return json.load(open('../testdata/json_data.json', 'r', encoding="utf-8"))['item']


@pytest.mark.parametrize('data', readJson())
def test_json(data):
    r = requests.post(
        url=data['request']['url'],
        json=data['request']['body'])
    assert str(r.json()).lower() == data['response']


if __name__ == '__main__':
    pytest.main(["-s", "-v", "pytest_json.py"])           

複制

準備json_data.json.xls内容如下:

{
  "item":
  [
    {
      "request":
      {
        "url": "http://localhost:9999/demo/update",
        "body":
        {
          "id":"111",
          "username": "pyauto1",
          "password": "123456"
        }
      },
      "response":"true"
    },
    {
      "request":
      {
        "url": "http://localhost:9999/demo/update",
        "body":
        {
          "id":"222",
          "username": "pyauto2",
          "password": "123456"
        }
      },
      "response":"true"
    }
  ]
}           

複制

3.5、pytest-allure測試報告

3.5.1、win安裝allure

allure下載下傳位址:https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/           

複制

下載下傳allure-commandline-x.x.x.zip。解壓後将allure/bin添加到系統變量中,在cmd中輸入allure驗證是否安裝成功。

3.5.2、生成allure測試報告

# 在測試檔案的目前路徑執行如下指令執行測試用例:
pytest -v pytest_json.py --alluredir ./allure

# 執行如下指令生成測試報告(自動打開浏覽器):
allure serve allure           

複制

3.5.3、allure測試報告如下

【Python系列】pytest自動化測試架構

四、總結

果然,pytest靈活、簡單、易上手,沒騙人(笑),有點Python基礎的情況下,實測1天可入門。