前言
使用go語言做開發差不多快一年了,主要用來寫后端Web服務,從一開始吐槽他的結構體,比如創建個復雜的JSON格式資料,那是相當的痛苦,還有 err 處理寫的巨麻煩,
當然,go 也有爽的地方,創建個線協程簡直太簡單了,
到后來慢慢接受,覺得效率還行,因為是靜態強型別語言,在修改完專案代碼之后,反而很有信心(如果出現低級的型別錯誤,直接編譯出錯了),相比 Python 就要反復檢查兩邊,對修改的代碼總時心里發虛,
go語言測驗相關的東西都不咋地,比如自帶的測驗框架相比較 pytest 那是相當的簡陋,今年開始給后端寫單元測驗(其實應該叫介面測驗),發現 apitest庫 眼前一亮,采用鏈式呼叫,和 HttpRunner 3.x 的鏈式呼叫頗有幾分相似,
- HttpRunner 3.x
# httprunner 3.x
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
class TestCaseTestCase(HttpRunner):
config = Config("basic test config").base_url("http://127.0.0.1:8000/api")
teststeps = [
Step(
RunRequest(" test_add_event_all_null")
.post("/add_event/")
.with_data({"eid": "", "limit": "", "address": "", "start_time": ""})
.validate()
.assert_equal("body.status", 10021)
.assert_equal("body.message", "parameter error")
)
]
if __name__ == "__main__":
TestCaseTestCase().test_start()
apitest 測驗庫
一個簡單且可擴展的行為測驗庫,
測驗庫: https://github.com/steinfletcher/apitest jsonpath庫: github.com/steinfletcher/apitest-jsonpath
- 簡單的get介面
package api
import (
"net/http"
"testing"
"time"
"github.com/steinfletcher/apitest"
)
func Client() http.Client {
cli := &http.Client{
Timeout: time.Second * 10,
}
return *cli
}
func TestGetSample(t *testing.T) {
cli := Client()
apitest.New().
EnableNetworking(&cli).
Get("http://httpbin.org/get").
Expect(t).
Status(http.StatusOK).
End()
}
New(): 創建一個新的API測驗,
EnableNetworking(): EnableNetworking為提供的客戶端啟用網路,需要一個 http.Clinet,
Get(): 發送get 請求,需要一個URL,
Expect(): Expect將請求規范標記為完整,
Status(): 斷言http狀態,http.StatusOK = 200
End(): End運行測驗,將結果回傳給呼叫者,
- get介面帶引數
import (
...
jsonpath "github.com/steinfletcher/apitest-jsonpath"
)
...
func TestGetParams(t *testing.T) {
cli := Client()
apitest.New().
EnableNetworking(&cli).
Intercept(func(req *http.Request) {
req.URL.RawQuery = "id=1&name=jack"
}).
Get("http://httpbin.org/get").
Expect(t).
Assert(
jsonpath.Contains(`$.args.id`, "1")).
Assert(
jsonpath.Equal(`$.args.name`, "jack")).
End()
}
req.URL.RawQuery: 用于定義get請求引數,
Assert() ,方法用于斷言,
jsonpath 提供了斷言方法,Contains判斷包含,Equal判斷相等,
- post介面Form-data引數
...
func TestPostFormData(t *testing.T) {
cli := Client()
apitest.New().
EnableNetworking(&cli).
Post("http://httpbin.org/post").
FormData("key1", "value1").
FormData("key2", "value2").
Expect(t).
Assert(
jsonpath.Chain().
Equal(`$.form.key1`, "value1").
Equal(`$.form.key2`, "value2").
End()).
End()
}
FormData() 用于設定form-Data格式的引數,
jsonpath 提供的斷言同樣支持鏈式呼叫,
- post介面JSON引數
...
func TestPostJson(t *testing.T) {
cli := Client()
apitest.New().
EnableNetworking(&cli).
Post("http://httpbin.org/post").
JSON(`{"message": "hi"}`).
Expect(t).
Assert(
jsonpath.Chain().
Contains(`$.data`, "message").
Contains(`$.data`, "hi").
End()).
End()
}
JSON() 用于設定JSON()請求方法,
apitest 評價
官網:https://apitest.dev/
apitest 在完成http介面測驗方面還是非常方便的,如果你被 go語言的 http 庫蹂躪過一段時間之后感觸更深;怎么說了,比如你經常被老板PUA,突然有一天老板居然當面表揚了你,大概就這種感覺,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/551720.html
標籤:其他
上一篇:Java8 Stream流的合并
下一篇:返回列表
