Replace try/catch with AssertJ

Replace manual try/catch/fail blocks with AssertJ calls.
This commit is contained in:
Phillip Webb
2020-09-10 12:06:07 -07:00
committed by Josh Cummings
parent d9276ed8f3
commit 910b81928f
98 changed files with 717 additions and 2122 deletions

View File

@@ -26,7 +26,7 @@ import org.springframework.security.config.authentication.AuthenticationManagerF
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests which make sure invalid configurations are rejected by the namespace. In
@@ -59,17 +59,14 @@ public class InvalidConfigurationTests {
@Test
public void missingAuthenticationManagerGivesSensibleErrorMessage() {
try {
setContext("<http auto-config='true' />");
fail();
}
catch (BeanCreationException ex) {
Throwable cause = ultimateCause(ex);
assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue();
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
}
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> setContext("<http auto-config='true' />")).satisfies((ex) -> {
Throwable cause = ultimateCause(ex);
assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
});
}
private Throwable ultimateCause(Throwable ex) {

View File

@@ -32,8 +32,7 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -78,15 +77,11 @@ public class SecurityNamespaceHandlerTests {
@Test
public void pre32SchemaAreNotSupported() {
try {
new InMemoryXmlApplicationContext("<user-service id='us'>"
+ " <user name='bob' password='bobspassword' authorities='ROLE_A' />" + "</user-service>", "3.0.3",
null);
fail("Expected BeanDefinitionParsingException");
}
catch (BeanDefinitionParsingException expected) {
assertThat(expected.getMessage().contains("You cannot use a spring-security-2.0.xsd"));
}
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(
"<user-service id='us'><user name='bob' password='bobspassword' authorities='ROLE_A' /></user-service>",
"3.0.3", null))
.withMessageContaining("You cannot use a spring-security-2.0.xsd");
}
// SEC-1868

View File

@@ -54,6 +54,7 @@ import org.springframework.security.test.web.servlet.response.SecurityMockMvcRes
import org.springframework.test.web.servlet.MockMvc;
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;
@@ -91,11 +92,8 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();
try {
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (AuthenticationException success) {
}
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")));
verify(aep).publishAuthenticationFailure(any(), any());
}

View File

@@ -110,11 +110,8 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")));
assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
}

View File

@@ -45,8 +45,7 @@ import org.springframework.web.socket.config.annotation.AbstractWebSocketMessage
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
@@ -76,13 +75,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
public void securityMappings() {
loadConfig(WebSocketSecurityConfig.class);
clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE));
try {
clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
.withCauseInstanceOf(AccessDeniedException.class);
}
private void loadConfig(Class<?>... configs) {

View File

@@ -78,7 +78,7 @@ import org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHa
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
@@ -108,13 +108,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void simpleRegistryMappings() {
loadConfig(SockJsSecurityConfig.class);
clientInboundChannel().send(message("/permitAll"));
try {
clientInboundChannel().send(message("/denyAll"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
@@ -158,13 +154,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel();
try {
messageChannel.send(message);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
.withCauseInstanceOf(MissingCsrfTokenException.class);
}
@Test
@@ -173,13 +164,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel();
try {
messageChannel.send(message);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
.withCauseInstanceOf(MissingCsrfTokenException.class);
}
@Test
@@ -236,39 +222,27 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void msmsRegistryCustomPatternMatcher() {
loadConfig(MsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a.b"));
try {
clientInboundChannel().send(message("/app/a.b.c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void overrideMsmsRegistryCustomPatternMatcher() {
loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b"));
try {
clientInboundChannel().send(message("/app/a/b/c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void defaultPatternMatcher() {
loadConfig(DefaultPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b"));
try {
clientInboundChannel().send(message("/app/a/b/c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
@@ -276,13 +250,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(CustomExpressionConfig.class);
clientInboundChannel().send(message("/denyRob"));
this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER");
try {
clientInboundChannel().send(message("/denyRob"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test

View File

@@ -59,7 +59,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Ben Alex
@@ -174,13 +174,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER
this.target.someOther(0);
try {
// String version should required admin role
this.target.someOther("somestring");
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// String version should required admin role
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.target.someOther("somestring"));
}
@Test
@@ -199,12 +194,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// String method should not be protected
this.target.someOther("somestring");
// All others should require ROLE_USER
try {
this.target.someOther(0);
fail("Expected AuthenticationCredentialsNotFoundException");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someOther(0));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
this.target.someOther(0);
@@ -389,12 +380,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// External MDS should take precedence over PreAuthorize
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A"));
@@ -415,12 +401,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// @formatter:on
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A"));

View File

@@ -36,6 +36,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 Ben Alex
*/
@@ -93,11 +95,8 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Test(expected = AccessDeniedException.class)
public void targetIsSerializableAfterUse() throws Exception {
try {
this.target.someAdminMethod();
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someAdminMethod);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();

View File

@@ -26,7 +26,7 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for SEC-428 (and SEC-1204).
@@ -97,12 +97,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
// Check both against interface and class
try {
target.makeLowerCase("TEST");
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
}
@@ -128,12 +124,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
try {
target.makeLowerCase("TEST");
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
}