| 1 | // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️ |
| 2 | // 🤖 Github Repository: https://github.com/gofiber/fiber |
| 3 | // 📌 API Documentation: https://docs.gofiber.io |
| 4 | |
| 5 | package utils |
| 6 | |
| 7 | import ( |
| 8 | "testing" |
| 9 | |
| 10 | "github.com/stretchr/testify/require" |
| 11 | ) |
| 12 | |
| 13 | func Test_AddTrailingSlashBytes(t *testing.T) { |
| 14 | t.Parallel() |
| 15 | |
| 16 | testCases := []struct { |
| 17 | name string |
| 18 | in []byte |
| 19 | want []byte |
| 20 | }{ |
| 21 | {name: "empty", in: []byte(""), want: []byte("/")}, |
| 22 | {name: "slash-only", in: []byte("/"), want: []byte("/")}, |
| 23 | {name: "short-no-slash", in: []byte("abc"), want: []byte("abc/")}, |
| 24 | {name: "short-with-slash", in: []byte("abc/"), want: []byte("abc/")}, |
| 25 | {name: "path-no-slash", in: []byte("/api/v1/users"), want: []byte("/api/v1/users/")}, |
| 26 | {name: "path-with-slash", in: []byte("/api/v1/users/"), want: []byte("/api/v1/users/")}, |
| 27 | {name: "double-slash", in: []byte("abc//"), want: []byte("abc//")}, |
| 28 | {name: "unicode", in: []byte("/日本語"), want: []byte("/日本語/")}, |
| 29 | } |
| 30 | |
| 31 | for _, tc := range testCases { |
| 32 | t.Run(tc.name, func(t *testing.T) { |
| 33 | t.Parallel() |
| 34 | result := AddTrailingSlashBytes(tc.in) |
| 35 | require.Equal(t, tc.want, result) |
| 36 | }) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | func Test_AddTrailingSlashBytes_NoMutation(t *testing.T) { |
| 41 | t.Parallel() |
| 42 | |
| 43 | original := []byte("test") |
| 44 | originalCopy := make([]byte, len(original)) |
| 45 | copy(originalCopy, original) |
| 46 | |
| 47 | _ = AddTrailingSlashBytes(original) |
| 48 | |
| 49 | require.Equal(t, originalCopy, original, "original slice should not be mutated") |
| 50 | } |
| 51 | |
| 52 | func Test_AddTrailingSlashBytes_ReturnsSame(t *testing.T) { |
| 53 | t.Parallel() |
| 54 | |
| 55 | input := []byte("test/") |
| 56 | result := AddTrailingSlashBytes(input) |
| 57 | require.Equal(t, input, result) |
| 58 | require.Same(t, &input[0], &result[0], "should return same slice instance") |
| 59 | } |
| 60 | |
| 61 | func Benchmark_AddTrailingSlashBytes(b *testing.B) { |
| 62 | cases := []struct { |
| 63 | name string |
| 64 | input []byte |
| 65 | }{ |
| 66 | {name: "empty", input: []byte("")}, |
| 67 | {name: "slash-only", input: []byte("/")}, |
| 68 | {name: "short-no-slash", input: []byte("abc")}, |
| 69 | {name: "short-with-slash", input: []byte("abc/")}, |
| 70 | {name: "path-no-slash", input: []byte("/api/v1/users")}, |
| 71 | {name: "path-with-slash", input: []byte("/api/v1/users/")}, |
| 72 | } |
| 73 | |
| 74 | for _, tc := range cases { |
| 75 | b.Run(tc.name, func(b *testing.B) { |
| 76 | b.ReportAllocs() |
| 77 | var res []byte |
| 78 | for i := 0; i < b.N; i++ { |
| 79 | res = AddTrailingSlashBytes(tc.input) |
| 80 | } |
| 81 | _ = res |
| 82 | }) |
| 83 | } |
| 84 | } |