Beego - 端点测试

时间:2016-05-02 12:59:29

标签: go beego

我正在为beego测试http自定义端点

package test

import (
    "github.com/astaxie/beego"
    . "github.com/smartystreets/goconvey/convey"
    _ "golife-api-cons/routers"
    "net/http"
    "net/http/httptest"
    "path/filepath"
    "runtime"
    "testing"
)

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

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

    beego.Trace("testing", "TestGet", "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)
        })
    })
}

当我使用go test -v

运行时

我得到回复dial tcp :0: getsockopt: connection refused

我正在使用在本地运行的MariaDB, 我已经使用netstat -tulpn验证了我的数据库运行正常(如果我使用postman并且我的服务器正在运行,我会得到有效的响应)

一个奇怪的观察,在包含行_ "golife-api-cons/routers"后,即使在测试运行之前我也会收到此错误

我的测试通过响应200 OK,但没有任何数据,因为我得到了响应上面提到的错误

修改

TestBeegoInit函数使用的默认路径为/path/to/my/project/test 这不是理想的路径,所以我尝试给出绝对路径,但我仍然无法连接数据库。

2 个答案:

答案 0 :(得分:1)

您正在将应用初始化为

apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
    beego.TestBeegoInit(apppath)
}

file是调用者文件。

TestBeegoInit是:

func TestBeegoInit(ap string) {
    os.Setenv("BEEGO_RUNMODE", "test")
    appConfigPath = filepath.Join(ap, "conf", "app.conf")
    os.Chdir(ap)
    initBeforeHTTPRun()
}

因此,您的测试正在寻找配置的位置是

<this_file>/../conf/app.conf

基本上是默认的配置文件。

基本上您无法连接到数据库。也许是因为您在不知不觉中连接到测试的默认数据库。我怀疑这不是你想要做的。

答案 1 :(得分:1)

经过多次尝试后,我开始知道beego在 beego / conf.go 中初始化名为AppPath的变量,如 -

AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))

运行测试时,请使用go test -v

运行测试

但是因此os.Args[0]是文本可执行文件,它将是 / tmp / path / to / test 而不是 path / to / app / exe

因此,它找不到 config / app.conf ,它位于您的应用程序路径中,其中包含数据库连接详细信息。 负责人 beego / conf.go -

appConfigPath = filepath.Join(AppPath, "conf", "app.conf")

当你说

时,这一切都发生在beego的init函数中
import (
  "github.com/astaxie/beego"
  _ "path/to/routers"
)

哈哈就是这个 -

使用init函数创建一个新的包/文件,看起来有 -

package common

import (
    "os"
    "strings"
)

func init() {
    cwd := os.Getenv("PWD")
    rootDir := strings.Split(cwd, "tests/")
    os.Args[0] = rootDir[0] // path to you dir
}

此处您正在更改os.Args[0]并指定目录路径

确保在beego之前导入它,所以现在导入将是

import (
  _ "path/to/common"
  "github.com/astaxie/beego"
  _ "path/to/routers"
)

最后你连接到DB!