micro/api/handler/http/http_test.go

113 lines
1.8 KiB
Go
Raw Normal View History

2019-06-03 18:44:43 +01:00
package http
import (
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/micro/go-micro/v2/api/handler"
"github.com/micro/go-micro/v2/api/router"
regRouter "github.com/micro/go-micro/v2/api/router/registry"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-micro/v2/registry/memory"
2019-06-03 18:44:43 +01:00
)
2020-04-08 19:20:43 +01:00
func testHttp(t *testing.T, path, service string) {
2019-06-03 18:44:43 +01:00
r := memory.NewRegistry()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
s := &registry.Service{
Name: service,
Nodes: []*registry.Node{
{
2019-06-03 18:44:43 +01:00
Id: service + "-1",
2019-07-08 08:01:42 +01:00
Address: l.Addr().String(),
2019-06-03 18:44:43 +01:00
},
},
}
r.Register(s)
defer r.Deregister(s)
// setup the test handler
m := http.NewServeMux()
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`you got served`))
})
// start http test serve
go http.Serve(l, m)
// create new request and writer
w := httptest.NewRecorder()
req, err := http.NewRequest("POST", path, nil)
if err != nil {
t.Fatal(err)
}
// initialise the handler
rt := regRouter.NewRouter(
router.WithHandler("http"),
2019-12-30 17:39:02 +00:00
router.WithRegistry(r),
2019-06-03 18:44:43 +01:00
)
p := NewHandler(handler.WithRouter(rt))
// execute the handler
p.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
}
if w.Body.String() != "you got served" {
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
}
}
func TestHttpHandler(t *testing.T) {
testData := []struct {
2020-04-08 19:20:43 +01:00
path string
service string
2019-06-03 18:44:43 +01:00
}{
{
"/test/foo",
2020-04-08 19:20:43 +01:00
"test",
2019-06-03 18:44:43 +01:00
},
{
"/test/foo/baz",
2020-04-08 19:20:43 +01:00
"test",
2019-06-03 18:44:43 +01:00
},
{
"/v1/foo",
2020-04-08 19:20:43 +01:00
"v1.foo",
2019-06-03 18:44:43 +01:00
},
{
"/v1/foo/bar",
2020-04-08 19:20:43 +01:00
"v1.foo",
2019-06-03 18:44:43 +01:00
},
{
"/v2/baz",
2020-04-08 19:20:43 +01:00
"v2.baz",
2019-06-03 18:44:43 +01:00
},
{
"/v2/baz/bar",
2020-04-08 19:20:43 +01:00
"v2.baz",
2019-06-03 18:44:43 +01:00
},
{
"/v2/baz/bar",
"v2.baz",
},
}
for _, d := range testData {
2020-04-08 19:20:43 +01:00
testHttp(t, d.path, d.service)
2019-06-03 18:44:43 +01:00
}
}