-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproperty_test.go
More file actions
330 lines (284 loc) · 8.97 KB
/
property_test.go
File metadata and controls
330 lines (284 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !integration
package app
import (
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestProperty_RouteMatchingCommutativity tests that route matching is commutative:
// registering routes in different orders should produce the same results.
func TestProperty_RouteMatchingCommutativity(t *testing.T) {
t.Parallel()
// Generate test routes
routes := []struct {
method string
path string
body string
}{
{"GET", "/users/:id", "user"},
{"GET", "/posts/:id", "post"},
{"GET", "/api/v1/health", "health"},
{"POST", "/users", "create"},
{"PUT", "/users/:id", "update"},
}
// Test all permutations of route registration order
permutations := generatePermutations(len(routes))
for _, perm := range permutations {
t.Run(fmt.Sprintf("permutation_%v", perm), func(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
// Register routes in this permutation order
for _, idx := range perm {
route := routes[idx]
body := route.body // Capture for closure
switch route.method {
case "GET":
app.GET(route.path, func(c *Context) {
if err := c.Stringf(http.StatusOK, "%s", body); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
case "POST":
app.POST(route.path, func(c *Context) {
if err := c.Stringf(http.StatusOK, "%s", body); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
case "PUT":
app.PUT(route.path, func(c *Context) {
if err := c.Stringf(http.StatusOK, "%s", body); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
default:
app.GET(route.path, func(c *Context) {
if err := c.Stringf(http.StatusOK, "%s", body); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
}
}
// Test that all routes still work regardless of registration order
for _, route := range routes {
req := httptest.NewRequest(route.method, route.path, nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
// Replace :id with a test value for matching
testPath := strings.Replace(route.path, ":id", "123", 1)
req = httptest.NewRequest(route.method, testPath, nil)
w = httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code,
"route %s %s should work in any registration order",
route.method, route.path)
}
})
}
}
// TestProperty_MiddlewareIdempotency tests that adding the same middleware
// multiple times produces consistent results (idempotency property).
func TestProperty_MiddlewareIdempotency(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
var callCount int
middleware := func(c *Context) {
callCount++
c.Next()
}
// Add same middleware multiple times
for range 5 {
app.Use(middleware)
}
app.GET("/test", func(c *Context) {
if err := c.Stringf(http.StatusOK, "ok"); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
// Middleware should be called exactly 5 times
assert.Equal(t, 5, callCount, "middleware should be called for each registration")
assert.Equal(t, http.StatusOK, w.Code)
}
// TestProperty_ConfigurationDefaults tests that default configuration values
// satisfy all validation constraints (defaults should always be valid).
func TestProperty_ConfigurationDefaults(t *testing.T) {
t.Parallel()
// Test that default config is always valid
cfg := defaultConfig()
err := cfg.validate()
require.NoError(t, err, "default configuration should always be valid")
// Verify defaults satisfy constraints
assert.Greater(t, cfg.server.readTimeout, time.Duration(0))
assert.Greater(t, cfg.server.writeTimeout, time.Duration(0))
assert.GreaterOrEqual(t, cfg.server.readTimeout, cfg.server.writeTimeout,
"default read timeout should not exceed write timeout")
assert.GreaterOrEqual(t, cfg.server.shutdownTimeout, time.Second,
"default shutdown timeout should be at least 1 second")
assert.GreaterOrEqual(t, cfg.server.maxHeaderBytes, 1024,
"default max header bytes should be at least 1KB")
}
// TestProperty_ErrorMessagesCompleteness tests that all validation errors
// provide complete information (field, value, message, constraint).
func TestProperty_ErrorMessagesCompleteness(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
opts []Option
check func(*testing.T, error)
}{
{
name: "empty service name",
opts: []Option{
WithServiceName(""),
WithServiceVersion("1.0.0"),
},
check: func(t *testing.T, err error) {
t.Helper()
var ce *ConfigErrors
require.ErrorAs(t, err, &ce)
for _, e := range ce.All() {
assert.NotEmpty(t, e.Field, "error should have field name")
assert.NotEmpty(t, e.Message, "error should have message")
}
},
},
{
name: "invalid timeout",
opts: []Option{
WithServiceName("test"),
WithServiceVersion("1.0.0"),
WithServer(WithReadTimeout(-1 * time.Second)),
},
check: func(t *testing.T, err error) {
t.Helper()
var ce *ConfigErrors
require.ErrorAs(t, err, &ce)
for _, e := range ce.All() {
if e.Field == "server.readTimeout" {
assert.NotNil(t, e.Value, "error should include invalid value")
assert.NotEmpty(t, e.Constraint, "error should include constraint")
}
}
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
_, err := New(tc.opts...)
require.Error(t, err)
if tc.check != nil {
tc.check(t, err)
}
})
}
}
// TestProperty_RoutePathEquivalence tests that equivalent route paths
// (e.g., "/users/:id" and "/users/123") match correctly.
func TestProperty_RoutePathEquivalence(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
// Register parameter route
app.GET("/users/:id", func(c *Context) {
id := c.Param("id")
if err := c.Stringf(http.StatusOK, "user-%s", id); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
// Test various equivalent paths
testPaths := []string{
"/users/123",
"/users/abc",
"/users/123-456",
"/users/user_123",
}
for _, path := range testPaths {
t.Run(path, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, path, nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code,
"path %s should match /users/:id", path)
assert.Contains(t, w.Body.String(), strings.TrimPrefix(path, "/users/"),
"response should contain parameter value")
})
}
}
// Helper function to generate all permutations of indices
func generatePermutations(n int) [][]int {
if n == 0 {
return [][]int{{}}
}
if n == 1 {
return [][]int{{0}}
}
// Generate permutations recursively
smaller := generatePermutations(n - 1)
result := make([][]int, 0, len(smaller)*n)
for _, perm := range smaller {
for i := 0; i <= len(perm); i++ {
newPerm := make([]int, 0, len(perm)+1)
newPerm = append(newPerm, perm[:i]...)
newPerm = append(newPerm, n-1)
newPerm = append(newPerm, perm[i:]...)
result = append(result, newPerm)
}
}
return result
}
// TestProperty_ConfigurationComposition tests that configuration options
// can be composed in any order (commutativity of options).
func TestProperty_ConfigurationComposition(t *testing.T) {
t.Parallel()
opts1 := []Option{
WithServiceName("test"),
WithServiceVersion("1.0.0"),
WithEnvironment(EnvironmentDevelopment),
}
opts2 := []Option{
WithEnvironment(EnvironmentDevelopment),
WithServiceVersion("1.0.0"),
WithServiceName("test"),
}
app1, err1 := New(opts1...)
app2, err2 := New(opts2...)
assert.NoError(t, err1)
assert.NoError(t, err2)
assert.NotNil(t, app1)
assert.NotNil(t, app2)
// Both should have same configuration
assert.Equal(t, app1.ServiceName(), app2.ServiceName())
assert.Equal(t, app1.ServiceVersion(), app2.ServiceVersion())
assert.Equal(t, app1.Environment(), app2.Environment())
}