Python API 測試範例

之前在 Python 呼叫 API 示範(requests) 這篇文章中有示範呼叫 API 的方式,但是程式碼一定要經過測試,這裡就來示範模擬 API 請求的測試範例

最簡單範例

一定要在方法上增加 @responses.activate
    
import requests
import responses


@responses.activate
def api_test():
    # API URL
    url = "http://localhost:5000/api"

    # 假資料 Body
    fake_data = {
        "id": 1,
        "name": "Ruyut",
        "age": 100,
        "interests": ["C#", "Java", "Python"],
        "friends": [
            {"id": 2, "name": "John", "age": 90},
            {"id": 3, "name": "Tom", "age": 80},
        ],
        "phone": None,
        "alive": True,
    }

    # 設定模擬回應
    responses.add(responses.GET, url, json=fake_data, status=200)

    # 呼叫 API (執行測試)
    response = requests.get(url)

    # 確認回應狀態碼
    assert response.status_code == 200

    # 確認回應資料
    assert response.json() == fake_data

    print(f"API 收到的資料: {response.text}")
    # {"id": 1, "name": "Ruyut", "age": 100, "interests": ["C#", "Java", "Python"], "friends": [{"id": 2, "name": "John", "age": 90}, {"id": 3, "name": "Tom", "age": 80}], "phone": null, "alive": true}
    
    print(f"在 python 中的資料: {response.json()}")


if __name__ == '__main__':
    api_test()
    

一開始使用 responses 做模擬測試時遇到的問題就是不知道 json 要怎麼放,是要使用 """ xxx """ 還是使用字典的方式不太清楚,測試後發現如果 Body 是 json 直接使用字典來存放,json 的 null, true, false 在定義時是使用 None ,True, False。
然後稍微提一下 response.text 是取得回應的原始內容(字串),response.json() 是取得回應解析成 Python 中的資料類型(字典)的內容。

模擬請求的 Body:
    
{
  "id": 1,
  "name": "Ruyut",
  "age": 100,
  "interests": [
    "C#",
    "Java",
    "Python"
  ],
  "friends": [
    {
      "id": 2,
      "name": "John",
      "age": 90
    },
    {
      "id": 3,
      "name": "Tom",
      "age": 80
    }
  ],
  "phone": null,
  "alive": true
}
    

在 Python 物件中的資料:
    
{
  'id': 1,
  'name': 'Ruyut',
  'age': 100,
  'interests': [
    'C#',
    'Java',
    'Python'
  ],
  'friends': [
    {
      'id': 2,
      'name': 'John',
      'age': 90
    },
    {
      'id': 3,
      'name': 'Tom',
      'age': 80
    }
  ],
  'phone': None,
  'alive': True
}
    

headers

在 responses.add 中也有 headers 參數,可以直接傳入
    
    responses.add(
        responses.GET,
        url,
        json=fake_data,
        status=200,
        headers=
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer aaa.bbb.ccc",
        },
    )
    

留言