Skip to content

Commit

Permalink
refactor: AssertJ best practices
Browse files Browse the repository at this point in the history
Use this link to re-run the recipe: https://app.moderne.io/recipes/builder/bGVuS?organizationId=RGVmYXVsdA%3D%3D

Co-authored-by: Moderne <team@moderne.io>
  • Loading branch information
2 people authored and jzheaux committed Sep 12, 2023
1 parent 36a488a commit 9df9cb5
Show file tree
Hide file tree
Showing 69 changed files with 336 additions and 335 deletions.
Expand Up @@ -112,7 +112,7 @@ public void findOneChildren() {
given(this.jdbcOperations.query(anyString(), eq(args), any(RowMapper.class))).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577");
}

Expand All @@ -127,7 +127,7 @@ public void findNoChildren() {
public void findChildrenWithoutIdType() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L);
}
Expand All @@ -143,7 +143,7 @@ public void findChildrenForUnknownObject() {
public void findChildrenOfIdTypeLong() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL");
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(2);
assertThat(objectIdentities).hasSize(2);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L);
assertThat(objectIdentities.get(1).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
Expand All @@ -155,7 +155,7 @@ public void findChildrenOfIdTypeString() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("location");
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL");
}
Expand All @@ -165,7 +165,7 @@ public void findChildrenOfIdTypeUUID() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L);
this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter");
assertThat(objectIdentities.get(0).getIdentifier())
.isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762"));
Expand All @@ -186,7 +186,7 @@ public void findChildrenWhenObjectIdentityGeneratorSetThenUsed() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("location");
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("prefix:US-PAL");
}
Expand Down
Expand Up @@ -120,9 +120,9 @@ public void testGetters() {
PrincipalSid principalSid = new PrincipalSid(authentication);
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
assertThat("johndoe".equals(principalSid.getPrincipal())).isTrue();
assertThat("johndoe").isEqualTo(principalSid.getPrincipal());
assertThat("scott".equals(principalSid.getPrincipal())).isFalse();
assertThat("ROLE_TEST".equals(gaSid.getGrantedAuthority())).isTrue();
assertThat("ROLE_TEST").isEqualTo(gaSid.getGrantedAuthority());
assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse();
}

Expand Down
Expand Up @@ -143,8 +143,8 @@ public void postFilterIsApplied() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
List<String> objects = this.prePostSecured.postFilterMethod();
assertThat(objects).hasSize(2);
assertThat(objects.contains("apple")).isTrue();
assertThat(objects.contains("aubergine")).isTrue();
assertThat(objects).contains("apple");
assertThat(objects).contains("aubergine");
}

private void configureForElAnnotations() {
Expand Down
Expand Up @@ -87,7 +87,7 @@ public void userServiceReturnsExpectedData() {

Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPERS")).isTrue();
assertThat(authorities).contains("ROLE_DEVELOPERS");
}

@Test
Expand Down Expand Up @@ -128,7 +128,7 @@ public void differentGroupRoleAttributeWorksAsExpected() {

Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue();
assertThat(authorities).contains("ROLE_DEVELOPER");

}

Expand Down
Expand Up @@ -17,11 +17,13 @@
package org.springframework.security.config.annotation.authentication.configurers.provisioning;

import java.util.Arrays;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
Expand Down Expand Up @@ -73,7 +75,7 @@ public void authoritiesWithGrantedAuthorityWorks() {
.authorities(authority)
.build();
// @formatter:on
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
assertThat((Optional<GrantedAuthority>) userDetails.getAuthorities().stream().findFirst()).contains(authority);
}

@Test
Expand All @@ -99,7 +101,7 @@ public void authoritiesWithAListOfGrantedAuthorityWorks() {
.authorities(Arrays.asList(authority))
.build();
// @formatter:on
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
assertThat((Optional<GrantedAuthority>) userDetails.getAuthorities().stream().findFirst()).contains(authority);
}

private UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>> configurer() {
Expand Down
Expand Up @@ -47,23 +47,23 @@ public void setUp() {
public void requestMatchersWhenPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path");
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
}

@Test
public void requestMatchersWhenHttpMethodAndPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path");
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
}

@Test
public void requestMatchersWhenHttpMethodAndMvcNotPresentThenReturnAntPathMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET);
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
}

Expand Down
Expand Up @@ -75,7 +75,7 @@ public void regexMatchersWhenHttpMethodAndPatternParamsThenReturnRegexRequestMat
List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
}

Expand All @@ -84,7 +84,7 @@ public void regexMatchersWhenPatternParamThenReturnRegexRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new RegexRequestMatcher("/a.*", null));
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
}

Expand All @@ -93,15 +93,15 @@ public void antMatchersWhenHttpMethodAndPatternParamsThenReturnAntPathRequestMat
List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
}

@Test
public void antMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(new AntPathRequestMatcher("/a.*"));
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
}

Expand All @@ -110,39 +110,39 @@ public void dispatcherTypeMatchersWhenHttpMethodAndPatternParamsThenReturnAntPat
List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(HttpMethod.GET,
DispatcherType.ASYNC);
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class);
}

@Test
public void dispatcherMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(DispatcherType.INCLUDE);
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class);
}

@Test
public void requestMatchersWhenPatternAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path");
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
}

@Test
public void requestMatchersWhenHttpMethodAndPatternAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path");
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
}

@Test
public void requestMatchersWhenHttpMethodAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET);
assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1);
assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
}

Expand Down
Expand Up @@ -84,10 +84,10 @@ public void nullWebInvocationPrivilegeEvaluator() {
this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
.getFilterChains();
assertThat(filterChains.size()).isEqualTo(1);
assertThat(filterChains).hasSize(1);
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
assertThat(filterChain.getFilters().size()).isEqualTo(1);
assertThat(filterChain.getFilters()).hasSize(1);
long filter = filterChain.getFilters().stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
assertThat(filter).isEqualTo(1);
Expand All @@ -98,23 +98,23 @@ public void filterChainProxyBuilderIgnoringResources() {
this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
.getFilterChains();
assertThat(filterChains.size()).isEqualTo(2);
assertThat(filterChains).hasSize(2);
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
List<Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
.collect(Collectors.toList());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue();
assertThat(classes.contains(SecurityContextHolderFilter.class)).isTrue();
assertThat(classes.contains(HeaderWriterFilter.class)).isTrue();
assertThat(classes.contains(LogoutFilter.class)).isTrue();
assertThat(classes.contains(CsrfFilter.class)).isTrue();
assertThat(classes.contains(RequestCacheAwareFilter.class)).isTrue();
assertThat(classes.contains(SecurityContextHolderAwareRequestFilter.class)).isTrue();
assertThat(classes.contains(AnonymousAuthenticationFilter.class)).isTrue();
assertThat(classes.contains(ExceptionTranslationFilter.class)).isTrue();
assertThat(classes.contains(FilterSecurityInterceptor.class)).isTrue();
assertThat(classes).contains(WebAsyncManagerIntegrationFilter.class);
assertThat(classes).contains(SecurityContextHolderFilter.class);
assertThat(classes).contains(HeaderWriterFilter.class);
assertThat(classes).contains(LogoutFilter.class);
assertThat(classes).contains(CsrfFilter.class);
assertThat(classes).contains(RequestCacheAwareFilter.class);
assertThat(classes).contains(SecurityContextHolderAwareRequestFilter.class);
assertThat(classes).contains(AnonymousAuthenticationFilter.class);
assertThat(classes).contains(ExceptionTranslationFilter.class);
assertThat(classes).contains(FilterSecurityInterceptor.class);
}

@Test
Expand Down
Expand Up @@ -27,7 +27,6 @@
import jakarta.servlet.http.HttpServletResponse;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -412,7 +411,7 @@ private void performSaml2Login(String expected) throws IOException, ServletExcep
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
Assertions.assertNotNull(authentication, "Expected a valid authentication object.");
assertThat(authentication).as("Expected a valid authentication object.").isNotNull();
assertThat(authentication.getAuthorities()).hasSize(1);
assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class)
.hasToString(expected);
Expand Down
Expand Up @@ -286,8 +286,8 @@ public void inboundChannelSecurityDefinedByBean() {
private void assertHandshake(HttpServletRequest request) {
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
assertThat(handshakeHandler.attributes.get(this.sessionAttr))
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
assertThat(handshakeHandler.attributes).containsEntry(this.sessionAttr,
request.getSession().getAttribute(this.sessionAttr));
}

private HttpRequestHandler handler(HttpServletRequest request) throws Exception {
Expand Down
Expand Up @@ -371,8 +371,8 @@ public void sendMessageWhenAnonymousConfiguredAndLoggedInUserThenAccessDeniedExc
private void assertHandshake(HttpServletRequest request) {
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
assertThat(handshakeHandler.attributes.get(this.sessionAttr))
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
assertThat(handshakeHandler.attributes).containsEntry(this.sessionAttr,
request.getSession().getAttribute(this.sessionAttr));
}

private HttpRequestHandler handler(HttpServletRequest request) throws Exception {
Expand Down
Expand Up @@ -418,7 +418,7 @@ public void logoutWhenSpecifyingCookiesToDeleteThenSetCookieAdded() throws Excep
this.spring.configLocations(xml("DeleteCookies")).autowire();
MvcResult result = this.mvc.perform(post("/logout").with(csrf())).andReturn();
List<String> values = result.getResponse().getHeaders("Set-Cookie");
assertThat(values.size()).isEqualTo(2);
assertThat(values).hasSize(2);
assertThat(values).extracting((value) -> value.split("=")[0]).contains("JSESSIONID", "mycookie");
}

Expand Down
Expand Up @@ -16,7 +16,6 @@

package org.springframework.security.access.intercept;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import org.springframework.security.authentication.BadCredentialsException;
Expand Down Expand Up @@ -50,7 +49,7 @@ public void testAuthenticationSuccess() {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("my_password");
Authentication result = provider.authenticate(token);
Assertions.assertTrue(result instanceof RunAsUserToken, "Should have returned RunAsUserToken");
assertThat(result instanceof RunAsUserToken).as("Should have returned RunAsUserToken").isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
Expand Down

0 comments on commit 9df9cb5

Please sign in to comment.