2 * In Samsung Ukraine R&D Center (SRK under a contract between)
3 * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
6 package com.samsung.samserver.web.rest.controller.impl;
8 import com.samsung.samserver.SamserverApp;
9 import com.samsung.samserver.config.Constants;
10 import com.samsung.samserver.domain.*;
11 import com.samsung.samserver.repository.UserRepository;
12 import com.samsung.samserver.security.AuthoritiesConstants;
13 import com.samsung.samserver.service.*;
14 import com.samsung.samserver.service.dto.UserDTO;
15 import com.samsung.samserver.web.rest.TestUtil;
16 import com.samsung.samserver.web.rest.errors.ExceptionTranslator;
17 import com.samsung.samserver.web.rest.service.vm.*;
18 import org.apache.commons.lang3.RandomStringUtils;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.boot.test.context.SpringBootTest;
21 import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
22 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
23 import org.springframework.security.crypto.password.PasswordEncoder;
24 import org.springframework.security.test.context.support.WithMockUser;
25 import org.springframework.test.context.junit4.SpringRunner;
26 import org.springframework.test.web.servlet.*;
27 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
28 import org.springframework.transaction.annotation.Transactional;
29 import org.junit.runner.RunWith;
33 import static com.samsung.samserver.web.rest.TestUtil.createFormattingConversionService;
34 import static org.assertj.core.api.Assertions.assertThat;
35 import static org.hamcrest.Matchers.*;
36 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
37 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
38 import static com.samsung.samserver.web.rest.controller.impl.SampleObject.*;
41 * Test class for the Dashboard REST controller.
43 * @see RestDashboardTest
45 @RunWith(SpringRunner.class)
46 @SpringBootTest(classes = SamserverApp.class)
47 public class RestDashboardTest {
50 private RestDashboard restDashboard;
53 private UserRepository userRepository;
56 private PasswordEncoder passwordEncoder;
59 private DeviceTypeService deviceTypeService;
62 private DeviceService deviceService;
65 private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
68 private ExceptionTranslator exceptionTranslator;
71 private MappingJackson2HttpMessageConverter jacksonMessageConverter;
73 private MockMvc mockMvc;
77 this.mockMvc = MockMvcBuilders.standaloneSetup(restDashboard)
78 .setCustomArgumentResolvers(pageableArgumentResolver)
79 .setControllerAdvice(exceptionTranslator)
80 .setConversionService(createFormattingConversionService())
81 .setMessageConverters(jacksonMessageConverter)
87 public void testRegisterAccount() throws Exception {
88 UIRegistration uiRegistration = createRandomUIRegistration();
89 assertThat(userRepository.findOneByLogin(uiRegistration.getEmail()).isPresent()).isFalse();
91 mockMvc.perform(post("/dashboard/auth/register")
92 .contentType(TestUtil.APPLICATION_JSON_UTF8)
93 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
94 .andExpect(status().isCreated());
95 assertThat(userRepository.findOneByLogin(uiRegistration.getEmail()).isPresent()).isTrue();
100 public void testLogin() throws Exception {
102 User user = createRandomUser();
103 assertThat(userRepository.findOneByLogin(user.getEmail()).isPresent()).isFalse();
104 user.setPassword(passwordEncoder.encode("test"));
105 userRepository.saveAndFlush(user);
106 assertThat(userRepository.findOneByLogin(user.getEmail()).isPresent()).isTrue();
108 UILogin uiLogin = new UILogin();
109 uiLogin.setEmail(user.getEmail());
110 uiLogin.setPassword("test");
111 mockMvc.perform(post("/dashboard/auth/login")
112 .contentType(TestUtil.APPLICATION_JSON_UTF8)
113 .content(TestUtil.convertObjectToJsonBytes(uiLogin)))
114 .andExpect(status().isOk())
115 .andExpect(jsonPath("$.id_token").isString())
116 .andExpect(jsonPath("$.id_token").isNotEmpty())
117 .andExpect(header().string("Authorization", not(nullValue())))
118 .andExpect(header().string("Authorization", not(isEmptyString())));
123 public void testLogout() throws Exception {
124 mockMvc.perform(delete("/dashboard/auth/logout")).andExpect(status().isOk());
129 public void testGetAllDevices() throws Exception {
131 Device device = createRandomDevice();
132 assertThat(deviceService.findOne(device.getDuid()).isPresent()).isFalse();
133 deviceTypeService.save(device.getDtype());
134 deviceService.save(device);
135 assertThat(deviceService.findOne(device.getDuid()).isPresent()).isTrue();
137 int c = deviceService.findAll().size();
138 String p = "$.[?(@.id=="+device.getId()+")]";
139 mockMvc.perform(get("/dashboard/devices"))
140 .andExpect(status().isOk())
141 .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
142 .andExpect(jsonPath("$", hasSize(c)))
143 .andExpect(jsonPath(p+".duid", hasItem(device.getDuid())))
144 .andExpect(jsonPath(p+".ctime", hasItem(device.getCtime().toString())))
145 .andExpect(jsonPath(p+".model", hasItem(device.getModel())))
146 .andExpect(jsonPath(p+".sn", hasItem(device.getSn())))
147 .andExpect(jsonPath(p+".os.sw", hasItem(device.getSw())))
148 .andExpect(jsonPath(p+".os.name", hasItem(device.getOsname())))
149 .andExpect(jsonPath(p+".os.version", hasItem(device.getOsver())))
150 .andExpect(jsonPath(p+".geo.ip", hasItem(device.getIpaddr())))
151 .andExpect(jsonPath(p+".type.name",hasItem(device.getDtype().getName())))
152 .andExpect(jsonPath(p+".type.descr",hasItem(device.getDtype().getDescr())))
157 public void testUpdateDevice() throws Exception {
159 Device device = createRandomDevice();
160 assertThat(deviceService.findOne(device.getDuid()).isPresent()).isFalse();
161 deviceTypeService.save(device.getDtype());
162 deviceService.save(device);
163 assertThat(deviceService.findOne(device.getDuid()).isPresent()).isTrue();
165 UIDeviceUpdate uiDeviceUpdate = createUIDeviceUpdate(device.getId());;
167 mockMvc.perform(put("/dashboard/devices/update")
168 .contentType(TestUtil.APPLICATION_JSON_UTF8)
169 .content(TestUtil.convertObjectToJsonBytes(uiDeviceUpdate)))
170 .andExpect(status().isOk())
171 .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
172 .andExpect(jsonPath("$", hasSize(1)))
173 .andExpect(jsonPath("$[0].locked", is(1)))
174 .andExpect(jsonPath("$[0].duid", is(device.getDuid())))
175 .andExpect(jsonPath("$[0].ctime", is(device.getCtime().toString())))
176 .andExpect(jsonPath("$[0].model", is(device.getModel())))
177 .andExpect(jsonPath("$[0].sn", is(device.getSn())))
178 .andExpect(jsonPath("$[0].os.sw", is(device.getSw())))
179 .andExpect(jsonPath("$[0].os.name", is(device.getOsname())))
180 .andExpect(jsonPath("$[0].os.version", is(device.getOsver())))
181 .andExpect(jsonPath("$[0].geo.ip", is(device.getIpaddr())))
182 .andExpect(jsonPath("$[0].type.name",is(device.getDtype().getName())))
183 .andExpect(jsonPath("$[0].type.descr",is(device.getDtype().getDescr())))
188 public void testSendDashboardLogs() throws Exception {
189 UIDashboardLog uiDashboardLog = new UIDashboardLog();
190 uiDashboardLog.setLevel("level");
191 uiDashboardLog.setMessage("message");
192 uiDashboardLog.setTimestamp("timestamp");
193 uiDashboardLog.setAdditional(new ArrayList<>());
194 mockMvc.perform(delete("/dashboard/auth/logout")
195 .contentType(TestUtil.APPLICATION_JSON_UTF8)
196 .content(TestUtil.convertObjectToJsonBytes(uiDashboardLog)))
197 .andExpect(status().isOk());
203 public void testAuthorizeWithRememberMe() throws Exception {
204 User user = new User();
205 user.setLogin("dashboard-user-remember-me@example.com");
206 user.setEmail("dashboard-user-remember-me@example.com");
207 user.setActivated(true);
208 user.setPassword(passwordEncoder.encode("test"));
210 userRepository.saveAndFlush(user);
212 UILogin login = new UILogin();
213 login.setEmail("dashboard-user-remember-me@example.com");
214 login.setPassword("test");
215 login.setRememberMe(true);
216 mockMvc.perform(post("/dashboard/auth/login")
217 .contentType(TestUtil.APPLICATION_JSON_UTF8)
218 .content(TestUtil.convertObjectToJsonBytes(login)))
219 .andExpect(status().isOk())
220 .andExpect(jsonPath("$.id_token").isString())
221 .andExpect(jsonPath("$.id_token").isNotEmpty())
222 .andExpect(header().string("Authorization", not(nullValue())))
223 .andExpect(header().string("Authorization", not(isEmptyString())));
228 public void testAuthorizeFails() throws Exception {
229 UILogin login = new UILogin();
230 login.setEmail("wrong-user@example.com");
231 login.setPassword("wrong password");
232 mockMvc.perform(post("/dashboard/auth/login")
233 .contentType(TestUtil.APPLICATION_JSON_UTF8)
234 .content(TestUtil.convertObjectToJsonBytes(login)))
235 .andExpect(status().isUnauthorized())
236 .andExpect(jsonPath("$.id_token").doesNotExist())
237 .andExpect(header().doesNotExist("Authorization"));
242 public void testRegisterInvalidLogin() throws Exception {
243 UIRegistration uiRegistration = new UIRegistration();
244 uiRegistration.setEmail("funky-log!n@example.com");
245 uiRegistration.setPassword("test");
246 uiRegistration.setFullName("Funky-fullName");
249 post("/dashboard/auth/register")
250 .contentType(TestUtil.APPLICATION_JSON_UTF8)
251 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
252 .andExpect(status().isBadRequest());
254 Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky-log!n@example.com");
255 assertThat(user.isPresent()).isFalse();
260 public void testRegisterInvalidPassword() throws Exception {
261 UIRegistration uiRegistration = createRandomUIRegistration();
262 uiRegistration.setPassword("123");
264 post("/dashboard/auth/register")
265 .contentType(TestUtil.APPLICATION_JSON_UTF8)
266 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
267 .andExpect(status().isBadRequest());
269 Optional<User> user = userRepository.findOneByEmailIgnoreCase(uiRegistration.getEmail());
270 assertThat(user.isPresent()).isFalse();
275 public void testRegisterNullPassword() throws Exception {
276 UIRegistration uiRegistration = new UIRegistration();
277 uiRegistration.setEmail("dashboard-user@example.com");
278 uiRegistration.setPassword(null);// invalid null password
279 uiRegistration.setFullName("dashboard-user-fullName");
282 post("/dashboard/auth/register")
283 .contentType(TestUtil.APPLICATION_JSON_UTF8)
284 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
285 .andExpect(status().isBadRequest());
287 Optional<User> user = userRepository.findOneByEmailIgnoreCase("dashboard-user@example.com");
288 assertThat(user.isPresent()).isFalse();
293 public void testRegisterDuplicateEmail() throws Exception {
295 UIRegistration uiRegistration = new UIRegistration();
296 uiRegistration.setEmail("dashboard-user@example.com");
297 uiRegistration.setPassword(passwordEncoder.encode("test"));
298 uiRegistration.setFullName("dashboard-user-fullName");
301 UIRegistration duplicatedRegistration = new UIRegistration();
302 duplicatedRegistration.setEmail("dashboard-user@example.com");
303 duplicatedRegistration.setPassword(passwordEncoder.encode("test"));
304 duplicatedRegistration.setFullName("dashboard-user-fullName");
308 post("/dashboard/auth/register")
309 .contentType(TestUtil.APPLICATION_JSON_UTF8)
310 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
311 .andExpect(status().isCreated());
315 post("/dashboard/auth/register")
316 .contentType(TestUtil.APPLICATION_JSON_UTF8)
317 .content(TestUtil.convertObjectToJsonBytes(duplicatedRegistration)))
318 .andExpect(status().is4xxClientError());
320 // Duplicate email - with uppercase email address
321 UIRegistration duplicatedWithUpperCaseEmailRegistration = new UIRegistration();
322 duplicatedWithUpperCaseEmailRegistration.setEmail(uiRegistration.getEmail().toUpperCase());
323 duplicatedWithUpperCaseEmailRegistration.setPassword(passwordEncoder.encode("test"));
324 duplicatedWithUpperCaseEmailRegistration.setFullName("dashboard-user-fullName");
327 post("/dashboard/auth/register")
328 .contentType(TestUtil.APPLICATION_JSON_UTF8)
329 .content(TestUtil.convertObjectToJsonBytes(duplicatedRegistration)))
330 .andExpect(status().is4xxClientError());
335 @WithMockUser("save-invalid-email")
336 public void testSaveInvalidEmail() throws Exception {
337 User user = new User();
338 user.setLogin("save-invalid-email");
339 user.setEmail("save-invalid-email@example.com");
340 user.setPassword(RandomStringUtils.random(60));
341 user.setActivated(true);
343 userRepository.saveAndFlush(user);
345 UserDTO userDTO = new UserDTO();
346 userDTO.setLogin("not-used");
347 userDTO.setFirstName("firstname");
348 userDTO.setLastName("lastname");
349 userDTO.setEmail("invalid email");
350 userDTO.setActivated(false);
351 userDTO.setImageUrl("http://placehold.it/50x50");
352 userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
353 userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
356 post("/dashboard/auth/register")
357 .contentType(TestUtil.APPLICATION_JSON_UTF8)
358 .content(TestUtil.convertObjectToJsonBytes(userDTO)))
359 .andExpect(status().isBadRequest());
361 assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
366 @WithMockUser("save-existing-email")
367 public void testSaveExistingEmail() throws Exception {
368 User user = new User();
369 user.setLogin("save-existing-email");
370 user.setEmail("save-existing-email@example.com");
371 user.setPassword(RandomStringUtils.random(60));
372 user.setActivated(true);
374 userRepository.saveAndFlush(user);
376 User anotherUser = new User();
377 anotherUser.setLogin("save-existing-email2");
378 anotherUser.setEmail("save-existing-email2@example.com");
379 anotherUser.setPassword(RandomStringUtils.random(60));
380 anotherUser.setActivated(true);
382 userRepository.saveAndFlush(anotherUser);
384 UserDTO userDTO = new UserDTO();
385 userDTO.setLogin("not-used");
386 userDTO.setFirstName("firstname");
387 userDTO.setLastName("lastname");
388 userDTO.setEmail("save-existing-email2@example.com");
389 userDTO.setActivated(false);
390 userDTO.setImageUrl("http://placehold.it/50x50");
391 userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
392 userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
395 post("/dashboard/auth/register")
396 .contentType(TestUtil.APPLICATION_JSON_UTF8)
397 .content(TestUtil.convertObjectToJsonBytes(userDTO)))
398 .andExpect(status().isBadRequest());
400 User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
401 assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");