TestExplainDenied tests Explain for a denied request.
(t *testing.T)
| 119 | |
| 120 | // TestExplainDenied tests Explain for a denied request. |
| 121 | func TestExplainDenied(t *testing.T) { |
| 122 | // Create a mock server |
| 123 | mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 124 | resp := aiChatResponse{ |
| 125 | Choices: []struct { |
| 126 | Message aiMessage `json:"message"` |
| 127 | }{ |
| 128 | { |
| 129 | Message: aiMessage{ |
| 130 | Role: "assistant", |
| 131 | Content: "The request was denied because there is no policy rule that allows alice to write to data1.", |
| 132 | }, |
| 133 | }, |
| 134 | }, |
| 135 | } |
| 136 | |
| 137 | w.Header().Set("Content-Type", "application/json") |
| 138 | w.WriteHeader(http.StatusOK) |
| 139 | json.NewEncoder(w).Encode(resp) |
| 140 | })) |
| 141 | defer mockServer.Close() |
| 142 | |
| 143 | // Create enforcer |
| 144 | e, err := NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") |
| 145 | if err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | |
| 149 | // Set AI config |
| 150 | e.SetAIConfig(AIConfig{ |
| 151 | Endpoint: mockServer.URL, |
| 152 | APIKey: "test-api-key", |
| 153 | Model: "gpt-3.5-turbo", |
| 154 | Timeout: 5 * time.Second, |
| 155 | }) |
| 156 | |
| 157 | // Test explanation for denied request |
| 158 | explanation, err := e.Explain("alice", "data1", "write") |
| 159 | if err != nil { |
| 160 | t.Fatalf("Failed to get explanation: %v", err) |
| 161 | } |
| 162 | |
| 163 | if explanation == "" { |
| 164 | t.Error("Expected non-empty explanation") |
| 165 | } |
| 166 | |
| 167 | if !strings.Contains(explanation, "denied") { |
| 168 | t.Errorf("Expected explanation to mention 'denied', got: %s", explanation) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // TestExplainAPIError tests handling of API errors. |
| 173 | func TestExplainAPIError(t *testing.T) { |
nothing calls this directly
no test coverage detected
searching dependent graphs…