我們都知道go語言的testing包提供了豐富的測試功能茬腿,方便我們在開發(fā)時進(jìn)行單元測試挎峦,但是之前一直沒有看到過如何進(jìn)行文件上傳單元測試相關(guān)的文章遵湖,直到看到了B站的這個視頻「教程」Go語言基礎(chǔ) (O'Reilly)泳桦,不得不說這個go語言學(xué)習(xí)視頻比國內(nèi)的不知要高到哪里去了景用,講解清晰,涵蓋范圍廣坤邪,學(xué)完感覺水平瞬間上了一個等級熙含。
文件上傳服務(wù)端代碼
func upload(w http.ResponseWriter, r *http.Request) {
file, head, err := r.FormFile("my_file")
if err != nil {
fmt.Sprintln(err)
fmt.Fprintln(w, err)
return
}
localFileDir := "/tmp/upload/"
err = os.MkdirAll(localFileDir, 0777)
if err != nil {
fmt.Sprintln(err)
fmt.Fprintln(w, err)
return
}
localFilePath := localFileDir + head.Filename
localFile, err := os.Create(localFilePath)
if err != nil {
fmt.Sprintln(err)
fmt.Fprintln(w, err)
return
}
defer localFile.Close()
io.Copy(localFile, file)
fmt.Fprintln(w, localFilePath)
}
測試代碼
func TestUpload(t *testing.T) {
path := "/home/ubuntu/test.go"http://要上傳文件所在路徑
file, err := os.Open(path)
if err != nil {
t.Error(err)
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("my_file", filepath.Base(path))
if err != nil {
writer.Close()
t.Error(err)
}
io.Copy(part, file)
writer.Close()
req := httptest.NewRequest("POST", "/upload", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
res := httptest.NewRecorder()
upload(res, req)
if res.Code != http.StatusOK {
t.Error("not 200")
}
t.Log(res.Body.String())
// t.Log(io.read)
}
測試代碼中關(guān)鍵的部分在于使用了"mime/multipart"包
- 首先創(chuàng)建一個writer
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
- 然后往multipart中寫入域"my_file"和文件名filepath.Base(path)
"my_file"和服務(wù)端中
file, head, err := r.FormFile("my_file")
對應(yīng)。
3.最后上傳文件
io.Copy(part, file)
writer.Close()