Projekt

Obecné

Profil

Stáhnout (13.4 KB) Statistiky
| Větev: | Tag: | Revize:
1
package cz.zcu.kiv.backendapi.user;
2

    
3
import cz.zcu.kiv.backendapi.exception.ApiRequestException;
4
import cz.zcu.kiv.backendapi.user.password.PasswordDto;
5
import cz.zcu.kiv.backendapi.user.permission.PermissionDto;
6
import org.junit.jupiter.api.BeforeEach;
7
import org.junit.jupiter.api.Test;
8
import org.junit.jupiter.api.extension.ExtendWith;
9
import org.mockito.ArgumentCaptor;
10
import org.mockito.Mock;
11
import org.mockito.junit.jupiter.MockitoExtension;
12
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13
import org.springframework.security.core.Authentication;
14
import org.springframework.security.core.context.SecurityContext;
15
import org.springframework.security.core.context.SecurityContextHolder;
16
import org.springframework.security.core.userdetails.UsernameNotFoundException;
17
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
18

    
19
import java.util.Collections;
20
import java.util.List;
21
import java.util.Optional;
22

    
23
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
24
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
25
import static org.junit.jupiter.api.Assertions.assertTrue;
26
import static org.mockito.ArgumentMatchers.anyString;
27
import static org.mockito.BDDMockito.given;
28
import static org.mockito.Mockito.*;
29

    
30
@ExtendWith(MockitoExtension.class)
31
class UserServiceImplTest {
32

    
33
    @Mock
34
    private UserRepository userRepository;
35

    
36
    @Mock
37
    private BCryptPasswordEncoder bCryptPasswordEncoder;
38

    
39
    private UserServiceImpl underTest;
40

    
41
    @BeforeEach
42
    void setUp() {
43
        underTest = new UserServiceImpl(userRepository, bCryptPasswordEncoder);
44
    }
45

    
46
    @Test
47
    void testCanLoadUserByUsername() {
48
        // given
49
        String email = "test@test.com";
50
        UserEntity userEntity = new UserEntity("John Doe", email, "password", (byte) 1, false);
51
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
52

    
53
        // when
54
        UserEntity user = (UserEntity) underTest.loadUserByUsername(email);
55

    
56
        // then
57
        verify(userRepository).findByEmail(email);
58
        assertThat(user).isEqualTo(userEntity);
59
    }
60

    
61
    @Test
62
    void testCanNotLoadUserByUsername() {
63
        String email = "test@test.com";
64

    
65
        // when
66
        // then
67
        assertThatThrownBy(() -> underTest.loadUserByUsername(email))
68
                .isInstanceOf(UsernameNotFoundException.class)
69
                .hasMessageContaining("User with username " + email + " not found");
70

    
71
        verify(userRepository).findByEmail(email);
72
    }
73

    
74
    @Test
75
    void testCanGetUserByName() {
76
        // given
77
        String email = "test@test.com";
78
        UserEntity userEntity = new UserEntity("John Doe", email, "password", (byte) 1, false);
79
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
80

    
81
        // when
82
        UserEntity user = underTest.getUserByName(email);
83

    
84
        // then
85
        verify(userRepository).findByEmail(email);
86
        assertThat(user).isEqualTo(userEntity);
87
    }
88

    
89
    @Test
90
    void testCanNotGetUserByName() {
91
        String email = "test@test.com";
92

    
93
        // when
94
        // then
95
        assertThatThrownBy(() -> underTest.getUserByName(email))
96
                .isInstanceOf(UsernameNotFoundException.class)
97
                .hasMessageContaining("User with username " + email + " not found");
98

    
99
        verify(userRepository).findByEmail(email);
100
    }
101

    
102
    @Test
103
    void canRegisterNewUser() {
104
        // given
105
        String email = "test@test.com";
106
        String password = "password";
107
        UserDto userDto = new UserDto("John Doe", email, new PermissionDto(), new PasswordDto(password, password));
108
        UserEntity userEntity = new UserEntity(userDto.getName(), userDto.getEmail(), bCryptPasswordEncoder.encode(password), (byte) 0, false);
109
        // when
110
        underTest.registerNewUser(userDto);
111

    
112
        // then
113
        ArgumentCaptor<UserEntity> argumentCaptor = ArgumentCaptor.forClass(UserEntity.class);
114

    
115
        verify(userRepository).save(argumentCaptor.capture());
116

    
117
        UserEntity capturedUser = argumentCaptor.getValue();
118

    
119
        assertThat(capturedUser).isEqualTo(userEntity);
120
    }
121

    
122
    @Test
123
    void canNotRegisterNewUser() {
124
        // given
125
        String email = "test@test.com";
126
        String password = "password";
127
        UserDto userDto = new UserDto("John Doe", email, new PermissionDto(), new PasswordDto(password, password));
128

    
129

    
130
        given(userRepository.findByEmail(anyString())).willReturn(Optional.of(new UserEntity()));
131

    
132
        // when
133
        // then
134
        assertThatThrownBy(() -> underTest.registerNewUser(userDto))
135
                .isInstanceOf(ApiRequestException.class)
136
                .hasMessageContaining("User with username " + email + " already exists");
137

    
138
        verify(userRepository, never()).save(any());
139
    }
140

    
141
    @Test
142
    void testCanUpdatePermissions() {
143
        // given
144
        String email = "test@test.com";
145
        String password = "password";
146
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(password), (byte) 0, false);
147
        UserEntity userEntityWithChangedPermissions = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(password), (byte) 7, false);
148
        PermissionDto permissionDto = new PermissionDto(true, true, true);
149
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
150

    
151
        // when
152
        underTest.updatePermissions(email, permissionDto);
153

    
154
        // then
155
        ArgumentCaptor<UserEntity> argumentCaptor = ArgumentCaptor.forClass(UserEntity.class);
156

    
157
        verify(userRepository).save(argumentCaptor.capture());
158

    
159
        UserEntity capturedUser = argumentCaptor.getValue();
160

    
161
        assertThat(capturedUser).isEqualTo(userEntityWithChangedPermissions);
162
    }
163

    
164
    @Test
165
    void testCanNotUpdatePermissions() {
166
        // given
167
        String email = "test@test.com";
168
        PermissionDto permissionDto = new PermissionDto();
169
        given(userRepository.findByEmail(anyString())).willReturn(Optional.empty());
170

    
171
        // when
172
        // then
173
        assertThatThrownBy(() -> underTest.updatePermissions(email, permissionDto))
174
                .isInstanceOf(UsernameNotFoundException.class)
175
                .hasMessageContaining("User with username " + email + " not found");
176

    
177
        verify(userRepository, never()).save(any());
178
    }
179

    
180
    @Test
181
    void testCanResetPassword() {
182
        // given
183
        String email = "test@test.com";
184
        String password = "password";
185
        String newPassword = "password123";
186
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(password), (byte) 0, false);
187
        UserEntity userEntityWithChangedPassword = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(newPassword), (byte) 0, false);
188
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
189

    
190
        // when
191
        underTest.resetPassword(email, newPassword);
192

    
193
        // then
194
        ArgumentCaptor<UserEntity> argumentCaptor = ArgumentCaptor.forClass(UserEntity.class);
195

    
196
        verify(userRepository).save(argumentCaptor.capture());
197

    
198
        UserEntity capturedUser = argumentCaptor.getValue();
199

    
200
        assertThat(capturedUser).isEqualTo(userEntityWithChangedPassword);
201
    }
202

    
203
    @Test
204
    void testCanNotResetPassword() {
205
        // given
206
        String email = "test@test.com";
207
        String newPassword = "password123";
208
        given(userRepository.findByEmail(anyString())).willReturn(Optional.empty());
209

    
210
        // when
211
        // then
212
        assertThatThrownBy(() -> underTest.resetPassword(email, newPassword))
213
                .isInstanceOf(UsernameNotFoundException.class)
214
                .hasMessageContaining("User with username " + email + " not found");
215

    
216
        verify(userRepository, never()).save(any());
217
    }
218

    
219
    @Test
220
    void testCanDeleteUser() {
221
        // given
222
        String email = "test@test.com";
223
        UserEntity userEntity = new UserEntity("John Doe", email, "", (byte) 0, false);
224
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
225

    
226
        // when
227
        underTest.deleteUser(email);
228

    
229
        // then
230
        verify(userRepository).delete(userEntity);
231
    }
232

    
233
    @Test
234
    void testCanNotDeleteUser() {
235
        // given
236
        String email = "test@test.com";
237
        given(userRepository.findByEmail(email)).willReturn(Optional.empty());
238

    
239
        // when
240
        assertThatThrownBy(() -> underTest.deleteUser(email))
241
                .isInstanceOf(UsernameNotFoundException.class)
242
                .hasMessageContaining("User with username " + email + " not found");
243

    
244
        // then
245
        verify(userRepository, never()).delete(any());
246
    }
247

    
248
    @Test
249
    void testCanNotDeleteUserAdmin() {
250
        // given
251
        String email = "test@test.com";
252
        UserEntity userEntity = new UserEntity("John Doe", email, "", (byte) 0, true);
253
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
254

    
255
        // when
256
        assertThatThrownBy(() -> underTest.deleteUser(email))
257
                .isInstanceOf(ApiRequestException.class)
258
                .hasMessageContaining("User with ADMIN rights can not be deleted");
259

    
260
        // then
261
        verify(userRepository, never()).delete(any());
262
    }
263

    
264
    @Test
265
    void getAllUsers() {
266
        // given
267
        UserEntity userEntity1 = new UserEntity("first", "first@test.com", "password", (byte) 0, false);
268
        UserEntity userEntity2 = new UserEntity("second", "second@test.com", "password2", (byte) 1, false);
269
        UserEntity userEntity3 = new UserEntity("third", "third@test.com", "password3", (byte) 7, true);
270

    
271
        UserDto userDto1 = new UserDto("first", "first@test.com", new PermissionDto(), null);
272
        UserDto userDto2 = new UserDto("second", "second@test.com", new PermissionDto(true, false, false), null);
273
        UserDto userDto3 = new UserDto("third", "third@test.com", new PermissionDto(true, true, true), null);
274

    
275
        given(userRepository.findAll()).willReturn(List.of(userEntity1, userEntity2, userEntity3));
276

    
277
        // when
278
        List<UserDto> allUsers = underTest.getAllUsers();
279

    
280
        // then
281
        assertThat(allUsers.size()).isEqualTo(3);
282
        assertTrue(allUsers.contains(userDto1));
283
        assertTrue(allUsers.contains(userDto2));
284
        assertTrue(allUsers.contains(userDto3));
285

    
286

    
287
        verify(userRepository).findAll();
288
    }
289

    
290
    @Test
291
    void testCanChangePassword() {
292
        // given
293
        String email = "test@test.com";
294
        String oldPassword = "password";
295
        String newPassword = "password123";
296
        given(bCryptPasswordEncoder.encode(oldPassword)).willReturn("encodedOldPassword");
297
        given(bCryptPasswordEncoder.encode(newPassword)).willReturn("encodedNewPassword");
298
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(oldPassword), (byte) 0, false);
299
        UserEntity userEntityWithChangedPassword = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(newPassword), (byte) 0, false);
300
        given(bCryptPasswordEncoder.matches(any(), any())).willReturn(true);
301
        SecurityContext securityContext = mock(SecurityContext.class);
302
        Authentication authentication = mock(Authentication.class);
303
        given(securityContext.getAuthentication()).willReturn(authentication);
304
        SecurityContextHolder.setContext(securityContext);
305
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, null, Collections.emptySet());
306
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
307
        given(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).willReturn(email);
308
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
309
        // when
310
        underTest.changePassword(oldPassword, newPassword);
311

    
312
        // then
313
        ArgumentCaptor<UserEntity> argumentCaptor = ArgumentCaptor.forClass(UserEntity.class);
314

    
315
        verify(userRepository).save(argumentCaptor.capture());
316

    
317
        UserEntity capturedUser = argumentCaptor.getValue();
318

    
319
        assertThat(capturedUser).isEqualTo(userEntityWithChangedPassword);
320
    }
321

    
322
    @Test
323
    void testCanNotChangePassword() {
324
        // given
325
        String email = "test@test.com";
326
        String oldPassword = "password";
327
        String newPassword = "password123";
328
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(oldPassword), (byte) 0, false);
329
        given(bCryptPasswordEncoder.matches(any(), any())).willReturn(false);
330
        SecurityContext securityContext = mock(SecurityContext.class);
331
        Authentication authentication = mock(Authentication.class);
332
        given(securityContext.getAuthentication()).willReturn(authentication);
333
        SecurityContextHolder.setContext(securityContext);
334
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, null, Collections.emptySet());
335
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
336
        given(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).willReturn(email);
337
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
338

    
339
        // when
340
        // then
341
        assertThatThrownBy(() -> underTest.changePassword(oldPassword, newPassword))
342
                .isInstanceOf(ApiRequestException.class)
343
                .hasMessageContaining("Old password does not match");
344

    
345
        verify(userRepository, never()).save(any());
346
    }
347
}
(2-2/2)