基於Pytest框架的自動化測試開發實踐(萬字長文入門篇)

Pytest是Python的一種易用、高效和靈活的單元測試框架,可以支持單元測試和功能測試。本文不以介紹Pytest工具本身爲目的,而是以一個實際的API測試項目爲例,將Pytest的功能應用到實際的測試工程實踐中,教大家將Pytest用起來。

在開始本文之前,我想跟大家澄清兩個概念,一個是測試框架一個是測試工具。很多人容易把他們搞混了,測試框架是諸如Unittest、Pytest、TestNG這類,而測試工具指的則是Selenium、Appium、Jmeter這類。

測試框架的作用是,幫助我們管理測試用例、執行測試用例、參數化、斷言、生成測試報告等基礎性工作,讓我們將精力用在測試用例的編寫上。好的測試框架應該具有很高的擴展性,支持二次開發,並能夠支持多種類型的自動化測試。

測試工具的作用是爲了完成某一類型的測試,比如Selenium用於對WEB UI進行自動化測試,Appium用來對APP進行自動化測試,Jmeter可以用來進行API自動化測試和性能測試。另外,Java語言中OkHttp庫,Python語言中的requests庫,這些HTTP的client也可以看做是一種API測試工具。

澄清了這兩個概念,說一下本文的目的。其實網上已經有很多教程,包括官方文檔,都是以介紹Pytest的功能爲出發點,羅列了各種功能的使用方法,大家看完之後會感覺都明白了,但是還是不知道如何與實際項目相結合,真正落地用起來。本文不以介紹Pytest工具本身爲目的,而是以一個實際的API測試項目爲例,通過單元測試框架Pytest和Python的Requests庫相結合,將Pytest功能應用到實際的測試工程實踐中,教大家將Pytest用起來。

請相信我,使用Pytest會讓你的測試工作非常高效。

01 — Pytest核心功能

在開始使用Pytest之前,先來了解一下Pytest的核心功能,根據官方網站介紹,它具有如下功能和特點:

  1. 非常容易上手,入門簡單,文檔豐富,文檔中有很多實例可以參考。
  2. 能夠支持簡單的單元測試和複雜的功能測試。
  3. 支持參數化。
  4. 能夠執行全部測試用例,也可以挑選部分測試用例執行,並能重複執行失敗的用例。
  5. 支持併發執行,還能運行由nose, unittest編寫的測試用例。
  6. 方便、簡單的斷言方式。
  7. 能夠生成標準的Junit XML格式的測試結果。
  8. 具有很多第三方插件,並且可以自定義擴展。
  9. 方便的和持續集成工具集成。

Pytest的安裝方法與安裝其他的python軟件無異,直接使用pip安裝即可。

$ pip install -U pytest

安裝完成後,可以通過下面方式驗證是否安裝成功:

$ py.test --help

如果能夠輸出幫助信息,則表示安裝成功了。

接下來,通過開發一個API自動化測試項目,詳細介紹以上這些功能是如何使用的。

02 — 創建測試項目

先創建一個測試項目目錄api_pytest,爲這個項目創建虛擬環境。關於虛擬環境的創建,可以參考這篇文章《利用pyenv和pipenv管理多個相互獨立的Python虛擬開發環境》。這裏我們直接介紹如何使用,執行下面兩條命令:

$ mkdir api_pytest
$ pipenv --python 3.7.7

這樣,項目目錄和虛擬環境就創建完成了。

接着,安裝依賴包,第一個是要安裝pytest,另外本文是以API自動化測試爲例,因此還要安裝一下HTTP 的client包requests。

$ pipenv install pytest requests

現在我們創建一個data目錄,用來存放測試數據,一個tests目錄,用來存放測試腳本,一個config目錄,用來存放配置文件,一個utils目錄從來存放工具。

$ mkdir data
$ mkdir tests
$ mkdir config
$ mkdir utils

現在,項目的目錄結構應該是如下這樣:

$ tree
.
├── Pipfile
├── Pipfile.lock
├── config
├── data
├── tests
└── utils
​
4 directories, 2 files

至此測試項目就創建完成了。接着編寫測試用例。

03 — 編寫測試用例

在這部分,我們以測試豆瓣電影列表API和電影詳情API爲例,編寫測試用例。

這兩個API信息如下:

接口 示例
電影列表 http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=0&count=10
電影詳情 https://api.douban.com/v2/movie/subject/30261964?apikey=0df993c66c0c636e29ecbb5344252a4a

我們先寫電影列表API的自動化測試用例,設置3個校驗點:

  1. 驗證請求中的start與響應中的start一致。
  2. 驗證請求中的count與響應中的count一致。
  3. 驗證響應中的title是"正在上映的電影-上海"。

在tests目錄裏面,創建個test_in_theaters.py文件,裏面編寫測試用例,內容如下:

import requests
​
​
class TestInTheaters(object):
    def test_in_theaters(self):
        host = "http://api.douban.com"
        path = "/v2/movie/in_theaters"
        params = {"apikey": "0df993c66c0c636e29ecbb5344252a4a",
                  "start": 0,
                  "count": 10
                  }
        headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
        }
        r = requests.request("GET", url=host + path, headers=headers, params=params)
        response = r.json()
        assert response["count"] == params["count"]
        assert response["start"] == params["start"]
        assert response["title"] == "正在上映的電影-上海", "實際的標題是:{}".format(response["title"])

你可能會問,這就是測試用例了?這就是基於Pytest的測試用例了嗎?答案是肯定的。基於Pytest編寫自動化測試用例,與編寫平常的Python代碼沒有任何區別,唯一的區別在於文件名、函數名或者方法名要以test_開頭或者_test結尾,類名以Test開頭。

Pytest會在test_*.py 或者 *_test.py 文件中,尋找class外邊的test_開頭的函數,或者Test開頭的class裏面的test_開頭的方法,將這些函數和方法作爲測試用例來管理。可以通過下面的命令,查看Pytest收集到哪些測試用例:

$ py.test --collect-only
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest
collected 1 item                                                                                                                 
<Module tests/test_in_theaters.py>
  <Class TestInTheaters>
      <Function test_in_theaters>
​
===================================================== no tests ran in 0.10s ======================================================

從結果中看到,一共有一條測試用例,測試用例位於tests/test_in_theaters.py這個module裏面TestInTheaters這個類中的test_in_theaters這個方法。

在Pytest中斷言使用的是Python自帶的assert語句,非常簡單。

04 — 執行測試用例

下面來運行這個測試:

$ py.test tests/
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest
collected 1 item
​
tests/test_in_theaters.py .                                                                                                [100%]
​
======================================================= 1 passed in 0.61s ========================================================
(api_pytest) MBC02X21W4G8WN:api_pytest chunming.liu$ py.test tests/
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest
collected 1 item
​
tests/test_in_theaters.py F                                                                                                [100%]
​
============================================================ FAILURES ============================================================
________________________________________________ TestInTheaters.test_in_theaters _________________________________________________
​
self = <test_in_theaters.TestInTheaters object at 0x110eee9d0>
​
    def test_in_theaters(self):
        host = "http://api.douban.com"
        path = "/v2/movie/in_theaters"
        params = {"apikey": "0df993c66c0c636e29ecbb5344252a4a",
                  "start": 0,
                  "count": 10
                  }
        headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
        }
        r = requests.request("GET", url=host + path, headers=headers, params=params)
        response = r.json()
        assert response["count"] == params["count"]
        assert response["start"] == params["start"]
        assert response["total"] == len(response["subjects"])
​
>       assert response["title"] == "正在上映的電影-上海", "實際的標題是:{}".format(response["title"])
E       AssertionError: 實際的標題是:正在上映的電影-北京
E       assert '正在上映的電影-北京' == '正在上映的電影-上海'
E         - 正在上映的電影-上海
E         ?         ^^
E         + 正在上映的電影-北京
E         ?         ^^
​
tests/test_in_theaters.py:20: AssertionError
==================================================== short test summary info =====================================================
FAILED tests/test_in_theaters.py::TestInTheaters::test_in_theaters - AssertionError: 實際的標題是正在上映的電影-北京
======================================================= 1 failed in 0.96s ========================================================

這個命令執行時,會在tests/目錄裏面尋找測試用例。執行測試的時候,如果不指定測試用例所在目錄,Pytest會在當前的目錄下,按照前面介紹的規則尋找測試用例並執行。

通過上面的測試輸出,我們可以看到該測試過程中,一共收集到了一個測試用例,測試結果是失敗的(標記爲F),並且在FAILURES部分輸出了詳細的錯誤信息,通過這些信息,我們可以分析測試失敗的原因。上面測試用例的失敗原因是在斷言title的時候出錯了,預期的title是“正在上映的電影-上海”,但是實際是“正在上映的電影-北京”,預期和實際的對比非常直觀。

執行測試用例的方法還有很多種,都是在py.test後面添加不同的參數即可,我在下面羅列了一下:

$ py.test               # run all tests below current dir
$ py.test test_module.py   # run tests in module
$ py.test somepath      # run all tests below somepath
$ py.test -k stringexpr # only run tests with names that match the
                      # the "string expression", e.g. "MyClass and not method"
                      # will select TestMyClass.test_something
                      # but not TestMyClass.test_method_simple
$ py.test test_module.py::test_func # only run tests that match the "node ID",
                                    # e.g "test_mod.py::test_func" will select
                                    # only test_func in test_mod.py

上面這些用法,通過註釋很容易理解。在測試執行過程中,這些方法都有機會被用到,最好掌握一下。

05

數據與腳本分離

03小節的測試用例,將測試數據和測試代碼放到了同一個py文件中,而且是同一個測試方法中,產生了緊耦合,會導致修改測試數據或測試代碼時,可能會相互影響,不利於測試數據和測試腳本的維護。比如,爲測試用例添加幾組新的測試數據,除了準備測試數據外,還要修改測試代碼,降低了測試代碼的可維護性。

另外接口測試往往是數據驅動的測試,測試數據和測試代碼放到一起也不方便藉助Pytest做參數化。

將測試代碼和測試數據分離已經是測試領域中的共識了。在data/目錄下創建一個用於存放測試數據的Yaml文件test_in_theaters.yaml,內容如下:

---
tests:
- case: 驗證響應中start和count與請求中的參數一致
  http:
    method: GET
    path: /v2/movie/in_theaters
    headers:
      User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
    params:
      apikey: 0df993c66c0c636e29ecbb5344252a4a
      start: 0
      count: 10
  expected:
    response:
      title: 正在上映的電影-上海
      count: 10
      start: 0

熟悉Yaml格式的同學,應該很容易看懂上面測試數據文件的內容。這個測試數據文件中,有一個數組tests,裏面包含的是一條完整的測試數據。一個完整的測試數據由三部分組成:

  1. case,表示測試用例名稱。
  2. http,表示請求對象。
  3. expected,表示預期結果。

http這個請求對象包含了被測接口的所有參數,包括請求方法、請求路徑、請求頭、請求參數。
expected表示預期結果,上面的測試數據中,只列出了對請求響應的預期值,實際測試中,還可以列出對數據庫的預期值。

測試腳本也要做相應的改造,需要讀取test_in_theaters.yaml文件獲取請求數據和預期結果,然後通過requests發出請求。修改後的測試代碼如下:

import requests
import yaml
​
​
def get_test_data(test_data_path):
    case = []  # 存儲測試用例名稱
    http = []  # 存儲請求對象
    expected = []  # 存儲預期結果
    with open(test_data_path) as f:
        dat = yaml.load(f.read(), Loader=yaml.SafeLoader)
        test = dat['tests']
        for td in test:
            case.append(td.get('case', ''))
            http.append(td.get('http', {}))
            expected.append(td.get('expected', {}))
    parameters = zip(case, http, expected)
    return case, parameters
​
​
cases, parameters = get_test_data("/Users/chunming.liu/learn/api_pytest/data/test_in_theaters.yaml")
list_params=list(parameters)class TestInTheaters(object):
    def test_in_theaters(self):
        host = "http://api.douban.com"
        r = requests.request(list_params[0][1]["method"],
                             url=host + list_params[0][1]["path"],
                             headers=list_params[0][1]["headers"],
                             params=list_params[0][1]["params"])
        response = r.json()
        assert response["count"] == list_params[0][2]['response']["count"]
        assert response["start"] == list_params[0][2]['response']["start"]
        assert response["total"] == len(response["subjects"])
        assert response["title"] == list_params[0][2]['response']["title"], "實際的標題是:{}".format(response["title"])

注意,讀取Yaml文件,需要安裝PyYAML包。

測試腳本中定義了一個讀取測試數據的函數get_test_data,通過這個函數從測試數據文件test_in_theaters.yaml中讀取到了測試用例名稱case,請求對象http和預期結果expected。這三部分分別是一個列表,通過zip將他們壓縮到一起。

測試方法test_in_theaters並沒有太大變化,只是發送請求所使用的測試數據不是寫死的,而是來自於測試數據文件了。

通常情況下,讀取測試數據的函數不會定義在測試用例文件中,而是會放到utils包中,比如放到utils/commonlib.py中。至此,整個項目的目錄結構應該是如下所示:

$ tree
.
├── Pipfile
├── Pipfile.lock
├── config
├── data
│   └── test_in_theaters.yaml
├── tests
│   └── test_in_theaters.py
└── utils
    └── commlib.py

這樣,我們修改測試腳本,就修改test_in_theaters.py,變更測試數據,就修改test_in_theaters.yaml。但是目前看,感覺好像並沒有真正看到測試數據和腳本分離的厲害之處,或者更加有價值的地方,那麼我們接着往下看。

06 — 參數化

上面我們將測試數據和測試腳本相分離,如果要爲測試用例添加更多的測試數據,往tests數組中添加更多的同樣格式的測試數據即可。這個過程叫作參數化。

參數化的意思是對同一個接口,使用多種不同的輸入對其進行測試,以驗證是否每一組輸入參數都能得到預期結果。Pytest提供了pytest.mark.paramtrize這種方式來進行參數化,我們先看下官方網站提供的介紹pytest.mark.paramtrize用法的例子:

# content of tests/test_time.py
import pytest
​
from datetime import datetime, timedelta
​
testdata = [
    (datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),
    (datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
]
​
​
@pytest.mark.parametrize("a,b,expected", testdata)
def test_timedistance_v0(a, b, expected):
    diff = a - b
    assert diff == expected

執行上面的腳本將會得到下面的輸出,測試方法test_timedistance_v0被執行了兩遍,第一遍執行用的測試數據是testdata列表中的第一個元組,第二遍執行時用的測試數據是testdata列表中的第二個元組。這就是參數化的效果,同一個腳本可以使用不同的輸入參數執行測試。

============================= test session starts ==============================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -- /Users/chunming.liu/.local/share/virtualenvs/api_pytest-wCozfXSU/bin/python
cachedir: .pytest_cache
rootdir: /Users/chunming.liu/learn/api_pytest/tests
collecting ... collected 2 items
​
test_time.py::test_timedistance_v0[a0-b0-expected0] PASSED    [ 50%]
test_time.py::test_timedistance_v0[a1-b1-expected1] PASSED    [100%]
​
============================== 2 passed in 0.02s ===============================

照貓畫虎,對我們自己的測試項目中的測試腳本進行如下修改。

import pytest
import requests
​
from utils.commlib import get_test_data
​
cases, list_params = get_test_data("/Users/chunming.liu/learn/api_pytest/data/test_in_theaters.yaml")
​
​
class TestInTheaters(object):
    @pytest.mark.parametrize("case,http,expected", list(list_params), ids=cases)
    def test_in_theaters(self, case, http, expected):
        host = "http://api.douban.com"
        r = requests.request(http["method"],
                             url=host + http["path"],
                             headers=http["headers"],
                             params=http["params"])
        response = r.json()
        assert response["count"] == expected['response']["count"]
        assert response["start"] == expected['response']["start"]
        assert response["title"] == expected['response']["title"], "實際的標題是:{}".format(response["title"])

在測試方法上面添加了一個裝飾器@pytest.mark.parametrize,裝飾器會自動對list(list_params)解包並賦值給裝飾器的第一參數。裝飾器的第一個參數中逗號分隔的變量可以作爲測試方法的參數,在測試方法內就可以直接獲取這些變量的值,利用這些值發起請求和進行斷言。裝飾器還有一個參數叫ids,這個值作爲測試用例的名稱將打印到測試結果中。

在執行修改後的測試腳本前,我們在測試數據文件再增加一組測試數據,現在測試數據文件中,包含了兩組測試數據:

---
tests:
- case: 驗證響應中start和count與請求中的參數一致
  http:
    method: GET
    path: /v2/movie/in_theaters
    headers:
      User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
    params:
      apikey: 0df993c66c0c636e29ecbb5344252a4a
      start: 0
      count: 10
  expected:
    response:
      title: 正在上映的電影-上海
      count: 10
      start: 0
- case: 驗證響應中title是"正在上映的電影-北京"
  http:
    method: GET
    path: /v2/movie/in_theaters
    headers:
      User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
    params:
      apikey: 0df993c66c0c636e29ecbb5344252a4a
      start: 1
      count: 5
  expected:
    response:
      title: 正在上映的電影-北京
      count: 5
      start: 1

現在我們執行一下測試腳本,看看效果:

$ export PYTHONPATH=/Users/chunming.liu/learn/api_pytest
$ py.test tests/test_in_theaters.py 
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest, inifile: pytest.ini
collected 2 items                                                                                                                
​
tests/test_in_theaters.py F.                                                                                               [100%]
​
============================================================ FAILURES ============================================================
___________________________________ TestInTheaters.test_in_theaters[驗證響應中start和count與請求中的參數一致] ___________________________________


​
self = <test_in_theaters.TestInTheaters object at 0x102659510>, case = '驗證響應中start和count與請求中的參數一致'
http = {'headers': {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chr...T', 'params': {'apikey': '0df993c66c0c636e29ecbb5344252a4a', 'count': 10, 'start': 0}, 'path': '/v2/movie/in_theaters'}
expected = {'response': {'count': 10, 'start': 0, 'title': '正在上映的電影-上海'}}
​
    @pytest.mark.parametrize("case,http,expected", list(list_params), ids=cases)
    def test_in_theaters(self, case, http, expected):
        host = "http://api.douban.com"
        r = requests.request(http["method"],
                             url=host + http["path"],
                             headers=http["headers"],
                             params=http["params"])
        response = r.json()
        assert response["count"] == expected['response']["count"]
        assert response["start"] == expected['response']["start"]
>       assert response["title"] == expected['response']["title"], "實際的標題是:{}".format(response["title"])
E       AssertionError: 實際的標題是:正在上映的電影-北京
E       assert '正在上映的電影-北京' == '正在上映的電影-上海'
E         - 正在上映的電影-上海
E         ?         ^^
E         + 正在上映的電影-北京
E         ?         ^^
​
tests/test_in_theaters.py:20: AssertionError
==================================================== short test summary info =====================================================
FAILED tests/test_in_theaters.py::TestInTheaters::test_in_theaters[\u9a8c\u8bc1\u54cd\u5e94\u4e2dstart\u548ccount\u4e0e\u8bf7\u6c42\u4e2d\u7684\u53c2\u6570\u4e00\u81f4]
================================================== 1 failed, 1 passed in 0.69s ===================================================

從結果看,Pytest收集到了2個items,測試腳本執行了兩遍,第一遍執行用第一組測試數據,結果是失敗(F),第二遍執行用第二組測試數據,結果是通過(.)。執行完成後的summary info部分,看到了一些Unicode編碼,這裏其實是ids的內容,因爲是中文,所以默認這裏顯示Unicode編碼。爲了顯示中文,需要在測試項目的根目錄下創建一個Pytest的配置文件pytest.ini,在其中添加如下代碼:

[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True

再次執行測試腳本,在測試結果的summary_info部分,則會顯示正確中文內容了。

FAILED tests/test_in_theaters.py::TestInTheaters::test_in_theaters[驗證響應中start和count與請求中的參數一致] - AssertionError: ...

按照這種參數化的方法,如果想修改或者添加測試數據,只需要修改測試數據文件即可。

現在,自動化測試項目的目錄結構應該是如下這樣:

$ tree
.
├── Pipfile
├── Pipfile.lock
├── config
├── data
│   └── test_in_theaters.yaml
├── pytest.ini
├── tests
│   ├── test_in_theaters.py
│   └── test_time.py
└── utils
    └── commlib.py
​
4 directories, 7 files

07 — 測試配置管理

06小節的自動化測試代碼中,host是寫在測試腳本中的,這種硬編碼方式顯然是不合適的。這個host在不同的測試腳本都會用到,應該放到一個公共的地方來維護。如果需要對其進行修改,那麼只需要修改一個地方就可以了。根據我的實踐經驗,將其放到config文件夾中,是比較好的。

除了host外,其他與測試環境相關的配置信息也可以放到config文件夾中,比如數據庫信息、kafka連接信息等,以及與測試環境相關的基礎測試數據,比如測試賬號。很多時候,我們會有不同的測試環境,比如dev環境、test環境、stg環境、prod環境等。我們可以在config文件夾下面創建子目錄來區分不同的測試環境。因此config文件夾,應該是類似這樣的結構:

├── config
│   ├── prod
│   │   └── config.yaml
│   └── test
│       └── config.yaml

在config.yaml中存放不同環境的配置信息,以前面的例子爲例,應該是這樣:

host:
  douban: http://api.douban.com

將測試配置信息從腳本中拆分出來,就需要有一種機制將其讀取到,才能在測試腳本中使用。Pytest提供了fixture機制,通過它可以在測試執行前執行一些操作,在這裏我們利用fixture提前讀取到配置信息。我們先對官方文檔上的例子稍加修改,來介紹fixture的使用。請看下面的代碼:

import pytest
​
​
@pytest.fixture
def smtp_connection():
    import smtplib
    connection = smtplib.SMTP_SSL("smtp.163.com", 465, timeout=5)
    yield connection
    print("teardown smtp")
    connection.close()
​
​
def test_ehlo(smtp_connection):
    response, msg = smtp_connection.ehlo()
    assert response == 250
    assert 0

這段代碼中,smtp_connection被裝飾器@pytest.fixture裝飾,表明它是一個fixture函數。這個函數的功能是連接163郵箱服務器,返回一個連接對象。當test_ehlo的最後一次測試執行完成後,執行print(“teardown smtp”)和connection.close()斷開smtp連接。

fixture函數名可以作爲測試方法test_ehlo的參數,在測試方法內部,使用fixture函數名這個變量,就相當於是在使用fixture函數的返回值。

回到我們讀取測試配置信息的需求上,在自動化測試項目tests/目錄中創建一個文件conftest.py,定義一個fixture函數env:

@pytest.fixture(scope="session")
def env(request):
    config_path = os.path.join(request.config.rootdir, 
                               "config", 
                               "test", 
                               "config.yaml")
    with open(config_path) as f:
        env_config = yaml.load(f.read(), Loader=yaml.SafeLoader)
    return env_config

conftest.py文件是一個plugin文件,裏面可以實現Pytest提供的Hook函數或者自定義的fixture函數,這些函數只在conftest.py所在目錄及其子目錄中生效。scope="session"表示這個fixture函數的作用域是session級別的,在整個測試活動中開始前執行,並且只會被執行一次。除了session級別的fixture函數,還有function級別、class級別等。

env函數中有一個參數request,其實request也是一個fixture函數。在這裏用到了它的request.config.rootdir屬性,這個屬性表示的是pytest.ini這個配置文件所在的目錄,因爲我們的測試項目中pytest.ini處於項目的根目錄,所以config_path的完整路徑就是:

/Users/chunming.liu/learn/api_pytest/config/test/config.yaml

將env作爲參數傳入測試方法test_in_theaters,將測試方法內的host改爲env[“host”][“douban”]:

class TestInTheaters(object):
    @pytest.mark.parametrize("case,http,expected", list(list_params), ids=cases)
    def test_in_theaters(self, env, case, http, expected):
        r = requests.request(http["method"],
                             url=env["host"]["douban"] + http["path"],
                             headers=http["headers"],
                             params=http["params"])
        response = r.json()

這樣就達到了測試配置文件與測試腳本相互分離的效果,如果需要修改host,只需要修改配置文件即可,測試腳本文件就不用修改了。修改完成後執行測試的方法不變。

上面的env函數實現中,有點點小缺憾,就是讀取的配置文件是固定的,讀取的都是test環境的配置信息,我們希望在執行測試時,通過命令行選項,可指定讀取哪個環境的配置,以便在不同的測試環境下開展測試。Pytest提供了一個叫作pytest_addoption的Hook函數,可以接受命令行選項的參數,寫法如下:

def pytest_addoption(parser):
    parser.addoption("--env",
                     action="store",
                     dest="environment",
                     default="test",
                     help="environment: test or prod")

pytest_addoption的含義是,接收命令行選項–env選項的值,存到environment變量中,如果不指定命令行選項,environment變量默認值是test。將上面代碼也放入conftest.py中,並修改env函數,將os.path.join中的"test"替換爲request.config.getoption(“environment”),這樣就可以通過命令行選項來控制讀取的配置文件了。比如執行test環境的測試,可以指定–env test:

$ py.test --env test tests/test_in_theaters.py

如果不想每次都在命令行上指定–env,還可以將其放入pyest.ini中:

[pytest]
addopts = --env prod

命令行上的參數會覆蓋pyest.ini裏面的參數。

08 — 測試的準備與收尾

很多時候,我們需要在測試用例執行前做數據庫連接的準備,做測試數據的準備,測試執行後斷開數據庫連接,清理測試髒數據這些工作。通過07小節大家對於通過env這個fixture函數,如何在測試開始前的開展準備工作有所瞭解,本小節將介紹更多內容。

@pytest.fixture函數的scope可能的取值有function,class,module,package 或 session。他們的具體含義如下:

  1. function,表示fixture函數在測試方法執行前和執行後執行一次。
  2. class,表示fixture函數在測試類執行前和執行後執行一次。
  3. module,表示fixture函數在測試腳本執行前和執行後執行一次。
  4. package,表示fixture函數在測試包(文件夾)中第一個測試用例執行前和最後一個測試用例執行後執行一次。
  5. session,表示所有測試的最開始和測試結束後執行一次。

通常,數據庫連接和斷開、測試配置文件的讀取等工作,是需要放到session級別的fixture函數中,因爲這些操作針對整個測試活動只需要做一次。而針對測試數據的準備,通常是function級別或者class級別的,因爲測試數據針對不同的測試方法或者測試類往往都不相同。

在TestInTheaters測試類中,模擬一個準備和清理測試數據的fixture函數preparation,scope設置爲function:

@pytest.fixture(scope="function")
    def preparation(self):
        print("在數據庫中準備測試數據")
        test_data = "在數據庫中準備測試數據"
        yield test_data
        print("清理測試數據")

在測試方法中,將preparation作爲參數,通過下面的命令執行測試:

$ pipenv py.test -s -q --tb=no tests/test_in_theaters.py
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest, inifile: pytest.ini
collected 2 items                                                                                                                


tests/test_in_theaters.py 在數據庫中準備測試數據
F清理測試數據
在數據庫中準備測試數據
.清理測試數據
​
​
==================================================== short test summary info =====================================================
FAILED tests/test_in_theaters.py::TestInTheaters::test_in_theaters[驗證響應中start和count與請求中的參數一致] - AssertionError: ...
================================================== 1 failed, 1 passed in 0.81s ===================================================

通過輸出可以看到在每一條測試用例執行前後,各執行了一次“在數據庫中準備測試數據”和“清理測試數據”。如果scope的值改爲class,執行測試用例的輸出信息將是下面這樣:

tests/test_in_theaters.py 在數據庫中準備測試數據
F.清理測試數據
在測試類執行前後各執行一次“在數據庫中準備測試數據”和“清理測試數據”。

09 — 標記與分組

通過pytest.mark可以給測試用例打上標記,常見的應用場景是:針對某些還未實現的功能,將測試用例主動跳過不執行。或者在某些條件下,測試用例跳過不執行。還有可以主動將測試用例標記爲失敗等等。針對三個場景,pytest提供了內置的標籤,我們通過具體代碼來看一下:

import sys
​
import pytest
​
​
class TestMarks(object):
    @pytest.mark.skip(reason="not implementation")
    def test_the_unknown(self):
        """
        跳過不執行,因爲被測邏輯還沒有被實現
        """
        assert 0
​
    @pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
    def test_skipif(self):
        """
        低於python3.7版本不執行這條測試用例
        :return:
        """
        assert 1
​
    @pytest.mark.xfail
    def test_xfail(self):
        """
        Indicate that you expect it to fail
        這條用例失敗時,測試結果被標記爲xfail(expected to fail),並且不打印錯誤信息。
        這條用例執行成功時,測試結果被標記爲xpassed(unexpectedly passing)
        """
        assert 0
​
    @pytest.mark.xfail(run=False)
    def test_xfail_not_run(self):
        """
        run=False表示這條用例不用執行
        """
        assert 0

下面來運行這個測試:

$ py.test -s -q --tb=no tests/test_marks.py
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest, inifile: pytest.ini
collected 4 items                                                                                                                
​
tests/test_marks.py s.xx
============================================ 1 passed, 1 skipped, 2 xfailed in 0.06s =============================================

從結果中可以看到,第一條測試用例skipped了,第二條測試用例passed了,第三條和第四條測試用例xfailed了。

除了內置的標籤,還可以自定義標籤並加到測試方法上:

@pytest.mark.slow
    def test_slow(self):
        """
        自定義標籤
        """
        assert 0

這樣就可以通過-m過濾或者反過濾,比如只執行被標記爲slow的測試用例:

$ py.test -s -q --tb=no -m "slow" tests/test_marks.py
$ py.test -s -q --tb=no -m "not slow" tests/test_marks.py

對於自定義標籤,爲了避免出現PytestUnknownMarkWarning,最好在pytest.ini中註冊一下:

[pytest]
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')

10 — 併發執行

如果自動化測試用例數量成千上萬,那麼併發執行它們是個很好的主意,可以加快整體測試用例的執行時間。

pyest有一個插件pytest-xdist可以做到併發執行,安裝之後,執行測試用例通過執行-n參數可以指定併發度,通過auto參數自動匹配CPU數量作爲併發度。併發執行本文的所有測試用例:

$ py.test -s -q --tb=no -n auto tests/
====================================================== test session starts =======================================================
platform darwin -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /Users/chunming.liu/learn/api_pytest, inifile: pytest.ini
plugins: xdist-1.31.0, forked-1.1.3
gw0 [10] / gw1 [10] / gw2 [10] / gw3 [10] / gw4 [10] / gw5 [10] / gw6 [10] / gw7 [10]
s.FxxF..F.
==================================================== short test summary info =====================================================
FAILED tests/test_marks.py::TestMarks::test_slow - assert 0
FAILED tests/test_smtpsimple.py::test_ehlo - assert 0
FAILED tests/test_in_theaters.py::TestInTheaters::test_in_theaters[驗證響應中start和count與請求中的參數一致] - AssertionError: ...
======================================= 3 failed, 4 passed, 1 skipped, 2 xfailed in 1.91s ========================================

可以非常直觀的感受到,併發執行比順序執行快得多。但是併發執行需要注意的是,不同的測試用例之間不要有測試數據的相互干擾,最好不同的測試用例使用不同的測試數據。

這裏提一下,pytest生態中,有很多第三方插件很好用,更多的插件可以在這裏https://pypi.org/search/?q=pytest-查看和搜索,當然我們也可以開發自己的插件。

11 — 測試報告

Pytest可以方便的生成測試報告,通過指定–junitxml參數可以生成XML格式的測試報告,junitxml是一種非常通用的標準的測試報告格式,可以用來與持續集成工具等很多工具集成:

$ py.test -s -q --junitxml=./report.xml tests/

現在應用更加廣泛的測試報告是Allure,可以方便的與Pytest集成,大家可以參考我的另外一篇公衆號文章《用Pytest+Allure生成漂亮的HTML圖形化測試報告》。

12 — 總結

本文章以實際項目出發,介紹瞭如何編寫測試用例、如何參數化、如何進行測試配置管理、如何進行測試的準備和清理,如何進行併發測試並生成報告。根據本文的介紹,你能夠逐步搭建起一套完整的測試項目。

本文並沒有對Pytest的細節和比較高階的內容做充分介紹,以後再進行專題介紹,這篇文章主要目的是讓大家能夠將Pytest用起來。更高階的內容,公衆號後續文章還將繼續對其進行介紹。至此,我們的自動化測試項目完整目錄結構如下:

$ tree
.
├── Pipfile
├── Pipfile.lock
├── config
│   ├── prod
│   │   └── config.yaml
│   └── test
│       └── config.yaml
├── data
│   └── test_in_theaters.yaml
├── pytest.ini
├── tests
│   ├── conftest.py
│   ├── test_in_theaters.py
│   ├── test_marks.py
│   ├── test_smtpsimple.py
│   └── test_time.py
└── utils
    └── commlib.py
​
6 directories, 12 files

參考資料

[1] https://docs.pytest.org/en/latest/

[2] https://www.guru99.com/pytest-tutorial.html

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