1
0
mirror of synced 2026-05-22 21:33:16 +00:00

Replace expected @Test attributes with AssertJ

Replace JUnit expected @Test attributes with AssertJ calls.
This commit is contained in:
Phillip Webb
2020-09-10 21:33:16 -07:00
committed by Josh Cummings
parent 20baa7d409
commit c502312719
243 changed files with 2115 additions and 1591 deletions
@@ -20,8 +20,6 @@ import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.naming.directory.DirContext;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -32,6 +30,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Luke Taylor
@@ -80,21 +80,14 @@ public class DefaultSpringSecurityContextSourceTests {
}
// SEC-1145. Confirms that there is no issue here with pooling.
@Test(expected = AuthenticationException.class)
@Test
public void cantBindWithWrongPasswordImmediatelyAfterSuccessfulBind() throws Exception {
DirContext ctx = null;
try {
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword");
}
catch (Exception ex) {
}
assertThat(ctx).isNotNull();
this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword").close();
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
ctx.close();
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
// Now get it gain, with wrong password. Should fail.
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword");
ctx.close();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.contextSource
.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword").close());
}
@Test
@@ -105,12 +98,14 @@ public class DefaultSpringSecurityContextSourceTests {
contextSource.getContext("uid=space cadet,ou=space cadets,dc=springframework,dc=org", "spacecadetspassword");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void instantiationFailsWithEmptyServerList() {
List<String> serverUrls = new ArrayList<>();
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
ctxSrc.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> {
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
ctxSrc.afterPropertiesSet();
});
}
@Test
@@ -140,15 +135,15 @@ public class DefaultSpringSecurityContextSourceTests {
assertThat(ctxSrc.isPooled()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void instantiationFailsWithIncorrectServerUrl() {
List<String> serverUrls = new ArrayList<>();
// a simple trailing slash should be ok
serverUrls.add("ldaps://blah:636/");
// this url should be rejected because the root DN goes into a separate parameter
serverUrls.add("ldap://bar:389/dc=foobar,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
"dc=springframework,dc=org");
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultSpringSecurityContextSource(serverUrls, "dc=springframework,dc=org"));
}
static class EnvExposingDefaultSpringSecurityContextSource extends DefaultSpringSecurityContextSource {
@@ -60,9 +60,10 @@ public class BindAuthenticatorTests {
}
@Test(expected = BadCredentialsException.class)
@Test
public void emptyPasswordIsRejected() {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", ""));
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", "")));
}
@Test
@@ -37,6 +37,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link PasswordComparisonAuthenticator}.
@@ -84,11 +85,12 @@ public class PasswordComparisonAuthenticatorTests {
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")));
}
@Test(expected = BadCredentialsException.class)
@Test
public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password
this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass"));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass")));
}
@Test
@@ -121,9 +123,9 @@ public class PasswordComparisonAuthenticatorTests {
this.authenticator.authenticate(this.ben);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testPasswordEncoderCantBeNull() {
this.authenticator.setPasswordEncoder(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticator.setPasswordEncoder(null));
}
@Test
@@ -31,6 +31,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for FilterBasedLdapUserSearch.
@@ -81,16 +82,17 @@ public class FilterBasedLdapUserSearchTests {
assertThat(ben.getStringAttribute("cn")).isEqualTo("Ben Alex");
}
@Test(expected = IncorrectResultSizeDataAccessException.class)
@Test
public void searchFailsOnMultipleMatches() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(cn=*)", this.contextSource);
locator.searchForUser("Ignored");
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
.isThrownBy(() -> locator.searchForUser("Ignored"));
}
@Test(expected = UsernameNotFoundException.class)
@Test
public void searchForInvalidUserFails() {
FilterBasedLdapUserSearch locator = new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource);
locator.searchForUser("Joe");
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> locator.searchForUser("Joe"));
}
@Test
@@ -37,6 +37,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Luke Taylor
@@ -198,9 +199,9 @@ public class DefaultLdapAuthoritiesPopulatorTests {
assertThat(authorities).allMatch(LdapAuthority.class::isInstance);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void customAuthoritiesMappingFunctionThrowsIfNull() {
this.populator.setAuthorityMapper(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.populator.setAuthorityMapper(null));
}
}
@@ -118,9 +118,9 @@ public class LdapUserDetailsManagerTests {
assertThat(bob.getAuthorities()).hasSize(1);
}
@Test(expected = UsernameNotFoundException.class)
@Test
public void testLoadingInvalidUsernameThrowsUsernameNotFoundException() {
this.mgr.loadUserByUsername("jim");
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.mgr.loadUserByUsername("jim"));
}
@Test
@@ -201,7 +201,7 @@ public class LdapUserDetailsManagerTests {
.isTrue();
}
@Test(expected = BadCredentialsException.class)
@Test
public void testPasswordChangeWithWrongOldPasswordFails() {
InetOrgPerson.Essence p = new InetOrgPerson.Essence();
p.setDn("whocares");
@@ -210,13 +210,11 @@ public class LdapUserDetailsManagerTests {
p.setUid("johnyossarian");
p.setPassword("yossarianspassword");
p.setAuthorities(TEST_AUTHORITIES);
this.mgr.createUser(p.createUserDetails());
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("johnyossarian", "yossarianspassword", TEST_AUTHORITIES));
this.mgr.changePassword("wrongpassword", "yossariansnewpassword");
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.mgr.changePassword("wrongpassword", "yossariansnewpassword"));
}
}
@@ -30,6 +30,7 @@ import org.springframework.security.ldap.authentication.SpringSecurityAuthentica
import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Luke Taylor
@@ -57,11 +58,11 @@ public class SpringSecurityAuthenticationSourceTests {
assertThat(source.getPrincipal()).isEqualTo("");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getPrincipalRejectsNonLdapUserDetailsObject() {
AuthenticationSource source = new SpringSecurityAuthenticationSource();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new Object(), "password"));
source.getPrincipal();
assertThatIllegalArgumentException().isThrownBy(source::getPrincipal);
}
@Test
@@ -73,23 +73,23 @@ public class LdapAuthenticationProviderTests {
() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword")));
}
@Test(expected = BadCredentialsException.class)
@Test
public void usernameNotFoundExceptionIsHiddenByDefault() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.authenticate(joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe));
}
@Test(expected = UsernameNotFoundException.class)
@Test
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false);
provider.authenticate(joe);
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(joe));
}
@Test
@@ -49,6 +49,7 @@ import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAu
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -140,14 +141,14 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
assertThat(result.isAuthenticated()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setSearchFilterNull() {
this.provider.setSearchFilter(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setSearchFilter(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setSearchFilterEmpty() {
this.provider.setSearchFilter(" ");
assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setSearchFilter(" "));
}
@Test
@@ -164,35 +165,36 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
}
@Test(expected = BadCredentialsException.class)
@Test
public void failedUserSearchCausesBadCredentials() throws Exception {
DirContext ctx = mock(DirContext.class);
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willThrow(new NameNotFoundException());
this.provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
// SEC-2017
@Test(expected = BadCredentialsException.class)
@Test
public void noUserSearchCausesUsernameNotFound() throws Exception {
DirContext ctx = mock(DirContext.class);
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(new EmptyEnumeration<>());
this.provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
// SEC-2500
@Test(expected = BadCredentialsException.class)
@Test
public void sec2500PreventAnonymousBind() {
this.provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", ""));
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("rwinch", "")));
}
@Test
@SuppressWarnings("unchecked")
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void duplicateUserSearchCausesError() throws Exception {
DirContext ctx = mock(DirContext.class);
given(ctx.getNameInNamespace()).willReturn("");
@@ -204,30 +206,31 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(searchResults);
this.provider.contextFactory = createContextFactoryReturning(ctx);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class)
.isThrownBy(() -> this.provider.authenticate(this.joe));
}
static final String msg = "[LDAP: error code 49 - 80858585: LdapErr: DSID-DECAFF0, comment: AcceptSecurityContext error, data ";
@Test(expected = BadCredentialsException.class)
@Test
public void userNotFoundIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "525, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = BadCredentialsException.class)
@Test
public void incorrectPasswordIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "52e, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = BadCredentialsException.class)
@Test
public void notPermittedIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "530, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test
@@ -242,47 +245,48 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
.isEqualTo(dataCode));
}
@Test(expected = CredentialsExpiredException.class)
@Test
public void expiredPasswordIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(CredentialsExpiredException.class)
.isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = DisabledException.class)
@Test
public void accountDisabledIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "533, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = AccountExpiredException.class)
@Test
public void accountExpiredIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "701, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = LockedException.class)
@Test
public void accountLockedIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "775, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = BadCredentialsException.class)
@Test
public void unknownErrorCodeIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "999, xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test(expected = BadCredentialsException.class)
@Test
public void errorWithNoSubcodeIsHandledCleanly() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
}
@Test
@@ -293,13 +297,15 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
}).withCauseInstanceOf(org.springframework.ldap.CommunicationException.class);
}
@Test(expected = org.springframework.security.authentication.InternalAuthenticationServiceException.class)
@Test
public void connectionExceptionIsWrappedInInternalException() throws Exception {
ActiveDirectoryLdapAuthenticationProvider noneReachableProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", NON_EXISTING_LDAP_PROVIDER, "dc=ad,dc=eu,dc=mydomain");
noneReachableProvider
.setContextEnvironmentProperties(Collections.singletonMap("com.sun.jndi.ldap.connect.timeout", "5"));
noneReachableProvider.doAuthentication(this.joe);
assertThatExceptionOfType(
org.springframework.security.authentication.InternalAuthenticationServiceException.class)
.isThrownBy(() -> noneReachableProvider.doAuthentication(this.joe));
}
@Test
@@ -309,14 +315,15 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
checkAuthentication("dc=ad,dc=eu,dc=mydomain", provider);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setContextEnvironmentPropertiesNull() {
this.provider.setContextEnvironmentProperties(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setContextEnvironmentProperties(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setContextEnvironmentPropertiesEmpty() {
this.provider.setContextEnvironmentProperties(new Hashtable<>());
assertThatIllegalArgumentException()
.isThrownBy(() -> this.provider.setContextEnvironmentProperties(new Hashtable<>()));
}
@Test
@@ -30,6 +30,7 @@ import org.junit.Test;
import org.springframework.ldap.UncategorizedLdapException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@@ -67,18 +68,20 @@ public class PasswordPolicyAwareContextSourceTests {
assertThat(this.ctxSource.getContext("user", "ignored")).isNotNull();
}
@Test(expected = UncategorizedLdapException.class)
@Test
public void standardExceptionIsPropagatedWhenExceptionRaisedAndNoControlsAreSet() throws Exception {
willThrow(new NamingException("some LDAP exception")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
assertThatExceptionOfType(UncategorizedLdapException.class)
.isThrownBy(() -> this.ctxSource.getContext("user", "ignored"));
}
@Test(expected = PasswordPolicyException.class)
@Test
public void lockedPasswordPolicyControlRaisesPasswordPolicyException() throws Exception {
given(this.ctx.getResponseControls()).willReturn(new Control[] {
new PasswordPolicyResponseControl(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL) });
willThrow(new NamingException("locked message")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
assertThatExceptionOfType(PasswordPolicyException.class)
.isThrownBy(() -> this.ctxSource.getContext("user", "ignored"));
}
}
@@ -31,6 +31,7 @@ import org.springframework.security.ldap.authentication.MockUserSearch;
import org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link LdapUserDetailsService}
@@ -39,14 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class LdapUserDetailsServiceTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullSearchObject() {
new LdapUserDetailsService(null, new NullLdapAuthoritiesPopulator());
assertThatIllegalArgumentException()
.isThrownBy(() -> new LdapUserDetailsService(null, new NullLdapAuthoritiesPopulator()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullAuthoritiesPopulator() {
new LdapUserDetailsService(new MockUserSearch(), null);
assertThatIllegalArgumentException().isThrownBy(() -> new LdapUserDetailsService(new MockUserSearch(), null));
}
@Test