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

Function TestExplainDenied

ai_api_test.go:121–170  ·  view source on GitHub ↗

TestExplainDenied tests Explain for a denied request.

(t *testing.T)

Source from the content-addressed store, hash-verified

119
120// TestExplainDenied tests Explain for a denied request.
121func 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.
173func TestExplainAPIError(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…