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

Function TestExplainAPIError

ai_api_test.go:173–212  ·  view source on GitHub ↗

TestExplainAPIError tests handling of API errors.

(t *testing.T)

Source from the content-addressed store, hash-verified

171
172// TestExplainAPIError tests handling of API errors.
173func TestExplainAPIError(t *testing.T) {
174 // Create a mock server that returns an error
175 mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
176 resp := aiChatResponse{
177 Error: &struct {
178 Message string `json:"message"`
179 }{
180 Message: "Invalid API key",
181 },
182 }
183
184 w.Header().Set("Content-Type", "application/json")
185 w.WriteHeader(http.StatusUnauthorized)
186 json.NewEncoder(w).Encode(resp)
187 }))
188 defer mockServer.Close()
189
190 // Create enforcer
191 e, err := NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
192 if err != nil {
193 t.Fatal(err)
194 }
195
196 // Set AI config
197 e.SetAIConfig(AIConfig{
198 Endpoint: mockServer.URL,
199 APIKey: "invalid-key",
200 Model: "gpt-3.5-turbo",
201 Timeout: 5 * time.Second,
202 })
203
204 // Test that API error is properly handled
205 _, err = e.Explain("alice", "data1", "read")
206 if err == nil {
207 t.Error("Expected error for API failure")
208 }
209 if !strings.Contains(err.Error(), "Invalid API key") {
210 t.Errorf("Expected API error message, got: %v", err)
211 }
212}
213
214// TestBuildExplainContext tests the context building function.
215func TestBuildExplainContext(t *testing.T) {

Callers

nothing calls this directly

Calls 6

SetAIConfigMethod · 0.95
ExplainMethod · 0.95
NewEnforcerFunction · 0.85
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…