-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_loader_loading_test.go
More file actions
796 lines (672 loc) · 24.2 KB
/
dynamic_loader_loading_test.go
File metadata and controls
796 lines (672 loc) · 24.2 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
// dynamic_loader_loading_test.go: Tests for Dynamic Loader Loading Logic
//
// Copyright (c) 2025 AGILira - A. Giordano
// Series: an AGILira library
// SPDX-License-Identifier: MPL-2.0
package goplugins
import (
"context"
"fmt"
"runtime"
"sync"
"testing"
"time"
)
// TestBlock4PluginLoadingOperations - Tests for Plugin Loading/Unloading Operations
//
// Block 4 Functions Under Test:
// - LoadDiscoveredPlugin: Dynamic plugin loading with dependency resolution
// - UnloadPlugin: Safe plugin unloading with cleanup and dependency checking
// - loadPlugin: Core plugin loading implementation
// - Register: Plugin registration in manager
// - Unregister: Plugin deregistration and cleanup
// - Hot-swapping and reload scenarios
//
// Focus Areas:
// - Plugin lifecycle state management and transitions
// - Resource cleanup and memory leak prevention
// - Concurrent loading scenarios and race conditions
// - Dependency resolution edge cases
// - Error handling and rollback mechanisms
// - State consistency under failure conditions
// ==============================================
// CATEGORY 1: Core Plugin Loading Operations
// ==============================================
func TestLoadDiscoveredPlugin_BasicFunctionality(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Set up discovery engine with mock plugin
mockPlugin := createMockDiscoveredPlugin("test-plugin", "1.0.0")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
testCases := []struct {
pluginName string
shouldSucceed bool
name string
}{
{"test-plugin", true, "load valid discovered plugin"},
{"nonexistent-plugin", false, "load non-existent plugin should fail"},
{"test-plugin", false, "load already loaded plugin should fail"},
}
ctx := context.Background()
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := loader.LoadDiscoveredPlugin(ctx, tc.pluginName)
if tc.shouldSucceed && err != nil {
t.Errorf("Expected plugin %s to load successfully, got error: %v", tc.pluginName, err)
}
if !tc.shouldSucceed && err == nil {
t.Errorf("Expected plugin %s to fail loading, but succeeded", tc.pluginName)
}
// Verify loading state
if tc.shouldSucceed {
states := loader.GetLoadingStatus()
if state, exists := states[tc.pluginName]; !exists || state != LoadingStateLoaded {
t.Errorf("Expected plugin %s to be in loaded state, got %v", tc.pluginName, state)
}
}
})
}
}
func TestLoadDiscoveredPlugin_EdgeCasesAndBugs(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
testCases := []struct {
scenario string
setupFunc func(*DynamicLoader[TestRequest, TestResponse])
pluginName string
shouldFail bool
expectedBug string
}{
{
"load plugin with invalid version",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
mockPlugin := createMockDiscoveredPlugin("invalid-version-plugin", "not.a.version")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
},
"invalid-version-plugin",
true,
"Invalid versions should be rejected during loading",
},
{
"load plugin while shutting down",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
mockPlugin := createMockDiscoveredPlugin("shutdown-plugin", "1.0.0")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
// Simulate shutdown state
loader.manager.shutdown.Store(true)
},
"shutdown-plugin",
true,
"Loading during shutdown should be prevented",
},
// REMOVED CIRCULAR DEPENDENCY TEST - causes stack overflow (Bug #1)
// This test is moved to dedicated bug test file
{
"concurrent load same plugin",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
mockPlugin := createMockDiscoveredPlugin("concurrent-plugin", "1.0.0")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
},
"concurrent-plugin",
false, // One should succeed, others should fail gracefully
"Concurrent loading of same plugin should handle race conditions",
},
}
for _, tc := range testCases {
t.Run(tc.scenario, func(t *testing.T) {
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
tc.setupFunc(loader)
ctx := context.Background()
if tc.scenario == "concurrent load same plugin" {
// Test concurrent loading
const numGoroutines = 10
var wg sync.WaitGroup
errors := make(chan error, numGoroutines)
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
err := loader.LoadDiscoveredPlugin(ctx, tc.pluginName)
errors <- err
}()
}
wg.Wait()
close(errors)
successCount := 0
errorCount := 0
for err := range errors {
if err == nil {
successCount++
} else {
errorCount++
}
}
// Exactly one should succeed
if successCount != 1 {
t.Errorf("BUG (%s): Expected exactly 1 success in concurrent loading, got %d successes, %d errors",
tc.expectedBug, successCount, errorCount)
}
} else {
err := loader.LoadDiscoveredPlugin(ctx, tc.pluginName)
if tc.shouldFail && err == nil {
t.Errorf("BUG (%s): Expected loading to fail for %s, but succeeded", tc.expectedBug, tc.pluginName)
}
if !tc.shouldFail && err != nil {
t.Errorf("BUG (%s): Expected loading to succeed for %s, got error: %v", tc.expectedBug, tc.pluginName, err)
}
}
})
}
}
// ==============================================
// CATEGORY 2: Plugin Unloading and Cleanup
// ==============================================
func TestUnloadPlugin_BasicFunctionality(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Load some plugins first
plugin1 := createMockDiscoveredPlugin("plugin-1", "1.0.0")
plugin2 := createMockDiscoveredPluginWithDeps("plugin-2", "1.0.0", []string{"plugin-1"})
loader.discoveryEngine.AddMockPlugin(plugin1)
loader.discoveryEngine.AddMockPlugin(plugin2)
ctx := context.Background()
// Load plugins
if err := loader.LoadDiscoveredPlugin(ctx, "plugin-1"); err != nil {
t.Fatalf("Failed to load plugin-1: %v", err)
}
if err := loader.LoadDiscoveredPlugin(ctx, "plugin-2"); err != nil {
t.Fatalf("Failed to load plugin-2: %v", err)
}
testCases := []struct {
pluginName string
force bool
shouldSucceed bool
name string
}{
{"plugin-1", false, false, "unload plugin with dependents should fail"},
{"plugin-1", true, true, "force unload plugin with dependents should succeed"},
{"plugin-2", false, true, "unload plugin without dependents should succeed"},
{"nonexistent", false, false, "unload non-existent plugin should fail"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := loader.UnloadPlugin(ctx, tc.pluginName, tc.force)
if tc.shouldSucceed && err != nil {
t.Errorf("Expected unloading %s to succeed, got error: %v", tc.pluginName, err)
}
if !tc.shouldSucceed && err == nil {
t.Errorf("Expected unloading %s to fail, but succeeded", tc.pluginName)
}
// Verify state after unloading
if tc.shouldSucceed {
states := loader.GetLoadingStatus()
if _, exists := states[tc.pluginName]; exists {
t.Errorf("Expected plugin %s to be removed from loading states after unload", tc.pluginName)
}
}
})
}
}
func TestUnloadPlugin_ResourceCleanup(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Load plugin with resource tracking
mockPlugin := createMockDiscoveredPlugin("resource-plugin", "1.0.0")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
ctx := context.Background()
if err := loader.LoadDiscoveredPlugin(ctx, "resource-plugin"); err != nil {
t.Fatalf("Failed to load resource-plugin: %v", err)
}
// Verify plugin is loaded and consuming resources
states := loader.GetLoadingStatus()
if state := states["resource-plugin"]; state != LoadingStateLoaded {
t.Fatalf("Expected plugin to be loaded, got state: %v", state)
}
// Verify plugin is registered in manager
plugin, err := manager.GetPlugin("resource-plugin")
if err != nil {
t.Fatalf("Expected plugin to be registered in manager, got error: %v", err)
}
// Check plugin info before unload
info := plugin.Info()
if info.Name != "resource-plugin" {
t.Errorf("Expected plugin name to be 'resource-plugin', got %s", info.Name)
}
// Unload plugin
if err := loader.UnloadPlugin(ctx, "resource-plugin", false); err != nil {
t.Fatalf("Failed to unload plugin: %v", err)
}
// Verify complete cleanup
// 1. Plugin removed from loading states
states = loader.GetLoadingStatus()
if _, exists := states["resource-plugin"]; exists {
t.Error("BUG: Plugin still exists in loading states after unload")
}
// 2. Plugin removed from manager
_, err = manager.GetPlugin("resource-plugin")
if err == nil {
t.Error("BUG: Plugin still registered in manager after unload")
}
// 3. Plugin removed from dependency graph
graph := loader.GetDependencyGraph()
if deps := graph.GetDependencies("resource-plugin"); len(deps) > 0 {
t.Error("BUG: Plugin dependencies still exist in graph after unload")
}
}
// ==============================================
// CATEGORY 3: Dependency Resolution Testing
// ==============================================
func TestLoadDiscoveredPlugin_DependencyResolution(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Create dependency chain: app -> auth -> crypto -> base
plugins := []*DiscoveryResult{
createMockDiscoveredPlugin("base", "1.0.0"),
createMockDiscoveredPluginWithDeps("crypto", "1.0.0", []string{"base"}),
createMockDiscoveredPluginWithDeps("auth", "1.0.0", []string{"crypto"}),
createMockDiscoveredPluginWithDeps("app", "1.0.0", []string{"auth"}),
}
for _, plugin := range plugins {
loader.discoveryEngine.AddMockPlugin(plugin)
}
ctx := context.Background()
// Load top-level plugin, should auto-resolve dependencies
err := loader.LoadDiscoveredPlugin(ctx, "app")
if err != nil {
t.Fatalf("Failed to load app plugin: %v", err)
}
// Verify all dependencies are loaded in correct order
states := loader.GetLoadingStatus()
expectedPlugins := []string{"base", "crypto", "auth", "app"}
for _, pluginName := range expectedPlugins {
if state, exists := states[pluginName]; !exists || state != LoadingStateLoaded {
t.Errorf("Expected plugin %s to be loaded, got state: %v", pluginName, state)
}
}
// Verify dependency graph is correct
graph := loader.GetDependencyGraph()
if deps := graph.GetDependencies("app"); len(deps) == 0 {
t.Error("Expected app plugin to have dependencies in graph")
}
}
func TestLoadDiscoveredPlugin_BrokenDependencies(t *testing.T) {
testCases := []struct {
scenario string
setupFunc func(*DynamicLoader[TestRequest, TestResponse])
pluginName string
expectedBug string
}{
{
"missing dependency",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
// Plugin depends on non-existent dependency
plugin := createMockDiscoveredPluginWithDeps("broken-app", "1.0.0", []string{"missing-dep"})
loader.discoveryEngine.AddMockPlugin(plugin)
},
"broken-app",
"Missing dependencies should prevent loading",
},
{
"incompatible dependency version",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
// Set strict version constraint that dependency doesn't satisfy
dep := createMockDiscoveredPlugin("strict-dep", "2.0.0")
app := createMockDiscoveredPluginWithDeps("strict-app", "1.0.0", []string{"strict-dep"})
loader.discoveryEngine.AddMockPlugin(dep)
loader.discoveryEngine.AddMockPlugin(app)
loader.SetCompatibilityRule("strict-dep", "^1.0.0") // Incompatible with 2.0.0
},
"strict-app",
"Version incompatible dependencies should prevent loading",
},
}
for _, tc := range testCases {
t.Run(tc.scenario, func(t *testing.T) {
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
tc.setupFunc(loader)
ctx := context.Background()
err := loader.LoadDiscoveredPlugin(ctx, tc.pluginName)
if err == nil {
t.Errorf("BUG (%s): Expected loading to fail for %s, but succeeded", tc.expectedBug, tc.pluginName)
}
// Verify no partial state left behind
states := loader.GetLoadingStatus()
for pluginName, state := range states {
if state == LoadingStateLoading {
t.Errorf("BUG: Plugin %s left in loading state after failure", pluginName)
}
}
})
}
}
// ==============================================
// CATEGORY 4: Concurrent Operations and Race Conditions
// ==============================================
func TestPluginLoading_ConcurrentOperations(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Set up multiple plugins
plugins := make([]*DiscoveryResult, 20)
for i := 0; i < 20; i++ {
pluginName := "concurrent-plugin-" + string(rune('a'+i))
plugins[i] = createMockDiscoveredPlugin(pluginName, "1.0.0")
loader.discoveryEngine.AddMockPlugin(plugins[i])
}
ctx := context.Background()
// Test concurrent loading
t.Run("concurrent_loading", func(t *testing.T) {
var wg sync.WaitGroup
errors := make(chan error, len(plugins))
// Load all plugins concurrently
for i, plugin := range plugins {
wg.Add(1)
go func(pluginName string, index int) {
defer wg.Done()
// Add some randomization to increase chance of race conditions
time.Sleep(time.Duration(index%5) * time.Millisecond)
err := loader.LoadDiscoveredPlugin(ctx, pluginName)
errors <- err
}(plugin.Manifest.Name, i)
}
wg.Wait()
close(errors)
// Count successes and failures
successCount := 0
for err := range errors {
if err == nil {
successCount++
} else {
t.Logf("Loading error (expected for concurrent test): %v", err)
}
}
if successCount != len(plugins) {
t.Errorf("Expected all %d plugins to load successfully, got %d successes", len(plugins), successCount)
}
})
// Test concurrent load/unload operations
t.Run("concurrent_load_unload", func(t *testing.T) {
var wg sync.WaitGroup
operations := 100
wg.Add(operations)
for i := 0; i < operations; i++ {
go func(index int) {
defer wg.Done()
pluginName := "concurrent-plugin-a" // Use same plugin for race conditions
if index%2 == 0 {
// Load operation
if err := loader.LoadDiscoveredPlugin(ctx, pluginName); err != nil {
t.Logf("Load operation failed: %v", err)
}
} else {
// Unload operation
if err := loader.UnloadPlugin(ctx, pluginName, false); err != nil {
t.Logf("Unload operation failed: %v", err)
}
}
}(i)
}
wg.Wait()
// Verify system is in consistent state
states := loader.GetLoadingStatus()
for pluginName, state := range states {
if state == LoadingStateLoading || state == LoadingStateUnloading {
t.Errorf("BUG: Plugin %s left in intermediate state: %v", pluginName, state)
}
}
})
}
func TestPluginLoading_StateConsistency(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
mockPlugin := createMockDiscoveredPlugin("state-plugin", "1.0.0")
loader.discoveryEngine.AddMockPlugin(mockPlugin)
ctx := context.Background()
// Test state transitions
states := []struct {
operation string
expectedState LoadingState
}{
{"initial", LoadingState("")}, // Not in states initially
{"load", LoadingStateLoaded},
{"unload", LoadingState("")}, // Removed from states
}
for _, state := range states {
switch state.operation {
case "load":
err := loader.LoadDiscoveredPlugin(ctx, "state-plugin")
if err != nil {
t.Fatalf("Failed to load plugin: %v", err)
}
case "unload":
err := loader.UnloadPlugin(ctx, "state-plugin", false)
if err != nil {
t.Fatalf("Failed to unload plugin: %v", err)
}
}
// Verify state
currentStates := loader.GetLoadingStatus()
actualState, exists := currentStates["state-plugin"]
if state.expectedState == "" {
if exists {
t.Errorf("Expected plugin to not exist in states after %s, but found state: %v",
state.operation, actualState)
}
} else {
if !exists || actualState != state.expectedState {
t.Errorf("After %s operation, expected state %v, got %v (exists: %v)",
state.operation, state.expectedState, actualState, exists)
}
}
}
}
// ==============================================
// CATEGORY 5: Error Handling and Recovery
// ==============================================
func TestPluginLoading_ErrorHandling(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
testCases := []struct {
scenario string
setupFunc func(*DynamicLoader[TestRequest, TestResponse])
pluginName string
operation string
expectError bool
errorType string
}{
{
"load with factory error",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
// Plugin with unsupported transport
plugin := &DiscoveryResult{
Source: "test",
Manifest: &PluginManifest{
Name: "factory-error-plugin",
Version: "1.0.0",
Transport: TransportType("unsupported-transport"),
Endpoint: "test://localhost",
},
}
loader.discoveryEngine.AddMockPlugin(plugin)
},
"factory-error-plugin",
"load",
true,
"UnsupportedTransportError",
},
{
"unload non-existent plugin",
func(loader *DynamicLoader[TestRequest, TestResponse]) {
// No setup needed
},
"non-existent-plugin",
"unload",
true,
"PluginNotFoundError",
},
}
for _, tc := range testCases {
t.Run(tc.scenario, func(t *testing.T) {
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
tc.setupFunc(loader)
ctx := context.Background()
var err error
switch tc.operation {
case "load":
err = loader.LoadDiscoveredPlugin(ctx, tc.pluginName)
case "unload":
err = loader.UnloadPlugin(ctx, tc.pluginName, false)
}
if tc.expectError && err == nil {
t.Errorf("Expected error of type %s for %s, but operation succeeded", tc.errorType, tc.scenario)
}
if !tc.expectError && err != nil {
t.Errorf("Expected %s to succeed, got error: %v", tc.scenario, err)
}
// Verify system remains in clean state after errors
if tc.expectError {
states := loader.GetLoadingStatus()
if state, exists := states[tc.pluginName]; exists && state != LoadingStateFailed {
t.Errorf("Expected failed plugin to be in failed state or removed, got: %v", state)
}
}
})
}
}
func TestPluginLoading_PerformanceBenchmark(t *testing.T) {
// Skip on Windows due to complex subprocess communication requirements
if runtime.GOOS == "windows" {
t.Skip("Skipping dynamic loader test on Windows - requires proper plugin executables")
}
manager := createTestManagerForLoading(t)
loader := manager.dynamicLoader
// Set up many plugins for performance testing
const numPlugins = 100
for i := 0; i < numPlugins; i++ {
pluginName := fmt.Sprintf("perf-plugin-%d", i) // Use safe numeric suffix
plugin := createMockDiscoveredPlugin(pluginName, "1.0.0")
loader.discoveryEngine.AddMockPlugin(plugin)
}
ctx := context.Background()
// Measure loading performance
start := time.Now()
for i := 0; i < numPlugins; i++ {
pluginName := fmt.Sprintf("perf-plugin-%d", i) // Use safe numeric suffix
if err := loader.LoadDiscoveredPlugin(ctx, pluginName); err != nil {
t.Errorf("Failed to load plugin %s: %v", pluginName, err)
}
}
loadTime := time.Since(start)
// Measure unloading performance
start = time.Now()
for i := 0; i < numPlugins; i++ {
pluginName := fmt.Sprintf("perf-plugin-%d", i) // Use safe numeric suffix
if err := loader.UnloadPlugin(ctx, pluginName, false); err != nil {
t.Errorf("Failed to unload plugin %s: %v", pluginName, err)
}
}
unloadTime := time.Since(start)
t.Logf("Performance: Loaded %d plugins in %v (%.2f μs/plugin)",
numPlugins, loadTime, float64(loadTime.Nanoseconds())/float64(numPlugins)/1000.0)
t.Logf("Performance: Unloaded %d plugins in %v (%.2f μs/plugin)",
numPlugins, unloadTime, float64(unloadTime.Nanoseconds())/float64(numPlugins)/1000.0)
// Performance threshold check (adjust based on system capabilities)
maxTimePerPlugin := 1 * time.Millisecond
avgLoadTime := loadTime / time.Duration(numPlugins)
avgUnloadTime := unloadTime / time.Duration(numPlugins)
if avgLoadTime > maxTimePerPlugin {
t.Errorf("Plugin loading too slow: %v per plugin (max: %v)", avgLoadTime, maxTimePerPlugin)
}
if avgUnloadTime > maxTimePerPlugin {
t.Errorf("Plugin unloading too slow: %v per plugin (max: %v)", avgUnloadTime, maxTimePerPlugin)
}
}
// ==============================================
// Helper Functions
// ==============================================
func createTestManagerForLoading(_ *testing.T) *Manager[TestRequest, TestResponse] {
logger := NewTestLogger()
manager := NewManager[TestRequest, TestResponse](logger)
// Initialize discovery engine if not present
if manager.discoveryEngine == nil {
manager.discoveryEngine = &DiscoveryEngine{
discoveredPlugins: make(map[string]*DiscoveryResult),
}
}
return manager
}
func createMockDiscoveredPlugin(name, version string) *DiscoveryResult {
// Create a proper test plugin executable for cross-platform compatibility
executable := createMockPluginExecutable(name)
return &DiscoveryResult{
Source: "test",
Manifest: &PluginManifest{
Name: name,
Version: version,
Transport: TransportExecutable,
Endpoint: executable,
},
}
}
func createMockDiscoveredPluginWithDeps(name, version string, dependencies []string) *DiscoveryResult {
result := createMockDiscoveredPlugin(name, version)
if len(dependencies) > 0 {
result.Manifest.Requirements = &PluginRequirements{
RequiredPlugins: dependencies,
}
}
return result
}
// createMockPluginExecutable creates a simple test executable that behaves like a plugin
func createMockPluginExecutable(pluginName string) string {
// For dynamic loader tests, we need a plugin that can actually communicate
// Use the same approach as subprocess integration tests
if runtime.GOOS == "windows" {
// On Windows, skip dynamic loader tests that require complex subprocess communication
// These tests are more suitable for integration environments with proper plugin builds
// Return a mock path that includes the plugin name for better test isolation
return "cmd.exe" // This will fail gracefully and the test can handle the failure
}
// On Unix systems, use /usr/bin/true for simplicity
// Note: This also won't work for real communication, but Unix tests may be more tolerant
// The pluginName could be used to create unique mock executables in a real implementation
_ = pluginName // Acknowledge parameter for potential future use
return "/usr/bin/true"
}
// Mock discovery engine extension for testing
func (de *DiscoveryEngine) AddMockPlugin(result *DiscoveryResult) {
if de.discoveredPlugins == nil {
de.discoveredPlugins = make(map[string]*DiscoveryResult)
}
de.discoveredPlugins[result.Manifest.Name] = result
}