猿问

如何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.必须发布死机并发送错误:


--- 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"]}]

如何将 发送到我的 API?我想过通过卷曲,但我不确定这是否是一种干净的方式。localFile


智慧大石
浏览 135回答 1
1回答

SMILET

你不能只是通过这样的。您需要实际读取文件,构建MIME多部分请求正文(请参阅规范)并在POST请求中发送它。os.Filebuf := &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 understandablefileKey := "0" // file key in 'map'fileName := "file.xslx" // file namefileContentType := "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"fileContents, err := ioutil.ReadFile("./file.xlsx")// ...// make multipart bodyh := 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)//...这里有一个很好的工作示例,可以在存储库本身中执行此操作:example/fileupload/fileupload_test.go。gqlgen在该示例中,每个文件都被加载到(并由其表示)在我链接的行上定义的结构类型中,这可能会使它在第一眼时有点混乱。file
随时随地看视频慕课网APP

相关分类

Go
我要回答