2aad289806af972676986f41d73781f4ddc6552a
[dcaegen2/platform.git] / mod2 / auth-service / src / test / java / org / onap / dcaegen2 / platform / mod / web / AuthControllerTest.java
1 /*
2  *
3  *  * ============LICENSE_START=======================================================
4  *  *  org.onap.dcae
5  *  *  ================================================================================
6  *  *  Copyright (c) 2020 AT&T Intellectual Property. All rights reserved.
7  *  *  ================================================================================
8  *  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  *  you may not use this file except in compliance with the License.
10  *  *  You may obtain a copy of the License at
11  *  *
12  *  *       http://www.apache.org/licenses/LICENSE-2.0
13  *  *
14  *  *  Unless required by applicable law or agreed to in writing, software
15  *  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  *  See the License for the specific language governing permissions and
18  *  *  limitations under the License.
19  *  *  ============LICENSE_END=========================================================
20  *
21  */
22
23 package org.onap.dcaegen2.platform.mod.web;
24
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.google.gson.Gson;
27 import org.junit.Assert;
28 import org.junit.jupiter.api.BeforeEach;
29 import org.junit.jupiter.api.Test;
30 import org.junit.jupiter.api.extension.ExtendWith;
31 import org.mockito.Mock;
32 import org.onap.dcaegen2.platform.mod.controllers.AuthController;
33 import org.onap.dcaegen2.platform.mod.models.*;
34 import org.onap.dcaegen2.platform.mod.repositories.RoleRepository;
35 import org.onap.dcaegen2.platform.mod.repositories.UserRepository;
36 import org.onap.dcaegen2.platform.mod.security.jwt.AuthEntryPointJwt;
37 import org.onap.dcaegen2.platform.mod.security.jwt.JwtUtils;
38 import org.onap.dcaegen2.platform.mod.security.services.UserDetailsServiceImpl;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
41 import org.springframework.boot.test.context.SpringBootTest;
42 import org.springframework.boot.test.mock.mockito.MockBean;
43 import org.springframework.http.*;
44 import org.springframework.security.authentication.AuthenticationManager;
45 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
46 import org.springframework.security.core.Authentication;
47 import org.springframework.security.crypto.password.PasswordEncoder;
48 import org.springframework.security.test.context.support.WithMockUser;
49 import org.springframework.test.context.junit.jupiter.SpringExtension;
50 import org.springframework.test.web.servlet.MockMvc;
51 import org.springframework.web.client.RestTemplate;
52 import org.testng.annotations.BeforeTest;
53
54 import java.io.IOException;
55 import java.util.Optional;
56
57 import static org.hamcrest.core.IsNull.notNullValue;
58 import static org.mockito.Mockito.*;
59 import static org.onap.dcaegen2.platform.mod.objectmothers.AuthObjectMother.*;
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
61 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
62 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
63 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
64
65 /**
66  * @author
67  * @date 09/22/2020
68  * Mock Test cases for AuthenticationController
69  */
70 @WebMvcTest(AuthController.class)
71 public class AuthControllerTest {
72
73     @Autowired
74     private MockMvc mockMvc;
75
76     @MockBean
77     JwtUtils jwtUtils;
78
79     @MockBean
80     AuthenticationManager authenticationManager;
81
82     @MockBean
83     UserRepository userRepository;
84
85     @MockBean
86     RoleRepository roleRepository;
87
88     @MockBean
89     PasswordEncoder passwordEncoder;
90
91     @MockBean
92     UserDetailsServiceImpl userDetailsService;
93
94     @MockBean
95     AuthEntryPointJwt authEntryPointJwt;
96
97     @Mock
98     Authentication authentication;
99
100     @BeforeEach
101     void setUp() {
102     }
103
104
105     @Test
106     void test_signin_returnsSuccessResponse() throws Exception {
107
108         LoginRequest loginRequest = getLoginRequest();
109
110         when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()))).thenReturn(authentication);
111         when(authentication.getPrincipal()).thenReturn(getUserDetailsImpl());
112         when(jwtUtils.generateJwtToken(any())).thenReturn("Demo");
113
114         mockMvc.perform(post("/api/auth/signin")
115                 .contentType(MediaType.APPLICATION_JSON)
116                 .content(asJsonString(loginRequest)).accept(MediaType.APPLICATION_JSON))
117                 .andExpect(jsonPath("$.token", notNullValue()))
118                 .andExpect(status().isOk());
119
120         verify(authenticationManager, times(1)).authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
121         verify(jwtUtils, times(1)).generateJwtToken(any());
122     }
123
124
125     @WithMockUser(roles="ADMIN")
126     @Test
127     void test_signup_returnsSuccessResponse() throws Exception {
128
129         SignupRequest signUpRequest = getSignupRequest();
130
131         when(userRepository.existsByUsername(signUpRequest.getUsername())).thenReturn(false);
132         when(passwordEncoder.encode(signUpRequest.getPassword())).thenReturn("password");
133         when(roleRepository.findByName(anyString())).thenReturn(Optional.of(new Role()));
134         when(userRepository.save(any())).thenReturn(getModUser());
135
136         mockMvc.perform(post("/api/auth/signup")
137                 .contentType(MediaType.APPLICATION_JSON)
138                 .content(asJsonString(signUpRequest)).accept(MediaType.APPLICATION_JSON))
139                 .andExpect(jsonPath("$.message", notNullValue()))
140                 .andExpect(status().isOk());
141
142         verify(userRepository, times(1)).existsByUsername(signUpRequest.getUsername());
143         verify(passwordEncoder, times(1)).encode(signUpRequest.getPassword());
144         verify(roleRepository, times(1)).findByName(anyString());
145         verify(userRepository, times(1)).save(any());
146     }
147
148
149 }