修复 Beego 运行的报错 trace not declared by package web

Beego 近来已经更新了 2.X,因此,你现在可以使用更新版本的 Beego 来完成你的快速开发。

不过,beego 2.x 在使用 bee 工具初始化一个新的项目时,默认的项目中有一个 bug,当你在项目根目录下执行 go test ./... 时,会提示 tests 目录中有一个错误。而你并没有修改任何的源文件。

如果单独执行 tests 目录,就会报错如下内容

tests/default_test.go:28:2: undefined: web.Trace

你会发现这段代码指向了 default_test.go 中的这行代码。

beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String())

这段代码中的 Trace 找不到导致无法正常使用。

我通过一些搜索,找到了答案。在 GitHub 中,beego 的 repo 下有一个 issue 和一个 pull request 与这个 bug 相关。结论是这个方法已经被移动到 log 文件夹,因此需要调整一下输出的来源。

在代码中引入 "github.com/beego/beego/v2/core/logs" 并将 beego.Trace 替换为 logs.Trace ,即可解决这个问题。

修改后的代码如下:

package test

import (
    "net/http"
    "net/http/httptest"
    "testing"
    "runtime"
    "path/filepath"
    _ "backend-server/routers"
    "github.com/beego/beego/v2/core/logs"
    beego "github.com/beego/beego/v2/server/web"
    . "github.com/smartystreets/goconvey/convey"
)

func init() {
    _, file, _, _ := runtime.Caller(0)
    apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator))))
    beego.TestBeegoInit(apppath)
}


// TestBeego is a sample to run an endpoint test
func TestBeego(t *testing.T) {
    r, _ := http.NewRequest("GET", "/", nil)
    w := httptest.NewRecorder()
    beego.BeeApp.Handlers.ServeHTTP(w, r)

    logs.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String())

    Convey("Subject: Test Station Endpoint\n", t, func() {
            Convey("Status Code Should Be 200", func() {
                    So(w.Code, ShouldEqual, 200)
            })
            Convey("The Result Should Not Be Empty", func() {
                    So(w.Body.Len(), ShouldBeGreaterThan, 0)
            })
    })
}

修复完成。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值