github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/net/http/response.function_test.go (about) 1 package http 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "reflect" 7 "testing" 8 9 "github.com/sirupsen/logrus" 10 11 "github.com/angryronald/go-kit/cast" 12 "github.com/angryronald/go-kit/constant" 13 ) 14 15 func TestResponse(t *testing.T) { 16 // Prepare a sample data for the response 17 data := map[string]interface{}{ 18 "key": "value", 19 } 20 21 // Create a new HTTP request with a response recorder 22 _, err := http.NewRequest("GET", "/", nil) 23 if err != nil { 24 t.Fatal(err) 25 } 26 w := httptest.NewRecorder() 27 28 // Call the Response function 29 Response(w, http.StatusOK, data, logrus.New()) 30 31 // Check the response status code 32 if w.Code != http.StatusOK { 33 t.Errorf("expected status code %d but got %d", http.StatusOK, w.Code) 34 } 35 36 // Decode the response body 37 var response ResponseModel 38 err = cast.FromBytes(w.Body.Bytes(), &response) 39 if err != nil { 40 t.Fatal(err) 41 } 42 43 // Check the response data 44 if !reflect.DeepEqual(response.Data, data) { 45 t.Errorf("expected %v, got %s", response.Data, data) 46 } 47 } 48 49 func TestResponseError(t *testing.T) { 50 // Create a new HTTP request with a response recorder 51 _, err := http.NewRequest("GET", "/", nil) 52 if err != nil { 53 t.Fatal(err) 54 } 55 w := httptest.NewRecorder() 56 57 // Call the ResponseError function 58 ResponseError(w, http.StatusNotFound, "", logrus.New()) 59 60 // Check the response status code 61 if w.Code != http.StatusNotFound { 62 t.Errorf("expected status code %d but got %d", http.StatusNotFound, w.Code) 63 } 64 65 // Decode the response body 66 var response ResponseModel 67 err = cast.FromBytes(w.Body.Bytes(), &response) 68 if err != nil { 69 t.Fatal(err) 70 } 71 72 // Check the response message 73 if response.Message != string(constant.NotFoundResponseMessage) { 74 t.Errorf("expected response message 'Not Found' but got %s", response.Message) 75 } 76 }