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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package mocker

import (
	"context"
	"testing"

	bifrost "github.com/maximhq/bifrost/core"
	"github.com/maximhq/bifrost/core/schemas"
)

// BaseAccount implements the schemas.Account interface for testing purposes.
// It provides mock implementations of the required methods to test the Mocker plugin
// with a basic OpenAI configuration.
type BaseAccount struct{}

// GetConfiguredProviders returns a list of supported providers for testing.
func (baseAccount *BaseAccount) GetConfiguredProviders() ([]schemas.ModelProvider, error) {
	return []schemas.ModelProvider{schemas.OpenAI, schemas.Anthropic}, nil
}

// GetKeysForProvider returns a dummy API key configuration for testing.
// Since we're testing the mocker plugin, these keys should never be used
// as the plugin intercepts requests before they reach the actual providers.
func (baseAccount *BaseAccount) GetKeysForProvider(ctx context.Context, providerKey schemas.ModelProvider) ([]schemas.Key, error) {
	return []schemas.Key{
		{
			Value:  *schemas.NewEnvVar("dummy-api-key-for-testing"), // Dummy key
			Models: []string{"gpt-4", "gpt-4-turbo", "claude-3"},
			Weight: 1.0,
		},
	}, nil
}

// GetConfigForProvider returns default provider configuration for testing.
func (baseAccount *BaseAccount) GetConfigForProvider(providerKey schemas.ModelProvider) (*schemas.ProviderConfig, error) {
	return &schemas.ProviderConfig{
		NetworkConfig:            schemas.DefaultNetworkConfig,
		ConcurrencyAndBufferSize: schemas.DefaultConcurrencyAndBufferSize,
	}, nil
}

func (baseAccount *BaseAccount) GetGlobalKeys(ctx context.Context) ([]schemas.Key, error) {
	return nil, nil
}

// TestMockerPlugin_GetName tests the plugin name
func TestMockerPlugin_GetName(t *testing.T) {
	plugin, err := Init(MockerConfig{})
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}
	if plugin.GetName() != PluginName {
		t.Errorf("Expected '%s', got '%s'", PluginName, plugin.GetName())
	}
}

// TestMockerPlugin_Disabled tests that disabled plugin doesn't interfere
func TestMockerPlugin_Disabled(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	config := MockerConfig{
		Enabled: false,
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	// This should pass through to the real provider (but will fail due to dummy key)
	_, bifrostErr := client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
		Provider: schemas.OpenAI,
		Model:    "gpt-4",
		Input: []schemas.ChatMessage{
			{
				Role: schemas.ChatMessageRoleUser,
				Content: &schemas.ChatMessageContent{
					ContentStr: bifrost.Ptr("Hello, test message"),
				},
			},
		},
	})

	// Should get an authentication error from OpenAI, not a mock response
	// This proves the plugin is disabled and not intercepting requests
	if bifrostErr == nil {
		t.Error("Expected error from real provider with dummy API key")
	}
}

// TestMockerPlugin_DefaultMockRule tests the default catch-all rule
func TestMockerPlugin_DefaultMockRule(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	config := MockerConfig{
		Enabled: true, // No rules provided, should create default rule
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	response, bifrostErr := client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
		Provider: schemas.OpenAI,
		Model:    "gpt-4",
		Input: []schemas.ChatMessage{
			{
				Role: schemas.ChatMessageRoleUser,
				Content: &schemas.ChatMessageContent{
					ContentStr: bifrost.Ptr("Hello, test message"),
				},
			},
		},
	})

	if bifrostErr != nil {
		t.Fatalf("Expected no error, got: %v", bifrostErr)
	}
	if response == nil {
		t.Fatal("Expected response")
	}
	if len(response.Choices) == 0 {
		t.Fatal("Expected at least one choice")
	}
	if response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr == nil {
		t.Fatal("Expected content string")
	}
	if *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr != "This is a mock response from the Mocker plugin" {
		t.Errorf("Expected default mock message, got: %s", *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr)
	}
}

// TestMockerPlugin_CustomSuccessRule tests custom success response
func TestMockerPlugin_CustomSuccessRule(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	config := MockerConfig{
		Enabled: true,
		Rules: []MockRule{
			{
				Name:        "openai-success",
				Enabled:     true,
				Priority:    100,
				Probability: 1.0,
				Conditions: Conditions{
					Providers: []string{"openai"},
				},
				Responses: []Response{
					{
						Type: ResponseTypeSuccess,
						Content: &SuccessResponse{
							Message: "Custom OpenAI mock response",
							Usage: &Usage{
								PromptTokens:     15,
								CompletionTokens: 25,
								TotalTokens:      40,
							},
						},
					},
				},
			},
		},
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	response, bifrostErr := client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
		Provider: schemas.OpenAI,
		Model:    "gpt-4",
		Input: []schemas.ChatMessage{
			{
				Role: schemas.ChatMessageRoleUser,
				Content: &schemas.ChatMessageContent{
					ContentStr: bifrost.Ptr("Hello, test message"),
				},
			},
		},
	})

	if bifrostErr != nil {
		t.Fatalf("Expected no error, got: %v", bifrostErr)
	}
	if response == nil {
		t.Fatal("Expected response")
	}
	if len(response.Choices) == 0 {
		t.Fatal("Expected at least one choice")
	}
	if response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr == nil {
		t.Fatal("Expected content string")
	}
	if *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr != "Custom OpenAI mock response" {
		t.Errorf("Expected custom message, got: %s", *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr)
	}
	if response.Usage.TotalTokens != 40 {
		t.Errorf("Expected 40 total tokens, got %d", response.Usage.TotalTokens)
	}
}

// TestMockerPlugin_ErrorResponse tests error response generation
func TestMockerPlugin_ErrorResponse(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	allowFallbacks := false
	config := MockerConfig{
		Enabled: true,
		Rules: []MockRule{
			{
				Name:        "rate-limit-error",
				Enabled:     true,
				Priority:    100,
				Probability: 1.0,
				Conditions: Conditions{
					Providers: []string{"openai"},
				},
				Responses: []Response{
					{
						Type:           ResponseTypeError,
						AllowFallbacks: &allowFallbacks,
						Error: &ErrorResponse{
							Message:    "Rate limit exceeded",
							Type:       bifrost.Ptr("rate_limit"),
							Code:       bifrost.Ptr("429"),
							StatusCode: bifrost.Ptr(429),
						},
					},
				},
			},
		},
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	_, bifrostErr := client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
		Provider: schemas.OpenAI,
		Model:    "gpt-4",
		Input: []schemas.ChatMessage{
			{
				Role: schemas.ChatMessageRoleUser,
				Content: &schemas.ChatMessageContent{
					ContentStr: bifrost.Ptr("Hello, test message"),
				},
			},
		},
	})

	if bifrostErr == nil {
		t.Fatal("Expected error response")
	}
	if bifrostErr.Error.Message != "Rate limit exceeded" {
		t.Errorf("Expected 'Rate limit exceeded', got: %s", bifrostErr.Error.Message)
	}
	if bifrostErr.StatusCode == nil || *bifrostErr.StatusCode != 429 {
		t.Errorf("Expected status code 429, got: %v", bifrostErr.StatusCode)
	}
}

// TestMockerPlugin_MessageTemplate tests template variable substitution
func TestMockerPlugin_MessageTemplate(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	config := MockerConfig{
		Enabled: true,
		Rules: []MockRule{
			{
				Name:        "template-test",
				Enabled:     true,
				Priority:    100,
				Probability: 1.0,
				Conditions:  Conditions{}, // Match all
				Responses: []Response{
					{
						Type: ResponseTypeSuccess,
						Content: &SuccessResponse{
							MessageTemplate: bifrost.Ptr("Hello from {{provider}} using model {{model}}"),
						},
					},
				},
			},
		},
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	response, bifrostErr := client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
		Provider: schemas.Anthropic,
		Model:    "claude-3",
		Input: []schemas.ChatMessage{
			{
				Role: schemas.ChatMessageRoleUser,
				Content: &schemas.ChatMessageContent{
					ContentStr: bifrost.Ptr("Hello, test message"),
				},
			},
		},
	})

	if bifrostErr != nil {
		t.Fatalf("Expected no error, got: %v", bifrostErr)
	}
	if response == nil {
		t.Fatal("Expected response")
	}
	if len(response.Choices) == 0 {
		t.Fatal("Expected at least one choice")
	}
	if response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr == nil {
		t.Fatal("Expected content string")
	}
	expectedMessage := "Hello from anthropic using model claude-3"
	if *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr != expectedMessage {
		t.Errorf("Expected '%s', got: %s", expectedMessage, *response.Choices[0].ChatNonStreamResponseChoice.Message.Content.ContentStr)
	}
}

// TestMockerPlugin_Statistics tests plugin statistics tracking
func TestMockerPlugin_Statistics(t *testing.T) {
	ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
	config := MockerConfig{
		Enabled: true,
		Rules: []MockRule{
			{
				Name:        "stats-test",
				Enabled:     true,
				Priority:    100,
				Probability: 1.0,
				Conditions:  Conditions{}, // Match all
				Responses: []Response{
					{
						Type: ResponseTypeSuccess,
						Content: &SuccessResponse{
							Message: "Stats test response",
						},
					},
				},
			},
		},
	}
	plugin, err := Init(config)
	if err != nil {
		t.Fatalf("Expected no error creating plugin, got: %v", err)
	}

	account := BaseAccount{}
	client, err := bifrost.Init(ctx, schemas.BifrostConfig{
		Account:    &account,
		LLMPlugins: []schemas.LLMPlugin{plugin},
		Logger:     bifrost.NewDefaultLogger(schemas.LogLevelError),
	})
	if err != nil {
		t.Fatalf("Error initializing Bifrost: %v", err)
	}
	defer client.Shutdown()

	// Make multiple requests
	for i := 0; i < 3; i++ {
		_, _ = client.ChatCompletionRequest(ctx, &schemas.BifrostChatRequest{
			Provider: schemas.OpenAI,
			Model:    "gpt-4",
			Input: []schemas.ChatMessage{
				{
					Role: schemas.ChatMessageRoleUser,
					Content: &schemas.ChatMessageContent{
						ContentStr: bifrost.Ptr("Hello, test message"),
					},
				},
			},
		})
	}

	// Check statistics
	stats := plugin.GetStats()
	if stats.TotalRequests != 3 {
		t.Errorf("Expected 3 total requests, got %d", stats.TotalRequests)
	}
	if stats.MockedRequests != 3 {
		t.Errorf("Expected 3 mocked requests, got %d", stats.MockedRequests)
	}
	if stats.ResponsesGenerated != 3 {
		t.Errorf("Expected 3 responses generated, got %d", stats.ResponsesGenerated)
	}
	if stats.RuleHits["stats-test"] != 3 {
		t.Errorf("Expected 3 hits for 'stats-test' rule, got %d", stats.RuleHits["stats-test"])
	}
}

// TestMockerPlugin_ValidationErrors tests configuration validation
func TestMockerPlugin_ValidationErrors(t *testing.T) {
	tests := []struct {
		name        string
		config      MockerConfig
		expectError bool
	}{
		{
			name: "invalid default behavior",
			config: MockerConfig{
				Enabled:         true,
				DefaultBehavior: "invalid",
			},
			expectError: true,
		},
		{
			name: "missing rule name",
			config: MockerConfig{
				Enabled: true,
				Rules: []MockRule{
					{
						Name:    "", // Missing name
						Enabled: true,
						Responses: []Response{
							{
								Type: ResponseTypeSuccess,
								Content: &SuccessResponse{
									Message: "test",
								},
							},
						},
					},
				},
			},
			expectError: true,
		},
		{
			name: "invalid probability",
			config: MockerConfig{
				Enabled: true,
				Rules: []MockRule{
					{
						Name:        "test",
						Enabled:     true,
						Probability: 1.5, // Invalid probability > 1
						Responses: []Response{
							{
								Type: ResponseTypeSuccess,
								Content: &SuccessResponse{
									Message: "test",
								},
							},
						},
					},
				},
			},
			expectError: true,
		},
		{
			name: "valid configuration",
			config: MockerConfig{
				Enabled:         true,
				DefaultBehavior: DefaultBehaviorPassthrough,
				Rules: []MockRule{
					{
						Name:        "valid-rule",
						Enabled:     true,
						Probability: 0.5,
						Responses: []Response{
							{
								Type: ResponseTypeSuccess,
								Content: &SuccessResponse{
									Message: "Valid response",
								},
							},
						},
					},
				},
			},
			expectError: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := Init(tt.config)
			if tt.expectError && err == nil {
				t.Error("Expected error but got none")
			}
			if !tt.expectError && err != nil {
				t.Errorf("Expected no error but got: %v", err)
			}
		})
	}
}