亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何UT上傳文件

如何UT上傳文件

Go
智慧大石 2022-08-01 18:44:36
我正在努力為我的 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
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

你不能只是通過這樣的。您需要實際讀取文件,構建MIME多部分請求正文(請參閱規范)并在POST請求中發送它。os.File


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)

//...

這里有一個很好的工作示例,可以在存儲庫本身中執行此操作:example/fileupload/fileupload_test.go。gqlgen


在該示例中,每個文件都被加載到(并由其表示)在我鏈接的行上定義的結構類型中,這可能會使它在第一眼時有點混亂。file


查看完整回答
反對 回復 2022-08-01
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號