mirror of
https://github.com/spring-projects/spring-petclinic.git
synced 2025-07-22 15:25:49 +00:00
start UserControllerTest
This commit is contained in:
parent
37f8f05c01
commit
2f50fa5d6a
18 changed files with 658 additions and 35 deletions
|
@ -47,6 +47,8 @@ public final class CommonAttribute {
|
|||
|
||||
public static final String TOKEN = "token";
|
||||
|
||||
public static final String URLS = "urls";
|
||||
|
||||
public static final String USER = "user";
|
||||
|
||||
public static final String USER_ID = "userId";
|
||||
|
|
|
@ -7,6 +7,8 @@ package org.springframework.samples.petclinic.common;
|
|||
*/
|
||||
public final class CommonEndPoint {
|
||||
|
||||
public static final String PETCLINIC_CONFIRM_ACCOUNT = "http://localhost:8080/confirm-account?token=";
|
||||
|
||||
public static final String OWNERS = "/owners";
|
||||
|
||||
public static final String OWNERS_FIND = "/owners/find";
|
||||
|
@ -35,6 +37,8 @@ public final class CommonEndPoint {
|
|||
|
||||
public static final String LOGIN_SUCCESS = "/login/success";
|
||||
|
||||
public static final String OAUTH2_AUTHORIZATION = "oauth2/authorization/";
|
||||
|
||||
public static final String OAUTH2_SUCCESS = "/oauth2/success";
|
||||
|
||||
public static final String CONFIRM_ACCOUNT = "/confirm-account";
|
||||
|
|
|
@ -2,6 +2,10 @@ package org.springframework.samples.petclinic.common;
|
|||
|
||||
public class CommonParameter {
|
||||
|
||||
public static final boolean ASK_OAUTH2_CONFIRMATION = false;
|
||||
|
||||
public static final String PETCLINIC_ADMIN_MAIL = "admin@petclinic.com";
|
||||
|
||||
public static final int CITY_MAX = 50;
|
||||
|
||||
public static final int COUNTRY_MAX = 50;
|
||||
|
|
|
@ -63,5 +63,7 @@ class CacheConfiguration {
|
|||
cacheManager.createCache("vets", cacheConfiguration());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -33,8 +33,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
|
||||
private static final String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
// @Autowired
|
||||
// private UserDetailsService userDetailsService;
|
||||
|
||||
@Resource
|
||||
private Environment env;
|
||||
|
|
|
@ -38,7 +38,6 @@ import java.util.Map;
|
|||
public class UserController extends WebSocketSender {
|
||||
|
||||
// set true if you whant confirmation email for first provider connection
|
||||
private static final boolean ASK_OAUTH2_CONFIRMATION = false;
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
|
@ -105,10 +104,10 @@ public class UserController extends WebSocketSender {
|
|||
sendSuccessMessage(CommonWebSocket.USER_CREATED);
|
||||
|
||||
// send confirmation mail
|
||||
MessageDTO message = new MessageDTO(user.getFirstName(), user.getLastName(), "admin@petclinic.com",
|
||||
user.getEmail(), "New connexion",
|
||||
MessageDTO message = new MessageDTO(user.getFirstName(), user.getLastName(),
|
||||
CommonParameter.PETCLINIC_ADMIN_MAIL, user.getEmail(), "New connexion",
|
||||
"Your attempt to create new account. To confirm your account, please click here : ",
|
||||
"http://localhost:8080/confirm-account?token=" + credential.getToken());
|
||||
CommonEndPoint.PETCLINIC_CONFIRM_ACCOUNT + credential.getToken());
|
||||
|
||||
emailService.sendMailAsynch(message, Locale.getDefault());
|
||||
|
||||
|
@ -136,8 +135,8 @@ public class UserController extends WebSocketSender {
|
|||
|
||||
if (clientRegistrations != null) {
|
||||
clientRegistrations.forEach(registration -> oauth2AuthenticationUrls.put(registration.getClientName(),
|
||||
"oauth2/authorization/" + registration.getRegistrationId()));
|
||||
model.put("urls", oauth2AuthenticationUrls);
|
||||
CommonEndPoint.OAUTH2_AUTHORIZATION + registration.getRegistrationId()));
|
||||
model.put(CommonAttribute.URLS, oauth2AuthenticationUrls);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -156,7 +155,7 @@ public class UserController extends WebSocketSender {
|
|||
}
|
||||
|
||||
@GetMapping(CommonEndPoint.OAUTH2_SUCCESS)
|
||||
public String postLogin(Model model, OAuth2AuthenticationToken authentication) {
|
||||
public String postLoginOAUTH2(Model model, OAuth2AuthenticationToken authentication) {
|
||||
String firstName = authentication.getPrincipal().getAttribute("given_name");
|
||||
String lastName = authentication.getPrincipal().getAttribute("family_name");
|
||||
|
||||
|
@ -181,9 +180,9 @@ public class UserController extends WebSocketSender {
|
|||
user = userService.save(user);
|
||||
}
|
||||
|
||||
if (ASK_OAUTH2_CONFIRMATION) {
|
||||
if (CommonParameter.ASK_OAUTH2_CONFIRMATION) {
|
||||
// prepare message
|
||||
MessageDTO message = new MessageDTO(firstName, lastName, "admin@petclinic.com", email,
|
||||
MessageDTO message = new MessageDTO(firstName, lastName, CommonParameter.PETCLINIC_ADMIN_MAIL, email,
|
||||
"New connexion from " + credential.getProvider(),
|
||||
"Your attempt to connect from " + credential.getProvider()
|
||||
+ " To confirm this connection, please click the link below : ",
|
||||
|
@ -191,18 +190,21 @@ public class UserController extends WebSocketSender {
|
|||
|
||||
// send confirmation mail
|
||||
emailService.sendMailAsynch(message, Locale.getDefault());
|
||||
|
||||
// disconnect
|
||||
authentication.eraseCredentials();
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
else {
|
||||
credential.setExpiration(null);
|
||||
credential.setToken("");
|
||||
credential.setVerified(true);
|
||||
credentialService.save(credential);
|
||||
securityService.autoLogin(credential.getEmail(), credential.getPassword());
|
||||
String message = String.format(CommonWebSocket.USER_LOGGED_IN, firstName, lastName);
|
||||
sendSuccessMessage(message);
|
||||
}
|
||||
|
||||
// disconnect
|
||||
authentication.eraseCredentials();
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
}
|
||||
else if (Boolean.TRUE.equals(credential.isVerified())) {
|
||||
securityService.autoLogin(credential.getEmail(), credential.getPassword());
|
||||
|
@ -290,7 +292,7 @@ public class UserController extends WebSocketSender {
|
|||
}
|
||||
|
||||
@GetMapping(CommonEndPoint.USERS_ID)
|
||||
public ModelAndView showOwner(@PathVariable("userId") Integer userId) {
|
||||
public ModelAndView showOwner(@PathVariable(CommonAttribute.USER_ID) Integer userId) {
|
||||
ModelAndView modelAndView = new ModelAndView(CommonView.USER_DETAILS);
|
||||
UserDTO user = this.userService.findById(userId);
|
||||
|
||||
|
@ -298,8 +300,8 @@ public class UserController extends WebSocketSender {
|
|||
return modelAndView;
|
||||
}
|
||||
|
||||
@GetMapping("/user/{userId}/edit/password")
|
||||
public String editPassword(@PathVariable("userId") Integer userId, Model model) {
|
||||
@GetMapping(CommonEndPoint.USERS_ID_EDIT_PASSWORD)
|
||||
public String editPassword(@PathVariable(CommonAttribute.USER_ID) Integer userId, Model model) {
|
||||
try {
|
||||
UserDTO operator = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
UserDTO user = userService.findById(userId);
|
||||
|
@ -317,7 +319,7 @@ public class UserController extends WebSocketSender {
|
|||
return CommonView.HOME;
|
||||
}
|
||||
|
||||
@PostMapping("/user/{userId}/edit/password")
|
||||
@PostMapping(CommonEndPoint.USERS_ID_EDIT_PASSWORD)
|
||||
public String updatePassword(@ModelAttribute(CommonAttribute.USER) @Valid UserDTO user, BindingResult bindingResult,
|
||||
@PathVariable(CommonAttribute.USER_ID) Integer userId, @Param("oldPassword") String oldPassword,
|
||||
@Param("newPassword") String newPassword, @Param("newMatchingPassword") String newMatchingPassword,
|
||||
|
|
|
@ -1,10 +1,22 @@
|
|||
package org.springframework.samples.petclinic.dto.common;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Simple Data Transfert Object representing a Authorization Provider.
|
||||
*
|
||||
* @author Paul-Emmanuel DOS SANTOS FACAO
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class AuthProviderDTO extends NamedDTO {
|
||||
|
||||
public AuthProviderDTO(Integer id, String name) {
|
||||
this.setId(id);
|
||||
this.setName(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -56,7 +56,7 @@ public class User extends Person implements Serializable, UserDetails {
|
|||
@Column(name = "credential_unexpired")
|
||||
private boolean credentialsNonExpired;
|
||||
|
||||
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
|
||||
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
|
||||
private Collection<Role> roles;
|
||||
|
|
|
@ -1,9 +1,13 @@
|
|||
package org.springframework.samples.petclinic.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.samples.petclinic.service.common.UserDetailsServiceImpl;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
|
@ -17,11 +21,17 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
|
||||
public static final String TEST_USER = "petclinicuser";
|
||||
|
||||
private final static String USER_EMAIL = "Sam.Schultz@petclinic.com";
|
||||
|
||||
private final static String USER_PASSWORD = "PASSWORD_TEST9879879$^m$*ùm*^$*ù";
|
||||
|
||||
private final static String ROLE_NAME = "ROLE_TEST";
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
auth.inMemoryAuthentication().passwordEncoder(encoder).withUser(TEST_USER).password(encoder.encode("secret"))
|
||||
.roles("ROLE_USER");
|
||||
auth.inMemoryAuthentication().passwordEncoder(encoder).withUser(USER_EMAIL).password(USER_PASSWORD)
|
||||
.roles(ROLE_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -0,0 +1,337 @@
|
|||
package org.springframework.samples.petclinic.controller.common;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.samples.petclinic.common.CommonAttribute;
|
||||
import org.springframework.samples.petclinic.common.CommonEndPoint;
|
||||
import org.springframework.samples.petclinic.common.CommonView;
|
||||
import org.springframework.samples.petclinic.controller.WebSecurityConfig;
|
||||
import org.springframework.samples.petclinic.dto.common.*;
|
||||
import org.springframework.samples.petclinic.model.common.*;
|
||||
import org.springframework.samples.petclinic.service.common.*;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* Test class for {@link UserController}
|
||||
*
|
||||
* @author Paul-Emmanuel DOS SANTOS FACAO
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(UserController.class)
|
||||
class UserControllerTest extends WebSocketSender {
|
||||
|
||||
private final static Integer USER_ID = 11;
|
||||
|
||||
private final static String USER_FIRST_NAME = "Sam";
|
||||
|
||||
private final static String USER_LAST_NAME = "Schultz";
|
||||
|
||||
private final static String USER_EMAIL = "Sam.Schultz@petclinic.com";
|
||||
|
||||
private final static String USER_PASSWORD = "PASSWORD_TEST9879879$^m$*ùm*^$*ù";
|
||||
|
||||
private final static String USER_ADDRESS = "4, Evans Street";
|
||||
|
||||
private final static String USER_CITY = "Wollongong";
|
||||
|
||||
private final static String USER_ZIPCODE = "65879";
|
||||
|
||||
private final static String USER_COUNTRY = "USA";
|
||||
|
||||
private final static String USER_PHONE = "1234567890";
|
||||
|
||||
private final static Integer ROLE_ID = 4;
|
||||
|
||||
private final static String ROLE_NAME = "ROLE_TEST";
|
||||
|
||||
private final static Integer PRIVILEGE_ID = 3;
|
||||
|
||||
private final static String PRIVILEGE_NAME = "PRIVILEGE_TEST";
|
||||
|
||||
private static final String PROVIDER_TEST_NAME = "Provider Test";
|
||||
|
||||
private static final Integer PROVIDER_TEST_ID = 11;
|
||||
|
||||
private static final String EMAIL_TEST = "eduardo.rodriguez@petclinic.com";
|
||||
|
||||
private static final String PASSWORD_TEST = "$2a$10$8KypNYtPopFo8Sk5jbKJ4.lCKeBhdApsrkmFfhwjB8nCls8qpzjZG";
|
||||
|
||||
private static final String TOKEN_TEST = UUID.randomUUID().toString();
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private UserDetailsServiceImpl userDetailsService;
|
||||
|
||||
@MockBean
|
||||
private SecurityServiceImpl securityService;
|
||||
|
||||
@MockBean
|
||||
private SimpMessagingTemplate simpMessagingTemplate;
|
||||
|
||||
@MockBean
|
||||
private UserService userService;
|
||||
|
||||
@MockBean
|
||||
private CredentialService credentialService;
|
||||
|
||||
@MockBean
|
||||
private RoleService roleService;
|
||||
|
||||
@MockBean
|
||||
private EmailService emailService;
|
||||
|
||||
private User user;
|
||||
|
||||
private UserDTO userDTO;
|
||||
|
||||
private Role role;
|
||||
|
||||
private RoleDTO roleDTO;
|
||||
|
||||
private Privilege privilege;
|
||||
|
||||
private PrivilegeDTO privilegeDTO;
|
||||
|
||||
private Credential credential;
|
||||
|
||||
private CredentialDTO credentialDTO;
|
||||
|
||||
private AuthProvider authProvider;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
user = new User();
|
||||
userDTO = new UserDTO();
|
||||
privilege = new Privilege();
|
||||
privilegeDTO = new PrivilegeDTO();
|
||||
role = new Role();
|
||||
roleDTO = new RoleDTO();
|
||||
|
||||
privilege.setId(PRIVILEGE_ID);
|
||||
privilege.setName(PRIVILEGE_NAME);
|
||||
privilege.setRoles(Collections.singleton(role));
|
||||
privilegeDTO.setId(PRIVILEGE_ID);
|
||||
privilegeDTO.setName(PRIVILEGE_NAME);
|
||||
privilegeDTO.setRoles(Collections.singleton(roleDTO));
|
||||
|
||||
role.setId(ROLE_ID);
|
||||
role.setName(ROLE_NAME);
|
||||
role.setPrivileges(Collections.singleton(privilege));
|
||||
role.setUsers(Collections.singleton(user));
|
||||
roleDTO.setId(ROLE_ID);
|
||||
roleDTO.setName(ROLE_NAME);
|
||||
roleDTO.setPrivileges(Collections.singleton(privilegeDTO));
|
||||
roleDTO.setUsers(Collections.singleton(userDTO));
|
||||
|
||||
user.setId(USER_ID);
|
||||
user.setFirstName(USER_FIRST_NAME);
|
||||
user.setLastName(USER_LAST_NAME);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setPassword(USER_PASSWORD);
|
||||
user.setAccountNonExpired(true);
|
||||
user.setAccountNonLocked(true);
|
||||
user.setCredentialsNonExpired(true);
|
||||
user.setEnabled(true);
|
||||
user.setTelephone(USER_PHONE);
|
||||
user.setStreet1(USER_ADDRESS);
|
||||
user.setCity(USER_CITY);
|
||||
user.setZipCode(USER_ZIPCODE);
|
||||
user.setCountry(USER_COUNTRY);
|
||||
user.setRoles(Collections.singleton(role));
|
||||
role.addUser(user);
|
||||
|
||||
userDTO.setId(USER_ID);
|
||||
userDTO.setFirstName(USER_FIRST_NAME);
|
||||
userDTO.setLastName(USER_LAST_NAME);
|
||||
userDTO.setEmail(USER_EMAIL);
|
||||
userDTO.setPassword(USER_PASSWORD);
|
||||
userDTO.setMatchingPassword(USER_PASSWORD);
|
||||
userDTO.setAccountNonExpired(true);
|
||||
userDTO.setAccountNonLocked(true);
|
||||
userDTO.setCredentialsNonExpired(true);
|
||||
userDTO.setEnabled(true);
|
||||
userDTO.setTelephone(USER_PHONE);
|
||||
userDTO.setStreet1(USER_ADDRESS);
|
||||
userDTO.setCity(USER_CITY);
|
||||
userDTO.setZipCode(USER_ZIPCODE);
|
||||
userDTO.setCountry(USER_COUNTRY);
|
||||
userDTO.setRoles(Collections.singleton(roleDTO));
|
||||
roleDTO.addUser(userDTO);
|
||||
|
||||
authProvider = new AuthProvider(PROVIDER_TEST_ID, PROVIDER_TEST_NAME);
|
||||
credential = new Credential(PROVIDER_TEST_ID, EMAIL_TEST, PASSWORD_TEST, true);
|
||||
credential.setToken(TOKEN_TEST);
|
||||
credentialDTO = new CredentialDTO(PROVIDER_TEST_NAME, EMAIL_TEST, PASSWORD_TEST, true);
|
||||
credentialDTO.setToken(TOKEN_TEST);
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(new Timestamp(cal.getTime().getTime()));
|
||||
cal.add(Calendar.MINUTE, credential.getTokenExpiration());
|
||||
credential.setExpiration(cal.getTime());
|
||||
credentialDTO.setExpiration(cal.getTime());
|
||||
|
||||
doNothing().when(emailService).sendMailAsynch(any(MessageDTO.class), any(Locale.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("initCreationForm")
|
||||
@DisplayName("Verify that we get the right registration view and the right attribute name")
|
||||
void initCreationForm() throws Exception {
|
||||
mockMvc.perform(get(CommonEndPoint.REGISTER)).andExpect(status().is2xxSuccessful())
|
||||
.andExpect(view().name(CommonView.USER_REGISTRATION))
|
||||
.andExpect(model().attributeExists(CommonAttribute.USER));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("processCreationForm")
|
||||
@DisplayName("Verify that call the right view with parameters when attempt to create User with right parameters")
|
||||
void processCreationForm() throws Exception {
|
||||
given(userService.existByEmail(anyString())).willReturn(false);
|
||||
given(userService.save(any(UserDTO.class))).willReturn(userDTO);
|
||||
given(roleService.findByName(anyString())).willReturn(roleDTO);
|
||||
given(credentialService.save(any(CredentialDTO.class))).willReturn(credentialDTO);
|
||||
|
||||
mockMvc.perform(post(CommonEndPoint.REGISTER).flashAttr(CommonAttribute.USER, userDTO))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(view().name(CommonView.HOME + user.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("initLoginForm")
|
||||
@DisplayName("Verify that we get the right view for login")
|
||||
void initLoginForm() throws Exception {
|
||||
mockMvc.perform(get(CommonEndPoint.LOGIN)).andExpect(status().is2xxSuccessful())
|
||||
.andExpect(view().name(CommonView.USER_LOGIN)).andExpect(model().attributeExists(CommonAttribute.USER))
|
||||
.andExpect(model().attributeExists(CommonAttribute.URLS));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("postLogin")
|
||||
@DisplayName("Verify that we get the right parameters and view after login with email and password")
|
||||
void postLogin() throws Exception {
|
||||
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
|
||||
userDTO, USER_PASSWORD, userDTO.getAuthorities());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
|
||||
|
||||
mockMvc.perform(get(CommonEndPoint.LOGIN_SUCCESS)).andExpect(status().is3xxRedirection())
|
||||
.andExpect(view().name(CommonView.HOME));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("postLoginOAUTH2")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void postLoginOAUTH2() {
|
||||
given(credentialService.findByAuthentication(any(OAuth2AuthenticationToken.class))).willReturn(credentialDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("confirmUserAccount")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void confirmUserAccount() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("logout")
|
||||
@DisplayName("Verify the User is disconnected")
|
||||
void logout() throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
|
||||
mockMvc.perform(get(CommonEndPoint.LOGOUT)).andExpect(status().is3xxRedirection())
|
||||
.andExpect(redirectedUrl(CommonEndPoint.LOGOUT_SUCCESS));
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("initUpdateOwnerForm")
|
||||
@DisplayName("Verify that we get the right update view and the right attribute name when user is connected")
|
||||
void givenConnectedUser_whenCallUpdateForm_ThenRedirectUpdateViewWithUser() throws Exception {
|
||||
given(userService.findByEmail(anyString())).willReturn(userDTO);
|
||||
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
|
||||
userDTO, USER_PASSWORD, userDTO.getAuthorities());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
|
||||
|
||||
mockMvc.perform(get(CommonEndPoint.USERS_EDIT)).andExpect(status().is2xxSuccessful())
|
||||
.andExpect(view().name(CommonView.USER_UPDATE)).andExpect(model().attributeExists(CommonAttribute.USER))
|
||||
.andExpect(model().attributeExists(CommonAttribute.USER_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("initUpdateOwnerForm")
|
||||
@DisplayName("Verify that we get the right update view and the right attribute name when user is connected")
|
||||
void givenNoConnectedUser_whenCallUpdateForm_ThenRedirectHome() throws Exception {
|
||||
given(userService.findByEmail(anyString())).willReturn(userDTO);
|
||||
|
||||
mockMvc.perform(get(CommonEndPoint.USERS_EDIT)).andExpect(status().is3xxRedirection())
|
||||
.andExpect(view().name(CommonView.HOME)).andExpect(model().attributeDoesNotExist(CommonAttribute.USER))
|
||||
.andExpect(model().attributeDoesNotExist(CommonAttribute.USER_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("processUpdateOwnerForm")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void processUpdateOwnerForm() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("showOwner")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void showOwner() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("editPassword")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void editPassword() {
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(value = WebSecurityConfig.TEST_USER)
|
||||
@Tag("updatePassword")
|
||||
@DisplayName("Verify that we get UserDTO by his ID")
|
||||
void updatePassword() {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
package org.springframework.samples.petclinic.service.common;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.samples.petclinic.dto.common.AuthProviderDTO;
|
||||
import org.springframework.samples.petclinic.model.common.AuthProvider;
|
||||
import org.springframework.samples.petclinic.repository.AuthProviderRepository;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureTestDatabase
|
||||
@RunWith(SpringRunner.class)
|
||||
class AuthProviderServiceIntegrationTest {
|
||||
|
||||
private static final String PROVIDER_TEST_NAME = "Provider Test";
|
||||
|
||||
private static final Integer PROVIDER_TEST_ID = 11;
|
||||
|
||||
@Autowired
|
||||
private AuthProviderRepository authProviderRepository;
|
||||
|
||||
private AuthProviderService authProviderService;
|
||||
|
||||
private AuthProvider authProvider;
|
||||
|
||||
private AuthProviderDTO authProviderDTO;
|
||||
|
||||
private List<AuthProvider> allAuthProviders;
|
||||
|
||||
private List<AuthProviderDTO> allAuthProviderDTOS;
|
||||
|
||||
@BeforeEach
|
||||
void beforeEach() {
|
||||
authProviderService = new AuthProviderService(authProviderRepository);
|
||||
|
||||
authProvider = new AuthProvider(PROVIDER_TEST_ID, PROVIDER_TEST_NAME);
|
||||
authProviderDTO = new AuthProviderDTO(PROVIDER_TEST_ID, PROVIDER_TEST_NAME);
|
||||
|
||||
allAuthProviders = authProviderRepository.findAll();
|
||||
allAuthProviderDTOS = new ArrayList<>();
|
||||
allAuthProviders.forEach(
|
||||
provider -> allAuthProviderDTOS.add(new AuthProviderDTO(provider.getId(), provider.getName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findById")
|
||||
@DisplayName("Verify that we call right method to find AuthProvider by ID")
|
||||
void findById() {
|
||||
|
||||
allAuthProviderDTOS.forEach(provider -> {
|
||||
AuthProviderDTO found = authProviderService.findById(provider.getId());
|
||||
assertThat(found).isEqualTo(provider);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findAll")
|
||||
@DisplayName("Verify that we call right method to find all AuthProviders")
|
||||
void findAll() {
|
||||
|
||||
List<AuthProviderDTO> found = authProviderService.findAll();
|
||||
|
||||
assertThat(found).isEqualTo(allAuthProviderDTOS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findByName")
|
||||
@DisplayName("Verify that we call right method to find AuthProvider by name")
|
||||
void findByName() {
|
||||
|
||||
allAuthProviderDTOS.forEach(provider -> {
|
||||
AuthProviderDTO found = authProviderService.findByName(provider.getName());
|
||||
assertThat(found).isEqualTo(provider);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("save")
|
||||
@DisplayName("Verify that we call right method to save AuthProvider")
|
||||
void save() {
|
||||
AuthProviderDTO found = authProviderService.findByName(PROVIDER_TEST_NAME);
|
||||
|
||||
assertThat(found.isNew()).isTrue();
|
||||
authProviderDTO.setId(null);
|
||||
found = authProviderService.save(authProviderDTO);
|
||||
|
||||
assertThat(found).isEqualToIgnoringGivenFields(authProviderDTO, "id");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
package org.springframework.samples.petclinic.service.common;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.samples.petclinic.dto.common.AuthProviderDTO;
|
||||
import org.springframework.samples.petclinic.dto.common.CredentialDTO;
|
||||
import org.springframework.samples.petclinic.dto.common.UserDTO;
|
||||
import org.springframework.samples.petclinic.model.common.AuthProvider;
|
||||
import org.springframework.samples.petclinic.model.common.Credential;
|
||||
import org.springframework.samples.petclinic.model.common.Role;
|
||||
import org.springframework.samples.petclinic.repository.AuthProviderRepository;
|
||||
import org.springframework.samples.petclinic.repository.CredentialRepository;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureTestDatabase
|
||||
@RunWith(SpringRunner.class)
|
||||
class AuthProviderServiceTest {
|
||||
|
||||
private static final String PROVIDER_TEST_NAME = "Provider Test";
|
||||
|
||||
private static final Integer PROVIDER_TEST_ID = 11;
|
||||
|
||||
@MockBean
|
||||
private AuthProviderRepository authProviderRepository;
|
||||
|
||||
private AuthProviderService authProviderService;
|
||||
|
||||
private AuthProvider authProvider;
|
||||
|
||||
private AuthProviderDTO authProviderDTO;
|
||||
|
||||
private List<AuthProvider> allAuthProviders;
|
||||
|
||||
private List<AuthProviderDTO> allAuthProviderDTOS;
|
||||
|
||||
@BeforeEach
|
||||
void beforeEach() {
|
||||
authProviderService = new AuthProviderService(authProviderRepository);
|
||||
|
||||
authProvider = new AuthProvider(PROVIDER_TEST_ID, PROVIDER_TEST_NAME);
|
||||
authProviderDTO = new AuthProviderDTO(PROVIDER_TEST_ID, PROVIDER_TEST_NAME);
|
||||
|
||||
allAuthProviders = authProviderRepository.findAll();
|
||||
allAuthProviders.add(authProvider);
|
||||
allAuthProviderDTOS = new ArrayList<>();
|
||||
allAuthProviders.forEach(
|
||||
provider -> allAuthProviderDTOS.add(new AuthProviderDTO(provider.getId(), provider.getName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("dtoToEntity")
|
||||
@DisplayName("Verify the convertion from DTO to Entity")
|
||||
void dtoToEntity() {
|
||||
AuthProvider found = authProviderService.dtoToEntity(authProviderDTO);
|
||||
|
||||
assertThat(found).isEqualToComparingFieldByField(authProvider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("entityToDTO")
|
||||
@DisplayName("Verify the convertion from Entity to DTO")
|
||||
void entityToDTO() {
|
||||
AuthProviderDTO found = authProviderService.entityToDTO(authProvider);
|
||||
|
||||
assertThat(found).isEqualToComparingFieldByField(authProviderDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("dtosToEntities")
|
||||
@DisplayName("Verify the convertion from DTO List to Entity List")
|
||||
void dtosToEntities() {
|
||||
List<AuthProvider> found = authProviderService.dtosToEntities(allAuthProviderDTOS);
|
||||
|
||||
assertThat(found).hasSameSizeAs(allAuthProviders).isEqualTo(allAuthProviders);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("entitiesToDTOS")
|
||||
@DisplayName("Verify the convertion from Entity List to DTO List")
|
||||
void entitiesToDTOS() {
|
||||
List<AuthProviderDTO> found = authProviderService.entitiesToDTOS(allAuthProviders);
|
||||
|
||||
assertThat(found).hasSameSizeAs(allAuthProviderDTOS).isEqualTo(allAuthProviderDTOS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findById")
|
||||
@DisplayName("Verify that we call right method to find AuthProvider by ID")
|
||||
void findById() {
|
||||
given(authProviderRepository.findById(anyInt())).willReturn(authProvider);
|
||||
|
||||
AuthProviderDTO found = authProviderService.findById(PROVIDER_TEST_ID);
|
||||
|
||||
assertThat(found).isEqualTo(authProviderDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findAll")
|
||||
@DisplayName("Verify that we call right method to find all AuthProviders")
|
||||
void findAll() {
|
||||
given(authProviderRepository.findAll()).willReturn(allAuthProviders);
|
||||
|
||||
List<AuthProviderDTO> found = authProviderService.findAll();
|
||||
|
||||
assertThat(found).isEqualTo(allAuthProviderDTOS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("findByName")
|
||||
@DisplayName("Verify that we call right method to find AuthProvider by name")
|
||||
void findByName() {
|
||||
given(authProviderRepository.findByName(anyString())).willReturn(authProvider);
|
||||
|
||||
AuthProviderDTO found = authProviderService.findByName(PROVIDER_TEST_NAME);
|
||||
|
||||
assertThat(found).isEqualTo(authProviderDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("save")
|
||||
@DisplayName("Verify that we call right method to save AuthProvider")
|
||||
void save() {
|
||||
given(authProviderRepository.save(any(AuthProvider.class))).willReturn(authProvider);
|
||||
|
||||
AuthProviderDTO found = authProviderService.save(authProviderDTO);
|
||||
|
||||
assertThat(found).isEqualToComparingFieldByField(authProviderDTO);
|
||||
}
|
||||
|
||||
}
|
|
@ -76,16 +76,15 @@ class CredentialServiceIntegrationTest {
|
|||
credentialDTO.setExpiration(cal.getTime());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@Tag("findByEmailAndProvider")
|
||||
@DisplayName("Verify that we call right method to get Credential by Email and Provider")
|
||||
void findByEmailAndProvider() {
|
||||
|
||||
for(Credential credential: allCredentials) {
|
||||
for (Credential credential : allCredentials) {
|
||||
String email = credential.getEmail();
|
||||
String provider = authProviderRepository.findById(credential.getProviderId()).getName();
|
||||
CredentialDTO found = credentialService.findByEmailAndProvider(email,provider);
|
||||
CredentialDTO found = credentialService.findByEmailAndProvider(email, provider);
|
||||
assertThat(found).isEqualToComparingFieldByField(credentialService.entityToDTO(credential));
|
||||
}
|
||||
|
||||
|
|
|
@ -141,7 +141,7 @@ class PrivilegeServiceIntegrationTest {
|
|||
void save() {
|
||||
List<PrivilegeDTO> expected = privilegeService.findAll();
|
||||
|
||||
assertThat(expected).doesNotContain(privilegeDTO);
|
||||
assertThat(expected).isNotEmpty().doesNotContain(privilegeDTO);
|
||||
|
||||
privilegeDTO.setRoles(new HashSet<>());
|
||||
PrivilegeDTO saved = privilegeService.save(privilegeDTO);
|
||||
|
|
|
@ -30,15 +30,15 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||
@RunWith(SpringRunner.class)
|
||||
class PrivilegeServiceTest {
|
||||
|
||||
private final static Integer USER_ID = 2;
|
||||
private static final Integer USER_ID = 2;
|
||||
|
||||
private final static Integer ROLE_ID = 4;
|
||||
private static final Integer ROLE_ID = 4;
|
||||
|
||||
private final static Integer PRIVILEGE_ID = 5;
|
||||
private static final Integer PRIVILEGE_ID = 5;
|
||||
|
||||
private final static String PRIVILEGE_NAME = "TEST_UPDATE";
|
||||
private static final String PRIVILEGE_NAME = "TEST_UPDATE";
|
||||
|
||||
private final static String ROLE_NAME = "ROLE_TEST";
|
||||
private static final String ROLE_NAME = "ROLE_TEST";
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
@ -200,7 +200,7 @@ class PrivilegeServiceTest {
|
|||
void save() {
|
||||
List<PrivilegeDTO> expected = privilegeService.findAll();
|
||||
|
||||
assertThat(expected).doesNotContain(privilegeDTO);
|
||||
assertThat(expected).isNotEmpty().doesNotContain(privilegeDTO);
|
||||
|
||||
privilegeDTO.setRoles(new HashSet<>());
|
||||
PrivilegeDTO saved = privilegeService.save(privilegeDTO);
|
||||
|
|
|
@ -132,7 +132,7 @@ class RoleServiceIntegrationTest {
|
|||
@DisplayName("Verify that all RoleDTO list contain the new saved one")
|
||||
void save() {
|
||||
Collection<RoleDTO> expected = roleService.findAll();
|
||||
assertThat(expected).doesNotContain(roleDTO);
|
||||
assertThat(expected).isNotEmpty().doesNotContain(roleDTO);
|
||||
|
||||
roleDTO.setUsers(new HashSet<>());
|
||||
RoleDTO saved = roleService.save(roleDTO);
|
||||
|
|
|
@ -162,7 +162,7 @@ class UserServiceIntegrationTest {
|
|||
@DisplayName("Verify that all UserDTO list contain the new saved one")
|
||||
void save() {
|
||||
Collection<UserDTO> expected = userService.findAll();
|
||||
assertThat(expected).doesNotContain(userDTO);
|
||||
assertThat(expected).isNotEmpty().doesNotContain(userDTO);
|
||||
|
||||
UserDTO saved = userService.save(userDTO);
|
||||
|
||||
|
|
|
@ -218,7 +218,7 @@ class UserServiceTest {
|
|||
@DisplayName("Verify that all UserDTO list contain the new saved one")
|
||||
void save() {
|
||||
Collection<UserDTO> expected = userService.findAll();
|
||||
assertThat(expected).doesNotContain(userDTO);
|
||||
assertThat(expected).isNotEmpty().doesNotContain(userDTO);
|
||||
|
||||
UserDTO saved = userService.save(userDTO);
|
||||
|
||||
|
|
Loading…
Reference in a new issue