单元测试一个返回多个文件流的HTTP处理程序

huangapple go评论85阅读模式
英文:

Unit testing a HTTP handler that returns a stream of multiple files

问题

HTTP处理程序

我有一个像这样的HTTP处理程序:

func RouteHandler(c echo.Context) error {
    outs := make([]io.Reader, 5)
    for i := range outs {
        outs[i] = // ...来自逻辑。
    }

    return c.Stream(http.StatusOK, "application/binary", io.MultiReader(outs...))
}

单元测试

我打算为HTTP处理程序编写一个单元测试,并调查返回的多个文件流。

我为我的单元测试准备了以下辅助类型和函数:

type Handler func(echo.Context) error

// 发送请求到处理程序。获取响应体。
func Send(req *http.Request, handler Handler) ([]byte, error) {
    w := httptest.NewRecorder()
    e := echo.New()
    c := e.NewContext(req, w)
    // 调用处理程序。
    err := handler(c)
    if err != nil {
        return nil, err
    }
    res := w.Result()
    defer res.Body.Close()
    return ioutil.ReadAll(res.Body)
}

然后,我使用上述类型和函数从我的单元测试中向我的HTTP处理程序发送请求:

// 从我的单元测试中:

// 初始化请求...

var data []byte
data, err := Send(request, RouteHandler)

// 如何分离这里返回的多个文件?
// 如何处理HTTP处理程序返回的数据?

处理返回的文件流

我该如何分离HTTP处理程序返回的多个文件?我该如何处理HTTP处理程序返回的数据流?

英文:

HTTP handler

I have a HTTP handler like this:

func RouteHandler(c echo.Context) error {
    outs := make([]io.Reader, 5)
    for i := range outs {
        outs[i] = // ... comes from a logic.
    }

    return c.Stream(http.StatusOK, "application/binary", io.MultiReader(outs...))
}

Unit test

I intend to write a unit test for HTTP handler and investigate the returned stream of multiple files.

I have these helper type and function for my unit test:

type Handler func(echo.Context) error

// Send request to a handler. Get back response body.
func Send(req *http.Request, handler Handler) ([]byte, error) {
    w := httptest.NewRecorder()
    e := echo.New()
    c := e.NewContext(req, w)
    // Call the handler.
    err := handler(c)
    if err != nil {
        return nil, err
    }
    res := w.Result()
    defer res.Body.Close()
    return ioutil.ReadAll(res.Body)
}

Then, I use the above type and function to send a request to my HTTP handler from within my unit test:

// From within my unit test:

// Initialize request...

var data []byte
data, err := Send(request, RouteHandler)

// How to separate the multiple files returned here?
// How to work with the returned data?

Work with returned stream of files

How can I separate multiple files returned by the HTTP handler? How can I work with the stream of data returned by HTTP handler?

答案1

得分: 0

实际上,@CeriseLimón评论中提到的选项已经被实现并被前端使用。

单元测试一个返回多个文件流的HTTP处理程序

英文:

> ... Possible options: write a length followed by the content of a file...

Actually, the above option commented by @CeriseLimón was already implemented and was used by the front-end.

单元测试一个返回多个文件流的HTTP处理程序

huangapple
  • 本文由 发表于 2023年2月13日 01:21:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75428800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定