Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 7b891bc9

Přidáno uživatelem Jakub Šmíd před asi 3 roky(ů)

Added another unit tests
- for catalog, title page and user service
re #9363

Zobrazit rozdíly:

backend/src/main/java/cz/zcu/kiv/backendapi/alternativename/AlternativeName.java
1 1
package cz.zcu.kiv.backendapi.alternativename;
2 2

  
3 3
import cz.zcu.kiv.backendapi.catalog.CatalogEntry;
4
import lombok.AllArgsConstructor;
5
import lombok.Data;
6
import lombok.EqualsAndHashCode;
7
import lombok.NoArgsConstructor;
4
import lombok.*;
8 5

  
9 6
import javax.persistence.*;
10 7
import java.io.Serializable;
......
14 11
 */
15 12
@Data
16 13
@EqualsAndHashCode(exclude = "catalog")
14
@ToString(exclude = "catalog")
17 15
@NoArgsConstructor
18 16
@AllArgsConstructor
19 17
@Entity
backend/src/main/java/cz/zcu/kiv/backendapi/bibliography/Bibliography.java
1 1
package cz.zcu.kiv.backendapi.bibliography;
2 2

  
3 3
import cz.zcu.kiv.backendapi.catalog.CatalogEntry;
4
import lombok.AllArgsConstructor;
5
import lombok.Data;
6
import lombok.EqualsAndHashCode;
7
import lombok.NoArgsConstructor;
4
import lombok.*;
8 5

  
9 6
import javax.persistence.*;
10 7
import java.io.Serializable;
......
14 11
 */
15 12
@Data
16 13
@EqualsAndHashCode(exclude = "catalog")
14
@ToString(exclude = "catalog")
17 15
@NoArgsConstructor
18 16
@AllArgsConstructor
19 17
@Entity
backend/src/main/java/cz/zcu/kiv/backendapi/catalog/CatalogEntryServiceImpl.java
88 88

  
89 89
    @Override
90 90
    public void deleteCatalogEntry(UUID id) {
91
        CatalogEntry catalogEntry = catalogEntryRepository.findById(id).orElseThrow(() -> {
91
        if (!catalogEntryRepository.existsById(id)) {
92 92
            log.error(CATALOG_ENTRY_NOT_FOUND);
93 93
            throw new ApiRequestException(CATALOG_ENTRY_NOT_FOUND, HttpStatus.NOT_FOUND);
94
        });
95
        catalogEntryRepository.delete(catalogEntry);
94
        }
95
        catalogEntryRepository.deleteById(id);
96 96
        log.info("Catalog entry deleted");
97 97
    }
98 98

  
......
126 126
    /**
127 127
     * Converts catalog DTO to catalog entity
128 128
     *
129
     * @param catalogEntryDto    catalog DTO
130
     * @param catalogEntry catalog entity
129
     * @param catalogEntryDto catalog DTO
130
     * @param catalogEntry    catalog entity
131 131
     */
132 132
    private void convertDtoToEntity(CatalogEntryDto catalogEntryDto, CatalogEntry catalogEntry) {
133 133
        catalogEntry.setName(catalogEntryDto.getName());
backend/src/main/java/cz/zcu/kiv/backendapi/country/Country.java
1 1
package cz.zcu.kiv.backendapi.country;
2 2

  
3 3
import cz.zcu.kiv.backendapi.catalog.CatalogEntry;
4
import lombok.AllArgsConstructor;
5
import lombok.Data;
6
import lombok.EqualsAndHashCode;
7
import lombok.NoArgsConstructor;
4
import lombok.*;
8 5

  
9 6
import javax.persistence.*;
10 7
import java.io.Serializable;
......
14 11
 */
15 12
@Data
16 13
@EqualsAndHashCode(exclude = "catalog")
14
@ToString(exclude = "catalog")
17 15
@NoArgsConstructor
18 16
@AllArgsConstructor
19 17
@Entity
backend/src/main/java/cz/zcu/kiv/backendapi/security/SecurityConfig.java
3 3
import cz.zcu.kiv.backendapi.security.jwt.JwtTokenVerifier;
4 4
import cz.zcu.kiv.backendapi.security.jwt.JwtUsernameAndPasswordAuthenticationFilter;
5 5
import cz.zcu.kiv.backendapi.security.jwt.JwtUtils;
6
import cz.zcu.kiv.backendapi.user.Permission;
6
import cz.zcu.kiv.backendapi.user.permission.Permission;
7 7
import cz.zcu.kiv.backendapi.user.Role;
8 8
import lombok.RequiredArgsConstructor;
9 9
import org.springframework.context.annotation.Bean;
backend/src/main/java/cz/zcu/kiv/backendapi/user/IUserService.java
42 42
    /**
43 43
     * Changes password of the user
44 44
     *
45
     * @param oldPassword old poasswort
46
     * @param passwordDto password DTO containing new password and confirmation password
45
     * @param oldPassword old password
46
     * @param newPassword new password
47 47
     */
48
    void changePassword(String oldPassword, PasswordDto passwordDto);
48
    void changePassword(String oldPassword, String newPassword);
49 49

  
50 50
    /**
51 51
     * Updates permissions to given user
backend/src/main/java/cz/zcu/kiv/backendapi/user/Permission.java
1
package cz.zcu.kiv.backendapi.user;
2

  
3
import lombok.Getter;
4

  
5
/**
6
 * Enum of permission with given name end byte value which is used to extract permission from number
7
 */
8
@Getter
9
public enum Permission {
10
    READ("READ", (byte) 0x1),
11
    WRITE("WRITE", (byte) 0x2),
12
    DELETE("DELETE", (byte) 0x4);
13

  
14
    /**
15
     * Permission name
16
     */
17
    private final String name;
18

  
19
    /**
20
     * Hexadecimal number containing only one bit set to 1 (corresponds to given permission)
21
     */
22
    private final byte bit;
23

  
24
    /**
25
     * Creates new permission with given name and byte value
26
     *
27
     * @param name name
28
     * @param bit  byte value
29
     */
30
    Permission(String name, byte bit) {
31
        this.name = name;
32
        this.bit = bit;
33
    }
34
}
backend/src/main/java/cz/zcu/kiv/backendapi/user/UserController.java
66 66
     */
67 67
    @PatchMapping("/user/change-password")
68 68
    public void changePassword(@Valid @NotNull(message = "Old password must not be null") @RequestParam String oldPassword, @RequestBody @Valid PasswordDto passwordDto) {
69
        userService.changePassword(oldPassword, passwordDto);
69
        userService.changePassword(oldPassword, passwordDto.getPassword());
70 70
    }
71 71

  
72 72
    /**
backend/src/main/java/cz/zcu/kiv/backendapi/user/UserDto.java
3 3
import cz.zcu.kiv.backendapi.user.password.PasswordDto;
4 4
import cz.zcu.kiv.backendapi.validation.PasswordMatches;
5 5
import cz.zcu.kiv.backendapi.validation.ValidEmail;
6
import lombok.AllArgsConstructor;
6 7
import lombok.Data;
7 8
import cz.zcu.kiv.backendapi.user.permission.PermissionDto;
9
import lombok.NoArgsConstructor;
8 10

  
9 11
import javax.validation.Valid;
10 12
import javax.validation.constraints.NotEmpty;
......
15 17
 * User data object
16 18
 */
17 19
@Data
20
@NoArgsConstructor
21
@AllArgsConstructor
18 22
@PasswordMatches
19 23
public class UserDto {
20 24
    /**
backend/src/main/java/cz/zcu/kiv/backendapi/user/UserEntity.java
1 1
package cz.zcu.kiv.backendapi.user;
2 2

  
3
import lombok.AllArgsConstructor;
3
import cz.zcu.kiv.backendapi.user.permission.Permission;
4 4
import lombok.Data;
5 5
import lombok.NoArgsConstructor;
6 6
import org.hibernate.annotations.Type;
backend/src/main/java/cz/zcu/kiv/backendapi/user/UserServiceImpl.java
2 2

  
3 3
import cz.zcu.kiv.backendapi.exception.ApiRequestException;
4 4
import cz.zcu.kiv.backendapi.user.password.PasswordDto;
5
import cz.zcu.kiv.backendapi.user.permission.Permission;
5 6
import lombok.RequiredArgsConstructor;
6 7
import lombok.extern.slf4j.Slf4j;
7 8
import org.springframework.http.HttpStatus;
......
52 53

  
53 54
    @Override
54 55
    public UserEntity getUserByName(String username) {
55
        return userRepository.findByEmail(username).orElseThrow(() -> {
56
            log.error(String.format(USER_NOT_FOUND, username));
57
            throw new UsernameNotFoundException(String.format(USER_NOT_FOUND, username));
58
        });
56
        return userRepository.findByEmail(username).
57
                orElseThrow(() -> {
58
                    log.error(String.format(USER_NOT_FOUND, username));
59
                    throw new UsernameNotFoundException(String.format(USER_NOT_FOUND, username));
60
                });
59 61
    }
60 62

  
61 63
    @Override
......
71 73

  
72 74
    @Override
73 75
    public void updatePermissions(String username, PermissionDto permissionDto) {
74
        UserEntity userEntity = userRepository.findByEmail(username).orElseThrow(() ->{
76
        UserEntity userEntity = userRepository.findByEmail(username).orElseThrow(() -> {
75 77
            log.error(String.format(USER_NOT_FOUND, username));
76 78
            throw new UsernameNotFoundException(String.format(USER_NOT_FOUND, username));
77 79
        });
78 80
        userEntity.setPermissions(getPermissionsFromDto(permissionDto));
79
        userEntity.setEmail(username);
80 81
        userRepository.save(userEntity);
81 82
    }
82 83

  
......
93 94
    //TODO maybe check if user is not deleting himself - or it might be ok
94 95
    @Override
95 96
    public void deleteUser(String username) {
96
        UserEntity userEntity = userRepository.findByEmail(username).orElseThrow(() ->{
97
        if (!userRepository.existsById(username)) {
97 98
            log.error(String.format(USER_NOT_FOUND, username));
98 99
            throw new UsernameNotFoundException(String.format(USER_NOT_FOUND, username));
99
        });
100
        userRepository.delete(userEntity);
100
        }
101
        userRepository.deleteById(username);
101 102
    }
102 103

  
103 104
    @Override
......
106 107
    }
107 108

  
108 109
    @Override
109
    public void changePassword(String oldPassword, PasswordDto passwordDto) {
110
    public void changePassword(String oldPassword, String newPassword) {
110 111
        UserEntity loggedUser = getUserByName((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
111 112
        if (!bCryptPasswordEncoder.matches(oldPassword, loggedUser.getPassword())) {
112 113
            throw new ApiRequestException("Old password does not match", HttpStatus.BAD_REQUEST);
113 114
        }
114
        loggedUser.setPassword(bCryptPasswordEncoder.encode(passwordDto.getPassword()));
115
        loggedUser.setPassword(bCryptPasswordEncoder.encode(newPassword));
115 116
        userRepository.save(loggedUser);
116 117
    }
117 118

  
118 119

  
119

  
120 120
    /**
121 121
     * Converts user DTO to user entity
122 122
     *
backend/src/main/java/cz/zcu/kiv/backendapi/user/password/PasswordDto.java
2 2

  
3 3
import com.fasterxml.jackson.annotation.JsonIgnore;
4 4
import cz.zcu.kiv.backendapi.validation.PasswordMatches;
5
import lombok.AllArgsConstructor;
5 6
import lombok.Data;
6 7
import lombok.NoArgsConstructor;
7 8

  
......
15 16
@Data
16 17
@PasswordMatches
17 18
@NoArgsConstructor
19
@AllArgsConstructor
18 20
public class PasswordDto {
19 21
    /**
20 22
     * Minimal length for password
backend/src/main/java/cz/zcu/kiv/backendapi/user/permission/Permission.java
1
package cz.zcu.kiv.backendapi.user.permission;
2

  
3
import lombok.Getter;
4

  
5
/**
6
 * Enum of permission with given name end byte value which is used to extract permission from number
7
 */
8
@Getter
9
public enum Permission {
10
    READ("READ", (byte) 0x1),
11
    WRITE("WRITE", (byte) 0x2),
12
    DELETE("DELETE", (byte) 0x4);
13

  
14
    /**
15
     * Permission name
16
     */
17
    private final String name;
18

  
19
    /**
20
     * Hexadecimal number containing only one bit set to 1 (corresponds to given permission)
21
     */
22
    private final byte bit;
23

  
24
    /**
25
     * Creates new permission with given name and byte value
26
     *
27
     * @param name name
28
     * @param bit  byte value
29
     */
30
    Permission(String name, byte bit) {
31
        this.name = name;
32
        this.bit = bit;
33
    }
34
}
backend/src/main/java/cz/zcu/kiv/backendapi/user/permission/PermissionDto.java
1 1
package cz.zcu.kiv.backendapi.user.permission;
2 2

  
3
import lombok.AllArgsConstructor;
3 4
import lombok.Data;
5
import lombok.NoArgsConstructor;
4 6

  
5 7
/**
6 8
 * Permission DTO
7 9
 */
8 10
@Data
11
@NoArgsConstructor
12
@AllArgsConstructor
9 13
public class PermissionDto {
10 14
    /**
11 15
     * Whether user has 'READ' authority
backend/src/main/java/cz/zcu/kiv/backendapi/writtenform/WrittenForm.java
1 1
package cz.zcu.kiv.backendapi.writtenform;
2 2

  
3 3
import cz.zcu.kiv.backendapi.catalog.CatalogEntry;
4
import lombok.AllArgsConstructor;
5
import lombok.Data;
6
import lombok.EqualsAndHashCode;
7
import lombok.NoArgsConstructor;
4
import lombok.*;
8 5

  
9 6
import javax.persistence.*;
10 7
import java.io.Serializable;
......
14 11
 */
15 12
@Data
16 13
@EqualsAndHashCode(exclude = "catalog")
14
@ToString(exclude = "catalog")
17 15
@NoArgsConstructor
18 16
@AllArgsConstructor
19 17
@Entity
backend/src/test/java/cz/zcu/kiv/backendapi/catalog/CatalogEntryServiceImplTest.java
1
package cz.zcu.kiv.backendapi.catalog;
2

  
3
import cz.zcu.kiv.backendapi.alternativename.AlternativeName;
4
import cz.zcu.kiv.backendapi.bibliography.Bibliography;
5
import cz.zcu.kiv.backendapi.country.Country;
6
import cz.zcu.kiv.backendapi.exception.ApiRequestException;
7
import cz.zcu.kiv.backendapi.type.Type;
8
import cz.zcu.kiv.backendapi.type.TypeServiceImpl;
9
import cz.zcu.kiv.backendapi.writtenform.WrittenForm;
10
import org.junit.jupiter.api.BeforeEach;
11
import org.junit.jupiter.api.Test;
12
import org.junit.jupiter.api.extension.ExtendWith;
13
import org.mockito.*;
14
import org.mockito.junit.jupiter.MockitoExtension;
15

  
16
import java.util.List;
17
import java.util.Optional;
18
import java.util.Set;
19
import java.util.UUID;
20

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

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

  
33
    @Mock
34
    private CatalogEntryRepository catalogEntryRepository;
35

  
36
    @Mock
37
    private TypeServiceImpl typeService;
38

  
39

  
40
    private CatalogEntryServiceImpl underTest;
41

  
42
    @BeforeEach
43
    void setUp() {
44
        underTest = new CatalogEntryServiceImpl(catalogEntryRepository, typeService);
45
    }
46

  
47
    @Test
48
    void saveCatalog() {
49
        // given
50
        Type type = new Type("type");
51

  
52
        CatalogEntry catalogEntry = new CatalogEntry();
53
        catalogEntry.setName("aaacbbbbbbbaa");
54
        catalogEntry.setBibliography(Set.of(new Bibliography("bibl", catalogEntry)));
55
        catalogEntry.setTypes(Set.of(type));
56
        catalogEntry.setAlternativeNames(Set.of(new AlternativeName("altName", catalogEntry)));
57
        catalogEntry.setCountries(Set.of(new Country("aaaabbaa", catalogEntry)));
58
        catalogEntry.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry)));
59
        catalogEntry.setCertainty(0);
60
        catalogEntry.setLatitude(0.1);
61
        catalogEntry.setLongitude(0.2);
62

  
63
        CatalogEntry catalogEntry2 = new CatalogEntry();
64
        catalogEntry2.setName("name");
65
        catalogEntry2.setBibliography(Set.of(new Bibliography("bibl", catalogEntry2)));
66
        catalogEntry2.setTypes(Set.of(type));
67
        catalogEntry2.setAlternativeNames(Set.of(new AlternativeName("aaaabbbbbbaa", catalogEntry2)));
68
        catalogEntry2.setCountries(Set.of(new Country("aaaabbcccefaa", catalogEntry2)));
69
        catalogEntry2.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry2)));
70
        catalogEntry2.setCertainty(1);
71
        catalogEntry2.setLatitude(1.1);
72
        catalogEntry2.setLongitude(1.2);
73

  
74
        List<CatalogEntry> catalog = List.of(catalogEntry, catalogEntry2);
75

  
76
        given(typeService.getTypeByName(anyString())).willReturn(Optional.of(type));
77

  
78
        // when
79
        underTest.saveCatalog(catalog);
80

  
81
        // then
82
        verify(typeService, never()).saveType(type);
83
        verify(catalogEntryRepository).save(catalogEntry);
84
        verify(catalogEntryRepository).save(catalogEntry2);
85
    }
86

  
87
    @Test
88
    void saveCatalogEntry() {
89
        // given
90
        CatalogEntryDto catalogEntryDto = new CatalogEntryDto();
91
        catalogEntryDto.setName("name");
92
        catalogEntryDto.setBibliography(Set.of("bibl"));
93
        catalogEntryDto.setTypes(Set.of("type"));
94
        catalogEntryDto.setAlternativeNames(Set.of("altName"));
95
        catalogEntryDto.setCountries(Set.of("country"));
96
        catalogEntryDto.setWrittenForms(Set.of("written"));
97
        catalogEntryDto.setCertainty(0);
98
        catalogEntryDto.setLatitude(0.1);
99
        catalogEntryDto.setLongitude(0.2);
100

  
101
        Type type = new Type("type");
102

  
103
        CatalogEntry catalogEntry = new CatalogEntry();
104
        catalogEntry.setName("name");
105
        catalogEntry.setBibliography(Set.of(new Bibliography("bibl", catalogEntry)));
106
        catalogEntry.setTypes(Set.of(type));
107
        catalogEntry.setAlternativeNames(Set.of(new AlternativeName("altName", catalogEntry)));
108
        catalogEntry.setCountries(Set.of(new Country("country", catalogEntry)));
109
        catalogEntry.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry)));
110
        catalogEntry.setCertainty(0);
111
        catalogEntry.setLatitude(0.1);
112
        catalogEntry.setLongitude(0.2);
113

  
114
        given(typeService.getTypeByName(anyString())).willReturn(Optional.of(type));
115

  
116
        // when
117
        underTest.saveCatalogEntry(catalogEntryDto);
118

  
119
        // then
120
        ArgumentCaptor<CatalogEntry> argumentCaptor = ArgumentCaptor.forClass(CatalogEntry.class);
121

  
122
        verify(catalogEntryRepository).save(argumentCaptor.capture());
123
        verify(typeService, never()).saveType(type);
124

  
125
        CatalogEntry capturedEntry = argumentCaptor.getValue();
126

  
127
        assertThat(capturedEntry).isEqualTo(catalogEntry);
128

  
129
    }
130

  
131
    @Test
132
    void testCanUpdateCatalogEntry() {
133
        // given
134
        UUID id = UUID.randomUUID();
135

  
136
        CatalogEntryDto catalogEntryDto = new CatalogEntryDto();
137
        catalogEntryDto.setName("name");
138
        catalogEntryDto.setBibliography(Set.of("bibl"));
139
        catalogEntryDto.setTypes(Set.of("type"));
140
        catalogEntryDto.setAlternativeNames(Set.of("altName"));
141
        catalogEntryDto.setCountries(Set.of("country"));
142
        catalogEntryDto.setWrittenForms(Set.of("written"));
143
        catalogEntryDto.setCertainty(0);
144
        catalogEntryDto.setLatitude(0.1);
145
        catalogEntryDto.setLongitude(0.2);
146

  
147
        Type type = new Type("type");
148
        Type typeOld = new Type("old");
149

  
150
        CatalogEntry catalogEntry = new CatalogEntry();
151
        catalogEntry.setName("name");
152
        catalogEntry.setBibliography(Set.of(new Bibliography("bibl", catalogEntry)));
153
        catalogEntry.setTypes(Set.of(type));
154
        catalogEntry.setAlternativeNames(Set.of(new AlternativeName("altName", catalogEntry)));
155
        catalogEntry.setCountries(Set.of(new Country("country", catalogEntry)));
156
        catalogEntry.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry)));
157
        catalogEntry.setCertainty(0);
158
        catalogEntry.setLatitude(0.1);
159
        catalogEntry.setLongitude(0.2);
160

  
161
        CatalogEntry oldCatalogEntry = new CatalogEntry();
162
        oldCatalogEntry.setName("old");
163
        oldCatalogEntry.setBibliography(Set.of(new Bibliography("old", oldCatalogEntry)));
164
        oldCatalogEntry.setTypes(Set.of(typeOld));
165
        oldCatalogEntry.setAlternativeNames(Set.of(new AlternativeName("old", oldCatalogEntry)));
166
        oldCatalogEntry.setCountries(Set.of(new Country("old", oldCatalogEntry)));
167
        oldCatalogEntry.setWrittenForms(Set.of(new WrittenForm("old", catalogEntry)));
168
        oldCatalogEntry.setCertainty(10);
169
        oldCatalogEntry.setLatitude(10.1);
170
        oldCatalogEntry.setLongitude(10.2);
171

  
172
        given(catalogEntryRepository.findById(id)).willReturn(Optional.of(oldCatalogEntry));
173
        given(typeService.getTypeByName(anyString())).willReturn(Optional.empty());
174

  
175
        // when
176

  
177
        underTest.updateCatalogEntry(id, catalogEntryDto);
178

  
179
        // then
180
        verify(typeService).saveType(type);
181

  
182
        ArgumentCaptor<CatalogEntry> argumentCaptor = ArgumentCaptor.forClass(CatalogEntry.class);
183

  
184
        verify(catalogEntryRepository).save(argumentCaptor.capture());
185

  
186
        CatalogEntry capturedCatalogEntry = argumentCaptor.getValue();
187

  
188
        assertThat(capturedCatalogEntry).isEqualTo(catalogEntry);
189
    }
190

  
191
    @Test
192
    void testCanNotUpdateCatalogEntry() {
193
        // given
194
        UUID id = UUID.randomUUID();
195

  
196
        CatalogEntryDto catalogEntryDto = new CatalogEntryDto();
197
        catalogEntryDto.setName("name");
198
        catalogEntryDto.setBibliography(Set.of("bibl"));
199
        catalogEntryDto.setTypes(Set.of("type"));
200
        catalogEntryDto.setAlternativeNames(Set.of("altName"));
201
        catalogEntryDto.setCountries(Set.of("country"));
202
        catalogEntryDto.setWrittenForms(Set.of("written"));
203
        catalogEntryDto.setCertainty(0);
204
        catalogEntryDto.setLatitude(0.1);
205
        catalogEntryDto.setLongitude(0.2);
206

  
207
        // when
208
        // then
209
        assertThatThrownBy(() -> underTest.updateCatalogEntry(id, catalogEntryDto))
210
                .isInstanceOf(ApiRequestException.class)
211
                .hasMessageContaining("Catalog entry not found");
212

  
213
        verify(catalogEntryRepository, never()).save(any());
214
        verify(typeService, never()).saveType(any());
215
    }
216

  
217
    @Test
218
    void testCanDeleteCatalogEntry() {
219
        // given
220
        UUID id = UUID.randomUUID();
221
        given(catalogEntryRepository.existsById(id)).willReturn(true);
222

  
223
        // when
224
        underTest.deleteCatalogEntry(id);
225

  
226
        // then
227
        verify(catalogEntryRepository).deleteById(id);
228
    }
229

  
230
    @Test
231
    void testCanNotDeleteCatalogEntry() {
232
        // given
233
        UUID id = UUID.randomUUID();
234
        given(catalogEntryRepository.existsById(id)).willReturn(false);
235

  
236
        // when
237
        // then
238
        assertThatThrownBy(() -> underTest.deleteCatalogEntry(id))
239
                .isInstanceOf(ApiRequestException.class)
240
                .hasMessageContaining("Catalog entry not found");
241

  
242
        verify(catalogEntryRepository, never()).deleteById(any());
243
    }
244

  
245
    @Test
246
    void getCatalog() {
247
        // given
248
        String name = "aaa?bb*aa";
249
        String country = "aaa?bb*aa";
250
        String type = "aaa?bb*aa";
251
        String nameChanged = "aaa_bb%aa";
252
        String countryChanged = "aaa_bb%aa";
253
        String typeChanged = "aaa_bb%aa";
254

  
255
        Type typeEntity = new Type(type);
256

  
257
        CatalogEntry catalogEntry = new CatalogEntry();
258
        catalogEntry.setName("aaacbbbbbbbaa");
259
        catalogEntry.setBibliography(Set.of(new Bibliography("bibl", catalogEntry)));
260
        catalogEntry.setTypes(Set.of(typeEntity));
261
        catalogEntry.setAlternativeNames(Set.of(new AlternativeName("altName", catalogEntry)));
262
        catalogEntry.setCountries(Set.of(new Country("aaaabbaa", catalogEntry)));
263
        catalogEntry.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry)));
264
        catalogEntry.setCertainty(0);
265
        catalogEntry.setLatitude(0.1);
266
        catalogEntry.setLongitude(0.2);
267

  
268
        CatalogEntry catalogEntry2 = new CatalogEntry();
269
        catalogEntry2.setName("name");
270
        catalogEntry2.setBibliography(Set.of(new Bibliography("bibl", catalogEntry2)));
271
        catalogEntry2.setTypes(Set.of(typeEntity));
272
        catalogEntry2.setAlternativeNames(Set.of(new AlternativeName("aaaabbbbbbaa", catalogEntry2)));
273
        catalogEntry2.setCountries(Set.of(new Country("aaaabbcccefaa", catalogEntry2)));
274
        catalogEntry2.setWrittenForms(Set.of(new WrittenForm("written", catalogEntry2)));
275
        catalogEntry2.setCertainty(1);
276
        catalogEntry2.setLatitude(1.1);
277
        catalogEntry2.setLongitude(1.2);
278

  
279
        CatalogEntryDto catalogEntryDto = new CatalogEntryDto();
280
        catalogEntryDto.setName("aaacbbbbbbbaa");
281
        catalogEntryDto.setBibliography(Set.of("bibl"));
282
        catalogEntryDto.setTypes(Set.of("aaa?bb*aa"));
283
        catalogEntryDto.setAlternativeNames(Set.of("altName"));
284
        catalogEntryDto.setCountries(Set.of("aaaabbaa"));
285
        catalogEntryDto.setWrittenForms(Set.of("written"));
286
        catalogEntryDto.setCertainty(0);
287
        catalogEntryDto.setLatitude(0.1);
288
        catalogEntryDto.setLongitude(0.2);
289

  
290
        CatalogEntryDto catalogEntryDto2 = new CatalogEntryDto();
291
        catalogEntryDto2.setName("name");
292
        catalogEntryDto2.setBibliography(Set.of("bibl"));
293
        catalogEntryDto2.setTypes(Set.of("aaa?bb*aa"));
294
        catalogEntryDto2.setAlternativeNames(Set.of("aaaabbbbbbaa"));
295
        catalogEntryDto2.setCountries(Set.of("aaaabbcccefaa"));
296
        catalogEntryDto2.setWrittenForms(Set.of("written"));
297
        catalogEntryDto2.setCertainty(1);
298
        catalogEntryDto2.setLatitude(1.1);
299
        catalogEntryDto2.setLongitude(1.2);
300

  
301
        given(catalogEntryRepository.filterCatalog(nameChanged, countryChanged, typeChanged)).willReturn(Set.of(catalogEntry, catalogEntry2));
302

  
303
        // when
304
        List<CatalogEntryDto> results = underTest.getCatalog(name, country, type);
305

  
306
        // then
307
        assertThat(results.size()).isEqualTo(2);
308
        assertTrue(results.contains(catalogEntryDto));
309
        assertTrue(results.contains(catalogEntryDto2));
310

  
311
        verify(catalogEntryRepository).filterCatalog(nameChanged, countryChanged, typeChanged);
312
    }
313
}
backend/src/test/java/cz/zcu/kiv/backendapi/titlepage/TitlePageServiceImplementationTest.java
44 44

  
45 45
        TitlePage capturedTitlePage = argumentCaptor.getValue();
46 46

  
47
        titlePage.setId(id);
47
        assertThat(capturedTitlePage.getId()).isEqualTo(id);
48 48

  
49 49
        assertThat(capturedTitlePage).isEqualTo(titlePage);
50 50

  
backend/src/test/java/cz/zcu/kiv/backendapi/user/UserServiceImplTest.java
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
        given(userRepository.existsById(email)).willReturn(true);
224
        // when
225
        underTest.deleteUser(email);
226

  
227
        // then
228
        verify(userRepository).deleteById(email);
229
    }
230

  
231
    @Test
232
    void testCanNotDeleteUser() {
233
        // given
234
        String email = "test@test.com";
235
        given(userRepository.existsById(email)).willReturn(false);
236
        // when
237
        assertThatThrownBy(() -> underTest.deleteUser(email))
238
                .isInstanceOf(UsernameNotFoundException.class)
239
                .hasMessageContaining("User with username " + email + " not found");
240

  
241
        // then
242
        verify(userRepository, never()).deleteById(email);
243
    }
244

  
245
    @Test
246
    void getAllUsers() {
247
        // given
248
        UserEntity userEntity1 = new UserEntity("first", "first@test.com", "password", (byte) 0, false);
249
        UserEntity userEntity2 = new UserEntity("second", "second@test.com", "password2", (byte) 1, false);
250
        UserEntity userEntity3 = new UserEntity("third", "third@test.com", "password3", (byte) 7, true);
251

  
252
        UserDto userDto1 = new UserDto("first", "first@test.com", new PermissionDto(), null);
253
        UserDto userDto2 = new UserDto("second", "second@test.com", new PermissionDto(true, false, false), null);
254
        UserDto userDto3 = new UserDto("third", "third@test.com", new PermissionDto(true, true, true), null);
255

  
256
        given(userRepository.findAll()).willReturn(List.of(userEntity1, userEntity2, userEntity3));
257

  
258
        // when
259
        List<UserDto> allUsers = underTest.getAllUsers();
260

  
261
        // then
262
        assertThat(allUsers.size()).isEqualTo(3);
263
        assertTrue(allUsers.contains(userDto1));
264
        assertTrue(allUsers.contains(userDto2));
265
        assertTrue(allUsers.contains(userDto3));
266

  
267

  
268
        verify(userRepository).findAll();
269
    }
270

  
271
    @Test
272
    void testCanChangePassword() {
273
        // given
274
        String email = "test@test.com";
275
        String oldPassword = "password";
276
        String newPassword = "password123";
277
        given(bCryptPasswordEncoder.encode(oldPassword)).willReturn("encodedOldPassword");
278
        given(bCryptPasswordEncoder.encode(newPassword)).willReturn("encodedNewPassword");
279
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(oldPassword), (byte) 0, false);
280
        UserEntity userEntityWithChangedPassword = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(newPassword), (byte) 0, false);
281
        given(bCryptPasswordEncoder.matches(any(), any())).willReturn(true);
282
        SecurityContext securityContext = mock(SecurityContext.class);
283
        Authentication authentication = mock(Authentication.class);
284
        given(securityContext.getAuthentication()).willReturn(authentication);
285
        SecurityContextHolder.setContext(securityContext);
286
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, null, Collections.emptySet());
287
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
288
        given(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).willReturn(email);
289
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
290
        // when
291
        underTest.changePassword(oldPassword, newPassword);
292

  
293
        // then
294
        ArgumentCaptor<UserEntity> argumentCaptor = ArgumentCaptor.forClass(UserEntity.class);
295

  
296
        verify(userRepository).save(argumentCaptor.capture());
297

  
298
        UserEntity capturedUser = argumentCaptor.getValue();
299

  
300
        assertThat(capturedUser).isEqualTo(userEntityWithChangedPassword);
301
    }
302

  
303
    @Test
304
    void testCanNotChangePassword() {
305
        // given
306
        String email = "test@test.com";
307
        String oldPassword = "password";
308
        String newPassword = "password123";
309
        UserEntity userEntity = new UserEntity("John Doe", email, bCryptPasswordEncoder.encode(oldPassword), (byte) 0, false);
310
        given(bCryptPasswordEncoder.matches(any(), any())).willReturn(false);
311
        SecurityContext securityContext = mock(SecurityContext.class);
312
        Authentication authentication = mock(Authentication.class);
313
        given(securityContext.getAuthentication()).willReturn(authentication);
314
        SecurityContextHolder.setContext(securityContext);
315
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, null, Collections.emptySet());
316
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
317
        given(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).willReturn(email);
318
        given(userRepository.findByEmail(email)).willReturn(Optional.of(userEntity));
319

  
320
        // when
321
        // then
322
        assertThatThrownBy(() -> underTest.changePassword(oldPassword, newPassword))
323
                .isInstanceOf(ApiRequestException.class)
324
                .hasMessageContaining("Old password does not match");
325

  
326
        verify(userRepository, never()).save(any());
327
    }
328
}

Také k dispozici: Unified diff