我有一个HTTP处理程序功能(POST),该功能允许用户从Web浏览器应用程序上载文件夹。文件夹从JavaScript代码作为文件夹中的文件数组传递,并且在后端(Go API)上,它被接受为[]*multipart.FileHeader
。我正在为此功能编写Go单元测试。如何传递文件夹作为测试功能的输入?我需要帮助以正确的格式创建httpRequest
。
我尝试对FileHeader
数组使用/设置值,但是不允许导入某些属性。因此,必须有一种我不知道的测试此处理程序的方法。
用于文件夹上传的处理函数:
func FolderUpload(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// SOME LOGIC
files := r.MultipartForm.File["multiplefiles"] // files is of the type []*multipart.FileHeader
// SOME LOGIC TO PARSE THE FILE NAMES TO RECREATE THE SAME TREE STRUCTURE ON THE SERVER-SIDE AND STORE THEM AS A FOLDER
同一处理程序的单元测试功能:
func TestFolderUpload(t *testing.T) {
// FolderPreCondition()
request, err := http.NewRequest("POST", uri, body) //Q: HOW TO CREATE THE BODY ACCEPTABLE BY THE ABOVE HANDLER FUNC?
// SOME ASSERTION LOGIC
}
答案 0 :(得分:2)
您应编写文件以请求:
func newFileUploadRequest(url string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
if err != nil {
return nil, err
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", writer.FormDataContentType())
return req, err
}
然后使用它:
req, err := newFileUploadRequest("http://localhost:1234/upload", "multiplefiles", path)
client := &http.Client{}
resp, err := client.Do(req)
它对我有用,希望对您有帮助