From 5565123c295c696b95a489f5a3026ab5b8736ef4 Mon Sep 17 00:00:00 2001 From: ljyofme <2477354249@qq.com> Date: Wed, 20 Mar 2024 22:04:42 +0800 Subject: [PATCH] feat: add test class for casbin issue --- src/test/java/org/casbin/MenuTest.java | 78 ++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/test/java/org/casbin/MenuTest.java diff --git a/src/test/java/org/casbin/MenuTest.java b/src/test/java/org/casbin/MenuTest.java new file mode 100644 index 0000000..97cd543 --- /dev/null +++ b/src/test/java/org/casbin/MenuTest.java @@ -0,0 +1,78 @@ +package org.casbin; + +import org.casbin.jcasbin.main.Enforcer; +import org.junit.jupiter.api.Test; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +public class MenuTest { + @Test + public void testMenu() { + //model.conf and policy.csv are in the examples/casbin directory + Enforcer enforcer = new Enforcer("examples/casbin/model.conf","examples/casbin/policy.csv"); + List perms = Arrays.asList( + // ROLE_ROOT ROLE_ADMIN ROLE_USER + "SystemMenu", // ✅ ❌ ❌ + "UserMenu", // ❌ ✅ ✅ + "UserSubMenu_allow", // ❌ ✅ ✅ + "UserSubSubMenu", // ❌ ✅ ✅ + "UserSubMenu_deny", // ❌ ✅ ❌ + "AdminMenu", // ✅ ✅ ❌ + "AdminSubMenu_allow", // ✅ ✅ ❌ + "AdminSubMenu_deny" // ✅ ❌ ❌ + ); + + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); + + + List actualPermissions = new ArrayList<>(); + + // Read permissions for testing + for (String obj : perms) { + try { + // Write test results in format + writer.write(obj + repeat(" ",30 - obj.length())); + for (String sub : new String[]{"ROLE_ROOT", "ROLE_ADMIN", "ROLE_USER"}) { + boolean ok = enforcer.enforce(sub, obj, "read"); + actualPermissions.add(ok ? "✅": "❌"); + writer.write(ok ? "✅\t": "❌\t"); + } + writer.write("\n"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + try { + writer.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + + + // Store the expected results + List expectedPermissions = Arrays.asList("✅", "❌", "❌", "❌", "✅", "✅", "❌","✅", "✅","❌","✅","✅","❌","✅","❌","✅","✅","❌","✅","✅","❌","✅","❌","❌"); + // Compare expected results with actual results, if they do not match, the test fails + assertEquals(expectedPermissions,actualPermissions); + + } + + + + + private String repeat(String str, int times) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < times; i++) { + sb.append(str); + } + + return sb.toString(); + } +} +