golang如何测试一台http服务器? [英] golang how to live test an http server?

查看:157
本文介绍了golang如何测试一台http服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用gotests和gorilla mux,我可以单元测试我的http handlefunc处理程序,但它们不响应正确的http请求方法,因为它们应该在大猩猩多路复用器下。我如何做一个活服务器版本的测试?

  func main(){
router:= mux.NewRouter()
router.HandleFunc(/,views.Index).Methods(GET)
}

func索引(w http.ResponseWriter,r (http.Request){
w.Header()。Set(Content-Type,application / json; charset = UTF-8)
w.WriteHeader(http.StatusOK)

fmt.Fprintf(w,INDEX \ n)
}

func TestIndex(t * testing.T){

req,_:= http.NewRequest(GET,/,nil)
req1,_:= http.NewRequest(POST,/,nil)
rr:= httptest .NewRecorder()

处理程序:= http.HandlerFunc(索引)

类型参数struct {
w http.ResponseWriter
r * http.Request

tests:= [] struct {
name string
args args
} {
{name:1:testing get,args:args { w:rr,r:req}},
{name:2:testing post,args:args {w:rr,r:req1}},
}
for _,tt:=范围测试{
t.Run(tt.name,func(t * testing.T){
handler.ServeHTTP(tt.args.w, tt.args.r)
log.Println(tt.args.w)
})
}
}

这里的问题是函数对get和post请求做出响应,而
dons没有考虑到我的主要路由器。这对于单元测试函数
来说没什么问题,但我认为最好是编写一个集成测试来测试整个
的东西,并且一气呵成地完成一切。 使用 noreferrer> net / http / httptest.Server 类型以使用实时服务器进行测试。

  func TestIndex(t * testing.T){
//使用在其他地方初始化的路由器创建服务器。路由器
//可以是一个Gorilla mux,如问题所示,一个网络/ http ServeMux,
// http.DefaultServeMux或任何统计网络/ http
的值// Handler接口。
ts:= httptest.NewServer(router)
推迟ts.Close()

newreq:= func(方法,url string,body io.Reader)* http.Request {
r,err:= http.NewRequest(method,url,body)
if err!= nil {
t.Fatal(err)
}
return r


tests:= [] struct {
name string
r * http.Request
} {
{name:1:测试得到,r:newreq(GET,ts.URL +/,nil)},
{name:2:testing post,r:newreq(POST,ts.URL +/ ,nil)},// POST所需的读取参数
}
for _,tt:=范围测试{
t.Run(tt.name,func(t * testing.T ){
resp,err:= http.DefaultClient.Do(tt.r)
推迟resp.Body.Close()
if err!= nil {
t.Fatal (错误)
}
//检查预期的响应在这里。
})
}
}

虽然这个问题使用了Gorilla mux,但这个方法和细节swer适用于任何满足http.Handler接口的路由器。


I use gotests, and gorilla mux and I can unit test my http handlefunc handlers, but they do not respond to the proper http request methods as they should under the gorilla mux. How I can do a "live server" version of the test?

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", views.Index).Methods("GET")
}

func Index(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)

    fmt.Fprintf(w, "INDEX\n")
}

func TestIndex(t *testing.T) {

    req, _ := http.NewRequest("GET", "/", nil)
    req1, _ := http.NewRequest("POST", "/", nil)
    rr := httptest.NewRecorder()

    handler := http.HandlerFunc(Index)

    type args struct {
        w http.ResponseWriter
        r *http.Request
    }
    tests := []struct {
        name string
        args args
    }{
        {name: "1: testing get", args: args{w: rr, r: req}},
        {name: "2: testing post", args: args{w: rr, r: req1}},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            handler.ServeHTTP(tt.args.w, tt.args.r)
            log.Println(tt.args.w)
        })
    }
}

The problem here is that the function responds to both the get and post requests and doens't take into account my main router. This is fine for unit testing the function, but I think it would be better to just write an integrated test that tests the whole thing and gets everything out of the way in one go.

解决方案

Use the net/http/httptest.Server type to test with a live server.

func TestIndex(t *testing.T) {
  // Create server using the a router initialized elsewhere. The router
  // can be a Gorilla mux as in the question, a net/http ServeMux, 
  // http.DefaultServeMux or any value that statisfies the net/http
  // Handler interface.
  ts := httptest.NewServer(router)  
  defer ts.Close()

  newreq := func(method, url string, body io.Reader) *http.Request {
    r, err := http.NewRequest(method, url, body)
    if err != nil {
        t.Fatal(err)
    }
    return r
  }

  tests := []struct {
    name string
    r    *http.Request
  }{
    {name: "1: testing get", r: newreq("GET", ts.URL+"/", nil)},
    {name: "2: testing post", r: newreq("POST", ts.URL+"/", nil)}, // reader argument required for POST
  }
  for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        resp, err := http.DefaultClient.Do(tt.r)
        defer resp.Body.Close()
        if err != nil {
            t.Fatal(err)
        }
        // check for expected response here.
    })
  }
}

Although the question uses Gorilla mux, the approach and details in this answer apply to any router that satisfies the http.Handler interface.

这篇关于golang如何测试一台http服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆