我编写了一个将数据保存到 redis 数据库服务器的函数。挑战在于我想测试这些功能,但不知道如何测试。我只是以某种方式开始功能package sessrage/* * Save data into redis database. In the common case, * the data will be only valid during a request. Use * hash datatype in redis. */import ( "../context" "github.com/garyburd/redigo/redis" "net/http")const ( protocol string = "tcp" port string = ":6379")func connectAndCloseRedis(connectCall func(con redis.Conn)) { c, err := redis.Dial("tcp", ":6379") defer c.Close() if err != nil { panic(err.Error()) } connectCall(c)}func PostSessionData(r *http.Request, key, value string) { go connectAndCloseRedis(func(con redis.Conn) { sessionId := context.Get(r, context.JwtId).(string) con.Do("HMSET", sessionId, key, value) })}func GetSessionData(r *http.Request, key string) interface{} { var result interface{} sessionId := context.Get(r, context.JwtId).(string) reply, _ := redis.Values(c.Do("HMGET", sessionId, key)) redis.Scan(reply, &result) return result}和测试文件package sessrageimport ( //"fmt" "../context" . "github.com/smartystreets/goconvey/convey" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" "time")var server *httptest.Servervar glrw http.ResponseWritervar glr *http.Requestfunc init() { server = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { glrw = rw glr = r context.Set(glr, context.JwtId, "TestId") }))}func TestPostAndGetSession(t *testing.T) { Convey("POST and GET data on redis.", t, func() { PostSessionData(glr, "key1", "value1") time.Sleep(time.Second * 10) v := GetSessionData(glr, "key1") assert.Equal(t, "value1", v) })}当我尝试运行测试时an't load package: ......./sessrage.go:10:2: local import "../context" in non-local package和上下文包看起来像package contextimport ( "github.com/gorilla/context" "net/http")我怎么了?那是我第一次结合 http 测试代码。似乎很难测试。
1 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
有几个问题:
不要使用相对导入路径。
使用池而不是在每个操作上拨打 redis。
如果多路复用器或调用链中的更高层在 goroutine 运行之前清除了 Gorilla 上下文,则 PostSessionData 匿名函数中对 sessionId := context.Get(r, context.JwtId).(string) 的调用可能会失败。改为这样做:
func PostSessionData(r *http.Request, key, value string) {
c := pool.Get()
defer c.Close()
sessionId := context.Get(r, context.JwtId).(string)
if err := c.Do("HMSET", sessionId, key, value); err != nil {
// handle error
}
}
- 1 回答
- 0 关注
- 207 浏览
添加回答
举报
0/150
提交
取消