登录
首页 >  Golang >  Go问答

测试 Gin 中需要读取外部文件的处理程序该如何测试?

来源:stackoverflow

时间:2024-02-19 09:51:23 276浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《测试 Gin 中需要读取外部文件的处理程序该如何测试?》,涉及到,有需要的可以收藏一下

问题内容

我有一个简单的 gin 服务器,其中一条路由名为 /metadata

处理程序的作用是从系统读取文件,例如 /etc/myapp/metadata.json 并在响应中返回 json。

但是当找不到文件时,处理程序被配置为返回以下错误。

500: metadata.json does not exists or not readable

在我的具有metadata.json 文件的系统上,测试通过。这是我正在使用的测试函数:

package handlers_test

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "myapp/routes"

    "github.com/stretchr/testify/assert"
)

func testmetadataroute(t *testing.t) {
    router := routes.setuprouter()

    w := httptest.newrecorder()
    req, _ := http.newrequest("get", "/metadata", nil)
    router.servehttp(w, req)

    assert.notnil(t, w.body)
    assert.equal(t, 200, w.code)
    assert.contains(t, w.body.string(), "field1")
    assert.contains(t, w.body.string(), "field2")
    assert.contains(t, w.body.string(), "field3")
    assert.contains(t, w.body.string(), "field4")
}

但是在ci环境下,测试会失败,因为找不到metadata.json。并会返回配置的错误。

可以做什么?

我有这个处理程序:

func GetMetadata(c *gin.Context) {
    // read the info
    content, err := ioutil.ReadFile("/etc/myapp/metadata.json")
    if err != nil {
        c.JSON(http.StatusInternalServerError,
            gin.H{"error": "metadata.json does not exists or not readable"})
        return
    }

    // deserialize to json
    var metadata models.Metadata
    err = json.Unmarshal(content, &metadata)
    if err != nil {
        c.JSON(http.StatusInternalServerError,
            gin.H{"error": "unable to parse metadata.json"})
        return
    }

    c.JSON(http.StatusOK, metadata)
}

正确答案


volker 建议使用包级未导出变量。您可以为其指定一个固定的默认值,对应于生产中所需的路径,然后只需在单元测试中覆盖该变量即可。

处理程序代码:

var metadatafilepath = "/etc/myapp/metadata.json"

func getmetadata(c *gin.context) {
    // read the info
    content, err := ioutil.readfile(metadatafilepath)
    // ... rest of code
}

测试代码:

func testmetadataroute(t *testing.t) {
    metadatafilepath = "testdata/metadata_test.json"
    // ... rest of code
}

这是一个超级简单的解决方案。有很多方法可以对此进行改进,但都是 how to inject any variable in a Gin handler 的变体。对于简单的请求范围配置,我通常所做的是将变量注入到 gin 上下文中。这需要稍微重构一些代码:

带有用于生产的中间件的路由器设置代码

func setuprouter() {
    r := gin.new()
    r.get("/metadata", metadatapathmiddleware("/etc/myapp/metadata.json"), getmetadata)
    // ... rest of code
}

func metadatapathmiddleware(path string) gin.handlerfunc {
    return func(c *gin.context) {
        c.set("_mdpath", path)
    }
}

从上下文中提取路径的处理程序代码:

func getmetadata(c *gin.context) {
    metadatafilepath := c.getstring("_mdpath")
    content, err := ioutil.readfile(metadatafilepath)
    // ... rest of code
}

您应该重构以仅测试处理程序的测试代码(更多详细信息:How to unit test a Go Gin handler function?):

func TestMetadataRoute(t *testing.T) {
    // create Gin test context
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    // inject test value into context
    c.Set("_mdpath", "testdata/metadata_test.json")

    // just test handler, the passed context holds the test value
    GetMetadata(c)
   
    // ... assert
}

注意:不鼓励使用字符串键设置上下文值,但是 gin 上下文仅接受字符串键。

终于介绍完啦!小伙伴们,这篇关于《测试 Gin 中需要读取外部文件的处理程序该如何测试?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>