From 837cf92c16d02241bc52a546870f7ed19a7486ba Mon Sep 17 00:00:00 2001 From: robertc Date: Fri, 6 Dec 2024 14:31:33 -0600 Subject: [PATCH 1/2] 404-test-OK --- 404-handler/README.md | 151 +++++++++++++++++++++++++++++++++++++++ 404-handler/go.mod | 10 ++- 404-handler/go.sum | 12 +++- 404-handler/main.go | 2 +- 404-handler/main_test.go | 57 +++++++++++++++ 5 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 404-handler/main_test.go diff --git a/404-handler/README.md b/404-handler/README.md index 8f2ab3ba58..26b8f59943 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -21,6 +21,13 @@ In web applications, it's common to encounter requests to routes that do not exi ## Running the Example + +1. `go mod init 404` +2. `touch main.go` +3. edit main.go +4. `go run main.go` + + To run the example, use the following command: ```bash go run main.go @@ -75,7 +82,151 @@ func hello(c *fiber.Ctx) error { This example provides a basic setup for handling 404 Not Found errors in a Fiber application. It can be extended and customized further to fit the needs of more complex applications. + + +## Testing + +1. `go get github.com/stretchr/testify/assert` +2. `go test -v` + + +Here's an example of how to write a unit test for your `main.go` using the `testing` package in Go. You can use the `httptest` package to simulate HTTP requests and test your Fiber routes. + +Create a file named `main_test.go` alongside your `main.go` file: + +```go +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gofiber/fiber/v2" + "github.com/stretchr/testify/assert" +) + +// Setup function to initialize the Fiber app +func setupApp() *fiber.App { + app := fiber.New() + + // Routes + app.Get("/hello", hello) + + // 404 Handler + app.Use(func(c *fiber.Ctx) error { + return c.SendStatus(404) + }) + + return app +} + +func TestHelloRoute(t *testing.T) { + // Initialize the app + app := setupApp() + + // Create a test request + req := httptest.NewRequest(http.MethodGet, "/hello", nil) + resp, _ := app.Test(req, -1) // -1 disables timeout + + // Check the response + assert.Equal(t, http.StatusOK, resp.StatusCode) + + // Read the response body + body := make([]byte, resp.ContentLength) + resp.Body.Read(body) + defer resp.Body.Close() + + // Assert the response body + assert.Equal(t, "I made a ☕ for you!", string(body)) +} + +func TestNotFoundRoute(t *testing.T) { + // Initialize the app + app := setupApp() + + // Create a test request for an unknown route + req := httptest.NewRequest(http.MethodGet, "/unknown", nil) + resp, _ := app.Test(req, -1) // -1 disables timeout + + // Check the response + assert.Equal(t, http.StatusNotFound, resp.StatusCode) +} +``` + +### Explanation: + +1. **Setup Function**: + - The `setupApp` function creates a new instance of your Fiber app, defining all routes and middleware. This allows you to reuse it across tests without starting a real server. + +2. **TestHelloRoute**: + - Simulates a `GET` request to the `/hello` endpoint. + - Verifies that the status code is `200 OK`. + - Asserts that the response body matches the expected string. + +3. **TestNotFoundRoute**: + - Simulates a `GET` request to an unknown route. + - Verifies that the status code is `404 Not Found`. + +4. **Assertions**: + - Uses `github.com/stretchr/testify/assert` to make the code more readable and expressive. + +### Running the Tests + +Run the tests using the `go test` command: + +```bash +go test -v +``` + +This will execute the test cases and output the results. + ## References - [Fiber Documentation](https://docs.gofiber.io) - [GitHub Repository](https://github.com/gofiber/fiber) + + + + +I have the following code in main.go: + + +``` +// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️ +// 🤖 Github Repository: https://github.com/gofiber/fiber +// 📌 API Documentation: https://docs.gofiber.io + +package main + +import ( + "log" + + "github.com/gofiber/fiber/v2" +) + +func main() { + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/hello", hello) + + // 404 Handler + app.Use(func(c *fiber.Ctx) error { + return c.SendStatus(404) // => 404 "Not Found" + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} + +// Handler +func hello(c *fiber.Ctx) error { + return c.SendString("I made a ☕ for you!") +} + +``` + +Can you show me how to write a unit test file for this code? + diff --git a/404-handler/go.mod b/404-handler/go.mod index 5c0795116d..0a03464815 100644 --- a/404-handler/go.mod +++ b/404-handler/go.mod @@ -1,19 +1,23 @@ -module main +module 404 -go 1.18 +go 1.23.3 require github.com/gofiber/fiber/v2 v2.52.5 require ( github.com/andybalholm/brotli v1.0.5 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/google/uuid v1.5.0 // indirect github.com/klauspost/compress v1.17.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect - github.com/rivo/uniseg v0.4.4 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/stretchr/testify v1.10.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.51.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect golang.org/x/sys v0.15.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/404-handler/go.sum b/404-handler/go.sum index c31f686e03..09994f8cee 100644 --- a/404-handler/go.sum +++ b/404-handler/go.sum @@ -1,5 +1,7 @@ github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= @@ -13,9 +15,12 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= -github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA= @@ -26,3 +31,6 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/404-handler/main.go b/404-handler/main.go index c2d4da9061..c286ec747c 100644 --- a/404-handler/main.go +++ b/404-handler/main.go @@ -29,4 +29,4 @@ func main() { // Handler func hello(c *fiber.Ctx) error { return c.SendString("I made a ☕ for you!") -} +} \ No newline at end of file diff --git a/404-handler/main_test.go b/404-handler/main_test.go new file mode 100644 index 0000000000..171196b2ad --- /dev/null +++ b/404-handler/main_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gofiber/fiber/v2" + "github.com/stretchr/testify/assert" +) + +// Setup function to initialize the Fiber app +func setupApp() *fiber.App { + app := fiber.New() + + // Routes + app.Get("/hello", hello) + + // 404 Handler + app.Use(func(c *fiber.Ctx) error { + return c.SendStatus(404) + }) + + return app +} + +func TestHelloRoute(t *testing.T) { + // Initialize the app + app := setupApp() + + // Create a test request + req := httptest.NewRequest(http.MethodGet, "/hello", nil) + resp, _ := app.Test(req, -1) // -1 disables timeout + + // Check the response + assert.Equal(t, http.StatusOK, resp.StatusCode) + + // Read the response body + body := make([]byte, resp.ContentLength) + resp.Body.Read(body) + defer resp.Body.Close() + + // Assert the response body + assert.Equal(t, "I made a ☕ for you!", string(body)) +} + +func TestNotFoundRoute(t *testing.T) { + // Initialize the app + app := setupApp() + + // Create a test request for an unknown route + req := httptest.NewRequest(http.MethodGet, "/unknown", nil) + resp, _ := app.Test(req, -1) // -1 disables timeout + + // Check the response + assert.Equal(t, http.StatusNotFound, resp.StatusCode) +} From f20823c19b249135694f69dceaffe8aa1bc62290 Mon Sep 17 00:00:00 2001 From: robertc Date: Fri, 6 Dec 2024 14:56:50 -0600 Subject: [PATCH 2/2] updating-readme --- 404-handler/README.md | 84 +++++++++---------------------------------- 1 file changed, 17 insertions(+), 67 deletions(-) diff --git a/404-handler/README.md b/404-handler/README.md index 26b8f59943..0907a1abac 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -90,11 +90,10 @@ This example provides a basic setup for handling 404 Not Found errors in a Fiber 2. `go test -v` -Here's an example of how to write a unit test for your `main.go` using the `testing` package in Go. You can use the `httptest` package to simulate HTTP requests and test your Fiber routes. -Create a file named `main_test.go` alongside your `main.go` file: +When I submit my pull request, I am told to make the following suggested updates: -```go +``` package main import ( @@ -134,7 +133,11 @@ func TestHelloRoute(t *testing.T) { // Read the response body body := make([]byte, resp.ContentLength) - resp.Body.Read(body) + _, err := resp.Body.Read(body) + if err != nil { + t.Fatalf("Failed to read reponse body: %v", err) + } + defer resp.Body.Close() // Assert the response body @@ -154,32 +157,20 @@ func TestNotFoundRoute(t *testing.T) { } ``` -### Explanation: - -1. **Setup Function**: - - The `setupApp` function creates a new instance of your Fiber app, defining all routes and middleware. This allows you to reuse it across tests without starting a real server. - -2. **TestHelloRoute**: - - Simulates a `GET` request to the `/hello` endpoint. - - Verifies that the status code is `200 OK`. - - Asserts that the response body matches the expected string. - -3. **TestNotFoundRoute**: - - Simulates a `GET` request to an unknown route. - - Verifies that the status code is `404 Not Found`. +However when I now run the test: -4. **Assertions**: - - Uses `github.com/stretchr/testify/assert` to make the code more readable and expressive. -### Running the Tests - -Run the tests using the `go test` command: - -```bash -go test -v +``` +=== RUN TestHelloRoute + main_test.go:42: Failed to read reponse body: EOF +--- FAIL: TestHelloRoute (0.00s) +=== RUN TestNotFoundRoute +--- PASS: TestNotFoundRoute (0.00s) +FAIL +exit status 1 +FAIL 404 0.795s ``` -This will execute the test cases and output the results. ## References @@ -189,44 +180,3 @@ This will execute the test cases and output the results. -I have the following code in main.go: - - -``` -// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️ -// 🤖 Github Repository: https://github.com/gofiber/fiber -// 📌 API Documentation: https://docs.gofiber.io - -package main - -import ( - "log" - - "github.com/gofiber/fiber/v2" -) - -func main() { - // Fiber instance - app := fiber.New() - - // Routes - app.Get("/hello", hello) - - // 404 Handler - app.Use(func(c *fiber.Ctx) error { - return c.SendStatus(404) // => 404 "Not Found" - }) - - // Start server - log.Fatal(app.Listen(":3000")) -} - -// Handler -func hello(c *fiber.Ctx) error { - return c.SendString("I made a ☕ for you!") -} - -``` - -Can you show me how to write a unit test file for this code? -