登录
首页 >  Golang >  Go问答

在Golang单元测试中模拟上传文件

来源:stackoverflow

时间:2024-03-08 08:06:25 328浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《在Golang单元测试中模拟上传文件》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我想用 json 正文和测试文件测试 httprequest。 我不知道如何将创建的测试文件添加到请求正文 json 旁边。

body := strings.NewReader(URLTest.RequestBody)
        request, err := http.NewRequest(URLTest.MethodType, "localhost:"+string(listeningPort)+URLTest.URL, body)
        if err != nil {
            t.Fatalf("HTTP NOT WORKING")
        }

        fileBuffer := new(bytes.Buffer)
        mpWriter := multipart.NewWriter(fileBuffer)
        fileWriter, err := mpWriter.CreateFormFile("file", "testfile.pdf")
        if err != nil {
            t.Fatalf(err.Error())
        }
        file, err := os.Open("testfile.pdf")
        if err != nil {
            t.Fatalf(err.Error())
        }
        defer file.Close()
        _, err = io.Copy(fileWriter, file)
        if err != nil {
            t.Fatalf(err.Error())
        }

        rec := httptest.NewRecorder()
        UploadFiles(rec, request, nil)
        response := rec.Result()
        if response.StatusCode != URLTest.ExpectedStatusCode {
            t.Errorf(URLTest.URL + " status mismatch")
        }

        responseBody, err := ioutil.ReadAll(response.Body)
        defer response.Body.Close()

        if err != nil {
            t.Errorf(URLTest.URL + " cant read response")
        } else {
            if strings.TrimSpace(string(responseBody)) != URLTest.ExpectedResponseBody {
                t.Errorf(URLTest.URL + " response mismatch - have: " + string(responseBody) + " want: " + URLTest.ExpectedResponseBody)
            }
        }
    }

我可以将文件添加为 request.formfile.add(...) 之类的值吗?


解决方案


关于如何使用 go 在 http 请求中发送文件的问题,这里有一些示例代码。

您将需要 mime/multipart package 来构建表单。

package main

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "os"
    "strings"
)

func main() {

    var client *http.Client
    var remoteURL string
    {
        //setup a mocked http client.
        ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            b, err := httputil.DumpRequest(r, true)
            if err != nil {
                panic(err)
            }
            fmt.Printf("%s", b)
        }))
        defer ts.Close()
        client = ts.Client()
        remoteURL = ts.URL
    }

    //prepare the reader instances to encode
    values := map[string]io.Reader{
        "file":  mustOpen("main.go"), // lets assume its this file
        "other": strings.NewReader("hello world!"),
    }
    err := Upload(client, remoteURL, values)
    if err != nil {
        panic(err)
    }
}

func Upload(client *http.Client, url string, values map[string]io.Reader) (err error) {
    // Prepare a form that you will submit to that URL.
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    for key, r := range values {
        var fw io.Writer
        if x, ok := r.(io.Closer); ok {
            defer x.Close()
        }
        // Add an image file
        if x, ok := r.(*os.File); ok {
            if fw, err = w.CreateFormFile(key, x.Name()); err != nil {
                return
            }
        } else {
            // Add other fields
            if fw, err = w.CreateFormField(key); err != nil {
                return
            }
        }
        if _, err = io.Copy(fw, r); err != nil {
            return err
        }

    }
    // Don't forget to close the multipart writer.
    // If you don't close it, your request will be missing the terminating boundary.
    w.Close()

    // Now that you have a form, you can submit it to your handler.
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return
    }
    // Don't forget to set the content type, this will contain the boundary.
    req.Header.Set("Content-Type", w.FormDataContentType())

    // Submit the request
    res, err := client.Do(req)
    if err != nil {
        return
    }

    // Check the response
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}

希望您可以在单元测试中使用它

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在Golang单元测试中模拟上传文件》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>