我正在为我的GraphQL应用程序接口制作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","path":["uploadCSV","file"]}]如何将localFile发送到我的接口?我想过通过curl来实现,但我不确定这是否是一种干净的方式。
发布于 2021-01-28 10:18:20
您不能像这样传递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结构类型中,这可能会使它乍一看有点混乱。
https://stackoverflow.com/questions/65924693
复制相似问题