Skip to content

Commit

Permalink
[OT276-97] Test: Endpoints /auth (#81)
Browse files Browse the repository at this point in the history
* insert organization

* add @builder for integration test

* add @builder for integration test

* add test for all auth methods with diferent use cases

* add asserts

* fix

* unit test (not found)

* add mock for authenticationManager in register

* fix unit test

* fix login test

* fix me

* fix

* fix

* fix
  • Loading branch information
wilux authored Sep 22, 2022
1 parent d377a40 commit 8911ee6
Show file tree
Hide file tree
Showing 6 changed files with 317 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;


import javax.validation.Valid;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CreateUserRequest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotEmpty;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LoginRequest {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package com.alkemy.ong.ports.input.rs.controller;

import com.alkemy.ong.H2Config;
import com.alkemy.ong.config.util.JsonUtils;
import com.alkemy.ong.ports.input.rs.api.ApiConstants;
import com.alkemy.ong.ports.input.rs.request.CreateUserRequest;
import com.alkemy.ong.ports.input.rs.request.LoginRequest;
import com.alkemy.ong.ports.input.rs.response.UserResponse;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@DirtiesContext
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@SpringJUnitConfig(classes = H2Config.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class AuthControllerIT {

@Autowired
MockMvc mockMvc;

@Test
@Order(1)
void register_shouldReturn201() throws Exception {
CreateUserRequest request = CreateUserRequest.builder()
.email("[email protected]")
.password("test123")
.firstName("test")
.lastName("test")
.photo("img")
.build();

final String content = mockMvc.perform(post(ApiConstants.AUTHENTICATION_URI + "/register")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isCreated())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).contains("token", "expiration_date");

}

@Test
@Order(2)
void login_shouldReturn200() throws Exception {
LoginRequest request = LoginRequest.builder().userName("[email protected]").password("test123").build();
final String content = mockMvc.perform(post(ApiConstants.AUTHENTICATION_URI + "/login")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isOk())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).contains("token", "expiration_date");
}

@Test
@Order(3)
@WithUserDetails("[email protected]")
void getUserInformation_shouldReturn200() throws Exception {
final String content = mockMvc.perform(get(ApiConstants.AUTHENTICATION_URI + "/me"))
.andExpect(status().isOk())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).isNotBlank();

UserResponse response = JsonUtils.jsonToObject(content, UserResponse.class);

assertThat(response.getFirstName()).isEqualTo("test");


}

@Test
@Order(4)
void login_shouldReturn400() throws Exception {
LoginRequest request = LoginRequest.builder().userName("[email protected]").password("123test").build();
mockMvc.perform(post(ApiConstants.AUTHENTICATION_URI + "/login")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isUnauthorized());
}

@Test
@Order(5)
void register_shouldReturn409() throws Exception {
CreateUserRequest request = CreateUserRequest.builder()
.email("[email protected]")
.password("test123")
.firstName("test")
.lastName("test")
.photo("img")
.build();

mockMvc.perform(post(ApiConstants.AUTHENTICATION_URI + "/register")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isConflict());

}

@Test
@Order(6)
void register_shouldReturn400() throws Exception {
CreateUserRequest request = CreateUserRequest.builder()
.email("[email protected]")
.password("")
.firstName("test")
.lastName("test")
.photo("img")
.build();

mockMvc.perform(post(ApiConstants.AUTHENTICATION_URI + "/register")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isBadRequest());

}

@Test
@Order(7)
@WithAnonymousUser
void getUserInformation_shouldReturn401() throws Exception {
mockMvc.perform(get(ApiConstants.AUTHENTICATION_URI + "/me"))
.andExpect(status().isUnauthorized());

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package com.alkemy.ong.ports.input.rs.controller;

import com.alkemy.ong.config.exception.handler.GlobalExceptionHandler;
import com.alkemy.ong.config.security.JwtUtils;
import com.alkemy.ong.config.util.JsonUtils;
import com.alkemy.ong.core.model.User;
import com.alkemy.ong.core.usecase.UserService;
import com.alkemy.ong.ports.input.rs.api.ApiConstants;
import com.alkemy.ong.ports.input.rs.mapper.UserControllerMapper;
import com.alkemy.ong.ports.input.rs.request.CreateUserRequest;
import com.alkemy.ong.ports.input.rs.request.LoginRequest;
import com.alkemy.ong.ports.input.rs.response.UserResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mapstruct.factory.Mappers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.Date;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(MockitoExtension.class)
class AuthControllerTest {


private MockMvc mockMvc;

@InjectMocks
AuthController controller;
@Mock
UserService service;
@Mock
AuthenticationManager authenticationManager;

@Mock
JwtUtils jwtUtils;
@Spy
UserControllerMapper mapper = Mappers.getMapper(UserControllerMapper.class);


@BeforeEach
void setUp() {

mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(GlobalExceptionHandler.class)
.build();

}

@Test
void register_shouldReturn201() throws Exception {
CreateUserRequest request = CreateUserRequest.builder()
.email("[email protected]")
.password("test123")
.firstName("test")
.lastName("test")
.photo("img")
.build();


User user = mapper.createUserRequestToUser(request);
user.setId(99L);

given(service.createEntity(any(User.class))).willReturn(99L);
when(authenticationManager.authenticate(any(Authentication.class)))
.thenReturn(new UsernamePasswordAuthenticationToken(user, "test", List.of()));
when(jwtUtils.generateToken(any(UserDetails.class))).thenReturn("token");
when(jwtUtils.extractExpiration(any())).thenReturn(new Date());

String content = mockMvc.perform(
post(ApiConstants.AUTHENTICATION_URI + "/register")

.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isCreated())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).isNotBlank();
}


@Test
void login_shouldReturn201() throws Exception {
LoginRequest request = LoginRequest.builder()
.userName("[email protected]")
.password("jdoe123")
.build();

User user = new User();
user.setId(2L);
user.setEmail(request.getUserName());


given(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))).willReturn(new UsernamePasswordAuthenticationToken(
user, request.getPassword(), List.of()));
when(jwtUtils.generateToken(any(UserDetails.class))).thenReturn("token");
when(jwtUtils.extractExpiration(any())).thenReturn(new Date());

String content = mockMvc.perform(
post(ApiConstants.AUTHENTICATION_URI + "/login")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtils.objectToJson(request)))
.andExpect(status().isOk())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).isNotBlank();


}

@Test
void me_shouldReturn201() throws Exception {
User user = new User();
user.setId(2L);

String content = mockMvc.perform(get(ApiConstants.AUTHENTICATION_URI + "/me"))
.andExpect(status().isOk())
.andDo(print())
.andReturn()
.getResponse()
.getContentAsString();

assertThat(content).isNotBlank();
UserResponse response = mapper.userToUserResponse(user);
assertThat(response.getId()).isEqualTo(2);
}

}
7 changes: 3 additions & 4 deletions src/test/resources/test-data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ insert into `user` (user_id, first_name, last_name, email, password, photo, role
insert into `user` (user_id, first_name, last_name, email, password, photo, role_id, is_active, created_at) values (2, 'John', 'Doe', '[email protected]', '$2a$10$npmFpCbBFdtXjGGhgc1ste1quwGaF4MvkgYk9N2rBDFkOrV5Lj6M6', 'https://static-url.com/avatar.jpg', 2, true, CURRENT_DATE());
insert into `user` (user_id, first_name, last_name, email, password, photo, role_id, is_active, created_at) values (3, 'Jane', 'Smith', '[email protected]', '$2a$10$npmFpCbBFdtXjGGhgc1ste1quwGaF4MvkgYk9N2rBDFkOrV5Lj6M6', 'https://static-url.com/avatar.jpg', 2, true, CURRENT_DATE());

insert into category(category_id, name, description, image, created_at, is_active) values(1,'politica','for test','foo',CURRENT_DATE(),1);

insert into organization(organization_id, name, image, address, phone, email, welcome_text, about_us_text, facebook, linkedin, instagram, created_at, is_active, contact_text)
values (1,
'Somos Mas',
Expand All @@ -33,5 +31,6 @@ values (1,
1,
'¡Gracias por contactarte con Somos Más! A la brevedad vamos a estar respondiendo a tu consulta.');

insert into slide (slide_id, image_url, text, slide_order, organization_id, is_active, created_at)
values(1, 'image url', 'text', 1, 1, 1, CURRENT_DATE());
insert into category(category_id, name, description, image, created_at, is_active) values(1,'politica','for test','foo',CURRENT_DATE(),1);

insert into slide (slide_id, image_url, text, slide_order, organization_id, is_active, created_at) values(1, 'image url', 'text', 1, 1, 1, CURRENT_DATE());

0 comments on commit 8911ee6

Please sign in to comment.