From bed28f8e99b634b9b29589f9bd398ce2d1aa62d6 Mon Sep 17 00:00:00 2001 From: Neeraj319 Date: Sat, 30 Dec 2023 15:09:48 +0545 Subject: [PATCH] feat: update test file --- nirajan_test.go | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 nirajan_test.go diff --git a/nirajan_test.go b/nirajan_test.go new file mode 100644 index 0000000..f92fce0 --- /dev/null +++ b/nirajan_test.go @@ -0,0 +1,63 @@ +package nirajan + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" +) + +func TestSimpleRouter(t *testing.T) { + router := CreateRouter() + + router.AddRoute("/", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }, GET) + + router.AddRoute("/users/:Id", func(w http.ResponseWriter, r *http.Request, params struct{ Id string }) { + if params.Id != "1" { + w.WriteHeader(http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusOK) + }, GET) + for routeObj := range router.routeMapping { + fmt.Println(routeObj.route, routeObj.pathParams) + } + + req, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + router.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) + } + + req, err = http.NewRequest("GET", "/users/1", nil) + if err != nil { + t.Fatal(err) + } + + rr = httptest.NewRecorder() + router.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) + } + + req, err = http.NewRequest("GET", "/users/2", nil) + if err != nil { + t.Fatal(err) + } + + rr = httptest.NewRecorder() + router.ServeHTTP(rr, req) + + if status := rr.Code; status != http.StatusBadRequest { + t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusBadRequest) + } +}