Golang FormFile unit test

Viewed 40

I have the following function:

func CreateByID(w http.ResponseWriter, r *http.Request) {
    formFile, _, err := r.FormFile("audio")
    if err != nil {
        return
    }
    defer formFile.Close()
    defer r.MultipartForm.RemoveAll()

    tmpFile, err := os.CreateTemp("/tmp")
    if err != nil {
        return
    }
    defer os.Remove(tmpFile.Name())
    io.Copy(tmpFile, formFile)

    err = validateFile(tmpFile.Name())
    if err != nil {
        return
    }
}

func validateFile(path string) error {
    fs, err := os.Stat(path)
    if err != nil {
        return
    }
    if fs.Size() < allowedSize {
       return fmt.Errorf("file is too small")
    }
}


which is basically creating a temp file from the HTTP request and validating it before further processing. This works fine except for the unit test. When I'm testing this function - I'm getting always filesize = 0.

Below you can see the Test case:

func TestCreateByID(t *testing.T) {
    pr, pw := io.Pipe()
    writer := multipart.NewWriter(pw)

    go func() {
        defer writer.Close()
        _, err := writer.CreateFormFile("audio", "/tmp/audioFile")
        if err != nil {
            t.Error(err)
        }
        generateAudioSample("/tmp/audioFile")
    }()

    request := httptest.NewRequest(http.MethodGet, "/{id}")
    request.Header.Add("Content-Type", writer.FormDataContentType())

    response := httptest.NewRecorder()

    # Calling The Actual Function
    CreateByID(response, request)

    handler := http.NewServeMux()
    handler.ServeHTTP(response, request)

    if response.Code != 200 {
        t.Errorf("Expected %d, received %d", 200, response.Code)
        return
    }
}

generateAudioSample function is working fine because I can see the file on the filesystem and its size it bigger than 0 but for some reason this function io.Copy(tmpFile, formFile) doesn't seem to handle FormFile correctly, and is creating just an empty file on the filesystem and obviously fail the test. What else should I add to the test function in order to pass the test?

0 Answers
Related