MCPcopy
hub / github.com/apache/casbin / TestConstraintRolePre

Function TestConstraintRolePre

constraint_test.go:178–229  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

176}
177
178func TestConstraintRolePre(t *testing.T) {
179 modelText := `
180[request_definition]
181r = sub, obj, act
182
183[policy_definition]
184p = sub, obj, act
185
186[role_definition]
187g = _, _
188
189[constraint_definition]
190c = rolePre("db_admin", "security_trained")
191
192[policy_effect]
193e = some(where (p.eft == allow))
194
195[matchers]
196m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
197`
198
199 m, err := model.NewModelFromString(modelText)
200 if err != nil {
201 t.Fatalf("Failed to create model: %v", err)
202 }
203
204 e, err := NewEnforcer(m)
205 if err != nil {
206 t.Fatalf("Failed to create enforcer: %v", err)
207 }
208
209 // Try to add db_admin without prerequisite should fail
210 _, err = e.AddRoleForUser("alice", "db_admin")
211 if err == nil {
212 t.Fatal("Expected constraint violation error, got nil")
213 }
214 if !strings.Contains(err.Error(), "constraint violation") {
215 t.Fatalf("Expected constraint violation error, got: %v", err)
216 }
217
218 // Add prerequisite role first
219 _, err = e.AddRoleForUser("alice", "security_trained")
220 if err != nil {
221 t.Fatalf("Failed to add security_trained to alice: %v", err)
222 }
223
224 // Now adding db_admin should succeed
225 _, err = e.AddRoleForUser("alice", "db_admin")
226 if err != nil {
227 t.Fatalf("Failed to add db_admin to alice: %v", err)
228 }
229}
230
231func TestConstraintWithoutRBAC(t *testing.T) {
232 modelText := `

Callers

nothing calls this directly

Calls 4

AddRoleForUserMethod · 0.95
NewModelFromStringFunction · 0.92
NewEnforcerFunction · 0.85
ErrorMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…