How to make API test files with Beego

2019-07-07 02:42发布

问题:

I have below test file:

package tests

import (
    "net/http"
    "net/http/httptest"
    "testing"
    "runtime"
    "path/filepath"
    _ "hello/routers"
    _ "github.com/lib/pq"

    "github.com/astaxie/beego"
    . "github.com/smartystreets/goconvey/convey"
)

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", "/api/testing", 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)
            })
    })
}

Then when I run go test tests/*.go

I get:

2015/01/14 23:55:19 [config.go:284] [W] open /home/IdeaProjects/go/src/hello/tests/conf/app.conf: no such file or directory 
[ORM]register db Ping `default`, pq: password authentication failed for user "hello"
must have one register DataBase alias named `default`
FAIL    command-line-arguments  0.008s

I've bootstraped Beego with bee api then using pq Postgres Driver for PG database.

Also I'm not sure why it's looking at /hello/tests/conf/app.conf path for app.conf file it should look for /hello/conf/app.conf.

Is there a reason why this is happening?

回答1:

PG can't authenticate you probably because it can't find the password in the app.conf file, which it also can't find because it's looking in the wrong place.

Try using an absolute path to your config rather than the convoluted method you have in your init() function.