如何UT上传文件

问题描述

我正在为我的 GraphQL API 制作 UT。我需要在上传文件的地方测试突变。 我在这个项目中使用了 gqlgen。

...
localFile,err := os.Open("./file.xlsx")
if err != nil {
    fmt.Errorf(err.Error())
}

c.MustPost(queries.UPLOAD_CSV,&resp,client.Var("id",id),client.Var("file",localFile),client.AddHeader("Authorization","Bearer "+hub.Accesstoken))

c.MustPost 恐慌并发送错误

--- FAIL: TestUploadCSV (0.00s)
panic: [{"message":"map[string]interface {} is not an Upload","path":["uploadCSV","file"]}] [recovered]
panic: [{"message":"map[string]interface {} is not an Upload","file"]}]

如何将 localFile 发送到我的 API?我想通过 curl 来实现它,但我不确定这是否是一种干净的方法

解决方法

您不能像那样传递 os.File。您需要实际读取文件,构建 MIME 多部分请求正文(请参阅 spec)并在 POST 请求中发送。

buf := &bytes.Buffer{}
w := multipart.NewWriter(...)

// add other required fields (operations,map) here

// load file (you can do these directly I am emphasizing them 
// as variables so code below is more understandable
fileKey := "0" // file key in 'map'
fileName := "file.xslx" // file name
fileContentType := "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
fileContents,err := ioutil.ReadFile("./file.xlsx")
// ...

// make multipart body
h := make(textproto.MIMEHeader)

h.Set("Content-Disposition",fmt.Sprintf(`form-data; name="%s"; filename="%s"`,fileKey,fileName))
h.Set("Content-Type",fileContentType)
ff,err := bodyWriter.CreatePart(h)
// ...
_,err = ff.Write(fileContents)
// ...
err = bodyWriter.Close()
// ...

req,err := http.NewRequest("POST",fmt.Sprintf("https://endpoint"),buf)
//...

在此处的 gqlgen 存储库本身中有一个很好的工作示例:example/fileupload/fileupload_test.go

在那个例子中,每个文件都被加载到(并由)file 结构类型定义在我链接的行上,这可能会让它乍一看有点混乱。