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

View File

@ -166,7 +166,7 @@ public class AclImplTests {
assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
}
@Test(expected = NotFoundException.class)
@Test
public void insertAceFailsForNonExistentElement() {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
@ -174,7 +174,8 @@ public class AclImplTests {
// Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true));
}
@Test
@ -411,38 +412,40 @@ public class AclImplTests {
.isFalse();
}
@Test(expected = NotFoundException.class)
@Test
public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true));
}
@Test(expected = NotFoundException.class)
@Test
public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.deleteAce(-1);
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(-1));
}
@Test(expected = NotFoundException.class)
@Test
public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
// Insert at zero, OK.
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1
acl.insertAce(2, mock(Permission.class), mock(Sid.class), true);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(2, mock(Permission.class), mock(Sid.class), true));
}
// SEC-1151
@Test(expected = NotFoundException.class)
@Test
public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1
acl.deleteAce(1);
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(1));
}
// SEC-1795

View File

@ -72,9 +72,9 @@ public class ObjectIdentityImplTests {
assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorRejectsInvalidTypeParameter() {
new ObjectIdentityImpl("", 1L);
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L));
}
@Test

View File

@ -54,6 +54,7 @@ import org.springframework.security.acls.model.Sid;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link BasicLookupStrategy}
@ -294,12 +295,13 @@ public abstract class AbstractBasicLookupStrategyTests {
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void nullOwnerIsNotSupported() {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,104,null,null,1);";
getJdbcTemplate().execute(query);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
assertThatIllegalArgumentException()
.isThrownBy(() -> this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
}
@Test

View File

@ -31,6 +31,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.ConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
/**
@ -125,14 +126,14 @@ public class AclClassIdUtilsTests {
assertThat(newIdentifier).isEqualTo(identifier);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldNotAcceptNullConversionServiceInConstruction() {
new AclClassIdUtils(null);
assertThatIllegalArgumentException().isThrownBy(() -> new AclClassIdUtils(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldNotAcceptNullConversionServiceInSetter() {
this.aclClassIdUtils.setConversionService(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.aclClassIdUtils.setConversionService(null));
}
}

View File

@ -37,6 +37,8 @@ import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.ObjectIdentity;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests {@link BasicLookupStrategy} with Acl Class type id set to UUID.
*
@ -110,10 +112,11 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
Assert.assertNotNull(foundAcls.get(oid));
}
@Test(expected = ConversionFailedException.class)
@Test
public void testReadObjectIdentityUsingNonUuidInDatabase() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID);
this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
assertThatExceptionOfType(ConversionFailedException.class)
.isThrownBy(() -> this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
}
}

View File

@ -94,10 +94,11 @@ public class EhCacheBasedAclCacheTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorRejectsNullParameters() {
new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
assertThatIllegalArgumentException().isThrownBy(
() -> new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))));
}
@Test

View File

@ -44,6 +44,7 @@ import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid;
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.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
@ -95,13 +96,14 @@ public class JdbcAclServiceTests {
}
// SEC-1898
@Test(expected = NotFoundException.class)
@Test
public void readAclByIdMissingAcl() {
Map<ObjectIdentity, Acl> result = new HashMap<>();
given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user"));
this.aclService.readAclById(objectIdentity, sids);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.aclService.readAclById(objectIdentity, sids));
}
@Test

View File

@ -43,6 +43,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link org.springframework.security.acls.domain.SpringCacheBasedAclCache}
@ -74,9 +75,9 @@ public class SpringCacheBasedAclCacheTests {
return cache;
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorRejectsNullParameters() {
new SpringCacheBasedAclCache(null, null, null);
assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedAclCache(null, null, null));
}
@SuppressWarnings("rawtypes")

View File

@ -98,9 +98,10 @@ public class AnnotationSecurityAspectTests {
this.secured.securedMethod();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void securedClassMethodDeniesUnauthenticatedAccess() {
this.secured.securedClassMethod();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod());
}
@Test
@ -109,17 +110,17 @@ public class AnnotationSecurityAspectTests {
this.secured.securedClassMethod();
}
@Test(expected = AccessDeniedException.class)
@Test
public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate());
this.securedSub.publicCallsPrivate();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate());
}
@Test(expected = AccessDeniedException.class)
@Test
public void protectedMethodIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
this.secured.protectedMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod());
}
@Test
@ -129,11 +130,11 @@ public class AnnotationSecurityAspectTests {
}
// SEC-1262
@Test(expected = AccessDeniedException.class)
@Test
public void denyAllPreAuthorizeDeniesAccess() {
configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(this.anne);
this.prePostSecured.denyAllMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.prePostSecured::denyAllMethod);
}
@Test

View File

@ -41,6 +41,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
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.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
@ -199,7 +201,7 @@ public class CasAuthenticationProviderTests {
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
}
@Test(expected = BadCredentialsException.class)
@Test
public void missingTicketIdIsDetected() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
@ -211,10 +213,10 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "");
cap.authenticate(token);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token));
}
@Test(expected = BadCredentialsException.class)
@Test
public void invalidKeyIsDetected() throws Exception {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationProvider cap = new CasAuthenticationProvider();
@ -227,30 +229,30 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion);
cap.authenticate(token);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsMissingAuthoritiesPopulator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsMissingKey() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsMissingStatelessTicketCache() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
// set this explicitly to null to test failure
@ -259,17 +261,17 @@ public class CasAuthenticationProviderTests {
cap.setKey("qwerty");
cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsMissingTicketValidator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
}
@Test

View File

@ -68,10 +68,11 @@ public class CasAuthenticationTokenTests {
"Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenEmptyKeyThenThrowsException() {
new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(),
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null);
assertThatIllegalArgumentException().isThrownBy(
() -> new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(),
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null));
}
@Test

View File

@ -23,6 +23,7 @@ import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests
@ -56,9 +57,9 @@ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCac
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStartupDetectsMissingCache() throws Exception {
new SpringCacheBasedTicketCache(null);
assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedTicketCache(null));
}
}

View File

@ -36,6 +36,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
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.Mockito.mock;
@ -76,13 +77,14 @@ public class CasAuthenticationFilterTests {
assertThat(result != null).isTrue();
}
@Test(expected = AuthenticationException.class)
@Test
public void testNullServiceTicketHandledGracefully() throws Exception {
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager((a) -> {
throw new BadCredentialsException("Rejected");
});
filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse());
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test

View File

@ -31,10 +31,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/
public class ServicePropertiesTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsMissingService() throws Exception {
ServiceProperties sp = new ServiceProperties();
sp.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
}
@Test

View File

@ -33,6 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class LdapProviderBeanDefinitionParserTests {
@ -73,10 +74,10 @@ public class LdapProviderBeanDefinitionParserTests {
.containsExactly("member={0}", "uniqueMember={0}");
}
@Test(expected = ApplicationContextException.class)
@Test
public void missingServerEltCausesConfigException() {
new InMemoryXmlApplicationContext(
"<authentication-manager>" + " <ldap-authentication-provider />" + "</authentication-manager>");
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> new InMemoryXmlApplicationContext(
"<authentication-manager>" + " <ldap-authentication-provider />" + "</authentication-manager>"));
}
@Test

View File

@ -47,14 +47,16 @@ public class InvalidConfigurationTests {
}
// Parser should throw a SAXParseException
@Test(expected = XmlBeanDefinitionStoreException.class)
@Test
public void passwordEncoderCannotAppearAtTopLevel() {
setContext("<password-encoder hash='md5'/>");
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> setContext("<password-encoder hash='md5'/>"));
}
@Test(expected = XmlBeanDefinitionStoreException.class)
@Test
public void authenticationProviderCannotAppearAtTopLevel() {
setContext("<authentication-provider ref='blah'/>");
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> setContext("<authentication-provider ref='blah'/>"));
}
@Test

View File

@ -38,6 +38,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;
/**
* @author Rob Winch
@ -71,15 +72,17 @@ public class Issue50Tests {
// no exception
}
@Test(expected = UsernameNotFoundException.class)
@Test
public void authenticateWhenMissingUserThenUsernameNotFoundException() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("test", "password"));
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")));
}
@Test(expected = BadCredentialsException.class)
@Test
public void authenticateWhenInvalidPasswordThenBadCredentialsException() {
this.userRepo.save(User.withUsernameAndPassword("test", "password"));
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid"));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid")));
}
@Test
@ -90,12 +93,12 @@ public class Issue50Tests {
assertThat(result.getName()).isEqualTo("test");
}
@Test(expected = AccessDeniedException.class)
@Test
public void globalMethodSecurityIsEnabledWhenNotAllowedThenAccessDenied() {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER"));
this.userRepo.save(User.withUsernameAndPassword("denied", "password"));
Authentication result = this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password"));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")));
}
}

View File

@ -27,6 +27,8 @@ import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -44,14 +46,14 @@ public class AbstractConfiguredSecurityBuilderTests {
this.builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenObjectPostProcessorIsNullThenThrowIllegalArgumentException() {
new TestConfiguredSecurityBuilder(null);
assertThatIllegalArgumentException().isThrownBy(() -> new TestConfiguredSecurityBuilder(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void objectPostProcessorWhenNullThenThrowIllegalArgumentException() {
this.builder.objectPostProcessor(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.builder.objectPostProcessor(null));
}
@Test
@ -61,15 +63,15 @@ public class AbstractConfiguredSecurityBuilderTests {
assertThat(this.builder.getConfigurers(TestSecurityConfigurer.class)).hasSize(1);
}
@Test(expected = IllegalStateException.class)
@Test
public void buildWhenBuildTwiceThenThrowIllegalStateException() throws Exception {
this.builder.build();
this.builder.build();
assertThatIllegalStateException().isThrownBy(() -> this.builder.build());
}
@Test(expected = IllegalStateException.class)
@Test
public void getObjectWhenNotBuiltThenThrowIllegalStateException() {
this.builder.getObject();
assertThatIllegalStateException().isThrownBy(this.builder::getObject);
}
@Test
@ -81,22 +83,22 @@ public class AbstractConfiguredSecurityBuilderTests {
verify(DelegateSecurityConfigurer.CONFIGURER).configure(this.builder);
}
@Test(expected = IllegalStateException.class)
@Test
public void getConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception {
TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class),
true);
builder.apply(new DelegateSecurityConfigurer());
builder.apply(new DelegateSecurityConfigurer());
builder.getConfigurer(DelegateSecurityConfigurer.class);
assertThatIllegalStateException().isThrownBy(() -> builder.getConfigurer(DelegateSecurityConfigurer.class));
}
@Test(expected = IllegalStateException.class)
@Test
public void removeConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception {
TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class),
true);
builder.apply(new DelegateSecurityConfigurer());
builder.apply(new DelegateSecurityConfigurer());
builder.removeConfigurer(DelegateSecurityConfigurer.class);
assertThatIllegalStateException().isThrownBy(() -> builder.removeConfigurer(DelegateSecurityConfigurer.class));
}
@Test

View File

@ -26,6 +26,8 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link AbstractRequestMatcherRegistry}.
*
@ -33,29 +35,34 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
*/
public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Test(expected = BeanCreationException.class)
@Test
public void antMatchersCanNotWorkAfterAnyRequest() {
loadConfig(AntMatchersAfterAnyRequestConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(AntMatchersAfterAnyRequestConfig.class));
}
@Test(expected = BeanCreationException.class)
@Test
public void mvcMatchersCanNotWorkAfterAnyRequest() {
loadConfig(MvcMatchersAfterAnyRequestConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(MvcMatchersAfterAnyRequestConfig.class));
}
@Test(expected = BeanCreationException.class)
@Test
public void regexMatchersCanNotWorkAfterAnyRequest() {
loadConfig(RegexMatchersAfterAnyRequestConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(RegexMatchersAfterAnyRequestConfig.class));
}
@Test(expected = BeanCreationException.class)
@Test
public void anyRequestCanNotWorkAfterItself() {
loadConfig(AnyRequestAfterItselfConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(AnyRequestAfterItselfConfig.class));
}
@Test(expected = BeanCreationException.class)
@Test
public void requestMatchersCanNotWorkAfterAnyRequest() {
loadConfig(RequestMatchersAfterAnyRequestConfig.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(RequestMatchersAfterAnyRequestConfig.class));
}
private void loadConfig(Class<?>... configs) {

View File

@ -30,6 +30,7 @@ import org.springframework.security.config.test.SpringTestRule;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
@ -41,14 +42,16 @@ public class Sec2515Tests {
public final SpringTestRule spring = new SpringTestRule();
// SEC-2515
@Test(expected = FatalBeanException.class)
@Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanThenThrowFatalBeanException() {
this.spring.register(StackOverflowSecurityConfig.class).autowire();
assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(StackOverflowSecurityConfig.class).autowire());
}
@Test(expected = FatalBeanException.class)
@Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanCustomNameThenThrowFatalBeanException() {
this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire();
assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire());
}
// SEC-2549

View File

@ -34,6 +34,7 @@ import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.util.AntPathMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
@ -96,9 +97,9 @@ public class MessageSecurityMetadataSourceRegistryTests {
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void pathMatcherNull() {
this.messages.simpDestPathMatcher(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.messages.simpDestPathMatcher(null));
}
@Test

View File

@ -31,6 +31,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.crypto.password.LdapShaPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link AuthenticationProviderBeanDefinitionParser}.
*
@ -140,18 +142,20 @@ public class AuthenticationProviderBeanDefinitionParserTests {
}
// SEC-1466
@Test(expected = BeanDefinitionParsingException.class)
@Test
public void exernalProviderDoesNotSupportChildElements() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
// @formatter:off
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>"
+ " <authentication-provider ref='aProvider'> "
+ " <password-encoder ref='customPasswordEncoder'/>"
+ " </authentication-provider>"
+ " </authentication-manager>"
+ " <b:bean id='aProvider' class='org.springframework.security.authentication.TestingAuthenticationProvider'/>"
+ " <b:bean id='customPasswordEncoder' "
+ " class='org.springframework.security.authentication.encoding.Md5PasswordEncoder'/>");
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>"
+ " <authentication-provider ref='aProvider'> "
+ " <password-encoder ref='customPasswordEncoder'/>"
+ " </authentication-provider>"
+ " </authentication-manager>"
+ " <b:bean id='aProvider' class='org.springframework.security.authentication.TestingAuthenticationProvider'/>"
+ " <b:bean id='customPasswordEncoder' "
+ " class='org.springframework.security.authentication.encoding.Md5PasswordEncoder'/>")
// @formatter:on
);
}
private AuthenticationProvider getProvider() {

View File

@ -26,6 +26,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -122,26 +123,28 @@ public class UserServiceBeanDefinitionParserTests {
assertThat(bob.isEnabled()).isFalse();
}
@Test(expected = FatalBeanException.class)
@Test
public void userWithBothPropertiesAndEmbeddedUsersThrowsException() {
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
// @formatter:off
setContext("<user-service id='service' properties='doesntmatter.props'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>");
setContext("<user-service id='service' properties='doesntmatter.props'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>")
// @formatter:on
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
userService.loadUserByUsername("Joe");
);
}
@Test(expected = FatalBeanException.class)
@Test
public void multipleTopLevelUseWithoutIdThrowsException() {
setContext("<user-service properties='classpath:org/springframework/security/config/users.properties'/>"
+ "<user-service properties='classpath:org/springframework/security/config/users.properties'/>");
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> setContext(
"<user-service properties='classpath:org/springframework/security/config/users.properties'/>"
+ "<user-service properties='classpath:org/springframework/security/config/users.properties'/>"));
}
@Test(expected = FatalBeanException.class)
@Test
public void userServiceWithMissingPropertiesFileThrowsException() {
setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>");
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
() -> setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>"));
}
private void setContext(String context) {

View File

@ -50,6 +50,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ -110,16 +111,16 @@ public class GrantedAuthorityDefaultsJcTests {
this.messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
@Test
public void messageDenied() {
setup("DENIED");
this.messageService.getMessage();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getMessage);
}
@Test(expected = AccessDeniedException.class)
@Test
public void jsrMessageDenied() {
setup("DENIED");
this.messageService.getJsrMessage();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getJsrMessage);
}
// SEC-2926

View File

@ -43,6 +43,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ -103,16 +104,16 @@ public class GrantedAuthorityDefaultsXmlTests {
this.messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
@Test
public void messageDenied() {
setup("DENIED");
this.messageService.getMessage();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getMessage);
}
@Test(expected = AccessDeniedException.class)
@Test
public void jsrMessageDenied() {
setup("DENIED");
this.messageService.getJsrMessage();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getJsrMessage);
}
// SEC-2926

View File

@ -36,6 +36,7 @@ import org.springframework.security.web.access.expression.ExpressionBasedFilterI
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link FilterInvocationSecurityMetadataSourceParser}.
@ -119,11 +120,12 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
// @formatter:on
}
@Test(expected = BeanDefinitionParsingException.class)
@Test
public void parsingInterceptUrlServletPathFails() {
setContext("<filter-security-metadata-source id='fids' use-expressions='false'>"
+ " <intercept-url pattern='/secure' access='ROLE_USER' servlet-path='/spring' />"
+ "</filter-security-metadata-source>");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> setContext("<filter-security-metadata-source id='fids' use-expressions='false'>"
+ " <intercept-url pattern='/secure' access='ROLE_USER' servlet-path='/spring' />"
+ "</filter-security-metadata-source>"));
}
private FilterInvocation createFilterInvocation(String path, String method) {

View File

@ -96,10 +96,11 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
this.target = null;
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
loadContext();
this.target.someUserMethod1();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someUserMethod1);
}
@Test
@ -114,13 +115,13 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThat(((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder()).isEqualTo(1001);
}
@Test(expected = AccessDeniedException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
loadContext();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMEOTHERROLE");
token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
}
@Test
@ -138,7 +139,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThat(service.getPostProcessorWasHere()).isEqualTo("Hello from the post processor!");
}
@Test(expected = AccessDeniedException.class)
@Test
public void worksWithAspectJAutoproxy() {
// @formatter:off
setContext("<global-method-security>"
@ -155,7 +156,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
service.loadUserByUsername("notused");
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.loadUserByUsername("notused"));
}
@Test
@ -201,13 +202,14 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
this.target.someOther(0);
}
@Test(expected = BeanDefinitionParsingException.class)
@Test
public void duplicateElementCausesError() {
setContext("<global-method-security />" + "<global-method-security />");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> setContext("<global-method-security />" + "<global-method-security />"));
}
// SEC-936
@Test(expected = AccessDeniedException.class)
@Test
public void worksWithoutTargetOrClass() {
// @formatter:off
setContext("<global-method-security secured-annotations='enabled'/>"
@ -221,7 +223,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target = (BusinessService) this.appContext.getBean("businessService");
this.target.someUserMethod1();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someUserMethod1);
}
// Expression configuration tests
@ -242,7 +244,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
.isSameAs(FieldUtils.getFieldValue(aip, "postAdvice.expressionHandler"));
}
@Test(expected = AccessDeniedException.class)
@Test
public void accessIsDeniedForHasRoleExpression() {
// @formatter:off
setContext("<global-method-security pre-post-annotations='enabled'/>"
@ -251,7 +253,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// @formatter:on
SecurityContextHolder.getContext().setAuthentication(this.bob);
this.target = (BusinessService) this.appContext.getBean("target");
this.target.someAdminMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
}
@Test
@ -322,7 +324,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
}
// SEC-1450
@Test(expected = AuthenticationException.class)
@Test
@SuppressWarnings("unchecked")
public void genericsAreMatchedByProtectPointcut() {
// @formatter:off
@ -334,7 +336,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ ConfigTestUtils.AUTH_PROVIDER_XML);
// @formatter:on
Foo foo = (Foo) this.appContext.getBean("target");
foo.foo(new SecurityConfig("A"));
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
}
// SEC-1448

View File

@ -40,6 +40,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -82,9 +83,10 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
this.target.unprotected();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.doSomething();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::doSomething);
}
@Test
@ -95,17 +97,17 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
this.target.doSomething();
}
@Test(expected = AccessDeniedException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.doSomething();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::doSomething);
}
@Test(expected = AuthenticationException.class)
@Test
public void transactionalMethodsShouldBeSecured() {
this.transactionalTarget.doSomething();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(this.transactionalTarget::doSomething);
}
@Override

View File

@ -29,6 +29,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
*/
@ -57,9 +59,10 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
SecurityContextHolder.clearContext();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.someUserMethod1();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someUserMethod1());
}
@Test
@ -78,12 +81,12 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
this.target.someUserMethod1();
}
@Test(expected = AccessDeniedException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
}
@Test

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*
@ -43,11 +45,11 @@ public class PreAuthorizeTests {
SecurityContextHolder.clearContext();
}
@Test(expected = AccessDeniedException.class)
@Test
public void preAuthorizeAdminRoleDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
this.service.preAuthorizeAdminRole();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeAdminRole);
}
@Test
@ -64,11 +66,12 @@ public class PreAuthorizeTests {
this.service.contactPermission(new Contact("user"));
}
@Test(expected = AccessDeniedException.class)
@Test
public void preAuthorizeContactPermissionDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
this.service.contactPermission(new Contact("admin"));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.service.contactPermission(new Contact("admin")));
}
}

View File

@ -26,6 +26,8 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*
@ -34,14 +36,14 @@ public class Sec2196Tests {
private ConfigurableApplicationContext context;
@Test(expected = AccessDeniedException.class)
@Test
public void genericMethodsProtected() {
loadContext("<global-method-security secured-annotations=\"enabled\" pre-post-annotations=\"enabled\"/>"
+ "<b:bean class='" + Service.class.getName() + "'/>");
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("test", "pass", "ROLE_USER"));
Service service = this.context.getBean(Service.class);
service.save(new User());
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.save(new User()));
}
@Test

View File

@ -65,9 +65,10 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
SecurityContextHolder.clearContext();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.someUserMethod1();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someUserMethod1);
}
@Test
@ -78,28 +79,29 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
this.target.someUserMethod1();
}
@Test(expected = AccessDeniedException.class)
@Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
}
// SEC-1387
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void targetIsSerializableBeforeUse() throws Exception {
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(chompedTarget::someAdminMethod);
}
@Test(expected = AccessDeniedException.class)
@Test
public void targetIsSerializableAfterUse() throws Exception {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someAdminMethod);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(chompedTarget::someAdminMethod);
}
private Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*
@ -43,11 +45,11 @@ public class SecuredTests {
SecurityContextHolder.clearContext();
}
@Test(expected = AccessDeniedException.class)
@Test
public void securedAdminRoleDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
this.service.securedAdminRole();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::securedAdminRole);
}
@Test

View File

@ -31,6 +31,7 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
@ -44,9 +45,9 @@ public class Gh4020GlobalMethodSecurityConfigurationTests {
DenyAllService denyAll;
// gh-4020
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void denyAll() {
this.denyAll.denyAll();
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(this.denyAll::denyAll);
}
@Configuration

View File

@ -23,6 +23,8 @@ import org.springframework.security.config.annotation.web.reactive.ServerHttpSec
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Rob Winch
* @since 5.0
@ -105,31 +107,34 @@ public class AuthorizeExchangeSpecTests {
// @formatter:on
}
@Test(expected = IllegalStateException.class)
@Test
public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete");
this.http.authorizeExchange().pathMatchers("/throws-exception");
assertThatIllegalStateException()
.isThrownBy(() -> this.http.authorizeExchange().pathMatchers("/throws-exception"));
}
@Test(expected = IllegalStateException.class)
@Test
public void anyExchangeWhenFollowedByMatcherThenThrowsException() {
assertThatIllegalStateException().isThrownBy(() ->
// @formatter:off
this.http.authorizeExchange()
.anyExchange().denyAll()
.pathMatchers("/never-reached");
this.http.authorizeExchange()
.anyExchange().denyAll()
.pathMatchers("/never-reached")
// @formatter:on
);
}
@Test(expected = IllegalStateException.class)
@Test
public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete");
this.http.build();
assertThatIllegalStateException().isThrownBy(this.http::build);
}
@Test(expected = IllegalStateException.class)
@Test
public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() {
this.http.authorizeExchange((exchanges) -> exchanges.pathMatchers("/incomplete"));
this.http.build();
assertThatIllegalStateException().isThrownBy(this.http::build);
}
private WebTestClient buildClient() {

View File

@ -84,7 +84,7 @@ public class MethodSecurityInterceptorWithAopConfigTests {
}
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void securityInterceptorIsAppliedWhenUsedWithAopConfig() {
// @formatter:off
setContext("<aop:config>"
@ -99,10 +99,11 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// Check both against interface and class
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeUpperCase("test"));
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void securityInterceptorIsAppliedWhenUsedWithBeanNameAutoProxyCreator() {
// @formatter:off
setContext("<b:bean id='autoProxyCreator' class='org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator'>"
@ -126,7 +127,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeUpperCase("test"));
}
private void setContext(String context) {

View File

@ -22,6 +22,8 @@ import org.springframework.security.access.event.AuthenticationCredentialsNotFou
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AuthenticationCredentialsNotFoundEvent}.
*
@ -29,22 +31,24 @@ import org.springframework.security.util.SimpleMethodInvocation;
*/
public class AuthenticationCredentialsNotFoundEventTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls() {
new AuthenticationCredentialsNotFoundEvent(null, SecurityConfig.createList("TEST"),
new AuthenticationCredentialsNotFoundException("test"));
assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(null,
SecurityConfig.createList("TEST"), new AuthenticationCredentialsNotFoundException("test")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls2() {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
new AuthenticationCredentialsNotFoundException("test"));
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
new AuthenticationCredentialsNotFoundException("test")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls3() {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"),
null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
SecurityConfig.createList("TEST"), null));
}
}

View File

@ -25,6 +25,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AuthorizationFailureEvent}.
@ -39,24 +40,29 @@ public class AuthorizationFailureEventTests {
private AccessDeniedException exception = new AuthorizationServiceException("error", new Throwable());
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullSecureObject() {
new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception);
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullAttributesList() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, this.foo, this.exception);
assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, this.foo, this.exception));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullAuthentication() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null, this.exception);
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null,
this.exception));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullException() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, this.foo, null);
assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, this.foo, null));
}
@Test

View File

@ -22,6 +22,8 @@ import org.springframework.security.access.event.AuthorizedEvent;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AuthorizedEvent}.
*
@ -29,20 +31,22 @@ import org.springframework.security.util.SimpleMethodInvocation;
*/
public class AuthorizedEventTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls() {
new AuthorizedEvent(null, SecurityConfig.createList("TEST"),
new UsernamePasswordAuthenticationToken("foo", "bar"));
assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(null,
SecurityConfig.createList("TEST"), new UsernamePasswordAuthenticationToken("foo", "bar")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls2() {
new AuthorizedEvent(new SimpleMethodInvocation(), null, new UsernamePasswordAuthenticationToken("foo", "bar"));
assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNulls3() {
new AuthorizedEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null);
assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizedEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null));
}
}

View File

@ -19,6 +19,8 @@ package org.springframework.security.access;
import org.junit.Test;
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 {@link SecurityConfig}.
@ -33,19 +35,20 @@ public class SecurityConfigTests {
assertThat(config.hashCode()).isEqualTo("TEST".hashCode());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCannotConstructWithNullAttribute() {
new SecurityConfig(null); // SEC-727
assertThatIllegalArgumentException().isThrownBy(() -> new SecurityConfig(null)); // SEC-727
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCannotConstructWithEmptyAttribute() {
new SecurityConfig(""); // SEC-727
assertThatIllegalArgumentException().isThrownBy(() -> new SecurityConfig("")); // SEC-727
}
@Test(expected = NoSuchMethodException.class)
@Test
public void testNoArgConstructorDoesntExist() throws Exception {
SecurityConfig.class.getDeclaredConstructor((Class[]) null);
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> SecurityConfig.class.getDeclaredConstructor((Class[]) null));
}
@Test

View File

@ -27,6 +27,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -57,9 +58,9 @@ public class AbstractSecurityExpressionHandlerTests {
.isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setExpressionParserNull() {
this.handler.setExpressionParser(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setExpressionParser(null));
}
@Test

View File

@ -37,6 +37,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
@ -69,9 +70,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setTrustResolverNull() {
this.handler.setTrustResolver(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setTrustResolver(null));
}
@Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link ExpressionBasedPreInvocationAdvice}
@ -50,21 +51,23 @@ public class ExpressionBasedPreInvocationAdviceTests {
this.expressionBasedPreInvocationAdvice = new ExpressionBasedPreInvocationAdvice();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void findFilterTargetNameProvidedButNotMatch() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "filterTargetDoesNotMatch",
null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void findFilterTargetNameProvidedArrayUnsupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "param", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
}
@Test
@ -77,12 +80,13 @@ public class ExpressionBasedPreInvocationAdviceTests {
assertThat(result).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void findFilterTargetNameNotProvidedArrayUnsupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
}
@Test
@ -95,21 +99,23 @@ public class ExpressionBasedPreInvocationAdviceTests {
assertThat(result).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void findFilterTargetNameNotProvidedTypeNotSupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingString", new Class[] { String.class }, new Object[] { "param" });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void findFilterTargetNameNotProvidedMethodAcceptMoreThenOneArgument() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingTwoArgs", new Class[] { String.class, List.class },
new Object[] { "param", new ArrayList<>() });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
}
private class TestClass {

View File

@ -32,6 +32,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@SuppressWarnings("unchecked")
public class MethodExpressionVoterTests {
@ -86,28 +87,28 @@ public class MethodExpressionVoterTests {
assertThat(arg).containsExactly("joe", "sam");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void arraysCannotBePrefiltered() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray(),
createArrayArg("sam", "joe"));
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null)));
assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null))));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void incorrectFilterTargetNameIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
createCollectionArg("joe", "bob"));
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null)));
assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null))));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void nullNamedFilterTargetIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
new Object[] { null });
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null)));
assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null))));
}
@Test

View File

@ -26,6 +26,7 @@ import java.util.TreeMap;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link RoleHierarchyUtils}.
@ -52,42 +53,47 @@ public class RoleHierarchyUtilsTests {
assertThat(roleHierarchy).isEqualTo(expectedRoleHierarchy);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenMapNullThenThrowsIllegalArgumentException() {
RoleHierarchyUtils.roleHierarchyFromMap(null);
assertThatIllegalArgumentException().isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenMapEmptyThenThrowsIllegalArgumentException() {
RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap());
assertThatIllegalArgumentException().isThrownBy(
() -> RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenImpliedRolesNullThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("ROLE_A", null);
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void roleHierarchyFromMapWhenImpliedRolesEmptyThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList());
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap);
assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
}
}

View File

@ -23,6 +23,7 @@ import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -33,7 +34,7 @@ import static org.mockito.Mockito.mock;
*/
public class AbstractSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsIfInvocationPassedIncompatibleSecureObject() {
MockSecurityInterceptorWhichOnlySupportsStrings si = new MockSecurityInterceptorWhichOnlySupportsStrings();
si.setRunAsManager(mock(RunAsManager.class));
@ -41,10 +42,10 @@ public class AbstractSecurityInterceptorTests {
si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
si.beforeInvocation(new SimpleMethodInvocation());
assertThatIllegalArgumentException().isThrownBy(() -> si.beforeInvocation(new SimpleMethodInvocation()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void detectsViolationOfGetSecureObjectClassMethod() throws Exception {
MockSecurityInterceptorReturnsNull si = new MockSecurityInterceptorReturnsNull();
si.setRunAsManager(mock(RunAsManager.class));
@ -52,7 +53,7 @@ public class AbstractSecurityInterceptorTests {
si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
si.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(si::afterPropertiesSet);
}
private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor {

View File

@ -26,19 +26,21 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
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 {@link RunAsImplAuthenticationProvider}.
*/
public class RunAsImplAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
@Test
public void testAuthenticationFailDueToWrongKey() {
RunAsUserToken token = new RunAsUserToken("wrong_key", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("hello_world");
provider.authenticate(token);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -53,10 +55,10 @@ public class RunAsImplAuthenticationProviderTests {
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStartupFailsIfNoKey() throws Exception {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
}
@Test

View File

@ -48,6 +48,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
@ -124,63 +125,63 @@ public class MethodSecurityInterceptorTests {
assertThat(this.interceptor.getAfterInvocationManager()).isEqualTo(aim);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingAccessDecisionManagerIsDetected() throws Exception {
this.interceptor.setAccessDecisionManager(null);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingAuthenticationManagerIsDetected() throws Exception {
this.interceptor.setAuthenticationManager(null);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingMethodSecurityMetadataSourceIsRejected() throws Exception {
this.interceptor.setSecurityMetadataSource(null);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingRunAsManagerIsRejected() throws Exception {
this.interceptor.setRunAsManager(null);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
given(this.mds.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class);
given(ram.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setRunAsManager(ram);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
given(aim.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setAfterInvocationManager(aim);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
given(this.adm.supports(any(ConfigAttribute.class))).willReturn(false);
this.interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
}
@Test
@ -219,13 +220,14 @@ public class MethodSecurityInterceptorTests {
assertThat(!this.token.isAuthenticated()).isTrue();
}
@Test(expected = AuthenticationException.class)
@Test
public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() {
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole();
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
this.advisedTarget.makeLowerCase("HELLO");
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> this.advisedTarget.makeLowerCase("HELLO"));
}
@Test
@ -256,9 +258,9 @@ public class MethodSecurityInterceptorTests {
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullSecuredObjects() throws Throwable {
this.interceptor.invoke(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.invoke(null));
}
@Test
@ -299,10 +301,11 @@ public class MethodSecurityInterceptorTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
@Test
public void emptySecurityContextIsRejected() {
mdsReturnsUserRole();
this.advisedTarget.makeUpperCase("hello");
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
}
@Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
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.Mockito.mock;
@ -89,19 +90,21 @@ public class AffirmativeBasedTests {
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test(expected = AccessDeniedException.class)
@Test
public void oneDenyVoteTwoAbstainVotesDeniesAccess() {
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.abstain));
this.mgr.decide(this.user, new Object(), this.attrs);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
}
@Test(expected = AccessDeniedException.class)
@Test
public void onlyAbstainVotesDeniesAccessWithDefault() {
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
this.mgr.decide(this.user, new Object(), this.attrs);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
}
@Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.TestingAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests {@link ConsensusBased}.
@ -37,14 +37,14 @@ import static org.assertj.core.api.Assertions.fail;
*/
public class ConsensusBasedTests {
@Test(expected = AccessDeniedException.class)
@Test
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccessWithoutDefault() {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfEqualGrantedDeniedDecisions(false);
assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
mgr.decide(auth, new Object(), config);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
}
@Test
@ -63,20 +63,21 @@ public class ConsensusBasedTests {
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2"));
}
@Test(expected = AccessDeniedException.class)
@Test
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE"));
fail("Should have thrown AccessDeniedException");
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE")));
}
@Test(expected = AccessDeniedException.class)
@Test
public void testThreeAbstainVotesDeniesAccessWithDefault() {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")));
}
@Test

View File

@ -27,6 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@ -46,12 +47,13 @@ public class AbstractAuthenticationTokenTests {
this.authorities = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
assertThat(gotAuthorities).isNotSameAs(this.authorities);
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER")));
}
@Test

View File

@ -36,6 +36,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@ -111,12 +113,13 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test(expected = RuntimeException.class)
@Test
public void missingEventClassExceptionCausesException() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), "NoSuchClass");
this.publisher.setAdditionalExceptionMappings(p);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(p));
}
@Test
@ -132,27 +135,27 @@ public class DefaultAuthenticationEventPublisherTests {
verifyZeroInteractions(appPublisher);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void emptyMapCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingExceptionClassCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(null, AuthenticationFailureLockedEvent.class);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void missingEventClassAsMapValueCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(LockedException.class, null);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test
@ -168,10 +171,11 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void defaultAuthenticationFailureEventClassSetNullThen() {
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.publisher.setDefaultAuthenticationFailureEvent(null));
}
@Test
@ -185,11 +189,11 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
@Test(expected = RuntimeException.class)
@Test
public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() {
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.publisher
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class));
}
private static final class AuthenticationFailureEventWithoutAppropriateConstructor

View File

@ -29,6 +29,7 @@ import org.springframework.security.core.AuthenticationException;
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;
@ -45,7 +46,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class ProviderManagerTests {
@Test(expected = ProviderNotFoundException.class)
@Test
public void authenticationFailsWithUnsupportedToken() {
Authentication token = new AbstractAuthenticationToken(null) {
@Override
@ -60,7 +61,7 @@ public class ProviderManagerTests {
};
ProviderManager mgr = makeProviderManager();
mgr.setMessageSource(mock(MessageSource.class));
mgr.authenticate(token);
assertThatExceptionOfType(ProviderNotFoundException.class).isThrownBy(() -> mgr.authenticate(token));
}
@Test
@ -98,19 +99,20 @@ public class ProviderManagerTests {
verify(publisher).publishAuthenticationSuccess(result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStartupFailsIfProvidersNotSetAsList() {
new ProviderManager((List<AuthenticationProvider>) null);
assertThatIllegalArgumentException().isThrownBy(() -> new ProviderManager((List<AuthenticationProvider>) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStartupFailsIfProvidersNotSetAsVarargs() {
new ProviderManager((AuthenticationProvider) null);
assertThatIllegalArgumentException().isThrownBy(() -> new ProviderManager((AuthenticationProvider) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStartupFailsIfProvidersContainNullElement() {
new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null));
assertThatIllegalArgumentException()
.isThrownBy(() -> new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null)));
}
// gh-8689

View File

@ -27,6 +27,7 @@ import reactor.test.StepVerifier;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
@ -50,14 +51,14 @@ public class ReactiveAuthenticationManagerAdapterTests {
this.manager = new ReactiveAuthenticationManagerAdapter(this.delegate);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullAuthenticationManager() {
new ReactiveAuthenticationManagerAdapter(null);
assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveAuthenticationManagerAdapter(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setSchedulerNull() {
this.manager.setScheduler(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setScheduler(null));
}
@Test

View File

@ -33,6 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
@ -62,10 +63,10 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
this.password = "pass";
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullUserDetailsService() {
ReactiveUserDetailsService userDetailsService = null;
new UserDetailsRepositoryReactiveAuthenticationManager(userDetailsService);
assertThatIllegalArgumentException()
.isThrownBy(() -> new UserDetailsRepositoryReactiveAuthenticationManager(null));
}
@Test

View File

@ -165,7 +165,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
verifyZeroInteractions(this.postAuthenticationChecks);
}
@Test(expected = AccountExpiredException.class)
@Test
public void authenticateWhenAccountExpiredThenException() {
this.manager.setPasswordEncoder(this.encoder);
// @formatter:off
@ -178,10 +178,11 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
expiredUser.getPassword());
this.manager.authenticate(token).block();
assertThatExceptionOfType(AccountExpiredException.class)
.isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test(expected = LockedException.class)
@Test
public void authenticateWhenAccountLockedThenException() {
this.manager.setPasswordEncoder(this.encoder);
// @formatter:off
@ -194,10 +195,10 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
lockedUser.getPassword());
this.manager.authenticate(token).block();
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test(expected = DisabledException.class)
@Test
public void authenticateWhenAccountDisabledThenException() {
this.manager.setPasswordEncoder(this.encoder);
// @formatter:off
@ -210,7 +211,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
disabledUser.getPassword());
this.manager.authenticate(token).block();
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
}

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
@ -63,10 +64,11 @@ public class UsernamePasswordAuthenticationTokenTests {
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO");
}
@Test(expected = NoSuchMethodException.class)
@Test
public void testNoArgConstructorDoesntExist() throws Exception {
Class<?> clazz = UsernamePasswordAuthenticationToken.class;
clazz.getDeclaredConstructor((Class[]) null);
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null));
}
}

View File

@ -101,19 +101,21 @@ public class AnonymousAuthenticationTokenTests {
assertThat(!token.isAuthenticated()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenNullAuthoritiesThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "principal", null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "principal", null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenEmptyAuthoritiesThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList());
assertThatIllegalArgumentException().isThrownBy(
() -> new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenPrincipalIsEmptyStringThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "", ROLES_12);
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "", ROLES_12));
}
}

View File

@ -45,6 +45,7 @@ import org.springframework.test.util.ReflectionTestUtils;
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.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
@ -82,16 +83,16 @@ public class DefaultJaasAuthenticationProviderTests {
ReflectionTestUtils.setField(this.provider, "log", this.log);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void afterPropertiesSetNullConfiguration() throws Exception {
this.provider.setConfiguration(null);
this.provider.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(this.provider::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void afterPropertiesSetNullAuthorityGranters() throws Exception {
this.provider.setAuthorityGranters(null);
this.provider.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(this.provider::afterPropertiesSet);
}
@Test

View File

@ -29,6 +29,7 @@ import org.junit.Test;
import org.springframework.security.authentication.jaas.TestLoginModule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link InMemoryConfiguration}.
@ -55,9 +56,10 @@ public class InMemoryConfigurationTests {
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullMapped() {
new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null));
}
@Test
@ -72,9 +74,9 @@ public class InMemoryConfigurationTests {
.getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullMapNullDefault() {
new InMemoryConfiguration(null, null);
assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryConfiguration(null, null));
}
@Test

View File

@ -23,6 +23,7 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
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.BDDMockito.given;
@ -35,13 +36,14 @@ import static org.mockito.Mockito.mock;
*/
public class RemoteAuthenticationManagerImplTests {
@Test(expected = RemoteAuthenticationException.class)
@Test
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");
assertThatExceptionOfType(RemoteAuthenticationException.class)
.isThrownBy(() -> manager.attemptAuthentication("rod", "password"));
}
@Test

View File

@ -29,6 +29,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
/**
@ -120,42 +121,40 @@ public class AuthorityReactiveAuthorizationManagerTests {
assertThat(granted).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasRoleWhenNullThenException() {
String role = null;
AuthorityReactiveAuthorizationManager.hasRole(role);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasRole((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAuthorityWhenNullThenException() {
String authority = null;
AuthorityReactiveAuthorizationManager.hasAuthority(authority);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAuthority((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAnyRoleWhenNullThenException() {
String role = null;
AuthorityReactiveAuthorizationManager.hasAnyRole(role);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAnyAuthorityWhenNullThenException() {
String authority = null;
AuthorityReactiveAuthorizationManager.hasAnyAuthority(authority);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAnyRoleWhenOneIsNullThenException() {
String role1 = "ROLE_ADMIN";
String role2 = null;
AuthorityReactiveAuthorizationManager.hasAnyRole(role1, role2);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole("ROLE_ADMIN", (String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAnyAuthorityWhenOneIsNullThenException() {
String authority1 = "ADMIN";
String authority2 = null;
AuthorityReactiveAuthorizationManager.hasAnyAuthority(authority1, authority2);
assertThatIllegalArgumentException()
.isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority("ADMIN", (String) null));
}
}

View File

@ -27,6 +27,7 @@ import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ -57,9 +58,9 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
}
@Override
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegate() {
new DelegatingSecurityContextExecutorService(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextExecutorService(null));
}
@Test

View File

@ -22,6 +22,7 @@ import java.util.concurrent.ScheduledExecutorService;
import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.verify;
/**
@ -42,9 +43,9 @@ public abstract class AbstractDelegatingSecurityContextExecutorTests
private DelegatingSecurityContextExecutor executor;
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegate() {
new DelegatingSecurityContextExecutor(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextExecutor(null));
}
@Test

View File

@ -34,6 +34,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ -79,24 +80,26 @@ public class DelegatingSecurityContextCallableTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegate() {
new DelegatingSecurityContextCallable<>(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextCallable<>(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextCallable<>(null, this.securityContext);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextCallable<>(null, this.securityContext));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegateAndSecurityContext() {
new DelegatingSecurityContextCallable<>(null, null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextCallable<>(null, null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullSecurityContext() {
new DelegatingSecurityContextCallable<>(this.delegate, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextCallable<>(this.delegate, null));
}
@Test
@ -109,8 +112,8 @@ public class DelegatingSecurityContextCallableTests {
public void callDefaultSecurityContext() throws Exception {
SecurityContextHolder.setContext(this.securityContext);
this.callable = new DelegatingSecurityContextCallable<>(this.delegate);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the
// SecurityContextHolder
// ensure callable is what sets up the SecurityContextHolder
SecurityContextHolder.clearContext();
assertWrapped(this.callable);
}
@ -123,22 +126,23 @@ public class DelegatingSecurityContextCallableTests {
assertWrapped(this.callable.call());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createNullDelegate() {
DelegatingSecurityContextCallable.create(null, this.securityContext);
assertThatIllegalArgumentException()
.isThrownBy(() -> DelegatingSecurityContextCallable.create(null, this.securityContext));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createNullDelegateAndSecurityContext() {
DelegatingSecurityContextRunnable.create(null, null);
assertThatIllegalArgumentException().isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, null));
}
@Test
public void createNullSecurityContext() throws Exception {
SecurityContextHolder.setContext(this.securityContext);
this.callable = DelegatingSecurityContextCallable.create(this.delegate, null);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the
// SecurityContextHolder
// ensure callable is what sets up the SecurityContextHolder
SecurityContextHolder.clearContext();
assertWrapped(this.callable);
}

View File

@ -34,6 +34,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.verify;
@ -74,24 +75,26 @@ public class DelegatingSecurityContextRunnableTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegate() {
new DelegatingSecurityContextRunnable(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextRunnable(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextRunnable(null, this.securityContext);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextRunnable(null, this.securityContext));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullDelegateAndSecurityContext() {
new DelegatingSecurityContextRunnable(null, null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextRunnable(null, null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullSecurityContext() {
new DelegatingSecurityContextRunnable(this.delegate, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextRunnable(this.delegate, null));
}
@Test
@ -119,14 +122,15 @@ public class DelegatingSecurityContextRunnableTests {
assertWrapped(this.runnable);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createNullDelegate() {
DelegatingSecurityContextRunnable.create(null, this.securityContext);
assertThatIllegalArgumentException()
.isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, this.securityContext));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createNullDelegateAndSecurityContext() {
DelegatingSecurityContextRunnable.create(null, null);
assertThatIllegalArgumentException().isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, null));
}
@Test

View File

@ -25,6 +25,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
@ -75,9 +76,9 @@ public class DelegatingApplicationListenerTests {
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addNull() {
this.listener.addListener(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.listener.addListener(null));
}
}

View File

@ -28,6 +28,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Ruud Senden
@ -35,44 +36,41 @@ import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("unchecked")
public class MapBasedAttributes2GrantedAuthoritiesMapperTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testAfterPropertiesSetNoMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAfterPropertiesSetEmptyMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(new HashMap());
mapper.afterPropertiesSet();
assertThatIllegalArgumentException()
.isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(new HashMap()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put(new Object(), "ga1");
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1", new Object());
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap();
m.put("role1", new Object[] { new String[] { "ga1", "ga2" }, new Object() });
mapper.setAttributes2grantedAuthoritiesMap(m);
mapper.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
}
@Test

View File

@ -25,18 +25,19 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Luke Taylor
*/
public class SimpleAuthoritiesMapperTests {
@Test(expected = IllegalArgumentException.class)
public void rejectsInvalidCaseConversionFlags() throws Exception {
@Test
public void rejectsInvalidCaseConversionFlags() {
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
mapper.setConvertToLowerCase(true);
mapper.setConvertToUpperCase(true);
mapper.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
}
@Test

View File

@ -21,6 +21,7 @@ import java.util.Date;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link DefaultToken}.
@ -40,11 +41,11 @@ public class DefaultTokenTests {
assertThat(t2).isEqualTo(t1);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testRejectsNullExtendedInformation() {
String key = "key";
long created = new Date().getTime();
new DefaultToken(key, created, null);
assertThatIllegalArgumentException().isThrownBy(() -> new DefaultToken(key, created, null));
}
@Test

View File

@ -22,12 +22,12 @@ import java.util.Date;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link KeyBasedPersistenceTokenService}.
*
* @author Ben Alex
*
*/
public class KeyBasedPersistenceTokenServiceTests {
@ -80,20 +80,22 @@ public class KeyBasedPersistenceTokenServiceTests {
assertThat(result).isEqualTo(token);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testOperationWithMissingKey() {
KeyBasedPersistenceTokenService service = getService();
Token token = new DefaultToken("", new Date().getTime(), "");
service.verifyToken(token.getKey());
assertThatIllegalArgumentException().isThrownBy(() -> {
Token token = new DefaultToken("", new Date().getTime(), "");
service.verifyToken(token.getKey());
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testOperationWithTamperedKey() {
KeyBasedPersistenceTokenService service = getService();
Token goodToken = service.allocateToken("");
String fake = goodToken.getKey().toUpperCase();
Token token = new DefaultToken(fake, new Date().getTime(), "");
service.verifyToken(token.getKey());
assertThatIllegalArgumentException().isThrownBy(() -> service.verifyToken(token.getKey()));
}
}

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import reactor.core.publisher.Mono;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class MapReactiveUserDetailsServiceTests {
@ -35,16 +36,16 @@ public class MapReactiveUserDetailsServiceTests {
// @formatter:on
private MapReactiveUserDetailsService users = new MapReactiveUserDetailsService(Arrays.asList(USER_DETAILS));
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorNullUsers() {
Collection<UserDetails> users = null;
new MapReactiveUserDetailsService(users);
assertThatIllegalArgumentException()
.isThrownBy(() -> new MapReactiveUserDetailsService((Collection<UserDetails>) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorEmptyUsers() {
Collection<UserDetails> users = Collections.emptyList();
new MapReactiveUserDetailsService(users);
assertThatIllegalArgumentException()
.isThrownBy(() -> new MapReactiveUserDetailsService(Collections.emptyList()));
}
@Test

View File

@ -27,7 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link EhCacheBasedUserCache}.
@ -77,11 +77,10 @@ public class EhCacheBasedUserCacheTests {
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void startupDetectsMissingCache() throws Exception {
EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
cache.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet);
Ehcache myCache = getCache();
cache.setCache(myCache);
assertThat(cache.getCache()).isEqualTo(myCache);

View File

@ -27,6 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests
@ -75,9 +76,9 @@ public class SpringCacheBasedUserCacheTests {
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void startupDetectsMissingCache() throws Exception {
new SpringCacheBasedUserCache(null);
assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedUserCache(null));
}
}

View File

@ -156,10 +156,10 @@ public class JdbcDaoImplTests {
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setMessageSourceWhenNullThenThrowsException() {
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setMessageSource(null);
assertThatIllegalArgumentException().isThrownBy(() -> dao.setMessageSource(null));
}
@Test

View File

@ -29,6 +29,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jitendra Singh
@ -64,12 +65,13 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}
@Test(expected = JsonMappingException.class)
@Test
public void deserializeAnonymousAuthenticationTokenWithoutAuthoritiesTest() throws IOException {
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null,"
+ "\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + ","
+ "\"authorities\": [\"java.util.ArrayList\", []]}";
this.mapper.readValue(jsonString, AnonymousAuthenticationToken.class);
assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(jsonString, AnonymousAuthenticationToken.class));
}
@Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Jitendra Singh
@ -48,6 +49,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
// @formatter:off
private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\","
@ -58,14 +60,17 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}";
// @formatter:on
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNullPrincipal() {
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList());
assertThatIllegalArgumentException().isThrownBy(
() -> new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNullKey() {
new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList());
assertThatIllegalArgumentException().isThrownBy(
() -> new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList()));
}
@Test

View File

@ -27,6 +27,7 @@ import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Jitendra Singh
@ -56,10 +57,11 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
}
@Test(expected = JsonMappingException.class)
@Test
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
this.mapper.readValue(json, SimpleGrantedAuthority.class);
assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(json, SimpleGrantedAuthority.class));
}
}

View File

@ -32,6 +32,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Jitendra Singh
@ -67,11 +68,12 @@ public class UserDeserializerTests extends AbstractMixinTests {
JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[]");
this.mapper.readValue(userJsonWithoutPasswordString, User.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.mapper.readValue(userJsonWithoutPasswordString, User.class));
}
@Test
@ -85,11 +87,11 @@ public class UserDeserializerTests extends AbstractMixinTests {
assertThat(user.isEnabled()).isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception {
String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[{\"authority\": \"ROLE_USER\"}]");
this.mapper.readValue(userJson, User.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.readValue(userJson, User.class));
}
@Test

View File

@ -189,9 +189,10 @@ public class JdbcUserDetailsManagerTests {
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
}
@Test(expected = AccessDeniedException.class)
@Test
public void changePasswordFailsForUnauthenticatedUser() {
this.manager.changePassword("password", "newPassword");
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.manager.changePassword("password", "newPassword"));
}
@Test

View File

@ -29,6 +29,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
@ -65,9 +66,9 @@ public class DelegatingSecurityContextTaskSchedulerTests {
this.delegatingSecurityContextTaskScheduler = null;
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSchedulerIsNotNull() {
this.delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(null);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextTaskScheduler(null));
}
@Test

View File

@ -25,6 +25,7 @@ import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.security.access.annotation.BusinessServiceImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Luke Taylor
@ -44,9 +45,10 @@ public class MethodInvocationUtilsTests {
assertThat(mi).isNotNull();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void exceptionIsRaisedIfArgInfoOmittedAndMethodNameIsNotUnique() {
MethodInvocationUtils.createFromClass(BusinessServiceImpl.class, "methodReturningAList");
assertThatIllegalArgumentException().isThrownBy(
() -> MethodInvocationUtils.createFromClass(BusinessServiceImpl.class, "methodReturningAList"));
}
@Test

View File

@ -22,6 +22,7 @@ import org.bouncycastle.crypto.params.Argon2Parameters;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Simeon Macke
@ -66,69 +67,70 @@ public class Argon2EncodingUtilsTests {
this.testDataEntry2.decoded.getParameters())).isEqualTo(this.testDataEntry2.encoded);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void encodeWhenNonexistingAlgorithmThenThrowException() {
Argon2EncodingUtils.encode(new byte[] { 0, 1, 2, 3 }, (new Argon2Parameters.Builder(3)).withVersion(19)
.withMemoryAsKB(333).withIterations(5).withParallelism(2).build());
assertThatIllegalArgumentException().isThrownBy(
() -> Argon2EncodingUtils.encode(new byte[] { 0, 1, 2, 3 }, (new Argon2Parameters.Builder(3))
.withVersion(19).withMemoryAsKB(333).withIterations(5).withParallelism(2).build()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenNotAnArgon2HashThenThrowException() {
Argon2EncodingUtils.decode("notahash");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode("notahash"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenNonexistingAlgorithmThenThrowException() {
Argon2EncodingUtils.decode(
"$argon2x$v=19$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2x$v=19$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenIllegalVersionParameterThenThrowException() {
Argon2EncodingUtils.decode(
"$argon2i$v=x$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=x$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenIllegalMemoryParameterThenThrowException() {
Argon2EncodingUtils
.decode("$argon2i$v=19$m=x,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=19$m=x,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenIllegalIterationsParameterThenThrowException() {
Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=x,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=x,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenIllegalParallelityParameterThenThrowException() {
Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenMissingVersionParameterThenThrowException() {
Argon2EncodingUtils
.decode("$argon2i$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenMissingMemoryParameterThenThrowException() {
Argon2EncodingUtils
.decode("$argon2i$v=19$t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenMissingIterationsParameterThenThrowException() {
Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeWhenMissingParallelityParameterThenThrowException() {
Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,t=3$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs");
assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,t=3$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
}
private void assertArgon2HashEquals(Argon2EncodingUtils.Argon2Hash expected,

View File

@ -28,6 +28,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Simeon Macke
@ -181,9 +182,9 @@ public class Argon2PasswordEncoderTests {
assertThat(this.encoder.upgradeEncoding("")).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void upgradeEncodingWhenEncodedPassIsBogusThenThrowException() {
this.encoder.upgradeEncoding("thisIsNoValidHash");
assertThatIllegalArgumentException().isThrownBy(() -> this.encoder.upgradeEncoding("thisIsNoValidHash"));
}
private void injectPredictableSaltGen() throws Exception {

View File

@ -21,6 +21,7 @@ import java.security.SecureRandom;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Dave Syer
@ -129,14 +130,14 @@ public class BCryptPasswordEncoderTests {
assertThat(encoder.matches("password", result)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void badLowCustomStrength() {
new BCryptPasswordEncoder(3);
assertThatIllegalArgumentException().isThrownBy(() -> new BCryptPasswordEncoder(3));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void badHighCustomStrength() {
new BCryptPasswordEncoder(32);
assertThatIllegalArgumentException().isThrownBy(() -> new BCryptPasswordEncoder(32));
}
@Test
@ -189,22 +190,22 @@ public class BCryptPasswordEncoderTests {
* @see <a href=
* "https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496">https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496</a>
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void upgradeFromNonBCrypt() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.upgradeEncoding("not-a-bcrypt-password");
assertThatIllegalArgumentException().isThrownBy(() -> encoder.upgradeEncoding("not-a-bcrypt-password"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void encodeNullRawPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.encode(null);
assertThatIllegalArgumentException().isThrownBy(() -> encoder.encode(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void matchNullRawPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.matches(null, "does-not-matter");
assertThatIllegalArgumentException().isThrownBy(() -> encoder.matches(null, "does-not-matter"));
}
}

View File

@ -21,6 +21,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* JUnit unit tests for BCrypt routines
@ -328,19 +329,21 @@ public class BCryptTests {
assertThat(BCrypt.roundsForLogRounds(31)).isEqualTo(0x80000000L);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void emptyByteArrayCannotBeEncoded() {
BCrypt.encode_base64(new byte[0], 0, new StringBuilder());
assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.encode_base64(new byte[0], 0, new StringBuilder()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void moreBytesThanInTheArrayCannotBeEncoded() {
BCrypt.encode_base64(new byte[1], 2, new StringBuilder());
assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.encode_base64(new byte[1], 2, new StringBuilder()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodingMustRequestMoreThanZeroBytes() {
BCrypt.decode_base64("", 0);
assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.decode_base64("", 0));
}
private static String encode_base64(byte d[], int len) throws IllegalArgumentException {
@ -394,14 +397,14 @@ public class BCryptTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void genSaltFailsWithTooFewRounds() {
BCrypt.gensalt(3);
assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.gensalt(3));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void genSaltFailsWithTooManyRounds() {
BCrypt.gensalt(32);
assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.gensalt(32));
}
@Test
@ -410,24 +413,26 @@ public class BCryptTests {
assertThat(BCrypt.gensalt(31)).startsWith("$2a$31$");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hashpwFailsWhenSaltIsNull() {
BCrypt.hashpw("password", null);
assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.hashpw("password", null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hashpwFailsWhenSaltSpecifiesTooFewRounds() {
BCrypt.hashpw("password", "$2a$03$......................");
assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$03$......................"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hashpwFailsWhenSaltSpecifiesTooManyRounds() {
BCrypt.hashpw("password", "$2a$32$......................");
assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$32$......................"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void saltLengthIsChecked() {
BCrypt.hashpw("", "");
assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.hashpw("", ""));
}
@Test
@ -436,9 +441,10 @@ public class BCryptTests {
.isEqualTo("$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hashpwFailsWhenSaltIsTooShort() {
BCrypt.hashpw("password", "$2a$10$123456789012345678901");
assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$10$123456789012345678901"));
}
@Test

View File

@ -19,6 +19,8 @@ package org.springframework.security.crypto.codec;
import org.junit.Test;
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
@ -37,14 +39,14 @@ public class Base64Tests {
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) '`' })).isFalse();
}
@Test(expected = NullPointerException.class)
@Test
public void isBase64RejectsNull() {
Base64.isBase64(null);
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> Base64.isBase64(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void isBase64RejectsInvalidLength() {
Base64.isBase64(new byte[] { (byte) 'A' });
assertThatIllegalArgumentException().isThrownBy(() -> Base64.isBase64(new byte[] { (byte) 'A' }));
}
}

View File

@ -27,6 +27,8 @@ import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class BouncyCastleAesBytesEncryptorTests {
private byte[] testData;
@ -69,14 +71,16 @@ public class BouncyCastleAesBytesEncryptorTests {
Assert.assertArrayEquals(this.testData, decrypted2);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void bcCbcWithWrongLengthIv() {
new BouncyCastleAesCbcBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8));
assertThatIllegalArgumentException().isThrownBy(
() -> new BouncyCastleAesCbcBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void bcGcmWithWrongLengthIv() {
new BouncyCastleAesGcmBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8));
assertThatIllegalArgumentException().isThrownBy(
() -> new BouncyCastleAesGcmBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)));
}
}

View File

@ -21,6 +21,7 @@ import java.util.Base64;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
@ -28,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class Base64StringKeyGeneratorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorIntWhenLessThan32ThenIllegalArgumentException() {
new Base64StringKeyGenerator(31);
assertThatIllegalArgumentException().isThrownBy(() -> new Base64StringKeyGenerator(31));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorEncoderWhenEncoderNullThenThrowsIllegalArgumentException() {
Base64.Encoder encoder = null;
new Base64StringKeyGenerator(null);
assertThatIllegalArgumentException().isThrownBy(() -> new Base64StringKeyGenerator(null));
}
@Test

View File

@ -72,19 +72,21 @@ public class DelegatingPasswordEncoderTests {
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenIdForEncodeNullThenIllegalArgumentException() {
new DelegatingPasswordEncoder(null, this.delegates);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingPasswordEncoder(null, this.delegates));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorWhenIdForEncodeDoesNotExistThenIllegalArgumentException() {
new DelegatingPasswordEncoder(this.bcryptId + "INVALID", this.delegates);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId + "INVALID", this.delegates));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setDefaultPasswordEncoderForMatchesWhenNullThenIllegalArgumentException() {
this.passwordEncoder.setDefaultPasswordEncoderForMatches(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.setDefaultPasswordEncoderForMatches(null));
}
@Test
@ -180,9 +182,9 @@ public class DelegatingPasswordEncoderTests {
verifyZeroInteractions(this.bcrypt, this.noop);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void matchesWhenRawPasswordNotNullAndEncodedPasswordNullThenThrowsIllegalArgumentException() {
this.passwordEncoder.matches(this.rawPassword, null);
assertThatIllegalArgumentException().isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, null));
}
@Test

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link LdapShaPasswordEncoder}.
@ -92,15 +93,16 @@ public class LdapShaPasswordEncoderTests {
assertThat(this.sha.encode("somepassword").startsWith("{SSHA}"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidPrefixIsRejected() {
this.sha.matches("somepassword", "{MD9}xxxxxxxxxx");
assertThatIllegalArgumentException().isThrownBy(() -> this.sha.matches("somepassword", "{MD9}xxxxxxxxxx"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void malformedPrefixIsRejected() {
// No right brace
this.sha.matches("somepassword", "{SSHA25ro4PKC8jhQZ26jVsozhX/xaP0suHgX");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.sha.matches("somepassword", "{SSHA25ro4PKC8jhQZ26jVsozhX/xaP0suHgX"));
}
}

View File

@ -19,6 +19,7 @@ package org.springframework.security.crypto.password;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* <p>
@ -112,9 +113,9 @@ public class MessageDigestPasswordEncoderTests {
assertThat(pe.matches(raw, "{THIS_IS_A_SALT}4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7"));
}
@Test(expected = IllegalStateException.class)
@Test
public void testInvalidStrength() {
new MessageDigestPasswordEncoder("SHA-666");
assertThatIllegalStateException().isThrownBy(() -> new MessageDigestPasswordEncoder("SHA-666"));
}
}

View File

@ -19,6 +19,7 @@ package org.springframework.security.crypto.scrypt;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Shazin Sadakath
@ -91,29 +92,32 @@ public class SCryptPasswordEncoderTests {
assertThat(encoder.matches("password", "012345678901234567890123456789")).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidCpuCostParameter() {
new SCryptPasswordEncoder(Integer.MIN_VALUE, 16, 2, 32, 16);
assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(Integer.MIN_VALUE, 16, 2, 32, 16));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidMemoryCostParameter() {
new SCryptPasswordEncoder(2, Integer.MAX_VALUE, 2, 32, 16);
assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(2, Integer.MAX_VALUE, 2, 32, 16));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidParallelizationParameter() {
new SCryptPasswordEncoder(2, 8, Integer.MAX_VALUE, 32, 16);
assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(2, 8, Integer.MAX_VALUE, 32, 16));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidSaltLengthParameter() {
new SCryptPasswordEncoder(2, 8, 1, 16, -1);
assertThatIllegalArgumentException().isThrownBy(() -> new SCryptPasswordEncoder(2, 8, 1, 16, -1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidKeyLengthParameter() {
new SCryptPasswordEncoder(2, 8, 1, -1, 16);
assertThatIllegalArgumentException().isThrownBy(() -> new SCryptPasswordEncoder(2, 8, 1, -1, 16));
}
@Test
@ -153,9 +157,10 @@ public class SCryptPasswordEncoderTests {
assertThat(strongEncoder.upgradeEncoding(weakPassword)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void upgradeEncodingWhenInvalidInputThenException() {
new SCryptPasswordEncoder().upgradeEncoding("not-a-scrypt-password");
assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder().upgradeEncoding("not-a-scrypt-password"));
}
}

View File

@ -25,6 +25,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class SecurityEvaluationContextExtensionTests {
@ -40,9 +41,9 @@ public class SecurityEvaluationContextExtensionTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getRootObjectSecurityContextHolderAuthenticationNull() {
getRoot().getAuthentication();
assertThatIllegalArgumentException().isThrownBy(() -> getRoot().getAuthentication());
}
@Test

View File

@ -34,7 +34,7 @@ import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ContextConfiguration(locations = { "/http-path-param-stripping-app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@ -43,33 +43,35 @@ public class HttpPathParameterStrippingTests {
@Autowired
private FilterChainProxy fcp;
@Test(expected = RequestRejectedException.class)
@Test
public void securedFilterChainCannotBeBypassedByAddingPathParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setPathInfo("/secured;x=y/admin.html");
request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain());
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
}
@Test(expected = RequestRejectedException.class)
@Test
public void adminFilePatternCannotBeBypassedByAddingPathParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secured/admin.html;x=user.html");
request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain());
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
}
@Test(expected = RequestRejectedException.class)
@Test
public void adminFilePatternCannotBeBypassedByAddingPathParametersWithPathInfo() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secured");
request.setPathInfo("/admin.html;x=user.html");
request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain());
assertThat(response.getStatus()).isEqualTo(403);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
}
public HttpSession createAuthenticatedSession(String... roles) {

View File

@ -31,6 +31,8 @@ import org.springframework.security.integration.multiannotation.SecuredService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
*/
@ -57,16 +59,16 @@ public class MultiAnnotationTests {
SecurityContextHolder.clearContext();
}
@Test(expected = AccessDeniedException.class)
@Test
public void preAuthorizeDeniedIsDenied() {
SecurityContextHolder.getContext().setAuthentication(this.joe_a);
this.service.preAuthorizeDenyAllMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeDenyAllMethod);
}
@Test(expected = AccessDeniedException.class)
@Test
public void preAuthorizeRoleAIsDeniedIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.service.preAuthorizeHasRoleAMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeHasRoleAMethod);
}
@Test
@ -81,10 +83,10 @@ public class MultiAnnotationTests {
this.service.securedAnonymousMethod();
}
@Test(expected = AccessDeniedException.class)
@Test
public void securedRoleAIsDeniedIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.service.securedRoleAMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::securedRoleAMethod);
}
@Test
@ -93,16 +95,16 @@ public class MultiAnnotationTests {
this.service.securedRoleAMethod();
}
@Test(expected = AccessDeniedException.class)
@Test
public void preAuthorizedOnlyServiceDeniesIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.preService.preAuthorizedMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.preService::preAuthorizedMethod);
}
@Test(expected = AccessDeniedException.class)
@Test
public void securedOnlyRoleAServiceDeniesIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.secService.securedMethod();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.secService::securedMethod);
}
}

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.session.SessionRegistry;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
* @since 2.0
@ -35,17 +37,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
public class SEC936ApplicationContextTests {
@Autowired
/**
* SessionRegistry is used as the test service interface (nothing to do with the test)
*/
@Autowired
private SessionRegistry sessionRegistry;
@Test(expected = AccessDeniedException.class)
@Test
public void securityInterceptorHandlesCallWithNoTargetObject() {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword"));
this.sessionRegistry.getAllPrincipals();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.sessionRegistry::getAllPrincipals);
}
}

View File

@ -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 {

View File

@ -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

View File

@ -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

Some files were not shown because too many files have changed in this diff Show More