71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
|
package server
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"net/http/httptest"
|
||
|
"testing"
|
||
|
|
||
|
"github.com/stretchr/testify/assert"
|
||
|
)
|
||
|
|
||
|
func setupServer(t *testing.T) (*Server, error) {
|
||
|
t.Helper()
|
||
|
|
||
|
return NewServer()
|
||
|
}
|
||
|
|
||
|
func Test_Routes(t *testing.T) {
|
||
|
type testCase struct {
|
||
|
Name string
|
||
|
Method string
|
||
|
Path string
|
||
|
Setup func(t *testing.T, req *http.Request)
|
||
|
Expected func(t *testing.T, resp *http.Response)
|
||
|
}
|
||
|
|
||
|
testCases := []testCase{
|
||
|
{
|
||
|
Name: "Version Handler",
|
||
|
Method: http.MethodGet,
|
||
|
Path: "/api/version",
|
||
|
Setup: func(t *testing.T, req *http.Request) {
|
||
|
},
|
||
|
Expected: func(t *testing.T, resp *http.Response) {
|
||
|
contentType := resp.Header.Get("Content-Type")
|
||
|
assert.Equal(t, contentType, "application/json; charset=utf-8")
|
||
|
body, err := io.ReadAll(resp.Body)
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, `{"version":"0.0.0"}`, string(body))
|
||
|
},
|
||
|
},
|
||
|
}
|
||
|
|
||
|
s, err := setupServer(t)
|
||
|
assert.Nil(t, err)
|
||
|
|
||
|
router := s.GenerateRoutes()
|
||
|
|
||
|
httpSrv := httptest.NewServer(router)
|
||
|
t.Cleanup(httpSrv.Close)
|
||
|
|
||
|
for _, tc := range testCases {
|
||
|
u := httpSrv.URL + tc.Path
|
||
|
req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
|
||
|
assert.Nil(t, err)
|
||
|
|
||
|
if tc.Setup != nil {
|
||
|
tc.Setup(t, req)
|
||
|
}
|
||
|
|
||
|
resp, err := httpSrv.Client().Do(req)
|
||
|
assert.Nil(t, err)
|
||
|
|
||
|
if tc.Expected != nil {
|
||
|
tc.Expected(t, resp)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|