Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

404-test-OK #2725

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions 404-handler/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove redundant code example.

The code example at the end of the README is redundant as it's already shown in the "Code Overview" section above.

Consider removing lines 192-232 to avoid duplication and potential maintenance issues when the code changes.

🧰 Tools
🪛 LanguageTool

[style] ~230-~230: If you’re making a request, consider inserting ‘please’ to sound more courteous and respectful.
Context: ...ndString("I made a ☕ for you!") } ``` Can you show me how to write a unit test file f...

(CAN_YOU)

🪛 Markdownlint (0.35.0)

203-203: Column: 1
Hard tabs

(MD010, no-hard-tabs)


205-205: Column: 1
Hard tabs

(MD010, no-hard-tabs)


209-209: Column: 1
Hard tabs

(MD010, no-hard-tabs)


210-210: Column: 1
Hard tabs

(MD010, no-hard-tabs)


212-212: Column: 1
Hard tabs

(MD010, no-hard-tabs)


213-213: Column: 1
Hard tabs

(MD010, no-hard-tabs)


215-215: Column: 1
Hard tabs

(MD010, no-hard-tabs)


216-216: Column: 1
Hard tabs

(MD010, no-hard-tabs)


217-217: Column: 1
Hard tabs

(MD010, no-hard-tabs)


218-218: Column: 1
Hard tabs

(MD010, no-hard-tabs)


220-220: Column: 1
Hard tabs

(MD010, no-hard-tabs)


221-221: Column: 1
Hard tabs

(MD010, no-hard-tabs)


226-226: Column: 1
Hard tabs

(MD010, no-hard-tabs)


194-194: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)


195-195: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

10 changes: 7 additions & 3 deletions 404-handler/go.mod
Original file line number Diff line number Diff line change
@@ -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
)
12 changes: 10 additions & 2 deletions 404-handler/go.sum
Original file line number Diff line number Diff line change
@@ -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=
Expand All @@ -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=
Expand All @@ -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=
2 changes: 1 addition & 1 deletion 404-handler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ func main() {
// Handler
func hello(c *fiber.Ctx) error {
return c.SendString("I made a ☕ for you!")
}
}
57 changes: 57 additions & 0 deletions 404-handler/main_test.go
Original file line number Diff line number Diff line change
@@ -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()
Comment on lines +39 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential read errors.

The response body read operation should handle potential errors.

-	body := make([]byte, resp.ContentLength)
-	resp.Body.Read(body)
+	body := make([]byte, resp.ContentLength)
+	_, err := resp.Body.Read(body)
+	if err != nil {
+		t.Fatalf("Failed to read response body: %v", err)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
body := make([]byte, resp.ContentLength)
resp.Body.Read(body)
defer resp.Body.Close()
body := make([]byte, resp.ContentLength)
_, err := resp.Body.Read(body)
if err != nil {
t.Fatalf("Failed to read response body: %v", err)
}
defer resp.Body.Close()
🧰 Tools
🪛 golangci-lint (1.62.2)

40-40: Error return value of resp.Body.Read is not checked

(errcheck)


// 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)
}