iT邦幫忙

2023 iThome 鐵人賽

DAY 21
0

學習原因:

昨天講了如何設計 API 測試,今天要來用 Python 進行實作了。會應用到 Python 的 Requests 套件,建 Session 來模擬 API 的測試流程,最後也會講述如何設計 API Object。

學習目標:

  • 應用 Python Requests 使用 API
  • 應用 Session 來模擬 API 的測試流程
  • API Object 設計

應用 Python 的 Requests 套件

Python 有 Requests 套件可以發 API Requests,需要先安裝。

pip install requests
import json
import requests

url = "https://automationintesting.online/message/"

request_body = {
    "description": "012345678901234567890",
	"email": "abc@abc.com",
	"name": "Tester",
	"phone": "09123456789",
	"subject": "Booking"
}

# 以 post method 發出 request
# 由於 Content-Type 為 application/json,會使用 json 參數傳入 request body
response = requests.request("post", url, json=request_body, headers=headers)

# 可列印 Requests 的 headers
print("Requests:", response.request.headers)

# 由於知道 response 的 Content-Type 是 application/json
# 可用 json() 讀取 Response 內容
# 應用 json 套件作排版顯示,不然資料量大的時候,閱讀會比較困難
# 使用 indent 參數設定縮排為 4 個空格
print("Response:", json.dumps(response.json(), indent=4))

# 可列印 Response 的 Status Code, 若成功會顯示 201
print("Status Code:", response.status_code)

以上就是簡單的 API 應用。

應用 Session 來模擬 API 測試流程

之前的文章有提到 Cookies 跟 Session 的概念,我們需要知道系統需要什麼帶什麼資訊 (Cookies 內容 / Session ID) 才能跟它溝通。一般這些資訊都需要儲存在 Header,不過實際還是要看受測系統怎樣設計。

而我們做測試的時候,因為很多時候都需要連續用幾支 API 來完成測試流程,所以會建一個 session 作測試端的記錄。

以下例子會應用這個網站 https://restful-booker.herokuapp.com/apidoc/index.html 做訂房的操作。

會用到 4 支 API:

  • Auth - CreateToken: 登入並取得 Token
  • Booking - CreateBooking : 預訂房間
  • Booking - PartialUpdateBooking : 修改部分預訂資料 (需要登入,帶有 Cookie 才能執行)
  • Booking - DeleteBooking: 刪除預訂 (需要登入,帶有 Cookie 才能執行)
import requests

# 建立一個 Session
session = requests.session()

# Login
url = "https://restful-booker.herokuapp.com/auth"
body = {
    "username": "admin",
    "password": "password123"
}

response = session.request("post", url, json=body)
print(f"Create Token Response: {response.json()}")

# 把取得的 token 存入 headers 的 cookie
session.headers["Cookie"] = f"token={response.json()['token']}"
print(f"Cookie: {session.headers['Cookie']}")

# 預訂房間
create_booking_api = "https://restful-booker.herokuapp.com/booking"
create_booking_body = {
    "firstname": "Jim",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": True,
    "bookingdates": {
        "checkin": "2018-01-01",
        "checkout": "2019-01-01"
    },
    "additionalneeds": "Breakfast"
}

response = session.request("post", create_booking_api, json=create_booking_body)
print(f"Create Booking Response: {json.dumps(response.json(), indent=4)}")

# 取得 Booking ID
booking_id = response.json()["bookingid"]

# 更改預訂內容
update_booking_api = f"https://restful-booker.herokuapp.com/booking/{booking_id}"                              
update_body = {                                                                                                
    "firstname": "James"                                                                                       
}                     
# 繼續運用同一個 session 會帶之前存的 token                                                                                         
response = session.request("patch", update_booking_api, json=update_body)                                      
print(f"Partial Update Booking Response: {json.dumps(response.json(), indent=4)}")

# 刪除預訂
delete_booking_api = f"https://restful-booker.herokuapp.com/booking/{booking_id}"
response = session.request("delete", delete_booking_api)
print(f"Delete Booking Response status code: {response.status_code}")

Output:

Create Token Response: {'token': '5d760087607a3f3'}
Cookie: token=5d760087607a3f3
Create Booking Response: {
    "bookingid": 1346,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
Partial Update Booking Response: {
    "firstname": "James",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2018-01-01",
        "checkout": "2019-01-01"
    },
    "additionalneeds": "Breakfast"
}
Delete Booking Response status code: 201

這樣我們就可以用一個 session 去模擬 user 的一連串的使用流程。

若需要模擬多個 user 做不同的事情來完成測試,則可以開不同的 session 處理。
同時操作 2 個 session,他們的資料都獨立存在 session 內。

session_user_a = requests.session()
session_user_b = requests.session()

session_user_a.request("post", login_url, json=body)
session_user_b.request("post", login_url, json=body)

session_user_a.request("post", booking_url, json=body)
session_user_b.request("post", booking_url, json=body)

API Object

跟 Page Object Model 相似,我們可以把每支 API 封裝成 API Object,以供主程式的應用。
會含有 Attribute 儲存 API 的資訊,還有 API 的應用方法 (Method)。

以剛剛的 AuthAPI 為例:

class AuthAPI:

	def __init__(self, session, username, password):
		self.url = "https://restful-booker.herokuapp.com/auth"
		self.session = session
		self.body = {
		    "username": username,
		    "password": password
		}

	def get_response(self):
		self.response = self.session.request("post", self.url, json=self.body)
		print(f"AuthAPI Response: {self.response.json()}")	
		return self.response
	
	def set_cookie(self):
		self.session.headers["Cookie"] = f"token={self.response.json()['token']}"
		print(f"Set cookie: {self.session.headers['Cookie']}")

主程式則可簡化為

session = requests.Session()
auth_api = AuthAPI(session, "admin", "password123")
auth_api.get_response()
auth_api.set_cookie()

Output:

AuthAPI Response: {'token': 'aab7fcc18643350'}
Set cookie: token=aab7fcc18643350

就這樣把 AuthAPI 封裝完成了,其他的留給你練習看看吧。

由此,透過 Python 對 Requests 的套用,我們可以模擬 API 的測試流程,從而再做驗證。

可以繼續利用昨天提供的 Dummy API 測試網站 來練習。


上一篇
Day 20: 認識 API 測試
下一篇
Day 22: Git 的基礎應用
系列文
從 0 開始培育成為自動化測試工程師的學習指南30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言