MCPcopy Index your code
hub / github.com/apache/casbin / TestExplainWithMockAPI

Function TestExplainWithMockAPI

ai_api_test.go:43–118  ·  view source on GitHub ↗

TestExplainWithMockAPI tests Explain with a mock OpenAI-compatible API.

(t *testing.T)

Source from the content-addressed store, hash-verified

41
42// TestExplainWithMockAPI tests Explain with a mock OpenAI-compatible API.
43func TestExplainWithMockAPI(t *testing.T) {
44 // Create a mock server that simulates OpenAI API
45 mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
46 // Verify request
47 if r.Method != http.MethodPost {
48 t.Errorf("Expected POST request, got %s", r.Method)
49 }
50 if r.Header.Get("Content-Type") != "application/json" {
51 t.Errorf("Expected Content-Type: application/json, got %s", r.Header.Get("Content-Type"))
52 }
53 if !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
54 t.Errorf("Expected Bearer token in Authorization header, got %s", r.Header.Get("Authorization"))
55 }
56
57 // Parse request to verify structure
58 var req aiChatRequest
59 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
60 t.Errorf("Failed to decode request: %v", err)
61 }
62
63 if req.Model != "gpt-3.5-turbo" {
64 t.Errorf("Expected model gpt-3.5-turbo, got %s", req.Model)
65 }
66
67 if len(req.Messages) != 2 {
68 t.Errorf("Expected 2 messages, got %d", len(req.Messages))
69 }
70
71 // Send mock response
72 resp := aiChatResponse{
73 Choices: []struct {
74 Message aiMessage `json:"message"`
75 }{
76 {
77 Message: aiMessage{
78 Role: "assistant",
79 Content: "The request was allowed because alice has read permission on data1 according to the policy rule.",
80 },
81 },
82 },
83 }
84
85 w.Header().Set("Content-Type", "application/json")
86 w.WriteHeader(http.StatusOK)
87 json.NewEncoder(w).Encode(resp)
88 }))
89 defer mockServer.Close()
90
91 // Create enforcer
92 e, err := NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
93 if err != nil {
94 t.Fatal(err)
95 }
96
97 // Set AI config with mock server
98 e.SetAIConfig(AIConfig{
99 Endpoint: mockServer.URL,
100 APIKey: "test-api-key",

Callers

nothing calls this directly

Calls 7

SetAIConfigMethod · 0.95
ExplainMethod · 0.95
NewEnforcerFunction · 0.85
GetMethod · 0.65
SetMethod · 0.65
CloseMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…