1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.test;
20
21 import org.apache.shiro.SecurityUtils;
22 import org.apache.shiro.config.Ini;
23 import org.apache.shiro.mgt.DefaultSecurityManager;
24 import org.apache.shiro.mgt.SecurityManager;
25 import org.apache.shiro.realm.text.IniRealm;
26 import org.apache.shiro.subject.Subject;
27 import org.apache.shiro.util.LifecycleUtils;
28 import org.apache.shiro.util.ThreadContext;
29 import org.junit.After;
30 import org.junit.Before;
31
32
33
34
35
36
37
38
39
40
41 public class SecurityManagerTestSupport {
42
43 protected static SecurityManager createTestSecurityManager() {
44 Ini ini = new Ini();
45 ini.setSectionProperty("users", "test", "test");
46 return new DefaultSecurityManager(new IniRealm(ini));
47 }
48
49 protected void destroy(SecurityManager sm) {
50 LifecycleUtils.destroy(sm);
51 }
52
53 protected SecurityManager createAndBindTestSecurityManager() {
54 SecurityManager sm = createTestSecurityManager();
55 ThreadContext.bind(sm);
56 return sm;
57 }
58
59 protected Subject createAndBindTestSubject() {
60 SecurityManager sm = ThreadContext.getSecurityManager();
61 if (sm == null) {
62 createAndBindTestSecurityManager();
63 }
64 return SecurityUtils.getSubject();
65 }
66
67 @Before
68 public void setup() {
69 createAndBindTestSubject();
70 }
71
72 @After
73 public void teardown() {
74 ThreadContext.remove();
75 }
76 }