Skip to content

Commit 4c08ad4

Browse files
committed
Polish Tests
Closes gh-14768
1 parent 8bac87f commit 4c08ad4

File tree

7 files changed

+108
-109
lines changed

7 files changed

+108
-109
lines changed

core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerAfterMethodInterceptorTests.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
* Tests for {@link AuthorizationManagerAfterMethodInterceptor}.
5151
*
5252
* @author Evgeniy Cheban
53+
* @author Gengwu Zhao
5354
*/
5455
public class AuthorizationManagerAfterMethodInterceptorTests {
5556

@@ -84,9 +85,9 @@ public void beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject() throw
8485

8586
@Test
8687
public void afterWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
87-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
8888
Authentication authentication = TestAuthentication.authenticatedUser();
89-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
89+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
90+
new SecurityContextImpl(authentication));
9091
MethodInvocation invocation = mock(MethodInvocation.class);
9192
AuthorizationManager<MethodInvocationResult> authorizationManager = AuthenticatedAuthorizationManager
9293
.authenticated();
@@ -100,10 +101,10 @@ public void afterWhenMockSecurityContextHolderStrategyThenUses() throws Throwabl
100101
// gh-12877
101102
@Test
102103
public void afterWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
103-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
104104
Authentication authentication = new TestingAuthenticationToken("john", "password",
105105
AuthorityUtils.createAuthorityList("authority"));
106-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
106+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
107+
new SecurityContextImpl(authentication));
107108
MethodInvocation invocation = mock(MethodInvocation.class);
108109
AuthorizationManager<MethodInvocationResult> authorizationManager = AuthenticatedAuthorizationManager
109110
.authenticated();
@@ -159,6 +160,12 @@ public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() throws Thro
159160
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(mi));
160161
}
161162

163+
private SecurityContextHolderStrategy mockSecurityContextHolderStrategy(SecurityContextImpl securityContextImpl) {
164+
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
165+
given(strategy.getContext()).willReturn(securityContextImpl);
166+
return strategy;
167+
}
168+
162169
static class MyAuthzDeniedException extends AuthorizationDeniedException {
163170

164171
MyAuthzDeniedException(String msg, AuthorizationResult authorizationResult) {

core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptorTests.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
* Tests for {@link AuthorizationManagerBeforeMethodInterceptor}.
5050
*
5151
* @author Evgeniy Cheban
52+
* @author Gengwu Zhao
5253
*/
5354
public class AuthorizationManagerBeforeMethodInterceptorTests {
5455

@@ -79,10 +80,10 @@ public void beforeWhenMockAuthorizationManagerThenCheck() throws Throwable {
7980

8081
@Test
8182
public void beforeWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
82-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
8383
Authentication authentication = new TestingAuthenticationToken("user", "password",
8484
AuthorityUtils.createAuthorityList("authority"));
85-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
85+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
86+
new SecurityContextImpl(authentication));
8687
MethodInvocation invocation = mock(MethodInvocation.class);
8788
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
8889
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(
@@ -95,10 +96,11 @@ public void beforeWhenMockSecurityContextHolderStrategyThenUses() throws Throwab
9596
// gh-12877
9697
@Test
9798
public void beforeWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
98-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
99+
99100
Authentication authentication = new TestingAuthenticationToken("john", "password",
100101
AuthorityUtils.createAuthorityList("authority"));
101-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
102+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
103+
new SecurityContextImpl(authentication));
102104
MethodInvocation invocation = mock(MethodInvocation.class);
103105
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
104106
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(
@@ -150,6 +152,13 @@ public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() {
150152
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(null));
151153
}
152154

155+
private SecurityContextHolderStrategy mockSecurityContextHolderStrategy(SecurityContextImpl securityContextImpl) {
156+
157+
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
158+
given(strategy.getContext()).willReturn(securityContextImpl);
159+
return strategy;
160+
}
161+
153162
static class MyAuthzDeniedException extends AuthorizationDeniedException {
154163

155164
MyAuthzDeniedException(String msg, AuthorizationResult authorizationResult) {

core/src/test/java/org/springframework/security/authorization/method/PostFilterAuthorizationMethodInterceptorTests.java

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
* Tests for {@link PostFilterAuthorizationMethodInterceptor}.
5050
*
5151
* @author Evgeniy Cheban
52+
* @author Gengwu Zhao
5253
*/
5354
public class PostFilterAuthorizationMethodInterceptorTests {
5455

@@ -120,10 +121,11 @@ public void checkInheritedAnnotationsWhenConflictingThenAnnotationConfigurationE
120121

121122
@Test
122123
public void postFilterWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
123-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
124+
124125
Authentication authentication = new TestingAuthenticationToken("john", "password",
125126
AuthorityUtils.createAuthorityList("authority"));
126-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
127+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
128+
new SecurityContextImpl(authentication));
127129
String[] array = { "john", "bob" };
128130
MockMethodInvocation invocation = new MockMethodInvocation(new TestClass(), TestClass.class,
129131
"doSomethingArrayAuthentication", new Class[] { String[].class }, new Object[] { array }) {
@@ -141,10 +143,11 @@ public Object proceed() {
141143
// gh-12877
142144
@Test
143145
public void postFilterWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
144-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
146+
145147
Authentication authentication = new TestingAuthenticationToken("john", "password",
146148
AuthorityUtils.createAuthorityList("authority"));
147-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
149+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
150+
new SecurityContextImpl(authentication));
148151
String[] array = { "john", "bob" };
149152
MockMethodInvocation invocation = new MockMethodInvocation(new TestClass(), TestClass.class,
150153
"doSomethingArrayAuthentication", new Class[] { String[].class }, new Object[] { array }) {
@@ -161,6 +164,13 @@ public Object proceed() {
161164
SecurityContextHolder.setContextHolderStrategy(saved);
162165
}
163166

167+
private SecurityContextHolderStrategy mockSecurityContextHolderStrategy(SecurityContextImpl securityContextImpl) {
168+
169+
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
170+
given(strategy.getContext()).willReturn(securityContextImpl);
171+
return strategy;
172+
}
173+
164174
@PostFilter("filterObject == 'john'")
165175
public static class TestClass implements InterfaceAnnotationsOne, InterfaceAnnotationsTwo {
166176

core/src/test/java/org/springframework/security/authorization/method/PreFilterAuthorizationMethodInterceptorTests.java

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
* Tests for {@link PreFilterAuthorizationMethodInterceptor}.
5252
*
5353
* @author Evgeniy Cheban
54+
* @author Gengwu Zhao
5455
*/
5556
public class PreFilterAuthorizationMethodInterceptorTests {
5657

@@ -180,10 +181,10 @@ public void checkInheritedAnnotationsWhenConflictingThenAnnotationConfigurationE
180181

181182
@Test
182183
public void preFilterWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
183-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
184184
Authentication authentication = new TestingAuthenticationToken("john", "password",
185185
AuthorityUtils.createAuthorityList("authority"));
186-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
186+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
187+
new SecurityContextImpl(authentication));
187188
List<String> list = new ArrayList<>();
188189
list.add("john");
189190
list.add("bob");
@@ -198,10 +199,10 @@ public void preFilterWhenMockSecurityContextHolderStrategyThenUses() throws Thro
198199
// gh-12877
199200
@Test
200201
public void preFilterWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
201-
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
202202
Authentication authentication = new TestingAuthenticationToken("john", "password",
203203
AuthorityUtils.createAuthorityList("authority"));
204-
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
204+
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(
205+
new SecurityContextImpl(authentication));
205206
List<String> list = new ArrayList<>();
206207
list.add("john");
207208
list.add("bob");
@@ -215,6 +216,13 @@ public void preFilterWhenStaticSecurityContextHolderStrategyAfterConstructorThen
215216
SecurityContextHolder.setContextHolderStrategy(saved);
216217
}
217218

219+
private SecurityContextHolderStrategy mockSecurityContextHolderStrategy(SecurityContextImpl securityContextImpl) {
220+
221+
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
222+
given(strategy.getContext()).willReturn(securityContextImpl);
223+
return strategy;
224+
}
225+
218226
@PreFilter("filterObject == 'john'")
219227
public static class TestClass implements InterfaceAnnotationsOne, InterfaceAnnotationsTwo {
220228

ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java

Lines changed: 25 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -59,6 +59,7 @@
5959
/**
6060
* @author Luke Taylor
6161
* @author Rob Winch
62+
* @author Gengwu Zhao
6263
*/
6364
public class ActiveDirectoryLdapAuthenticationProviderTests {
6465

@@ -70,9 +71,13 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
7071

7172
UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
7273

74+
DirContext ctx;
75+
7376
@BeforeEach
74-
public void setUp() {
77+
public void setUp() throws NamingException {
7578
this.provider = new ActiveDirectoryLdapAuthenticationProvider("mydomain.eu", "ldap://192.168.1.200/");
79+
this.ctx = mock(DirContext.class);
80+
given(this.ctx.getNameInNamespace()).willReturn("");
7681
}
7782

7883
@Test
@@ -90,15 +95,13 @@ public void successfulAuthenticationProducesExpectedAuthorities() throws Excepti
9095
@Test
9196
public void customSearchFilterIsUsedForSuccessfulAuthentication() throws Exception {
9297
String customSearchFilter = "(&(objectClass=user)(sAMAccountName={0}))";
93-
DirContext ctx = mock(DirContext.class);
94-
given(ctx.getNameInNamespace()).willReturn("");
9598
DirContextAdapter dca = new DirContextAdapter();
9699
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
97-
given(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
100+
given(this.ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
98101
.willReturn(new MockNamingEnumeration(sr));
99102
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
100103
"mydomain.eu", "ldap://192.168.1.200/");
101-
customProvider.contextFactory = createContextFactoryReturning(ctx);
104+
customProvider.contextFactory = createContextFactoryReturning(this.ctx);
102105
customProvider.setSearchFilter(customSearchFilter);
103106
Authentication result = customProvider.authenticate(this.joe);
104107
assertThat(result.isAuthenticated()).isTrue();
@@ -107,34 +110,31 @@ public void customSearchFilterIsUsedForSuccessfulAuthentication() throws Excepti
107110
@Test
108111
public void defaultSearchFilter() throws Exception {
109112
final String defaultSearchFilter = "(&(objectClass=user)(userPrincipalName={0}))";
110-
DirContext ctx = mock(DirContext.class);
111-
given(ctx.getNameInNamespace()).willReturn("");
112113
DirContextAdapter dca = new DirContextAdapter();
113114
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
114-
given(ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
115+
given(this.ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
115116
.willReturn(new MockNamingEnumeration(sr));
116117
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
117118
"mydomain.eu", "ldap://192.168.1.200/");
118-
customProvider.contextFactory = createContextFactoryReturning(ctx);
119+
customProvider.contextFactory = createContextFactoryReturning(this.ctx);
119120
Authentication result = customProvider.authenticate(this.joe);
120121
assertThat(result.isAuthenticated()).isTrue();
121-
verify(ctx).search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class));
122+
verify(this.ctx).search(any(Name.class), eq(defaultSearchFilter), any(Object[].class),
123+
any(SearchControls.class));
122124
}
123125

124126
// SEC-2897,SEC-2224
125127
@Test
126128
public void bindPrincipalAndUsernameUsed() throws Exception {
127129
final String defaultSearchFilter = "(&(objectClass=user)(userPrincipalName={0}))";
128130
ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
129-
DirContext ctx = mock(DirContext.class);
130-
given(ctx.getNameInNamespace()).willReturn("");
131131
DirContextAdapter dca = new DirContextAdapter();
132132
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
133-
given(ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
133+
given(this.ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
134134
.willReturn(new MockNamingEnumeration(sr));
135135
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
136136
"mydomain.eu", "ldap://192.168.1.200/");
137-
customProvider.contextFactory = createContextFactoryReturning(ctx);
137+
customProvider.contextFactory = createContextFactoryReturning(this.ctx);
138138
Authentication result = customProvider.authenticate(this.joe);
139139
assertThat(captor.getValue()).containsExactly("[email protected]", "joe");
140140
assertThat(result.isAuthenticated()).isTrue();
@@ -153,36 +153,30 @@ public void setSearchFilterEmpty() {
153153
@Test
154154
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
155155
this.provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
156-
DirContext ctx = mock(DirContext.class);
157-
given(ctx.getNameInNamespace()).willReturn("");
158156
DirContextAdapter dca = new DirContextAdapter();
159157
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
160-
given(ctx.search(eq(LdapNameBuilder.newInstance("DC=mydomain,DC=eu").build()), any(String.class),
158+
given(this.ctx.search(eq(LdapNameBuilder.newInstance("DC=mydomain,DC=eu").build()), any(String.class),
161159
any(Object[].class), any(SearchControls.class)))
162160
.willReturn(new MockNamingEnumeration(sr));
163-
this.provider.contextFactory = createContextFactoryReturning(ctx);
161+
this.provider.contextFactory = createContextFactoryReturning(this.ctx);
164162
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
165163
this.provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("[email protected]", "password"));
166164
}
167165

168166
@Test
169167
public void failedUserSearchCausesBadCredentials() throws Exception {
170-
DirContext ctx = mock(DirContext.class);
171-
given(ctx.getNameInNamespace()).willReturn("");
172-
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
168+
given(this.ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
173169
.willThrow(new NameNotFoundException());
174-
this.provider.contextFactory = createContextFactoryReturning(ctx);
170+
this.provider.contextFactory = createContextFactoryReturning(this.ctx);
175171
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
176172
}
177173

178174
// SEC-2017
179175
@Test
180176
public void noUserSearchCausesUsernameNotFound() throws Exception {
181-
DirContext ctx = mock(DirContext.class);
182-
given(ctx.getNameInNamespace()).willReturn("");
183-
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
177+
given(this.ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
184178
.willReturn(new EmptyEnumeration<>());
185-
this.provider.contextFactory = createContextFactoryReturning(ctx);
179+
this.provider.contextFactory = createContextFactoryReturning(this.ctx);
186180
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
187181
}
188182

@@ -196,16 +190,14 @@ public void sec2500PreventAnonymousBind() {
196190
@Test
197191
@SuppressWarnings("unchecked")
198192
public void duplicateUserSearchCausesError() throws Exception {
199-
DirContext ctx = mock(DirContext.class);
200-
given(ctx.getNameInNamespace()).willReturn("");
201193
NamingEnumeration<SearchResult> searchResults = mock(NamingEnumeration.class);
202194
given(searchResults.hasMore()).willReturn(true, true, false);
203195
SearchResult searchResult = mock(SearchResult.class);
204196
given(searchResult.getObject()).willReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
205197
given(searchResults.next()).willReturn(searchResult);
206-
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
198+
given(this.ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
207199
.willReturn(searchResults);
208-
this.provider.contextFactory = createContextFactoryReturning(ctx);
200+
this.provider.contextFactory = createContextFactoryReturning(this.ctx);
209201
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
210202
.isThrownBy(() -> this.provider.authenticate(this.joe));
211203
}
@@ -357,16 +349,14 @@ DirContext createContext(Hashtable<?, ?> env) {
357349

358350
private void checkAuthentication(String rootDn, ActiveDirectoryLdapAuthenticationProvider provider)
359351
throws NamingException {
360-
DirContext ctx = mock(DirContext.class);
361-
given(ctx.getNameInNamespace()).willReturn("");
362352
DirContextAdapter dca = new DirContextAdapter();
363353
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
364354
@SuppressWarnings("deprecation")
365355
Name searchBaseDn = LdapNameBuilder.newInstance(rootDn).build();
366-
given(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
356+
given(this.ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
367357
.willReturn(new MockNamingEnumeration(sr))
368358
.willReturn(new MockNamingEnumeration(sr));
369-
provider.contextFactory = createContextFactoryReturning(ctx);
359+
provider.contextFactory = createContextFactoryReturning(this.ctx);
370360
Authentication result = provider.authenticate(this.joe);
371361
assertThat(result.getAuthorities()).isEmpty();
372362
dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");

0 commit comments

Comments
 (0)