測試Go:模擬Request.FormFile
在測試Go Web端點的過程中,可能會遇到模擬http的挑戰。 Request.FormFile 欄位。此欄位表示請求中上傳的文件,對於測試端點功能至關重要。
要解決此問題,可以考慮模擬整個 http.Request.FormFile 結構。然而,這是不必要的步驟。 mime/multipart 套件提供了更有效的方法。
mime/multipart 套件提供了一個 Writer 類型,可以產生 FormFile 實例。如文件所述:
CreateFormFile is a convenience wrapper around CreatePart. It creates a new form-data header with the provided field name and file name.
CreateFormFile 函數傳回一個 io.Writer,可用來建構 FormFile 欄位。然後可以將此 io.Writer 作為參數傳遞給 httptest.NewRequest,後者接受讀取器作為參數。
要實作此技術,可以將 FormFile 寫入 io.ReaderWriter 緩衝區或使用io.管道。以下範例示範了後一種方法:
<code class="go">import ( "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "github.com/codegangsta/multipart" ) func TestUploadFile(t *testing.T) { // Create a pipe to avoid buffering pr, pw := io.Pipe() // Create a multipart writer to transform data into multipart form data writer := multipart.NewWriter(pw) go func() { defer writer.Close() // Create the form data field 'fileupload' with a file name part, err := writer.CreateFormFile("fileupload", "someimg.png") if err != nil { t.Errorf("failed to create FormFile: %v", err) } // Generate an image dynamically and encode it to the multipart writer img := createImage() err = png.Encode(part, img) if err != nil { t.Errorf("failed to encode image: %v", err) } }() // Create an HTTP request using the multipart writer and set the Content-Type header request := httptest.NewRequest("POST", "/", pr) request.Header.Add("Content-Type", writer.FormDataContentType()) // Create a response recorder to capture the response response := httptest.NewRecorder() // Define the handler function to test handler := func(w http.ResponseWriter, r *http.Request) { // Parse the multipart form data if err := r.ParseMultipartForm(32 << 20); err != nil { http.Error(w, "failed to parse multipart form data", http.StatusBadRequest) return } // Read the uploaded file file, header, err := r.FormFile("fileupload") if err != nil { if err == http.ErrMissingFile { http.Error(w, "missing file", http.StatusBadRequest) return } http.Error(w, fmt.Sprintf("failed to read file: %v", err), http.StatusInternalServerError) return } defer file.Close() // Save the file to disk outFile, err := os.Create("./uploads/" + header.Filename) if err != nil { http.Error(w, fmt.Sprintf("failed to save file: %v", err), http.StatusInternalServerError) return } defer outFile.Close() if _, err := io.Copy(outFile, file); err != nil { http.Error(w, fmt.Sprintf("failed to copy file: %v", err), http.StatusInternalServerError) return } w.Write([]byte("ok")) } // Serve the request with the handler function handler.ServeHTTP(response, request) // Verify the response status code and file creation if response.Code != http.StatusOK { t.Errorf("incorrect HTTP status: %d", response.Code) } if _, err := os.Stat("./uploads/someimg.png"); os.IsNotExist(err) { t.Errorf("failed to create file: ./uploads/someimg.png") } else if body, err := ioutil.ReadAll(response.Body); err != nil { t.Errorf("failed to read response body: %v", err) } else if string(body) != "ok" { t.Errorf("incorrect response body: %s", body) } }</code>
此範例提供了用於測試處理檔案上傳的端點的完整流程,從產生模擬 FormFile 到斷言回應狀態程式碼和檔案建立。透過利用 mime/multipart 套件和管道,您可以有效地模擬包含上傳檔案的請求並徹底測試您的端點。
以上是如何在 Go 中模擬 `http.Request.FormFile` 來測試 Web 端點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!