1+ /*
2+ * Copyright 2020 The casbin Authors. All Rights Reserved.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ *
16+ * This is a test file showcasing the workflow of casbin::CachedEnforcer
17+ */
18+
19+ #include < gtest/gtest.h>
20+ #include < casbin/casbin.h>
21+
22+ TEST (TestEnforcerCached, TestCache) {
23+ std::string model = " ../../examples/basic_model.conf" ;
24+ std::string policy = " ../../examples/basic_policy.csv" ;
25+ casbin::CachedEnforcer e (model, policy);
26+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " read" }), true );
27+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " write" }), false );
28+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " read" }), false );
29+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " write" }), false );
30+
31+ // The cache is enabled, so even if we remove a policy rule, the decision
32+ // for ("alice", "data1", "read") will still be true, as it uses the cached result.
33+ e.RemovePolicy ({ " alice" , " data1" , " read" });
34+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " read" }), true );
35+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " write" }), false );
36+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " read" }), false );
37+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " write" }), false );
38+
39+ // Now we invalidate the cache, then all first-coming Enforce() has to be evaluated in real-time.
40+ // The decision for ("alice", "data1", "read") will be false now.
41+ e.InvalidateCache ();
42+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " read" }), false );
43+ ASSERT_EQ (e.Enforce ({ " alice" , " data1" , " write" }), false );
44+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " read" }), false );
45+ ASSERT_EQ (e.Enforce ({ " alice" , " data2" , " write" }), false );
46+ }
0 commit comments