forked from llm-d/llm-d-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmocks.go
More file actions
370 lines (317 loc) · 13.1 KB
/
Copy pathmocks.go
File metadata and controls
370 lines (317 loc) · 13.1 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
Copyright 2025 The Kubernetes 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.
*/
// Package mocks provides mocks for the interfaces defined in the `contracts` package.
//
// # Testing Philosophy: High-Fidelity Mocks
//
// The components that consume these contracts, particularly the `controller.Processor`, are complex, concurrent
// orchestrators. Testing them reliably requires more than simple stubs. It requires high-fidelity mocks that allow for
// the deterministic simulation of race conditions and specific failure modes.
//
// For this reason, mocks like `MockManagedQueue` are deliberately stateful and thread-safe. They provide a reliable,
// in-memory simulation of the real component's behavior, while also providing function-based overrides
// (e.g., `AddFunc`) that allow tests to inject specific errors or pause execution at critical moments. This strategy is
// essential for creating the robust, non-flaky tests needed to verify the correctness of the system's concurrent logic.
// For a more detailed defense of this strategy, see the comment at the top of `controller/internal/processor_test.go`.
package mocks
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/contracts"
fwkdl "github.com/llm-d/llm-d-router/pkg/epp/framework/interface/datalayer"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol/mocks"
)
// --- RegistryDataPlane Mocks ---
// MockRegistryDataPlane is a simple "stub-style" mock for testing.
// Its methods are implemented as function fields (e.g., `IDFunc`). A test can inject behavior by setting the desired
// function field in the test setup. If a func is nil, the method will return a zero value.
type MockRegistryDataPlane struct {
ManagedQueueFunc func(key flowcontrol.FlowKey) (contracts.ManagedQueue, error)
FairnessPolicyFunc func(priority int) (flowcontrol.FairnessPolicy, error)
PriorityBandAccessorFunc func(priority int) (flowcontrol.PriorityBandAccessor, error)
AllOrderedPriorityLevelsFunc func() []int
StatsFunc func() contracts.AggregateStats
WithConnectionFunc func(key flowcontrol.FlowKey, fn func(conn contracts.ActiveFlowConnection) error) error
}
func (m *MockRegistryDataPlane) ManagedQueue(key flowcontrol.FlowKey) (contracts.ManagedQueue, error) {
if m.ManagedQueueFunc != nil {
return m.ManagedQueueFunc(key)
}
return &MockManagedQueue{FlowKeyV: key}, nil
}
func (m *MockRegistryDataPlane) FairnessPolicy(priority int) (flowcontrol.FairnessPolicy, error) {
if m.FairnessPolicyFunc != nil {
return m.FairnessPolicyFunc(priority)
}
return nil, errors.New("sentinel error for mock data plane")
}
func (m *MockRegistryDataPlane) PriorityBandAccessor(priority int) (flowcontrol.PriorityBandAccessor, error) {
if m.PriorityBandAccessorFunc != nil {
return m.PriorityBandAccessorFunc(priority)
}
return nil, errors.New("sentinel error for mock data plane")
}
func (m *MockRegistryDataPlane) AllOrderedPriorityLevels() []int {
if m.AllOrderedPriorityLevelsFunc != nil {
return m.AllOrderedPriorityLevelsFunc()
}
return nil
}
func (m *MockRegistryDataPlane) Stats() contracts.AggregateStats {
if m.StatsFunc != nil {
return m.StatsFunc()
}
return contracts.AggregateStats{}
}
func (m *MockRegistryDataPlane) WithConnection(key flowcontrol.FlowKey, fn func(conn contracts.ActiveFlowConnection) error) error {
if m.WithConnectionFunc != nil {
return m.WithConnectionFunc(key, fn)
}
return nil
}
func (m *MockRegistryDataPlane) SubmitDesiredPriorities(_ map[int]struct{}) {}
func (m *MockRegistryDataPlane) PriorityBandUpdateChannel() <-chan map[int]struct{} {
return nil
}
func (m *MockRegistryDataPlane) FlowGCTimeout() time.Duration {
return time.Minute
}
func (m *MockRegistryDataPlane) ApplyDesiredPriorities(_ map[int]struct{}) {}
func (m *MockRegistryDataPlane) ExecuteGCCycle() {}
var _ contracts.FlowRegistry = &MockRegistryDataPlane{}
var _ contracts.FlowRegistryDataPlane = &MockRegistryDataPlane{}
// --- Dependency Mocks ---
// MockSaturationDetector is a simple "stub-style" mock for testing.
type MockSaturationDetector struct {
SaturationFunc func(ctx context.Context, candidatePods []fwkdl.Endpoint) float64
}
func (m *MockSaturationDetector) Saturation(ctx context.Context, candidatePods []fwkdl.Endpoint) float64 {
if m.SaturationFunc != nil {
return m.SaturationFunc(ctx, candidatePods)
}
return 0.0
}
// MockEndpointCandidates provides a mock implementation of the contracts.EndpointCandidates interface.
// It allows tests to control the exact set of endpoint candidates returned for a given request.
type MockEndpointCandidates struct {
// LocateFunc allows injecting custom logic.
LocateFunc func(ctx context.Context, requestMetadata map[string]any) []fwkdl.Endpoint
// Candidates is a static return value used if LocateFunc is nil.
Candidates []fwkdl.Endpoint
}
func (m *MockEndpointCandidates) Locate(ctx context.Context, requestMetadata map[string]any) []fwkdl.Endpoint {
if m.LocateFunc != nil {
return m.LocateFunc(ctx, requestMetadata)
}
// Return copy to be safe
if m.Candidates == nil {
return nil
}
result := make([]fwkdl.Endpoint, len(m.Candidates))
copy(result, m.Candidates)
return result
}
// --- SafeQueue Mock ---
// MockSafeQueue is a simple stub mock for the SafeQueue interface.
// It is used for tests that need to control the exact return values of a queue's methods without simulating the queue's
// internal logic or state.
type MockSafeQueue struct {
NameV string
LenV int
ByteSizeV uint64
PeekV flowcontrol.QueueItemAccessor
AddFunc func(item flowcontrol.QueueItemAccessor)
RemoveFunc func(handle flowcontrol.QueueItemHandle) (flowcontrol.QueueItemAccessor, error)
CleanupFunc func(predicate contracts.PredicateFunc) []flowcontrol.QueueItemAccessor
DrainFunc func() []flowcontrol.QueueItemAccessor
}
func (m *MockSafeQueue) Name() string { return m.NameV }
func (m *MockSafeQueue) Len() int { return m.LenV }
func (m *MockSafeQueue) ByteSize() uint64 { return m.ByteSizeV }
func (m *MockSafeQueue) Peek() flowcontrol.QueueItemAccessor {
return m.PeekV
}
func (m *MockSafeQueue) Add(item flowcontrol.QueueItemAccessor) {
if m.AddFunc != nil {
m.AddFunc(item)
}
}
func (m *MockSafeQueue) Remove(handle flowcontrol.QueueItemHandle) (flowcontrol.QueueItemAccessor, error) {
if m.RemoveFunc != nil {
return m.RemoveFunc(handle)
}
return nil, errors.New("sentinel error for mock queue")
}
func (m *MockSafeQueue) Cleanup(predicate contracts.PredicateFunc) []flowcontrol.QueueItemAccessor {
if m.CleanupFunc != nil {
return m.CleanupFunc(predicate)
}
return nil
}
func (m *MockSafeQueue) Drain() []flowcontrol.QueueItemAccessor {
if m.DrainFunc != nil {
return m.DrainFunc()
}
return nil
}
var _ contracts.SafeQueue = &MockSafeQueue{}
// --- ManagedQueue Mock ---
// MockManagedQueue is a high-fidelity, thread-safe mock of the `contracts.ManagedQueue` interface, designed
// specifically for testing the concurrent `controller/internal.Processor`.
//
// This mock is essential for creating deterministic and focused unit tests. It allows for precise control over queue
// behavior and enables the testing of critical edge cases (e.g., empty queues, dispatch failures) in complete
// isolation, which would be difficult and unreliable to achieve with the concrete `registry.managedQueue`
// implementation.
//
// ### Design Philosophy
//
// 1. **Stateful**: The mock maintains an internal map of items to accurately reflect a real queue's state. Its `Len()`
// and `ByteSize()` methods are derived directly from this state.
// 2. **Deadlock-Safe Overrides**: Test-specific logic (e.g., `AddFunc`) is executed instead of the default
// implementation. The override function is fully responsible for its own logic and synchronization, as the mock's
// internal mutex will *not* be held during its execution.
// 3. **Self-Wiring**: The `FlowQueueAccessor()` method returns the mock itself, ensuring the accessor is always
// correctly connected to the queue's state without manual wiring in tests.
type MockManagedQueue struct {
// FlowKeyV defines the flow specification for this mock queue. It should be set by the test.
FlowKeyV flowcontrol.FlowKey
// AddFunc allows a test to completely override the default Add behavior.
AddFunc func(item flowcontrol.QueueItemAccessor) error
// RemoveFunc allows a test to completely override the default Remove behavior.
RemoveFunc func(handle flowcontrol.QueueItemHandle) (flowcontrol.QueueItemAccessor, error)
// CleanupFunc allows a test to completely override the default Cleanup behavior.
CleanupFunc func(predicate contracts.PredicateFunc) []flowcontrol.QueueItemAccessor
// DrainFunc allows a test to completely override the default Drain behavior.
DrainFunc func() []flowcontrol.QueueItemAccessor
// OrderingPolicyFunc allows a test to override OrderingPolicy.
OrderingPolicyFunc func() flowcontrol.OrderingPolicy
// mu protects access to the internal `items` map.
mu sync.Mutex
initOnce sync.Once
items map[flowcontrol.QueueItemHandle]flowcontrol.QueueItemAccessor
}
func (m *MockManagedQueue) init() {
m.initOnce.Do(func() {
m.items = make(map[flowcontrol.QueueItemHandle]flowcontrol.QueueItemAccessor)
})
}
// FlowQueueAccessor returns the mock itself, as it fully implements the `flowcontrol.FlowQueueAccessor` interface.
func (m *MockManagedQueue) FlowQueueAccessor() flowcontrol.FlowQueueAccessor {
return m
}
// Add adds an item to the queue.
// It checks for a test override before locking. If no override is present, it executes the default stateful logic,
// which includes fulfilling the `SafeQueue.Add` contract.
func (m *MockManagedQueue) Add(item flowcontrol.QueueItemAccessor) error {
// If an override is provided, it is responsible for the full contract, including setting the handle.
if m.AddFunc != nil {
return m.AddFunc(item)
}
m.mu.Lock()
defer m.mu.Unlock()
m.init()
// Fulfill the `SafeQueue.Add` contract: the queue is responsible for setting the handle.
if item.Handle() == nil {
item.SetHandle(&mocks.MockQueueItemHandle{})
}
m.items[item.Handle()] = item
return nil
}
// Remove removes an item from the queue. It checks for a test override before locking.
func (m *MockManagedQueue) Remove(handle flowcontrol.QueueItemHandle) (flowcontrol.QueueItemAccessor, error) {
if m.RemoveFunc != nil {
return m.RemoveFunc(handle)
}
m.mu.Lock()
defer m.mu.Unlock()
m.init()
item, ok := m.items[handle]
if !ok {
return nil, fmt.Errorf("item with handle %v not found", handle)
}
delete(m.items, handle)
return item, nil
}
// Cleanup removes items matching a predicate. It checks for a test override before locking.
func (m *MockManagedQueue) Cleanup(predicate contracts.PredicateFunc) []flowcontrol.QueueItemAccessor {
if m.CleanupFunc != nil {
return m.CleanupFunc(predicate)
}
m.mu.Lock()
defer m.mu.Unlock()
m.init()
var removed []flowcontrol.QueueItemAccessor
for handle, item := range m.items {
if predicate(item) {
removed = append(removed, item)
delete(m.items, handle)
}
}
return removed
}
// Drain removes all items from the queue. It checks for a test override before locking.
func (m *MockManagedQueue) Drain() []flowcontrol.QueueItemAccessor {
if m.DrainFunc != nil {
return m.DrainFunc()
}
m.mu.Lock()
defer m.mu.Unlock()
m.init()
drained := make([]flowcontrol.QueueItemAccessor, 0, len(m.items))
for _, item := range m.items {
drained = append(drained, item)
}
m.items = make(map[flowcontrol.QueueItemHandle]flowcontrol.QueueItemAccessor)
return drained
}
func (m *MockManagedQueue) FlowKey() flowcontrol.FlowKey { return m.FlowKeyV }
func (m *MockManagedQueue) Name() string { return "" }
func (m *MockManagedQueue) OrderingPolicy() flowcontrol.OrderingPolicy {
if m.OrderingPolicyFunc != nil {
return m.OrderingPolicyFunc()
}
return nil
}
// Len returns the actual number of items currently in the mock queue.
func (m *MockManagedQueue) Len() int {
m.mu.Lock()
defer m.mu.Unlock()
m.init()
return len(m.items)
}
// ByteSize returns the actual total byte size of all items in the mock queue.
func (m *MockManagedQueue) ByteSize() uint64 {
m.mu.Lock()
defer m.mu.Unlock()
m.init()
var size uint64
for _, item := range m.items {
size += item.OriginalRequest().ByteSize()
}
return size
}
// Peek returns the first item found in the mock queue. Note: map iteration order is not guaranteed.
func (m *MockManagedQueue) Peek() flowcontrol.QueueItemAccessor {
m.mu.Lock()
defer m.mu.Unlock()
m.init()
for _, item := range m.items {
return item // Return first item found
}
return nil // Queue is empty
}