golift.io/starr@v1.0.0/starrtest/starrtest.go (about) 1 // Package starrtest provides methods that are shared by all the tests in the other sub packages. 2 package starrtest 3 4 import ( 5 "io" 6 "net/http" 7 "net/http/httptest" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 // MockData allows generic testing of http inputs and outputs. 14 // This is used by the submodule tests. 15 type MockData struct { 16 // A name for the test. 17 Name string 18 // The path expected in the request ie. /api/v1/thing 19 ExpectedPath string 20 // The request body (json) expected from the caller. 21 ExpectedRequest string 22 // The request method (GET/POST) expected from the caller. 23 ExpectedMethod string 24 // This is the status that gets returned the caller. 25 ResponseStatus int 26 // The (json) response body returned to caller. 27 ResponseBody string 28 // Caller's request. 29 WithRequest interface{} 30 // Caller's response. 31 WithResponse interface{} 32 // Caller's response. 33 WithError error 34 } 35 36 const ( 37 // Error body for 401 response. 38 BodyUnauthorized = `{"error": "Unauthorized"}` 39 // Error body for 404 response. 40 BodyNotFound = `{"message": "NotFound"}` 41 // Error body for 405 response. 42 BodyMethodNotAllowed = `{"message": "MethodNotAllowed"}` 43 ) 44 45 // GetMockServer is used in all the submodule http tests. 46 func (test *MockData) GetMockServer(t *testing.T) *httptest.Server { 47 t.Helper() 48 49 return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) { 50 assert.EqualValues(t, test.ExpectedPath, req.URL.String(), 51 "test.ExpectedPath does not match the actual path") 52 writer.WriteHeader(test.ResponseStatus) 53 assert.EqualValues(t, test.ExpectedMethod, req.Method, 54 "test.ExpectedMethod does not match the actual method") 55 56 body, err := io.ReadAll(req.Body) 57 assert.NoError(t, err) 58 assert.EqualValues(t, test.ExpectedRequest, string(body), 59 "test.ExpectedRequest does not match body for actual request") 60 61 _, err = writer.Write([]byte(test.ResponseBody)) 62 assert.NoError(t, err) 63 })) 64 }