登录
首页 >  Golang >  Go问答

Go Fiber的主体无法在单元测试中被解析

来源:stackoverflow

时间:2024-02-10 10:57:23 247浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Go Fiber的主体无法在单元测试中被解析》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正式向 stack overflow 的仁慈的撒玛利亚人喊一声叔叔。

我正在尝试使用模拟数据库对我的 gorm (postgres) + fiber api 进行单元测试。我有一个用于 post 请求正文的 card 模型和 createcardreqbody 模型。为了设置测试,我创建一个随机 createcardreqbody 实例,将其编组为 json,然后将其传递到 *httptest.request 中。该处理程序使用 fiber 的 (* fiber.ctx).bodyparser 函数将请求正文“解组”为空 card 结构。但是,当我运行应该通过的测试时,fiber 抛出“无法处理的实体”错误。

以下是我的代码的相关部分;测试文件是本教程和 fiber 关于 (*app).test 方法的文档的组合。 (我意识到代码可以清理;我只是想获得生命的证明,然后专注于修改:)

我做了一些事情来调试这个:我使用与测试相同的值发出了 postman post 请求,并且它有效。在测试本身中,我编组然后解组 createcardreqbody 结构,并且该结构有效。我已经三次检查了 json 字段的拼写是否匹配、结构体字段是否已导出等。我还运行了 vscode 调试器,fiber.ctx 中的 body 字段对我来说看起来也是正确的。

我开始怀疑这是否与 fiber 从测试请求和真实请求中解析正文的方式有关。我将非常感谢任何人能分享对此的见解!

模型定义

type card struct {
gorm.model

// implicit gorm foreign key to fleet id
fleetid uint `gorm:"index"  json:"fleet_id" validate:"required,min=1"`

// card provider's account number
provideraccountnumber string `json:"provider_account_number"`

// card provider's external card identifier
cardidentifier string `gorm:"index" json:"card_identifier" validate:"min=1"`

// implicit gorm foreign key to driver id. driver association is optional.
driverid uint `json:"associated_driver_id" validate:"min=1"`

// implicit gorm foreign key to vehicle id.
vehicleid uint `json:"associated_vehicle_id" validate:"required,min=1"`

// user-inputted start date, formatted "2020-01-26t22:38:25.000z" in utc
startdate pq.nulltime

}

测试文件

// adapted from tutorial
type testcase struct {
    name          string
    body          createcardreqbody
    setupauth     func(t *testing.t, request *http.request)
    buildstubs    func(db *mockdb.mockdbinterface)
    checkresponse func(response *http.response, outputerr error)
}

type createcardreqbody struct {
    fleetid               int    `json:"fleet_id"`
    provideraccountnumber string `json:"provider_account_number"`
    cardidentifier        string `json:"card_identifier"`
    startdate             string `json:"start_date"`
    associateddriverid    int    `json:"associated_driver_id"`
    associatedvehicleid   int    `json:"associated_vehicle_id"`
}

func testcreatecard(t *testing.t) {
    user := randomuser(t)
    vehicle := randomvehicle()
    driver := randomdriver(vehicle.fleetid)
    okreqcard := randomcard(vehicle.fleetid)

    finaloutputcard := okreqcard
    finaloutputcard.id = 1

    testcases := []testcase{
        {
            name: "ok",
            body: createcardreqbody{
                fleetid:               int(okreqcard.fleetid),
                provideraccountnumber: okreqcard.provideraccountnumber,
                cardidentifier:        okreqcard.cardidentifier,
                startdate:             okreqcard.startdate.time.format("2006-01-02t15:04:05.999z"),
                associateddriverid:    int(okreqcard.driverid),
                associatedvehicleid:   int(okreqcard.vehicleid),
            },
            setupauth: func(t *testing.t, request *http.request) {
                addauthorization(t, request, user)
            },
            // tell mock database what calls to expect and what values to return
            buildstubs: func(db *mockdb.mockdbinterface) {
                db.expect().
                    userexist(gomock.eq(fmt.sprint(vehicle.fleetid))).
                    times(1).return(user, true, user.id)

                db.expect().
                    searchtsp(gomock.eq(fmt.sprint(vehicle.fleetid))).
                    times(1)

                db.expect().
                    searchvehicle(gomock.eq(fmt.sprint(okreqcard.vehicleid))).
                    times(1).
                    return(vehicle, nil)

                db.expect().
                    searchdriver(gomock.eq(fmt.sprint(driver.id))).
                    times(1).
                    return(driver, nil)

                db.expect().
                    cardcreate(gomock.eq(okreqcard)).
                    times(1).
                    return(finaloutputcard, nil)

            },
            checkresponse: func(res *http.response, outputerr error) {
                require.noerror(t, outputerr)
                // internal helper func, excluded for brevity
                requirebodymatchcard(t, finaloutputcard, res.body)
            },
        },
    }

    for _, test := range testcases {
        t.run(test.name, func(t *testing.t) {
            ctrl := gomock.newcontroller(t)
            defer ctrl.finish()

            mockdb := mockdb.newmockdbinterface(ctrl)
            test.buildstubs(mockdb)

            jsonbytes, err := json.marshal(test.body)
            require.noerror(t, err)
            jsonbody := bytes.newreader(jsonbytes)

            // debug check: am i able to unmarshal it back? yes.
            errunmarsh := json.unmarshal(jsonbytes, &createcardreqbody{})
            require.noerror(t, errunmarsh)

            endpoint := "/v1/transactions/card"
            request := httptest.newrequest("post", endpoint, jsonbody)
            // setupauth is helper function (not shown in this post) that adds authorization to httptest request
            test.setupauth(t, request)
            
            app := init("test", mockdb)
            res, err := app.test(request)

            test.checkresponse(res, err)

        })
    }
}

正在测试路由处理程序

func (server *Server) CreateCard(c *fiber.Ctx) error {
    var card models.Card

    var err error
    // 1) Parse POST data
    if err = c.BodyParser(&card); err != nil {
        return c.Status(http.StatusUnprocessableEntity).SendString(err.Error())
    }
    ...
}

调试器输出

测试中定义的 json 主体

纤维上下文中的主体


正确答案


捂脸

我忘了 request.Header.Set("Content-Type", "application/json")!发布此内容以防对其他人有帮助:)

今天关于《Go Fiber的主体无法在单元测试中被解析》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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