TestExplainAPIError tests handling of API errors.
(t *testing.T)
| 171 | |
| 172 | // TestExplainAPIError tests handling of API errors. |
| 173 | func 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. |
| 215 | func TestBuildExplainContext(t *testing.T) { |
nothing calls this directly
no test coverage detected
searching dependent graphs…