端午節我寫了一個項目,幫助你學習HTTP接口測試。
GitHub地址:
https://github.com/defnngj/learning-API-test
整個項目基於Flask和 Requests實現。
Flask是Python主流的Web框架,以簡單著稱,它可非常方便的實現API,整個項目中的API都通過一個文件實現。
Requests是模擬HTTP的測試庫,同樣是Python語言的明星庫,它可以以非常簡單的方式模擬HTTP請求。
如何開始學習
克隆或下載項目,安裝依賴。
$ pip install -r requirements.txt
啟動Flask項目。
$ python api_server.py
* Serving Flask app "api_server.py" (lazy loading)
* Environment:production
WARNING: Do not use thedevelopment server in a production environment.
Use a production WSGI serverinstead.
* Debug mode: on
* Running onhttp://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting withstat
* Debugger isactive!
* Debugger PIN:208-740-173
接下來,你可根據項目文檔中所提供的Requests例子,調用啟動的服務所提供的接口。
最簡單的接口調用。
import requests
r = requests.get("http://127.0.0.1:5000/")
result = r.json()
print(result)
接口的返回結果。
{"code": 10200, "message": "Welcome toAPI testing"}
如果,你想知道上面調用的接口是如何實現的,可以查看api_server.py文件。
# 最簡單的json格式返回
@app.route('/')
def hello_world():
return jsonify({
"code": 10200,
"message": "Welcome to API testing"
})
Flask 實現接口是不是很簡單?當然,還有更多復雜的接口實現,不過,這里的所有接口實現忽略了數據庫的操作。
如果想做接口自動化測試,請參考tests/目錄,里面提供了基於unittest 單元測試框架的用例。
如果本項目對你幫助,請幫忙加 star,有什么問題也可以通過issues提問。