v2 / vlib / veb / request_id / request_id_test.v
100 lines · 81 sloc · 2.05 KB · ab2eb0016ce83f20184fe1e3cf6f727cf17c7272
Raw
1module request_id
2
3import veb
4
5// Test context that includes our RequestIdContext
6struct TestContext {
7 veb.Context
8 RequestIdContext
9}
10
11fn test_config_default() {
12 default_config := Config{}
13 assert default_config.header == 'X-Request-ID'
14 assert default_config.allow_empty == false
15 assert default_config.force == false
16 assert default_config.next == none
17 assert default_config.generator != unsafe { nil }
18}
19
20fn test_middleware_handler() {
21 cfg := Config{
22 header: 'Test-Request-ID'
23 generator: fn () string {
24 return 'test-123'
25 }
26 }
27
28 // Create middleware handler
29 handler := middleware[TestContext](cfg).handler
30
31 // Create test context
32 mut ctx := TestContext{}
33
34 // Test handler execution
35 result := handler(mut ctx)
36 assert result == true
37
38 // Verify request ID was set
39 assert ctx.request_id == 'test-123'
40}
41
42fn test_middleware_next_function() {
43 mut ctx := TestContext{}
44
45 // Test with next function that returns true
46 skip_cfg := Config{
47 next: fn (ctx &veb.Context) bool {
48 return true
49 }
50 }
51 skip_handler := middleware[TestContext](skip_cfg).handler
52
53 result := skip_handler(mut ctx)
54 assert result == true
55 assert ctx.request_id == ''
56
57 // Test with next function that returns false
58 continue_cfg := Config{
59 next: fn (ctx &veb.Context) bool {
60 return false
61 }
62 generator: fn () string {
63 return 'test-123'
64 }
65 }
66 continue_handler := middleware[TestContext](continue_cfg).handler
67
68 result2 := continue_handler(mut ctx)
69 assert result2 == true
70 assert ctx.request_id == 'test-123'
71}
72
73fn test_middleware_force_option() {
74 mut ctx := TestContext{}
75 ctx.request_id = 'existing-id'
76
77 force_cfg := Config{
78 force: true
79 generator: fn () string {
80 return 'forced-id'
81 }
82 }
83 force_handler := middleware[TestContext](force_cfg).handler
84
85 result := force_handler(mut ctx)
86 assert result == true
87 assert ctx.request_id == 'forced-id'
88}
89
90fn test_middleware_exempt() {
91 mut ctx := TestContext{
92 request_id_exempt: true
93 }
94
95 handler := middleware[TestContext](Config{}).handler
96
97 result := handler(mut ctx)
98 assert result == true
99 assert ctx.request_id == ''
100}
101