duan5362 2019-04-15 08:32
浏览 67

如何测试以文件夹为输入的HTTP函数?

I have an HTTP handler function (POST) which allows a user to upload a folder from a web browser application. The folder is passed from JavaScript code as an array of files in a folder and on the backend (Go API) it is accepted as a []*multipart.FileHeader. I am struggling in writing a Go unit test for this function. How can I pass a folder as input from a test function? I need help in creating the httpRequest in the right format.

I have tried to use / set values for an array of FileHeader, but some attributes are not allowed to be imported. So there must be a different way of testing this handler that I am not aware of.

Handler Function for folder upload:

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

Unit Test function for the same handler:

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
}
  • 写回答

1条回答 默认 最新

  • duanjiati1755 2019-04-15 09:08
    关注

    You should write your file to request:

    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
    

    }

    then use it:

        req, err := newFileUploadRequest("http://localhost:1234/upload", "multiplefiles", path)
    
    client := &http.Client{}
    
    resp, err := client.Do(req)
    

    It works for me, hope it helps you)

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)