準備環境
首先需要一個測試檔案,通常會在專案底下建立testdata
目錄,裡面放置一個叫
hello.txt
檔案,內容為
world
。接著安裝
gofight
套件,可以用團隊內喜愛的 vendor 工具,我個人偏好
govendor :
$ govendor fetch github.com/kardianos/govendor 或 $ go get -u github.com/kardianos/govendor
檔案上傳範例
這邊用 gin 框架當作範例,如果您用其他框架只要支援http.HandlerFunc
都可以使用。
func gintFileUploadHandler(c *gin.Context) { ip := c.ClientIP() file, err := c.FormFile("test") if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } foo := c.PostForm("foo") bar := c.PostForm("bar") c.JSON(http.StatusOK, gin.H{ "hello": "world", "filename": file.Filename, "foo": foo, "bar": bar, "ip": ip, }) } // GinEngine is gin router. func GinEngine() *gin.Engine { gin.SetMode(gin.TestMode) r := gin.New() r.POST("/upload", gintFileUploadHandler) return r }上面例子可以發現,測試端需要傳兩個 post 參數,加上一個檔案 (檔名為 test),底下看看 gofight 怎麼寫測試。
檔案上傳測試
gofight 現在支援一個函式叫SetFileFromPath
此 func 支援三個參數。
- 檔案讀取路徑
- POST 檔案名稱
- POST 參數
testdata/hello.txt
那該參數就是填寫
testdata/hello.txt
,請注意這是相對於
*_test.go
檔案路徑,第二個參數就是定義該檔案的 post 參數,請依照 handler 內的
c.FormFile("test")
來決定變數名稱,第三個參數可有可無,也就是檔案上傳頁面,可能會需要上傳其他 post 參數,這時候就要寫在第三個參數,看底下實際例子:
func TestUploadFile(t *testing.T) { r := New() r.POST("/upload"). SetFileFromPath("fixtures/hello.txt", "test", H{ "foo": "bar", "bar": "foo", }). Run(framework.GinEngine(), func(r HTTPResponse, rq HTTPRequest) { data := []byte(r.Body.String()) hello := gjson.GetBytes(data, "hello") filename := gjson.GetBytes(data, "filename") foo := gjson.GetBytes(data, "foo") bar := gjson.GetBytes(data, "bar") ip := gjson.GetBytes(data, "ip") assert.Equal(t, "world", hello.String()) assert.Equal(t, "hello.txt", filename.String()) assert.Equal(t, "bar", foo.String()) assert.Equal(t, "foo", bar.String()) assert.Equal(t, "", ip.String()) assert.Equal(t, http.StatusOK, r.Code) assert.Equal(t, "application/json; charset=utf-8", r.HeaderMap.Get("Content-Type")) }) }可以看到上面例子正確拿到檔案上傳資料,並且測試成功。
心得
其實這類測試 HTTP Handler API 的套件相當多,當時就自幹一套當作練習,後來每個 Go 專案,我個人都用自己寫的這套,測試起來相當方便。更多詳細的用法請直接看 gofight 文件 。對於 Go 語言有興趣的朋友們,可以直接參考我的 線上課程 。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 支援一波 《面试数十人有感》
- iOS App 如何支援 RTL 語言
- RDS 支援 Storage Auto Scaling
- 開源專案 Gitea 支援 OAuth Provider
- 如何使 VS Code 支援 CSS Intellisense ?
- 如何用NLP与知识图谱支援MarTech建设?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Think Python
Allen B. Downey / O'Reilly Media / 2012-8-23 / GBP 29.99
Think Python is an introduction to Python programming for students with no programming experience. It starts with the most basic concepts of programming, and is carefully designed to define all terms ......一起来看看 《Think Python》 这本书的介绍吧!