-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_isolation_comprehensive_test.go
More file actions
1913 lines (1612 loc) · 60.1 KB
/
plugin_isolation_comprehensive_test.go
File metadata and controls
1913 lines (1612 loc) · 60.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// plugin_isolation_comprehensive_test.go: Comprehensive production-level tests for plugin isolation system
//
// This file provides complete test coverage for the plugin isolation system using sophisticated
// mocking to test complex process isolation, resource monitoring, recovery mechanisms, and
// fallback strategies. Tests simulate real production scenarios including process crashes,
// resource exhaustion, network failures, and system-level errors.
//
// Copyright (c) 2025 AGILira - A. Giordano
// Series: an AGILira library
// SPDX-License-Identifier: MPL-2.0
package goplugins
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// MockPluginClient provides a sophisticated mock for testing isolation with real plugin behavior
type MockPluginClient struct {
Name string
mockBehavior MockBehavior
callCount atomic.Int32
lastMethod string
lastArgs interface{}
responseDelay time.Duration
shouldFail atomic.Bool
shouldTimeout atomic.Bool
capabilities map[string]bool
mutex sync.RWMutex
}
// MockBehavior defines how the mock plugin should behave
type MockBehavior struct {
FailAfterCalls int
TimeoutAfterCall int
ResponseData interface{}
ErrorType string
}
// NewMockPluginClient creates a new mock plugin client with production-like behavior
func NewMockPluginClient(name string) *MockPluginClient {
return &MockPluginClient{
Name: name,
capabilities: make(map[string]bool),
mockBehavior: MockBehavior{
ResponseData: map[string]interface{}{
"status": "success",
"data": "mock response",
},
},
}
}
// Call implements the PluginClient interface with sophisticated mock behavior
func (m *MockPluginClient) Call(ctx context.Context, method string, args interface{}, tracker *RequestTracker) (interface{}, error) {
m.mutex.Lock()
count := int(m.callCount.Add(1))
m.lastMethod = method
m.lastArgs = args
m.mutex.Unlock()
// Simulate response delay if configured
if m.responseDelay > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(m.responseDelay):
// Continue
}
}
// Check if should timeout
if m.shouldTimeout.Load() || (m.mockBehavior.TimeoutAfterCall > 0 && count >= m.mockBehavior.TimeoutAfterCall) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(2 * time.Second): // Simulate long operation
return nil, context.DeadlineExceeded
}
}
// Check if should fail
if m.shouldFail.Load() || (m.mockBehavior.FailAfterCalls > 0 && count > m.mockBehavior.FailAfterCalls) {
switch m.mockBehavior.ErrorType {
case "connection":
return nil, errors.New("connection lost")
case "crash":
return nil, errors.New("plugin process crashed")
case "timeout":
return nil, context.DeadlineExceeded
default:
return nil, errors.New("mock failure")
}
}
return m.mockBehavior.ResponseData, nil
}
// SetFailureMode configures the mock to fail under specified conditions
func (m *MockPluginClient) SetFailureMode(shouldFail bool, errorType string) {
m.shouldFail.Store(shouldFail)
m.mockBehavior.ErrorType = errorType
}
// SetTimeoutMode configures the mock to timeout under specified conditions
func (m *MockPluginClient) SetTimeoutMode(shouldTimeout bool, delay time.Duration) {
m.shouldTimeout.Store(shouldTimeout)
m.responseDelay = delay
}
// SetBehavior configures complex mock behavior patterns
func (m *MockPluginClient) SetBehavior(behavior MockBehavior) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.mockBehavior = behavior
}
// GetCallStats returns statistics about calls made to this mock
func (m *MockPluginClient) GetCallStats() (int32, string, interface{}) {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.callCount.Load(), m.lastMethod, m.lastArgs
}
// MockMetricsCollector provides comprehensive metrics mocking for observability testing
type MockMetricsCollector struct {
counters map[string]*MockCounter
histograms map[string]*MockHistogram
gauges map[string]*MockGauge
mutex sync.RWMutex
}
// MockCounter implements CounterMetric for testing
type MockCounter struct {
name string
help string
labels []string
value atomic.Int64
}
// MockHistogram implements HistogramMetric for testing
type MockHistogram struct {
name string
help string
labels []string
buckets []float64
values []float64
mutex sync.RWMutex
}
// MockGauge implements GaugeMetric for testing
type MockGauge struct {
name string
help string
labels []string
value atomic.Uint64 // Store as bits for float64
}
// NewMockMetricsCollector creates a comprehensive metrics collector for testing
func NewMockMetricsCollector() *MockMetricsCollector {
return &MockMetricsCollector{
counters: make(map[string]*MockCounter),
histograms: make(map[string]*MockHistogram),
gauges: make(map[string]*MockGauge),
}
}
// Implement basic MetricsCollector interface methods
func (m *MockMetricsCollector) IncrementCounter(name string, labels map[string]string, value int64) {
m.mutex.Lock()
defer m.mutex.Unlock()
if counter, exists := m.counters[name]; exists {
counter.value.Add(value)
}
}
func (m *MockMetricsCollector) SetGauge(name string, labels map[string]string, value float64) {
m.mutex.Lock()
defer m.mutex.Unlock()
if gauge, exists := m.gauges[name]; exists {
gauge.Set(value)
}
}
func (m *MockMetricsCollector) RecordHistogram(name string, labels map[string]string, value float64) {
m.mutex.Lock()
defer m.mutex.Unlock()
if histogram, exists := m.histograms[name]; exists {
histogram.Observe(value)
}
}
func (m *MockMetricsCollector) RecordCustomMetric(name string, labels map[string]string, value interface{}) {
// Mock implementation - just log the call
}
func (m *MockMetricsCollector) GetMetrics() map[string]interface{} {
m.mutex.RLock()
defer m.mutex.RUnlock()
metrics := make(map[string]interface{})
for name, counter := range m.counters {
metrics[name] = counter.GetValue()
}
for name, gauge := range m.gauges {
metrics[name] = gauge.GetValue()
}
for name, histogram := range m.histograms {
metrics[name] = histogram.GetValues()
}
return metrics
}
func (m *MockMetricsCollector) GetPrometheusMetrics() []PrometheusMetric {
// Return nil as this is optional advanced feature
return nil
}
// CounterWithLabels implements MetricsCollector interface
func (m *MockMetricsCollector) CounterWithLabels(name, help string, labels ...string) CounterMetric {
m.mutex.Lock()
defer m.mutex.Unlock()
counter := &MockCounter{
name: name,
help: help,
labels: labels,
}
m.counters[name] = counter
return counter
}
// HistogramWithLabels implements MetricsCollector interface
func (m *MockMetricsCollector) HistogramWithLabels(name, help string, buckets []float64, labels ...string) HistogramMetric {
m.mutex.Lock()
defer m.mutex.Unlock()
histogram := &MockHistogram{
name: name,
help: help,
labels: labels,
buckets: buckets,
}
m.histograms[name] = histogram
return histogram
}
// GaugeWithLabels implements MetricsCollector interface
func (m *MockMetricsCollector) GaugeWithLabels(name, help string, labels ...string) GaugeMetric {
m.mutex.Lock()
defer m.mutex.Unlock()
gauge := &MockGauge{
name: name,
help: help,
labels: labels,
}
m.gauges[name] = gauge
return gauge
}
// MockCounter methods
func (c *MockCounter) Inc(labels ...string) {
c.value.Add(1)
}
func (c *MockCounter) Add(delta float64, labels ...string) {
c.value.Add(int64(delta))
}
func (c *MockCounter) GetValue() float64 {
return float64(c.value.Load())
}
// MockHistogram methods
func (h *MockHistogram) Observe(value float64, labels ...string) {
h.mutex.Lock()
defer h.mutex.Unlock()
h.values = append(h.values, value)
}
func (h *MockHistogram) GetValues() []float64 {
h.mutex.RLock()
defer h.mutex.RUnlock()
values := make([]float64, len(h.values))
copy(values, h.values)
return values
}
// MockGauge methods
func (g *MockGauge) Set(value float64, labels ...string) {
// Store float64 as uint64 bits for atomic operations
g.value.Store(uint64(value))
}
func (g *MockGauge) Inc(labels ...string) {
// For simplicity in mock, just increment by 1
current := g.GetValue()
g.Set(current + 1.0)
}
func (g *MockGauge) Dec(labels ...string) {
// For simplicity in mock, just decrement by 1
current := g.GetValue()
g.Set(current - 1.0)
}
func (g *MockGauge) Add(delta float64, labels ...string) {
current := g.GetValue()
g.Set(current + delta)
}
func (g *MockGauge) GetValue() float64 {
// Convert back from uint64 bits to float64
return float64(g.value.Load())
}
// MockExecutablePlugin creates a real executable plugin for process isolation testing
func CreateMockExecutablePlugin(t *testing.T, name string, behavior MockBehavior) string {
t.Helper()
// Create temporary directory for plugin
tmpDir := t.TempDir()
pluginPath := filepath.Join(tmpDir, name)
// Create a simple executable that behaves like a plugin
pluginCode := fmt.Sprintf(`#!/bin/bash
# Mock plugin executable for testing
# Behavior: %s
case "$1" in
"health")
echo '{"status": "healthy", "message": "Mock plugin running"}'
;;
"call")
if [ "$2" = "fail" ]; then
exit 1
elif [ "$2" = "timeout" ]; then
sleep 10
else
echo '{"result": "success", "data": "mock response"}'
fi
;;
*)
echo '{"error": "unknown command"}'
exit 1
;;
esac
`, behavior.ErrorType)
// Write the plugin script
err := os.WriteFile(pluginPath, []byte(pluginCode), 0755)
require.NoError(t, err, "Failed to create mock plugin executable")
return pluginPath
}
// TestIsolatedPluginClient_CallComprehensive tests the complete Call method with all branches
func TestIsolatedPluginClient_CallComprehensive(t *testing.T) {
// Setup comprehensive test configuration
config := IsolationConfig{
CircuitBreakerConfig: CircuitBreakerConfig{
Enabled: true,
FailureThreshold: 3,
RecoveryTimeout: 500 * time.Millisecond,
MinRequestThreshold: 1,
SuccessThreshold: 2,
},
RecoveryConfig: RecoveryConfig{
Enabled: true,
MaxAttempts: 3,
BackoffStrategy: BackoffStrategyExponential,
InitialDelay: 10 * time.Millisecond,
MaxDelay: 1 * time.Second,
BackoffMultiplier: 2.0,
},
FallbackConfig: FallbackConfig{
Enabled: true,
Strategy: FallbackStrategyGraceful,
DefaultResponse: map[string]string{"status": "fallback"},
EnableCaching: true,
CacheDuration: 100 * time.Millisecond,
},
ResourceLimits: ResourceLimitsConfig{
Enabled: true,
MaxExecutionTime: 200 * time.Millisecond,
},
ObservabilityConfig: ObservabilityConfig{
Level: ObservabilityAdvanced,
MetricsCollector: NewMockMetricsCollector(),
MetricsPrefix: "test_isolation",
},
}
manager := NewPluginIsolationManager(config)
err := manager.Start()
require.NoError(t, err)
defer manager.Stop()
// Create mock plugin client
mockPlugin := NewMockPluginClient("comprehensive-test")
pluginClient := &PluginClient{Name: "comprehensive-test"}
isolatedClient := manager.WrapClient(pluginClient)
ctx := context.Background()
t.Run("SuccessfulCall", func(t *testing.T) {
// Test successful call path
mockPlugin.SetBehavior(MockBehavior{
ResponseData: map[string]string{"result": "success"},
})
// This will fail due to no real RPC connection, but we test the isolation flow
result, err := isolatedClient.Call(ctx, "test_method", map[string]string{"key": "value"})
// Verify isolation components were exercised
stats := isolatedClient.circuitBreaker.GetStats()
assert.Equal(t, StateClosed, stats.State, "Circuit breaker should remain closed for initial failures")
// Verify stats tracking
assert.True(t, isolatedClient.stats.TotalRequests.Load() > 0, "Should track total requests")
// The call will likely fail due to no real connection, but fallback should handle it
if err == nil {
t.Logf("Call succeeded with result: %v", result)
} else {
t.Logf("Call failed as expected (no real connection): %v", err)
}
})
t.Run("CircuitBreakerTrip", func(t *testing.T) {
// Force circuit breaker to trip by recording multiple failures
for i := 0; i < 5; i++ {
isolatedClient.circuitBreaker.RecordFailure()
}
result, err := isolatedClient.Call(ctx, "test_method", nil)
// Should get fallback response when circuit is open
if err == nil && result != nil {
if fallbackMap, ok := result.(map[string]string); ok {
assert.Equal(t, "fallback", fallbackMap["status"], "Should receive fallback response")
}
}
// Verify circuit breaker trip was recorded
assert.True(t, isolatedClient.stats.CircuitBreakerTrips.Load() > 0, "Should record circuit breaker trips")
})
t.Run("TimeoutHandling", func(t *testing.T) {
// Test timeout handling with very short timeout
shortTimeoutConfig := config
shortTimeoutConfig.ResourceLimits.MaxExecutionTime = 1 * time.Millisecond
shortTimeoutManager := NewPluginIsolationManager(shortTimeoutConfig)
shortTimeoutManager.Start()
defer shortTimeoutManager.Stop()
shortTimeoutClient := shortTimeoutManager.WrapClient(pluginClient)
start := time.Now()
_, err := shortTimeoutClient.Call(ctx, "slow_method", nil)
duration := time.Since(start)
// Should complete quickly due to timeout
assert.True(t, duration < 100*time.Millisecond, "Should respect timeout configuration")
// Error is expected due to timeout or connection failure
if err != nil {
t.Logf("Expected timeout/connection error: %v", err)
}
})
t.Run("FallbackCaching", func(t *testing.T) {
// Test caching functionality
isolatedClient.config.FallbackConfig.EnableCaching = true
// Simulate a successful response for caching
response := map[string]interface{}{"cached": "data"}
isolatedClient.cacheResponse("cache_test", map[string]string{"arg": "value"}, response)
// Retrieve cached response
cachedResp := isolatedClient.getCachedResponse("cache_test", map[string]string{"arg": "value"})
assert.NotNil(t, cachedResp, "Should retrieve cached response")
if cachedResp != nil {
assert.Equal(t, response, cachedResp.Response, "Cached response should match original")
}
})
}
// TestIsolatedPluginClient_ProcessManagement tests process isolation capabilities
func TestIsolatedPluginClient_ProcessManagement(t *testing.T) {
config := IsolationConfig{
ProcessIsolation: ProcessIsolationConfig{
Enabled: true,
ProcessGroup: true,
SandboxDir: t.TempDir(),
},
RecoveryConfig: RecoveryConfig{
Enabled: true,
MaxAttempts: 2,
},
}
manager := NewPluginIsolationManager(config)
err := manager.Start()
require.NoError(t, err)
defer manager.Stop()
// Create a real executable plugin for testing
pluginPath := CreateMockExecutablePlugin(t, "process-test", MockBehavior{})
pluginClient := &PluginClient{Name: pluginPath}
isolatedClient := manager.WrapClient(pluginClient)
t.Run("StartProcess", func(t *testing.T) {
// Test process starting
err := isolatedClient.startProcess()
// Process start might fail due to binary not being a real plugin
// But we test the process management flow
if err != nil {
t.Logf("Process start failed as expected (mock plugin): %v", err)
} else {
// If it starts, verify process state
assert.True(t, isolatedClient.process.isRunning.Load(), "Process should be marked as running")
assert.True(t, isolatedClient.process.pid > 0, "Should have valid PID")
// Test process stopping
err = isolatedClient.stopProcess()
if err != nil {
t.Logf("Process stop error: %v", err)
}
}
})
t.Run("ProcessRestart", func(t *testing.T) {
// Test process restart functionality
err := isolatedClient.restartProcess()
// Restart might fail due to mock plugin, but we test the flow
if err != nil {
t.Logf("Process restart failed as expected (mock plugin): %v", err)
}
// Verify restart was attempted (even if failed)
isolatedClient.recovery.mutex.RLock()
attempts := isolatedClient.recovery.attempts
isolatedClient.recovery.mutex.RUnlock()
// Attempts might be incremented due to restart failures
assert.True(t, attempts >= 0, "Recovery attempts should be tracked")
})
t.Run("ProcessValidation", func(t *testing.T) {
// Test binary path validation
err := validatePluginBinaryPath("")
assert.Error(t, err, "Should reject empty path")
err = validatePluginBinaryPath("../dangerous/path")
assert.Error(t, err, "Should reject path traversal")
err = validatePluginBinaryPath("safe_path; rm -rf /")
assert.Error(t, err, "Should reject dangerous characters")
// Test with plugin path (might fail due to non-existence, but validates logic)
err = validatePluginBinaryPath(pluginPath)
if err != nil {
t.Logf("Plugin path validation: %v", err)
}
})
}
// TestIsolatedPluginClient_FallbackStrategies tests all fallback strategy implementations
func TestIsolatedPluginClient_FallbackStrategies(t *testing.T) {
baseConfig := IsolationConfig{
FallbackConfig: FallbackConfig{
Enabled: true,
EnableCaching: true,
CacheDuration: 100 * time.Millisecond,
},
}
testCases := []struct {
name string
strategy FallbackStrategy
defaultResponse interface{}
setupCache bool
expectedResponse interface{}
shouldSucceed bool
}{
{
name: "DefaultStrategy",
strategy: FallbackStrategyDefault,
defaultResponse: map[string]string{"type": "default", "value": "fallback"},
setupCache: false,
expectedResponse: map[string]string{"type": "default", "value": "fallback"},
shouldSucceed: true,
},
{
name: "CachedStrategy_WithCache",
strategy: FallbackStrategyCached,
defaultResponse: nil,
setupCache: true,
expectedResponse: map[string]string{"cached": "response"},
shouldSucceed: true,
},
{
name: "CachedStrategy_NoCache",
strategy: FallbackStrategyCached,
defaultResponse: nil,
setupCache: false,
expectedResponse: nil,
shouldSucceed: false,
},
{
name: "GracefulStrategy_WithCache",
strategy: FallbackStrategyGraceful,
defaultResponse: map[string]string{"type": "graceful"},
setupCache: true,
expectedResponse: map[string]string{"cached": "response"},
shouldSucceed: true,
},
{
name: "GracefulStrategy_WithDefault",
strategy: FallbackStrategyGraceful,
defaultResponse: map[string]string{"type": "graceful"},
setupCache: false,
expectedResponse: map[string]string{"type": "graceful"},
shouldSucceed: true,
},
{
name: "NoneStrategy",
strategy: FallbackStrategyNone,
defaultResponse: map[string]string{"ignored": "value"},
setupCache: false,
expectedResponse: nil,
shouldSucceed: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
config := baseConfig
config.FallbackConfig.Strategy = tc.strategy
config.FallbackConfig.DefaultResponse = tc.defaultResponse
manager := NewPluginIsolationManager(config)
pluginClient := &PluginClient{Name: "fallback-test-" + tc.name}
isolatedClient := manager.WrapClient(pluginClient)
// Setup cache if needed
if tc.setupCache {
cacheResponse := map[string]string{"cached": "response"}
isolatedClient.cacheResponse("test_method", map[string]string{"arg": "value"}, cacheResponse)
}
// Test fallback handling
originalError := errors.New("test failure")
result, err := isolatedClient.handleFallback("test_method", map[string]string{"arg": "value"}, originalError)
if tc.shouldSucceed {
assert.NoError(t, err, "Fallback should succeed")
assert.Equal(t, tc.expectedResponse, result, "Should return expected fallback response")
} else {
assert.Error(t, err, "Fallback should fail and return original error")
assert.Equal(t, originalError, err, "Should return original error")
}
})
}
}
// TestIsolatedPluginClient_SafeResponses tests getSafeResponse method patterns
func TestIsolatedPluginClient_SafeResponses(t *testing.T) {
config := IsolationConfig{
FallbackConfig: FallbackConfig{
Enabled: true,
Strategy: FallbackStrategyGraceful,
},
}
manager := NewPluginIsolationManager(config)
pluginClient := &PluginClient{Name: "safe-response-test"}
isolatedClient := manager.WrapClient(pluginClient)
testCases := []struct {
method string
expectedType string
expectedResponse interface{}
}{
// Health method patterns
{"health", "health", map[string]interface{}{"status": "degraded", "message": "Plugin unavailable, using fallback response"}},
{"getHealth", "health", map[string]interface{}{"status": "degraded", "message": "Plugin unavailable, using fallback response"}},
{"checkStatus", "health", map[string]interface{}{"status": "degraded", "message": "Plugin unavailable, using fallback response"}},
// Query method patterns
{"listUsers", "query", []interface{}{}},
{"getConfig", "query", []interface{}{}},
{"findItems", "query", []interface{}{}},
// Count method patterns
{"countItems", "count", 0},
{"getCount", "query", []interface{}{}}, // "get" pattern matches before "count"
// Boolean method patterns
{"isReady", "boolean", false},
{"hasPermission", "boolean", false},
{"canAccess", "boolean", false},
// Unknown pattern
{"unknownMethod", "unknown", nil},
}
for _, tc := range testCases {
t.Run(tc.method, func(t *testing.T) {
result := isolatedClient.getSafeResponse(tc.method)
if tc.expectedType == "unknown" {
assert.Nil(t, result, "Unknown methods should return nil")
} else {
assert.Equal(t, tc.expectedResponse, result, "Should return expected safe response for %s pattern", tc.expectedType)
}
})
}
}
// TestIsolatedPluginClient_CacheManagement tests response caching functionality
func TestIsolatedPluginClient_CacheManagement(t *testing.T) {
config := IsolationConfig{
FallbackConfig: FallbackConfig{
Enabled: true,
EnableCaching: true,
CacheDuration: 50 * time.Millisecond,
},
}
manager := NewPluginIsolationManager(config)
pluginClient := &PluginClient{Name: "cache-test"}
isolatedClient := manager.WrapClient(pluginClient)
t.Run("CacheStorage", func(t *testing.T) {
// Test caching response
response := map[string]interface{}{"data": "test response"}
method := "cache_test"
args := map[string]string{"key": "value"}
isolatedClient.cacheResponse(method, args, response)
// Verify response was cached
cached := isolatedClient.getCachedResponse(method, args)
require.NotNil(t, cached, "Response should be cached")
assert.Equal(t, response, cached.Response, "Cached response should match original")
assert.Equal(t, int64(0), cached.UseCount, "Use count should start at 0")
})
t.Run("CacheRetrieval", func(t *testing.T) {
// Store a response
response := map[string]interface{}{"cached": "data"}
isolatedClient.cacheResponse("retrieve_test", nil, response)
// Retrieve and use it
cached := isolatedClient.getCachedResponse("retrieve_test", nil)
require.NotNil(t, cached, "Should retrieve cached response")
// Use the cached response
atomic.AddInt64(&cached.UseCount, 1)
assert.Equal(t, int64(1), cached.UseCount, "Use count should increment")
})
t.Run("CacheExpiration", func(t *testing.T) {
// Store a response
isolatedClient.cacheResponse("expire_test", nil, "expires soon")
// Wait for expiration
time.Sleep(60 * time.Millisecond)
// Should be expired
cached := isolatedClient.getCachedResponse("expire_test", nil)
assert.Nil(t, cached, "Expired response should not be returned")
})
t.Run("CacheKeyGeneration", func(t *testing.T) {
// Test cache key generation
key1 := isolatedClient.generateCacheKey("method1", nil)
key2 := isolatedClient.generateCacheKey("method1", map[string]string{"arg": "value"})
key3 := isolatedClient.generateCacheKey("method2", nil)
assert.Equal(t, "method1", key1, "Nil args should use method name only")
assert.Contains(t, key2, "method1:", "Args should be included in key")
assert.NotEqual(t, key1, key2, "Different args should generate different keys")
assert.NotEqual(t, key1, key3, "Different methods should generate different keys")
})
t.Run("CacheCleanup", func(t *testing.T) {
// Add some entries that will expire
isolatedClient.cacheResponse("cleanup1", nil, "data1")
isolatedClient.cacheResponse("cleanup2", nil, "data2")
// Verify they exist
isolatedClient.cacheMutex.RLock()
initialCount := len(isolatedClient.responseCache)
isolatedClient.cacheMutex.RUnlock()
assert.True(t, initialCount >= 2, "Should have cached entries")
// Wait for expiration
time.Sleep(60 * time.Millisecond)
// Trigger cleanup
isolatedClient.cleanupExpiredCache()
// Verify cleanup occurred
isolatedClient.cacheMutex.RLock()
finalCount := len(isolatedClient.responseCache)
isolatedClient.cacheMutex.RUnlock()
assert.True(t, finalCount < initialCount, "Expired entries should be cleaned up")
})
}
// TestIsolatedPluginClient_RecoveryMechanisms tests comprehensive recovery functionality
func TestIsolatedPluginClient_RecoveryMechanisms(t *testing.T) {
config := IsolationConfig{
RecoveryConfig: RecoveryConfig{
Enabled: true,
MaxAttempts: 3,
BackoffStrategy: BackoffStrategyExponential,
InitialDelay: 10 * time.Millisecond,
MaxDelay: 100 * time.Millisecond,
BackoffMultiplier: 2.0,
},
ProcessIsolation: ProcessIsolationConfig{
Enabled: true,
},
}
manager := NewPluginIsolationManager(config)
pluginClient := &PluginClient{Name: "recovery-test"}
isolatedClient := manager.WrapClient(pluginClient)
t.Run("ShouldAttemptRecovery", func(t *testing.T) {
// Fresh client should attempt recovery
err := errors.New("connection lost")
should := isolatedClient.shouldAttemptRecovery(err)
assert.True(t, should, "Should attempt recovery for fresh client")
// After max attempts, should not retry
isolatedClient.recovery.mutex.Lock()
isolatedClient.recovery.attempts = config.RecoveryConfig.MaxAttempts
isolatedClient.recovery.mutex.Unlock()
should = isolatedClient.shouldAttemptRecovery(err)
assert.False(t, should, "Should not attempt recovery after max attempts")
})
t.Run("BackoffCalculation", func(t *testing.T) {
testCases := []struct {
strategy BackoffStrategy
attempts []int
expected []time.Duration
}{
{
strategy: BackoffStrategyLinear,
attempts: []int{1, 2, 3},
expected: []time.Duration{10 * time.Millisecond, 20 * time.Millisecond, 30 * time.Millisecond},
},
{
strategy: BackoffStrategyExponential,
attempts: []int{1, 2, 3},
expected: []time.Duration{10 * time.Millisecond, 20 * time.Millisecond, 40 * time.Millisecond},
},
{
strategy: BackoffStrategyFixed,
attempts: []int{1, 2, 3},
expected: []time.Duration{10 * time.Millisecond, 10 * time.Millisecond, 10 * time.Millisecond},
},
}
for _, tc := range testCases {
t.Run(string(tc.strategy), func(t *testing.T) {
isolatedClient.recovery.backoffStrategy = tc.strategy
for i, attempt := range tc.attempts {
isolatedClient.recovery.mutex.Lock()
isolatedClient.recovery.attempts = attempt
isolatedClient.recovery.mutex.Unlock()
delay := isolatedClient.calculateBackoffDelay()
expectedDelay := tc.expected[i]
assert.Equal(t, expectedDelay, delay, "Backoff delay should match expected for attempt %d", attempt)
}
})
}
})
t.Run("MaxDelayRespected", func(t *testing.T) {
// Test that max delay is respected
isolatedClient.recovery.mutex.Lock()
isolatedClient.recovery.attempts = 10 // High number of attempts
isolatedClient.recovery.backoffStrategy = BackoffStrategyExponential
isolatedClient.recovery.mutex.Unlock()
delay := isolatedClient.calculateBackoffDelay()
maxDelay := config.RecoveryConfig.MaxDelay
assert.True(t, delay <= maxDelay, "Delay should not exceed max delay: got %v, max %v", delay, maxDelay)
})
t.Run("RecoveryAttemptTracking", func(t *testing.T) {
// Reset recovery state
isolatedClient.recovery.mutex.Lock()
isolatedClient.recovery.attempts = 0
isolatedClient.recovery.history = nil
isolatedClient.recovery.mutex.Unlock()
// Simulate recovery attempt
isolatedClient.attemptRecovery()
// Verify attempt was recorded
isolatedClient.recovery.mutex.RLock()
attempts := isolatedClient.recovery.attempts
historyLen := len(isolatedClient.recovery.history)
isolatedClient.recovery.mutex.RUnlock()
assert.Equal(t, 1, attempts, "Should record recovery attempt")
assert.Equal(t, 1, historyLen, "Should record attempt in history")
// Verify stats were updated
recoveryAttempts := isolatedClient.stats.RecoveryAttempts.Load()
assert.True(t, recoveryAttempts > 0, "Should track recovery attempts in stats")
})
}
// TestPluginIsolationManager_ProcessMonitoring tests process monitoring capabilities
func TestPluginIsolationManager_ProcessMonitoring(t *testing.T) {
config := IsolationConfig{
ProcessIsolation: ProcessIsolationConfig{
Enabled: true,
ProcessGroup: true,
SandboxDir: t.TempDir(),
},
ResourceLimits: ResourceLimitsConfig{
Enabled: true,
MaxMemoryMB: 64,
MaxCPUPercent: 80,
},
}
manager := NewPluginIsolationManager(config)
err := manager.Start()
require.NoError(t, err)
defer manager.Stop()
t.Run("ProcessMonitorCreation", func(t *testing.T) {
monitor := NewProcessMonitor(100 * time.Millisecond)
assert.NotNil(t, monitor, "Should create process monitor")
assert.Equal(t, 100*time.Millisecond, monitor.monitorInterval, "Should set monitoring interval")
})
t.Run("ProcessRegistration", func(t *testing.T) {
monitor := manager.processMonitor
// Create a mock process
process := &PluginProcess{
pid: 12345,
startTime: time.Now(),
maxMemoryMB: 64,
}
process.isRunning.Store(true)
// Register process
monitor.RegisterProcess("test-process", process)
// Verify registration
monitor.mutex.RLock()
registered := monitor.processes["test-process"]
monitor.mutex.RUnlock()
assert.NotNil(t, registered, "Process should be registered")
assert.Equal(t, process, registered, "Should be same process instance")
})
t.Run("ProcessUnregistration", func(t *testing.T) {
monitor := manager.processMonitor
// Register then unregister
process := &PluginProcess{}
monitor.RegisterProcess("unregister-test", process)
monitor.UnregisterProcess("unregister-test")
// Verify removal
monitor.mutex.RLock()