diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java b/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java index e2efea72..5799bfc8 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java @@ -1,7 +1,7 @@ package com.RDS.skilltree.Authentication; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRole; +import com.RDS.skilltree.User.JwtUserModel; +import com.RDS.skilltree.User.UserRoleEnum; import java.util.List; import javax.security.auth.Subject; import org.springframework.security.authentication.AbstractAuthenticationToken; @@ -9,11 +9,12 @@ public class UserAuthenticationToken extends AbstractAuthenticationToken { - private final UserModel user; + private final JwtUserModel user; public UserAuthenticationToken(String role, String rdsUserId) { - super(List.of(new SimpleGrantedAuthority(UserRole.fromString(role).name()))); - this.user = UserModel.builder().rdsUserId(rdsUserId).role(UserRole.fromString(role)).build(); + super(List.of(new SimpleGrantedAuthority(UserRoleEnum.fromString(role).name()))); + + this.user = new JwtUserModel(rdsUserId, UserRoleEnum.fromString(role)); setAuthenticated(true); } @@ -23,7 +24,7 @@ public Object getCredentials() { } @Override - public UserModel getPrincipal() { + public JwtUserModel getPrincipal() { return user; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java b/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java index ac4fa3dc..24c0e28a 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java @@ -3,7 +3,7 @@ import com.RDS.skilltree.Authentication.AuthEntryPoint; import com.RDS.skilltree.Authentication.CustomAccessDeniedHandler; import com.RDS.skilltree.Filters.JWTAuthenticationFilter; -import com.RDS.skilltree.User.UserRole; +import com.RDS.skilltree.User.UserRoleEnum; import java.util.Arrays; import java.util.List; import org.springframework.context.annotation.Bean; @@ -50,10 +50,10 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { && request.getQueryString().contains("dummyData=true")) .permitAll() .requestMatchers(HttpMethod.GET, "/v1/**") - .hasAnyAuthority(UserRole.getAllRoles()) // give read-only access to all + .hasAnyAuthority(UserRoleEnum.getAllRoles()) // give read-only access to all .requestMatchers("/v1/**") .hasAnyAuthority( - UserRole.USER.name(), UserRole.MEMBER.name(), UserRole.SUPERUSER.name()) + UserRoleEnum.USER.name(), UserRoleEnum.MEMBER.name(), UserRoleEnum.SUPERUSER.name()) .anyRequest() .authenticated()) .exceptionHandling( diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java index d0910431..de152bab 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java @@ -1,7 +1,9 @@ package com.RDS.skilltree.Endorsement; import jakarta.validation.constraints.NotNull; + import java.util.UUID; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -16,5 +18,5 @@ public class EndorsementDRO { private UUID endorseeId; @NotNull(message = "skill id cannot be null") - private UUID skillId; + private Integer skillId; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java index 3047e63f..e0698bb3 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java @@ -29,8 +29,6 @@ public static EndorsementDTO toDto(EndorsementModel endorsementModel) { .build(); endorsementDTO.setCreatedAt(endorsementModel.getCreatedAt()); endorsementDTO.setUpdatedAt(endorsementModel.getUpdatedAt()); - endorsementDTO.setCreatedBy(endorsementModel.getCreatedBy()); - endorsementDTO.setUpdatedBy(endorsementModel.getUpdatedBy()); return endorsementDTO; } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java index 68a3faec..19691be9 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java @@ -1,7 +1,7 @@ package com.RDS.skilltree.Endorsement; import com.RDS.skilltree.EndorsementList.EndorsementListModel; -import com.RDS.skilltree.Skill.SkillModel; +import com.RDS.skilltree.Skill.Skill; import com.RDS.skilltree.utils.TrackedProperties; import com.fasterxml.jackson.annotation.JsonManagedReference; import jakarta.persistence.*; @@ -25,9 +25,9 @@ public class EndorsementModel extends TrackedProperties { @Column(name = "endorsee_id") private UUID endorseeId; - @ManyToOne(targetEntity = SkillModel.class, cascade = CascadeType.ALL) + @ManyToOne(targetEntity = Skill.class, cascade = CascadeType.ALL) @JoinColumn(name = "skill_id", referencedColumnName = "id") - private SkillModel skill; + private Skill skill; @OneToMany(mappedBy = "endorsement") @JsonManagedReference diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java index 6da326dd..3b68c3b3 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java @@ -9,5 +9,5 @@ public interface EndorsementRepository extends JpaRepository { List findByEndorseeId(UUID userId); - List findBySkillId(UUID skillId); + List findBySkillId(Integer skillId); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java index fce1ed63..b248ed2d 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java @@ -4,18 +4,20 @@ import com.RDS.skilltree.Exceptions.EntityAlreadyExistsException; import com.RDS.skilltree.Exceptions.InvalidParameterException; import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; +import com.RDS.skilltree.Skill.Skill; import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRole; +import com.RDS.skilltree.User.JwtUserModel; +import com.RDS.skilltree.User.UserRoleEnum; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.EntityNotFoundException; + import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; + import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,7 +80,8 @@ public Page getEndorsementsFromDummyData( private List readEndorsementsFromJSON() throws IOException { ClassPathResource resource = new ClassPathResource(dummyEndorsementDataPath); return objectMapper.readValue( - resource.getInputStream(), new TypeReference>() {}); + resource.getInputStream(), new TypeReference>() { + }); } private List filterEndorsements( @@ -118,9 +121,9 @@ private Page createPagedEndorsements( @Override public EndorsementModel createEndorsement(EndorsementDRO endorsementDRO) { UUID userId = endorsementDRO.getEndorseeId(); - UUID skillId = endorsementDRO.getSkillId(); + Integer skillId = endorsementDRO.getSkillId(); - Optional skillOptional = skillRepository.findById(skillId); + Optional skillOptional = skillRepository.findById(skillId); if (skillOptional.isPresent()) { EndorsementModel endorsementModel = EndorsementModel.builder().endorseeId(userId).skill(skillOptional.get()).build(); @@ -134,9 +137,9 @@ public EndorsementModel createEndorsement(EndorsementDRO endorsementDRO) { @Override public GenericResponse updateEndorsementStatus(UUID id, String status) { - UserModel user = - (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - if (!user.getRole().equals(UserRole.SUPERUSER)) { + JwtUserModel user = + (JwtUserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + if (!user.getRole().equals(UserRoleEnum.SUPERUSER)) { throw new AccessDeniedException("Unauthorized, Access is only available to super users"); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/Skill.java similarity index 50% rename from skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java rename to skill-tree/src/main/java/com/RDS/skilltree/Skill/Skill.java index 0074c602..574674d9 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/Skill.java @@ -1,41 +1,41 @@ package com.RDS.skilltree.Skill; -import com.RDS.skilltree.User.UserModel; import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonBackReference; -import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; -import java.util.Set; -import java.util.UUID; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.UUID; + @AllArgsConstructor @NoArgsConstructor @Entity @Builder @Getter -@Table(name = "Skill") -public class SkillModel extends TrackedProperties { +@Table(name = "skills") +public class Skill extends TrackedProperties { @Id @GeneratedValue - @Column(name = "id", columnDefinition = "BINARY(16)") - private UUID id; + @Column(name = "id") + private Integer id; @Column(name = "name", unique = true, nullable = false) private String name; @Column(name = "skill_type", nullable = false) @Enumerated(value = EnumType.STRING) - private SkillType type = SkillType.ATOMIC; + private SkillTypeEnum type = SkillTypeEnum.ATOMIC; @Column(name = "is_deleted", nullable = false) - private boolean deleted; + private boolean isDeleted; + + // TODO : Confirm the type of this column from tejas + @Column(name = "created_by", nullable = false) + private UUID createdBy; - @JsonBackReference - @JsonIgnore - @ManyToMany(mappedBy = "skills", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - private Set users; + @Column(name = "updated_by") + private UUID updatedBy; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java index 543c4ace..f541daab 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java @@ -2,7 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.validation.constraints.NotNull; -import java.util.UUID; + import lombok.Builder; import lombok.Getter; @@ -14,16 +14,5 @@ public class SkillDRO { private String name; @NotNull(message = "SkillType cannot be null") - private SkillType type; - - @NotNull(message = "Created by user Id cannot be null") - private UUID createdBy; - - public static SkillModel toModel(SkillDRO skillDRO) { - return SkillModel.builder() - .name(skillDRO.getName()) - .type(skillDRO.getType()) - .deleted(false) - .build(); - } + private SkillTypeEnum type; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java index a6304e2b..b3748e35 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java @@ -2,10 +2,10 @@ import com.RDS.skilltree.User.UserDTO; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.HashSet; import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; + import lombok.Builder; import lombok.Getter; @@ -13,28 +13,26 @@ @Builder @JsonIgnoreProperties(ignoreUnknown = true) public class SkillDTO { - private UUID id; - private SkillType type; + private Integer id; + private SkillTypeEnum type; private String name; private Set users; - public static SkillDTO toDto(SkillModel skillModel) { + public static SkillDTO toDto(Skill skill) { return SkillDTO.builder() - .id(skillModel.getId()) - .name(skillModel.getName()) - .type(skillModel.getType()) + .id(skill.getId()) + .name(skill.getName()) + .type(skill.getType()) .build(); } - public static SkillDTO getSkillsWithUsers(SkillModel skillModel) { + public static SkillDTO getSkillsWithUsers(Skill skill) { Set users = new HashSet<>(); - if (skillModel.getUsers() != null) { - users = skillModel.getUsers().stream().map(UserDTO::toDTO).collect(Collectors.toSet()); - } + return SkillDTO.builder() - .id(skillModel.getId()) - .name(skillModel.getName()) - .type(skillModel.getType()) + .id(skill.getId()) + .name(skill.getName()) + .type(skill.getType()) .users(users) .build(); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java index a523a3b0..39f048dc 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java @@ -2,14 +2,11 @@ import java.util.Optional; import java.util.UUID; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface SkillRepository extends JpaRepository { - Optional findByName(String name); - - Page findAll(Pageable pageable); +public interface SkillRepository extends JpaRepository { + Optional findByName(String name); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillTypeEnum.java similarity index 57% rename from skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java rename to skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillTypeEnum.java index 32500383..0a5bc9b1 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillTypeEnum.java @@ -1,6 +1,5 @@ package com.RDS.skilltree.Skill; -public enum SkillType { +public enum SkillTypeEnum { ATOMIC, - DERIVED } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java index 00e9f669..837607a0 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java @@ -1,69 +1,61 @@ package com.RDS.skilltree.Skill; -import com.RDS.skilltree.utils.MessageResponse; +import com.RDS.skilltree.Common.Response.GenericResponse; +import com.RDS.skilltree.User.JwtUserModel; import jakarta.validation.Valid; -import jakarta.validation.constraints.Min; -import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.util.ObjectUtils; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; -@RestController +import java.time.Instant; +import java.util.List; +import java.util.UUID; + @Slf4j +@RestController @RequestMapping("/v1/skills") public class SkillsController { - private final SkillsService skillsService; + private final SkillRepository repository; - public SkillsController(SkillsService skillsService) { - this.skillsService = skillsService; + public SkillsController(SkillRepository repository) { + this.repository = repository; } - @PostMapping("/") - public ResponseEntity createSkill(@RequestBody(required = true) @Valid SkillDRO skillDRO) { - try { - return ResponseEntity.status(HttpStatus.CREATED).body(skillsService.createSkill(skillDRO)); - } catch (DataIntegrityViolationException ex) { - return ResponseEntity.status(HttpStatus.CONFLICT) - .body(new MessageResponse("Cannot create entry for Skill as Skill name is duplicate")); - } catch (Exception ex) { - log.error( - "There is some error in storing the skills, error message: {}", ex.getMessage(), ex); - throw ex; - } + @GetMapping + public GenericResponse> getAllSkills(@RequestParam(required = false) String name) { + repository.findByName(name); + return new GenericResponse<>(repository.findAll(), null); } - @GetMapping("/") - public Page getAllSkills( - @RequestParam(value = "offset", defaultValue = "0", required = false) @Min(0) int offset, - @RequestParam(value = "limit", defaultValue = "10", required = false) @Min(1) int limit) { - Pageable pageable = PageRequest.of(offset, limit); - return skillsService.getAllSkills(pageable); - } + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + // TODO : Return only the valid fields by using a DTO. + public GenericResponse createSkill(Authentication authentication, @RequestBody(required = true) @Valid SkillDRO skill) { + JwtUserModel userDetails = (JwtUserModel) authentication.getPrincipal(); - @GetMapping("/name/{name}") - public ResponseEntity getSkillByName( - @PathVariable(value = "name", required = true) String name) { - SkillDTO skillDTO = skillsService.getSkillByName(name); - if (ObjectUtils.isEmpty(skillDTO)) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new MessageResponse("Skill not found with the given name")); + // TODO : return a correct http status instead of 201 + if (repository.findByName(skill.getName()).isPresent()) { + return new GenericResponse<>(null, String.format("Skill with name %s already exists", skill.getName())); } - return ResponseEntity.ok(skillDTO); - } - @GetMapping("/{id}") - public ResponseEntity getSkillById(@PathVariable(value = "id", required = true) UUID id) { - SkillDTO skillDTO = skillsService.getSkillById(id); - if (ObjectUtils.isEmpty(skillDTO)) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new MessageResponse("Skill not found with given Id")); + Skill newSkill = Skill.builder() + .name(skill.getName()) + .type(skill.getType()) + // TODO : use the id from userDetails once login is implemented + .createdBy(UUID.fromString("ae7a6673-c557-41e0-838f-209de4c644fc")) + .isDeleted(false) + .build(); + + newSkill.setCreatedAt(Instant.now()); + + try { + return new GenericResponse<>(repository.save(newSkill), "Skill created"); + } catch (DataIntegrityViolationException error) { + log.error("Error saving skill {}, error: {}", skill.getName(), error.getMessage()); + // TODO : return a correct http status instead of 201 + return new GenericResponse<>(null, "Something went wrong please try again"); } - return ResponseEntity.ok(skillDTO); } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java deleted file mode 100644 index b8a4e015..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.RDS.skilltree.Skill; - -import java.util.UUID; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -public interface SkillsService { - SkillDTO getSkillById(UUID id); - - SkillDTO getSkillByName(String skillName); - - Page getAllSkills(Pageable pageable); - - SkillDTO createSkill(SkillDRO skillDRO); -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java deleted file mode 100644 index 61943723..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.RDS.skilltree.User.UserRepository; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - -@Service -@Slf4j -@RequiredArgsConstructor -public class SkillsServiceImpl implements SkillsService { - private final SkillRepository skillRepository; - private final UserRepository userRepository; - - @Override - public SkillDTO getSkillById(UUID id) { - Optional skillModel = skillRepository.findById(id); - return skillModel.map(SkillDTO::getSkillsWithUsers).orElse(null); - } - - @Override - public SkillDTO getSkillByName(String skillName) { - Optional skillModel = skillRepository.findByName(skillName); - return skillModel.map(SkillDTO::getSkillsWithUsers).orElse(null); - } - - @Override - public Page getAllSkills(Pageable pageable) { - Page skillModels = skillRepository.findAll(pageable); - return skillModels.map(SkillDTO::getSkillsWithUsers); - } - - @Override - public SkillDTO createSkill(SkillDRO skillDRO) { - SkillModel newSkill = SkillDRO.toModel(skillDRO); - newSkill.setCreatedAt(Instant.now()); - newSkill.setUpdatedAt(Instant.now()); - - try { - skillRepository.save(newSkill); - } catch (DataIntegrityViolationException ex) { - log.error( - "Error saving the skills object with name : {}, with exception :{}", - skillDRO.getName(), - ex.getMessage(), - ex); - throw ex; - } - return SkillDTO.toDto(newSkill); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java new file mode 100644 index 00000000..29b92988 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java @@ -0,0 +1,14 @@ +package com.RDS.skilltree.User; + +import lombok.Getter; + +@Getter +public class JwtUserModel { + private final String rdsUserId; + private final UserRoleEnum role; + + public JwtUserModel(String rdsUserId, UserRoleEnum role) { + this.role = role; + this.rdsUserId = rdsUserId; + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java index c0141963..aff3097e 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java @@ -20,25 +20,19 @@ public class UserDRO { private URL imageUrl; - private UserRole role; + private UserRoleEnum role; public static UserModel toModel(UserDRO user) { return UserModel.builder() .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .role(user.getRole()) - .imageUrl(user.getImageUrl()) +// .role(user.getRole()) .build(); } public static UserDRO fromModel(UserModel user) { return UserDRO.builder() .rdsUserId(user.getRdsUserId()) - .role(user.getRole()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) +// .role(user.getRole()) .build(); } @@ -46,18 +40,9 @@ public static UserModel compareAndUpdateModel(UserModel user, UserDRO userDRO) { if (userDRO.getRdsUserId() != null) { user.setRdsUserId(user.getRdsUserId()); } - if (userDRO.getFirstName() != null) { - user.setFirstName(user.getFirstName()); - } - if (userDRO.getLastName() != null) { - user.setLastName(user.getLastName()); - } - if (userDRO.getImageUrl() != null) { - user.setImageUrl(user.getImageUrl()); - } - if (userDRO.getRole() != null) { - user.setRole(user.getRole()); - } +// if (userDRO.getRole() != null) { +// user.setRole(user.getRole()); +// } user.setUpdatedAt(Instant.now()); return user; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java index fedccf7b..e5b97a3f 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java @@ -4,7 +4,7 @@ import java.net.URL; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; + import lombok.Builder; import lombok.Getter; @@ -22,7 +22,7 @@ public class UserDTO { private URL imageUrl; - private UserRole role; + private UserRoleEnum role; private Set skills; @@ -31,25 +31,18 @@ public static UserDTO toDTO(UserModel user) { return UserDTO.builder() .id(user.getId()) .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) - .role(user.getRole()) .build(); } public static UserDTO getUsersWithSkills(UserModel user) { - Set skills = - user.getSkills().stream().map(SkillDTO::toDto).collect(Collectors.toSet()); +// Set skills = [] +// user.getSkills().stream().map(SkillDTO::toDto).collect(Collectors.toSet()); return UserDTO.builder() .id(user.getId()) .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) - .skills(skills) - .role(user.getRole()) +// .skills(skills) +// .role(user.getRole()) .build(); } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java index 42776846..fd8eab73 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java @@ -1,12 +1,9 @@ package com.RDS.skilltree.User; -import com.RDS.skilltree.Skill.SkillModel; import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import jakarta.persistence.*; -import java.net.URL; -import java.util.Set; + import java.util.UUID; import lombok.*; @@ -17,7 +14,7 @@ @JsonSerialize @NoArgsConstructor @AllArgsConstructor -@Table(name = "Users") +@Table(name = "users") public class UserModel extends TrackedProperties { @Id @GeneratedValue @@ -26,25 +23,4 @@ public class UserModel extends TrackedProperties { @Column(name = "rds_user_id", unique = true) private String rdsUserId; - - @Column(name = "first_name", nullable = false) - private String firstName; - - @Column(name = "last_name") - private String lastName; - - @Column(name = "image_url", nullable = false) - private URL imageUrl; - - @Column(name = "user_role", nullable = false) - @Enumerated(value = EnumType.STRING) - private UserRole role = UserRole.USER; - - @JsonManagedReference - @ManyToMany(targetEntity = SkillModel.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable( - name = "user_skill", - joinColumns = @JoinColumn(name = "user_id"), - inverseJoinColumns = @JoinColumn(name = "skill_id")) - private Set skills; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java similarity index 55% rename from skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java rename to skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java index 04e1adaa..78caeac6 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java @@ -2,7 +2,7 @@ import java.util.Arrays; -public enum UserRole { +public enum UserRoleEnum { USER("user"), MEMBER("member"), SUPERUSER("super_user"), @@ -10,20 +10,20 @@ public enum UserRole { public final String label; - UserRole(String label) { + UserRoleEnum(String label) { this.label = label; } - public static UserRole fromString(String text) { - for (UserRole role : UserRole.values()) { + public static UserRoleEnum fromString(String text) { + for (UserRoleEnum role : UserRoleEnum.values()) { if (role.label.equalsIgnoreCase(text)) { return role; } } - return UserRole.GUEST; + return UserRoleEnum.GUEST; } public static String[] getAllRoles() { - return Arrays.stream(UserRole.values()).map(UserRole::name).toArray(String[]::new); + return Arrays.stream(UserRoleEnum.values()).map(UserRoleEnum::name).toArray(String[]::new); } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java index f853bf04..4f7d2a38 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java @@ -12,5 +12,5 @@ public interface UserService { List getAllUsers(); - void addSkill(UUID skill, UUID userId); + void addSkill(Integer skill, UUID userId); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java index c85f9d94..5739eb48 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java @@ -1,12 +1,14 @@ package com.RDS.skilltree.User; import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; +import com.RDS.skilltree.Skill.Skill; import com.RDS.skilltree.Skill.SkillRepository; import jakarta.transaction.Transactional; + import java.util.List; import java.util.Optional; import java.util.UUID; + import org.springframework.stereotype.Service; @Service @@ -27,7 +29,8 @@ public UserDTO createUser(UserDRO user) { } @Override - public void updateUser(UUID id, UserDRO user) {} + public void updateUser(UUID id, UserDRO user) { + } @Override public UserDTO getUserById(UUID id) { @@ -42,24 +45,25 @@ public List getAllUsers() { /** * updates the user and skill both + * * @param skillId * @param userId */ @Override @Transactional - public void addSkill(UUID skillId, UUID userId) { + public void addSkill(Integer skillId, UUID userId) { Optional userOptional = userRepository.findById(userId); - Optional skillOptional = skillRepository.findById(skillId); + Optional skillOptional = skillRepository.findById(skillId); if (userOptional.isPresent() && skillOptional.isPresent()) { UserModel userModel = userOptional.get(); - SkillModel skillModel = skillOptional.get(); + Skill skill = skillOptional.get(); - userModel.getSkills().add(skillModel); - skillModel.getUsers().add(userModel); +// userModel.getSkills().add(skillModel); +// skillModel.getUsers().add(userModel); userRepository.save(userModel); - skillRepository.save(skillModel); + skillRepository.save(skill); } else { if (skillOptional.isEmpty()) { throw new NoEntityException("Skill Id is not passed in the input"); diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java new file mode 100644 index 00000000..79637df6 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.User; + +public enum UserSkillStatusEnum { + APPROVED, + REJECTED, + PENDING +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java new file mode 100644 index 00000000..a068d2f7 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java @@ -0,0 +1,37 @@ +package com.RDS.skilltree.User; + +import com.RDS.skilltree.Skill.Skill; +import com.fasterxml.jackson.annotation.JsonBackReference; +import jakarta.persistence.*; + +import lombok.*; + +import java.util.UUID; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "user_skills") +public class UserSkillsModel { + @Id + @GeneratedValue + @Column(name = "id", columnDefinition = "BINARY(16)") + private UUID id; + + @JsonBackReference + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private UserModel user; + + @JsonBackReference + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "skill_id", nullable = false) + private Skill skill; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private UserSkillStatusEnum status = UserSkillStatusEnum.PENDING; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java b/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java index 23601457..7cb55e6f 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java @@ -9,14 +9,7 @@ @Data @MappedSuperclass public abstract class TrackedProperties { - - @Column(name = "created_by") - private UUID createdBy; - - @Column(name = "updated_by") - private UUID updatedBy; - - @Column(name = "created_at") + @Column(name = "created_at", nullable = false) private Instant createdAt; @Column(name = "updated_at") diff --git a/skill-tree/src/main/resources/application-dev.properties b/skill-tree/src/main/resources/application-dev.properties index 8fa24448..21199428 100644 --- a/skill-tree/src/main/resources/application-dev.properties +++ b/skill-tree/src/main/resources/application-dev.properties @@ -1 +1,2 @@ -cookieName=rds-session-v2-development \ No newline at end of file +cookieName=rds-session-v2-development +logging.level.root=DEBUG \ No newline at end of file diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java deleted file mode 100644 index a4b5cb1b..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java +++ /dev/null @@ -1,589 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -import com.RDS.skilltree.Endorsement.*; -import com.RDS.skilltree.Skill.*; -import com.RDS.skilltree.User.*; -import io.restassured.response.Response; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class EndorsementsIntegrationTests extends TestContainerManager { - - private UserRepository userRepository; - private SkillRepository skillRepository; - private final UserService userService; - private final SkillsService skillsService; - private UserDTO user; - private SkillDTO skill; - private EndorsementRepository endorsementRepository; - - @Autowired - public EndorsementsIntegrationTests( - UserService userService, - UserRepository userRepository, - SkillsService skillsService, - SkillRepository skillRepository, - EndorsementRepository endorsementRepository) { - this.userService = userService; - this.userRepository = userRepository; - this.skillsService = skillsService; - this.skillRepository = skillRepository; - this.endorsementRepository = endorsementRepository; - } - - @BeforeEach - private void addData() throws MalformedURLException { - user = - userService.createUser( - UserDRO.builder() - .role(UserRole.MEMBER) - .rdsUserId("p6Bo61VEClhtVdwW0ihg") - .lastName("Doe") - .firstName("John") - .imageUrl( - new URL( - "https://res.cloudinary.com/realdevsquad/image/upload/v1666193594/profile/p6Bo61VEClhtVdwW0iGH/lezguwdq5bgzawa3.jpg")) - .build()); - - skill = - skillsService.createSkill( - SkillDRO.builder().name("Java").type(SkillType.ATOMIC).createdBy(user.getId()).build()); - } - - @AfterEach - private void cleanUp() { - endorsementRepository.deleteAll(); - skillRepository.deleteAll(); - userRepository.deleteAll(); - } - - private UUID createEndorsementModel(Boolean isStatusPending) { - EndorsementStatus endorsementStatus; - if (isStatusPending) { - endorsementStatus = EndorsementStatus.PENDING; - } else { - endorsementStatus = EndorsementStatus.APPROVED; - } - EndorsementModel endorsementModel = - EndorsementModel.builder().status(endorsementStatus).build(); - return endorsementRepository.save(endorsementModel).getId(); - } - - @Test - @Disabled - @DisplayName("Fetch all the endorsements") - public void testAPIReturnsAllEndorsements() { - Response response = given().cookies(RestAPIHelper.getUserCookie()).get("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("data", hasSize(1)) - .body("data[0].endorseeId", equalTo("user-1")) - .body("data[0].skillName", equalTo("Java")) - .body("data[0].status", anyOf(equalTo("APPROVED"), equalTo("REJECTED"), equalTo("PENDING"))) - .body("data[0].endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data[0].endorsersList", hasSize(1)) - .body("data[0].endorserList[0].endorseeId", equalTo("user-2")) - .body("data[0].endorserList[0].description", isA(String.class)) - .body( - "data[0].endorserList[0].userType", - anyOf(equalTo("NORMAL_USER"), equalTo("SUPER_USER"), equalTo("MAVEN"))); - } - - @Test - @Disabled - @DisplayName("Fetch all the endorsements given endorsement status") - public void testAPIReturnsEndorsementsGivenStatus() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", "PENDING") - .get("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("data", hasSize(1)) - .body("data[0].endorseeId", equalTo("user-1")) - .body("data[0].skillName", equalTo("Java")) - .body("data[0].status", equalTo("PENDING")) - .body("data[0].endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data[0].endorsersList", hasSize(1)) - .body("data[0].endorserList[0].endorseeId", equalTo("user-2")) - .body("data[0].endorserList[0].description", isA(String.class)) - .body( - "data[0].endorserList[0].userType", - anyOf(equalTo("NORMAL_USER"), equalTo("SUPER_USER"), equalTo("MAVEN"))); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsement status passed") - public void testAPIReturns400_OnInvalidStatusPassed() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", "APPROVAL") - .get("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid status passed")); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsementId passed") - public void testAPIReturns400_OnInvalidParameterPassed() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .patch("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid endorsementId passed")); - } - - @Test - @DisplayName("Return 201 on endorsements creation") - public void testAPIReturns201_OnEndorsementCreation() { - UUID endorseeId = user.getId(); - UUID skillId = skill.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorseeId); - endorsementDRO.setSkillId(skillId); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(201) - .contentType("application/json") - .body("data.endorseeId", equalTo(endorseeId.toString())) - .body("data.skill.name", equalTo("Java")); - } - - @Test - @DisplayName("Return 400 on endorsements userid null") - public void testAPIReturns400_OnEndorsementCreationUserIdNull() { - - UUID skillId = skill.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - - endorsementDRO.setSkillId(skillId); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(400) - .contentType("application/json") - .body("data", equalTo(null)) - .body("message", equalTo("user id cannot be null")); - } - - @Test - @DisplayName("Return 400 on endorsements skillid null") - public void testAPIReturns400_OnEndorsementCreationSkillIdNull() { - UUID endorseeId = user.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorseeId); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(400) - .contentType("application/json") - .body("data", equalTo(null)) - .body("message", equalTo("skill id cannot be null")); - } - - @Test - @Disabled - @DisplayName("Return 200 on endorsements updation") - public void testAPIReturns200_OnEndorsementGivenId() { - String endorsementId = "e-1"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .patch("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("code", equalTo(200)) - .body("data.endorseeId", equalTo("user-1")) - .body("data.skillName", equalTo("Java")) - .body("data.status", anyOf(equalTo("APPROVED"), equalTo("PENDING"), equalTo("REJECTED"))) - .body("data.endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data.endorsersList", hasSize(1)) - .body("data.endorsersList[0].endorseeId", equalTo("user-2")) - .body("data.endorsersList[0].description", isA(String.class)) - .body( - "data.endorsersList[0].userType", - anyOf(equalTo("SUPER_USER"), equalTo("MAVEN"), equalTo("USER"))); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsementId passed") - public void testAPIReturn400_OnInvalidIdPassed() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .get("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid endorsementId passed")); - } - - @Test - @Disabled - @DisplayName("Return 404 when endorsement not found given endorsementId") - public void testAPIReturn404_OnEndorsementNotFound() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .get("/endorsements"); - - response - .then() - .statusCode(404) - .body("code", equalTo(404)) - .body("message", equalTo("Endorsement not found")); - } - - @Test - @DisplayName("Return 200, with the endorsements of a particular user given userID") - public void itShouldReturn200OnEndorsementSearchByUserIDPresentInList() { - String userID = "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb"; - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("user_id"))) - .body("content.user_id", everyItem(equalTo(userID))) - .body("content.size()", equalTo(7)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(7)); - } - - @Test - @DisplayName("Return 200, with the endorsements of a particular skill given skillID") - public void itShouldReturn200OnEndorsementSearchBySkillIDPresentInList() { - String skillID = "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9"; - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("skill_id"))) - .body("content.skill_id", everyItem(equalTo(skillID))) - .body("content.size()", equalTo(1)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(1)); - } - - @Test - @DisplayName("Return 200, with 1st page all the endorsements with default pagesize") - public void itShouldReturn200OnEndorsementSearchAllEndorsements() { - Response response = given().get("/v1/endorsements?dummyData=true"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(2)) - .body("content.size()", equalTo(10)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 1st page all the endorsements with custom limit value") - public void itShouldReturn200OnEndorsementSearchAllEndorsementsWithLimit() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=15"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(1)) - .body("content.size()", equalTo(14)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(15)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 1st page of all endorsements result where page size is 5") - public void itShouldReturn200OnEndorsementSearchAllEndorsementsWithMultiplePages() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=5"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(3)) - .body("content.size()", equalTo(5)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(5)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 2nd page of all the endorsements result") - public void itShouldReturn200With2ndPageOnEndorsementSearchAllEndorsementsWithMultiplePages() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=5&offset=1"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(3)) - .body("content.size()", equalTo(5)) - .body("pageable.pageNumber", equalTo(1)) - .body("pageable.pageSize", equalTo(5)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with the endorsements matching the given userID and skillID") - public void itShouldReturn200OnEndorsementSearchGivenBothUserIDAndSkillID() { - String userID = "73e0b7c4-d128-4e53-9501-0e7f4ff5a261"; - String skillID = "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9"; - - Response response = - given().get("/v1/endorsements?dummyData=true&skillID=" + skillID + "&userID=" + userID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("skill_id"))) - .body("content.skill_id", everyItem(equalTo(skillID))) - .body("content", everyItem(hasKey("user_id"))) - .body("content.user_id", everyItem(equalTo(userID))) - .body("content.size()", equalTo(1)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(1)); - } - - @Test - @DisplayName( - "Return 204, when there are no endorsements present for the given userID in UUID form") - public void itShouldReturn204OnEndorsementSearchWithValidUserIDButNotPresentInList() { - String userID = UUID.randomUUID().toString(); - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response.then().statusCode(204); - } - - @Test - @DisplayName( - "Return 204, when there are no endorsements present for the given skillID in UUID form") - public void itShouldReturn204OnEndorsementSearchWithValidSkillIDButNotPresentInList() { - String skillID = UUID.randomUUID().toString(); - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response.then().statusCode(204); - } - - @Test - @DisplayName("Return 400, given a userID which is not a UUID") - public void itShouldReturn400OnEndorsementSearchWithInvalidUserID() { - String userID = "invalid-user-id"; - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response.then().statusCode(400); - } - - @Test - @DisplayName("Return 400, given a skillID which is not a UUID") - public void itShouldReturn400OnEndorsementSearchWithInvalidSkillID() { - String skillID = "invalid-skill-id"; - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response.then().statusCode(400); - } - - @Test - @DisplayName("Return 204, given an offset value greater than maximum endorsements") - public void itShouldReturn204OnEndorsementSearchWithOffsetGreaterThanMaximumEndorsements() { - Response response = given().get("/v1/endorsements?dummyData=true&offset=10"); - - response.then().statusCode(204); - } - - @Test - @Disabled - @DisplayName("Return 401, when request is made without a valid cookie") - public void itShouldReturn401OnEndorsementSearchWithoutCookie() { - Response response = given().get("/v1/endorsements"); - - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - @DisplayName( - "Return 200, when request is made using super user cookie and status is APPROVED/REJECTED") - public void - itShouldReturn200OnUpdateEndorsementStatusWithSuperUserCookieAndAcceptOrRejectEndorsementStatus() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(200) - .body("data", equalTo(null)) - .body("message", equalTo("Successfully updated endorsement status")); - } - - @Test - @DisplayName( - "Return 403, when request is made without using super user cookie and status is APPROVED/REJECTED") - public void - itShouldReturn403OnUpdateEndorsementStatusWithOutSuperUserCookieAndAcceptOrRejectEndorsementStatus() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(403) - .body("data", equalTo(null)) - .body("message", equalTo("Unauthorized, Access is only available to super users")); - } - - @Test - @DisplayName( - "Return 400, when request is made with using super user cookie and status is invalid") - public void - itShouldReturn400OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementStatusIsInvalid() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", "invalid-status") - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Invalid parameter endorsement status: invalid-status")); - } - - @Test - @DisplayName( - "Return 400, when request is made with using super user cookie and status is PENDING") - public void - itShouldReturn400OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementStatusIsPending() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.PENDING.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Invalid parameter endorsement status: PENDING")); - } - - @Test - @DisplayName( - "Return 409, when request is made with using super user cookie and endorsement is already updated") - public void - itShouldReturn409OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementAlreadyUpdated() { - UUID endorsementId = createEndorsementModel(false); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(409) - .body("data", equalTo(null)) - .body("message", equalTo("Endorsement is already updated. Cannot modify status")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java deleted file mode 100644 index 19754e71..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.equalTo; - -import io.restassured.response.Response; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SecurityContextIntegrationTest extends TestContainerManager { - - @Test - public void testTokenIsNotPresent() { - - Response response = given().get("/v1/endorsement"); - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - public void testInvalidToken() { - Response response = given().cookie("rds-session-v2", "invalidtoken").get("/v1/endorsement"); - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - public void test_GetSkill_WithGuestToken() { - Response response = - given() - .cookies(RestAPIHelper.getGuestUserCookie()) - .contentType("application/json") - .get("/v1/skills/"); - response.then().statusCode(200); - } - - @Test - public void test_CreateSkill_WithGuestToken() { - Response response = - given() - .cookies(RestAPIHelper.getGuestUserCookie()) - .contentType("application/json") - .post("/v1/skills/"); - response.then().statusCode(403).body("message", equalTo("Access Denied")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java deleted file mode 100644 index 9fd65268..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -import com.RDS.skilltree.Skill.*; -import com.RDS.skilltree.User.*; -import io.restassured.response.Response; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SkillsIntegrationTests extends TestContainerManager { - private UserRepository userRepository; - private SkillRepository skillRepository; - private final UserService userService; - private final SkillsService skillsService; - private UserDTO user; - private SkillDTO skill; - - @Autowired - public SkillsIntegrationTests( - UserService userService, - UserRepository userRepository, - SkillsService skillsService, - SkillRepository skillRepository) { - this.userService = userService; - this.userRepository = userRepository; - this.skillsService = skillsService; - this.skillRepository = skillRepository; - } - - @BeforeEach - private void addData() throws MalformedURLException { - user = - userService.createUser( - UserDRO.builder() - .role(UserRole.MEMBER) - .rdsUserId("p6Bo61VEClhtVdwW0ihg") - .lastName("Doe") - .firstName("John") - .imageUrl( - new URL( - "https://res.cloudinary.com/realdevsquad/image/upload/v1666193594/profile/p6Bo61VEClhtVdwW0iGH/lezguwdq5bgzawa3.jpg")) - .build()); - - skill = - skillsService.createSkill( - SkillDRO.builder().name("Java").type(SkillType.ATOMIC).createdBy(user.getId()).build()); - } - - @AfterEach - private void cleanUp() { - skillRepository.deleteAll(); - userRepository.deleteAll(); - } - - @Test - @DisplayName("Return 200, on all skills") - public void testAPIReturns200_OnAllSkillsFound() { - Response response = - given() - .queryParam("offset", 0) - .queryParam("limit", 1) - .cookies(RestAPIHelper.getUserCookie()) - .get("/v1/skills/"); - - response - .then() - .statusCode(200) - .body("content", hasSize(1)) - .body("content[0].type", equalTo("ATOMIC")) - .body("content[0].name", equalTo("Java")) - .body("content[0].users", empty()) - .body("totalPages", equalTo(1)) - .body("totalElements", equalTo(1)) - .body("last", equalTo(true)) - .body("size", equalTo(1)) - .body("number", equalTo(0)) - .body("numberOfElements", equalTo(1)) - .body("empty", equalTo(false)); - } - - @Test - @DisplayName("Return 200, on no skills found") - public void testAPIReturns200_OnNoSkillsFound() { - skillRepository.deleteAll(); - Response response = given().cookies(RestAPIHelper.getUserCookie()).get("/v1/skills/"); - - response - .then() - .statusCode(200) - .body("content", hasSize(0)) - .body("totalPages", equalTo(0)) - .body("totalElements", equalTo(0)) - .body("last", equalTo(true)) - .body("size", equalTo(10)) - .body("number", equalTo(0)) - .body("numberOfElements", equalTo(0)) - .body("empty", equalTo(true)); - } - - @Test - @DisplayName("Return 200, on skill found given skillId") - public void testAPIReturns200_OnSkillFoundById() { - UUID skillId = skill.getId(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("id", skillId) - .get("/v1/skills/{id}"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("id", equalTo(String.valueOf(skillId))) - .body("name", equalTo("Java")) - .body("type", equalTo("ATOMIC")); - } - - @Test - @DisplayName("Return 404, on skill not found given SkillId") - public void testAPIReturns404_OnSkillNotFound() { - UUID skillId = UUID.randomUUID(); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("id", skillId) - .get("/v1/skills/{id}"); - - response.then().statusCode(404).body("message", equalTo("Skill not found with given Id")); - } - - @Test - @DisplayName("Return 200, on skill with given name") - public void testAPIReturns200_OnSkillFoundGivenName() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("name", "Java") - .get("/v1/skills/name/{name}"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("name", equalTo("Java")) - .body("id", equalTo(skill.getId().toString())) - .body("type", equalTo("ATOMIC")); - } - - @Test - @DisplayName("Return 404, if skill given skill name is not found") - public void testAPIReturns404_OnSkillGivenSkillNameNotFound() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("name", "Go") - .get("/v1/skills/name/{name}"); - - response.then().statusCode(404).body("message", equalTo("Skill not found with the given name")); - } - - @Test - @DisplayName("Return 400, if createdBy is not passed for Skill creation") - public void testAPIReturns400_OnCreatedByNotPassedForSKillCreation() { - SkillDRO skillDRO = SkillDRO.builder().name("Go").type(SkillType.ATOMIC).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Created by user Id cannot be null")); - } - - @Test - @DisplayName("Return 400, if type is not passed for Skill creation") - public void testAPIReturns400_OnTypeNotPassedForSkillCreation() { - SkillDRO skillDRO = SkillDRO.builder().name("Go").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("SkillType cannot be null")); - } - - @Test - @DisplayName("Return 400, if name is not passed for Skill creation") - public void testAPIReturns400_OnNameNotPassedForSkillCreation() { - SkillDRO skillDRO = SkillDRO.builder().type(SkillType.ATOMIC).createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Name cannot be null")); - } - - @Test - @DisplayName("Return 409, if name is already used for Skill creation") - public void testAPIReturns409_OnNameAlreadyUsedForSkillCreation() { - SkillDRO skillDRO = - SkillDRO.builder().type(SkillType.ATOMIC).name("Java").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(409) - .body("message", equalTo("Cannot create entry for Skill as Skill name is duplicate")); - } - - @Test - @DisplayName("Return 201, on successful Skill creation") - public void testAPIReturns201_OnSuccessfulSkillCreation() { - SkillDRO skillDRO = - SkillDRO.builder().type(SkillType.ATOMIC).name("Go").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(201) - .contentType("application/json") - .body("name", equalTo("Go")) - .body("type", equalTo("ATOMIC")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java deleted file mode 100644 index ecd0ff75..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.RDS.skilltree.integration; - -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.testcontainers.containers.MySQLContainer; - -abstract class TestContainerManager { - @ServiceConnection static final MySQLContainer mysqlContainer; - - static { - mysqlContainer = - new MySQLContainer("mysql:8.1") - .withDatabaseName("skilltree-test") - .withUsername("root") - .withPassword("password"); - mysqlContainer.start(); - } - - @DynamicPropertySource - static void configureTestProperties(DynamicPropertyRegistry registry) { - registry.add("spring.jpa.hibernate.ddl-auto", () -> "update"); - registry.add("cookieName", () -> "rds-session-v2"); - registry.add( - "jwt.rds.public.key", - () -> - "-----BEGIN PUBLIC KEY-----MIICITANBgkqhkiG9w0BAQEFAAOCAg4AMIICCQKCAgBpAet8sOf64PtzdnwtkZB4JEJTCtQT9ZQMuuWUDXZGTG0iO7x3WZw6GanBboKGblU4VZEgd8H7bKOOIaQF4AsiXsw/vUsOV5Ue73a9Jj5d57jyon7M8fFmjna3afZfb5SBru5Iv0ECePqIKUIhSmToML+y3bFKF2cbUTEe2qPK5xzBeH4AWq4Zb2N0gHNstinwrXL9LWawQPkJr23TohZZEFSzyZbeklWWwz67A6YnE01w42R/TLE3LmU8YKkrHkgFsAHtUMQO++JsH4q3F9J0e0VkLzj5sB5RgAYscs6YFKoFD5jKgtSRPIXz7O9GsC76dHtwGXOk47/NWxu7bUQ0VcD2hJYprR28PjdNk5KiRKO5Z83JkiM6ed9UAkiD/fIRI8LITaLayHdFfQvXM+d9v4ugPHEq+aVllFMH1lUu/2B1aJpk4D4w5JcIzIZ9og4cMz00EGU/1o+BX2S55/Ok 4MaxX6Zl3QYm1K0cPLOdisYoygPtnNEav32JLgM2yOXdyuhpYzmn66yyFFck2nnCkezG5Gvlf3MejMavRO+sfIz0gDIhXEwWu0EJDrG5nmNRwejrSXx42YxmYZGkK/c8 2fiwbOVqIuFgsI6lWGdyDayFRg9bjrk6KiQZFnP4KcmUXk4PhiSItDJAUEkNz0+4StHNoqFhNH5pnEj4VbmJqwIDAQAB -----END PUBLIC KEY-----"); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java deleted file mode 100644 index 4a7e0ad4..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Endorsement.EndorsementModel; -import com.RDS.skilltree.Endorsement.EndorsementRepository; -import com.RDS.skilltree.EndorsementList.*; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRepository; -import java.util.Optional; -import java.util.UUID; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -class EndorsementListServiceTest { - - @Mock private EndorsementListRepository endorsementListRepository; - - @Mock private EndorsementRepository endorsementRepository; - - @Mock private UserRepository userRepository; - - @InjectMocks private EndorsementListService endorsementListService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - } - - @Test - void testCreateEndorsementListEntry() { - // Mock data - UUID endorserId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementListDRO endorsementListDRO = new EndorsementListDRO(); - endorsementListDRO.setEndorserId(endorserId); - endorsementListDRO.setEndorsementId(endorsementId); - endorsementListDRO.setDescription("Test Description"); - endorsementListDRO.setType(EndorsementType.POSITIVE); - - UserModel mockUser = new UserModel(); - mockUser.setId(endorserId); - - EndorsementModel mockEndorsement = EndorsementModel.builder().id(endorsementId).build(); - - // Mock the repository behavior - when(userRepository.findById(endorserId)).thenReturn(Optional.of(mockUser)); - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - // Call the service method - EndorsementListModel result = - endorsementListService.createEndorsementListEntry(endorsementListDRO); - - // Verify the interactions - verify(endorsementListRepository, times(1)).save(any(EndorsementListModel.class)); - - // Assertions - assertNotNull(result); - assertEquals(endorserId, result.getEndorserId()); - assertEquals(endorsementId, result.getEndorsement().getId()); - assertEquals("Test Description", result.getDescription()); - assertEquals(EndorsementType.POSITIVE, result.getType()); - } - - @Test - void testCreateEndorsementListEntryWithInvalidEndorsement() { - UUID endorserId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementListDRO endorsementListDRO = new EndorsementListDRO(); - endorsementListDRO.setEndorserId(endorserId); - endorsementListDRO.setEndorsementId(endorsementId); - - UserModel mockUser = new UserModel(); - mockUser.setId(endorserId); - - // Mock the repository behavior for an invalid endorsement - when(userRepository.findById(endorserId)).thenReturn(Optional.of(mockUser)); - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.empty()); - - // Assert that a NoEntityException is thrown - NoEntityException exception = - assertThrows( - NoEntityException.class, - () -> endorsementListService.createEndorsementListEntry(endorsementListDRO)); - assertEquals("Endorsement with id:" + endorsementId + " not found", exception.getMessage()); - - // Verify that save method is not called - verify(endorsementListRepository, never()).save(any(EndorsementListModel.class)); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java deleted file mode 100644 index 2ee4dcef..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java +++ /dev/null @@ -1,746 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Common.Response.GenericResponse; -import com.RDS.skilltree.Endorsement.*; -import com.RDS.skilltree.Exceptions.EntityAlreadyExistsException; -import com.RDS.skilltree.Exceptions.InvalidParameterException; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRepository; -import com.RDS.skilltree.User.UserRole; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import jakarta.persistence.EntityNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.*; -import org.junit.jupiter.api.*; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.util.ReflectionTestUtils; - -@ExtendWith(MockitoExtension.class) -public class EndorsementServiceTest { - @Mock private EndorsementRepository endorsementRepository; - - @Mock private UserRepository userRepository; - - @Mock private SkillRepository skillRepository; - - @Mock private ObjectMapper objectMapper; - - @InjectMocks @Autowired private EndorsementServiceImpl endorsementService; - - @Mock private Authentication auth; - - @BeforeEach - public void setUp() { - ReflectionTestUtils.setField( - endorsementService, "dummyEndorsementDataPath", "dummy-data/endorsements.json"); - } - - @AfterEach - public void clearSecurityContext() { - SecurityContextHolder.clearContext(); - } - - private void setupUpdateEndorsementTests(Boolean useSuperUserRole) { - UserModel userModel = new UserModel(); - if (useSuperUserRole) { - userModel.setRole(UserRole.SUPERUSER); - } else { - userModel.setRole(UserRole.USER); - } - when(auth.getPrincipal()).thenReturn(userModel); - SecurityContextHolder.getContext().setAuthentication(auth); - } - - @Test - public void itShouldGetEndorsementsById() { - UUID endorsementId = UUID.randomUUID(); - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - - SkillModel skillModel = SkillModel.builder().id(skillId).build(); - EndorsementModel endorsementModel = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorserId) - .skill(skillModel) - .build(); - endorsementModel.setCreatedAt(Instant.now()); - endorsementModel.setUpdatedAt(Instant.now()); - endorsementModel.setCreatedBy(endorsementId); - endorsementModel.setUpdatedBy(endorsementId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(endorsementModel)); - - EndorsementDTO result = endorsementService.getEndorsementById(endorsementId); - - assertNotNull(result); - assertEquals( - endorsementId, - result.getId(), - "The Endorsement Id doesn't matches the expected endorsement Id"); - } - - @Test - @DisplayName("Get endorsements given a valid skillID") - public void itShouldReturnEndorsementsGivenSkillID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, null); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Get endorsements given a valid userID") - void itShouldGetEndorsementsGivenUserID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Get endorsements given an invalid userID") - public void itShouldThrowErrorIfInvalidUserIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData(pageRequest, null, "invalid-user-id")); - } - - @Test - @DisplayName("Get endorsements given an invalid skillID") - public void itShouldThrowIllegalArgumentExceptionIfInvalidSkillIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData(pageRequest, "invalid-skill-id", null)); - } - - @Test - @DisplayName("Get endorsements given a valid userID and invalid skillID") - public void itShouldThrowIllegalArgumentExceptionIfInvalidUserIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData( - pageRequest, "invalid-skill-id", UUID.randomUUID().toString())); - } - - @Test - @DisplayName( - "Return paginated result having 2 pages when number of endorsements with a given userID is 15") - public void itShouldReturnPaginatedResultOnSearch() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - for (int i = 0; i < 15; i++) { - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - } - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(2, result.getTotalPages()); - assertEquals(15, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty page when accessing out of bound page in paginated result") - public void itShouldReturnEmptyPaginatedResultOnSearch() throws IOException { - PageRequest pageRequest = PageRequest.of(10, 10); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - for (int i = 0; i < 15; i++) { - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - } - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(Page.empty(pageRequest), result); - } - - @Test - @DisplayName( - "Return empty endorsement list given a valid userID but skillID which is not present") - public void itShouldReturnEmptyDataGivenUserIDAndSkillIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty page when no endorsements are present in dummy data") - public void itShouldReturnEmptyDataWhenNoEndorsementsArePresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID); - - assertEquals(Page.empty(pageRequest), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a userID which is not present") - public void itShouldReturnEmptyDataGivenUserIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, null, UUID.randomUUID().toString()); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given empty userID and skillID") - public void itShouldReturnEmptyDataGivenEmptyUserIDAndSkillID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, "", ""); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a skillID which is not present") - public void itShouldReturnEmptyDataGivenSkillIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, UUID.randomUUID().toString(), null); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a skillID and userID which is not present") - public void itShouldReturnEmptyDataGivenSkillIDAndUserIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, UUID.randomUUID().toString(), UUID.randomUUID().toString()); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return IO exception on error reading data") - void itShouldReturnIOExceptionIfErrorReadingData() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = null; - String userID = null; - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenThrow(new IOException("Error reading data")); - - assertThrows( - IOException.class, - () -> endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID)); - } - - @Test - public void itShouldHandleEndorsementNotFound() { - UUID nonExistentEndorsementId = UUID.randomUUID(); - when(endorsementRepository.findById(nonExistentEndorsementId)).thenReturn(Optional.empty()); - - EntityNotFoundException exception = - assertThrows( - EntityNotFoundException.class, - () -> endorsementService.getEndorsementById(nonExistentEndorsementId)); - - // Verify the exception message - assertEquals( - "No endorsement with the id " + nonExistentEndorsementId + " found", - exception.getMessage()); - } - - @Test - void testCreateEndorsement() { - // Mock data - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorserId); - endorsementDRO.setSkillId(skillId); - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorserId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorserId); - mockEndorsement.setUpdatedBy(endorserId); - - // Mock the repository behavior - when(skillRepository.findById(skillId)).thenReturn(Optional.of(mockSkill)); - when(endorsementRepository.save(any(EndorsementModel.class))).thenReturn(mockEndorsement); - - // Call the service method - EndorsementModel result = endorsementService.createEndorsement(endorsementDRO); - - // Verify the interactions - verify(endorsementRepository, times(1)).save(any(EndorsementModel.class)); - - // Assertions - assertNotNull(result); - assertEquals(endorserId, result.getEndorseeId()); - assertEquals(skillId, result.getSkill().getId()); - } - - @Test - void testCreateEndorsementWithInvalidSkill() { - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorserId); - endorsementDRO.setSkillId(skillId); - - // Mock the repository behavior for an invalid skill - when(skillRepository.findById(skillId)).thenReturn(Optional.empty()); - - // Assert that a NoEntityException is thrown - NoEntityException exception = - assertThrows( - NoEntityException.class, () -> endorsementService.createEndorsement(endorsementDRO)); - assertEquals("Skill with id:" + skillId + " not found", exception.getMessage()); - - // Verify that save method is not called - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName( - "Return unauthorized access, given user is not a super user to update endorsement status") - public void itShouldReturnUnauthorizedGivenUserIsNotSuperUser() { - setupUpdateEndorsementTests(false); - - UUID endorsementId = UUID.randomUUID(); - String status = EndorsementStatus.APPROVED.name(); - - AccessDeniedException exception = - assertThrows( - AccessDeniedException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Unauthorized, Access is only available to super users", exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return invalid status given status is pending") - public void itShouldReturnInvalidStatusGivenEndorsementStatusIsPending() { - setupUpdateEndorsementTests(true); - - UUID endorsementId = UUID.randomUUID(); - String status = EndorsementStatus.PENDING.name(); - - InvalidParameterException exception = - assertThrows( - InvalidParameterException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Invalid parameter endorsement status: " + status, exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return invalid status given status is invalid") - public void itShouldReturnInvalidStatusGivenInvalidEndorsementStatus() { - setupUpdateEndorsementTests(true); - - UUID endorsementId = UUID.randomUUID(); - String status = "invalid-status"; - - InvalidParameterException exception = - assertThrows( - InvalidParameterException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Invalid parameter endorsement status: " + status, exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return cannot modify status given status is already updated") - public void itShouldThrowEntityAlreadyExistsExceptionGivenEndorsementIsUpdated() { - setupUpdateEndorsementTests(true); - - UUID endorseeId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .status(EndorsementStatus.APPROVED) - .endorseeId(endorseeId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - EntityAlreadyExistsException exception = - assertThrows( - EntityAlreadyExistsException.class, - () -> - endorsementService.updateEndorsementStatus( - endorsementId, EndorsementStatus.APPROVED.name())); - assertEquals("Endorsement is already updated. Cannot modify status", exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return endorsement not found given an unknown endorsement id") - public void itShouldReturnEndorsementNotFoundGivenUnknownEndorsementId() { - setupUpdateEndorsementTests(true); - - UUID nonExistentEndorsementId = UUID.randomUUID(); - String status = EndorsementStatus.APPROVED.name(); - - when(endorsementRepository.findById(nonExistentEndorsementId)).thenReturn(Optional.empty()); - - NoEntityException exception = - assertThrows( - NoEntityException.class, - () -> endorsementService.updateEndorsementStatus(nonExistentEndorsementId, status)); - assertEquals( - "No endorsement with id " + nonExistentEndorsementId + " was found", - exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName( - "Update endorsement status given a valid endorsement id and status is approved or rejected") - public void itShouldUpdateEndorsementStatusGivenEndorsementIdAndStatusApprovedOrRejected() { - setupUpdateEndorsementTests(true); - - UUID endorseeId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementStatus status = EndorsementStatus.APPROVED; - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .status(EndorsementStatus.PENDING) - .endorseeId(endorseeId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - GenericResponse result = - endorsementService.updateEndorsementStatus(endorsementId, status.name()); - assertEquals("Successfully updated endorsement status", result.getMessage()); - - verify(endorsementRepository, times(1)).save(any(EndorsementModel.class)); - - EndorsementModel updatedMockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorseeId) - .skill(mockSkill) - .status(EndorsementStatus.APPROVED) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)) - .thenReturn(Optional.of(updatedMockEndorsement)); - Optional updatedEndorsement = endorsementRepository.findById(endorsementId); - assertTrue(updatedEndorsement.isPresent()); - assertEquals(EndorsementStatus.APPROVED, updatedEndorsement.get().getStatus()); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java deleted file mode 100644 index a10ae257..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Health.HealthCheckController; -import com.RDS.skilltree.metrics.MetricService; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -class HealthCheckTest { - - @Mock private MetricService metricService; - - private HealthCheckController healthCheckController; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - healthCheckController = new HealthCheckController(metricService); - } - - @Test - void checkHealth() { - // Setup - when(metricService.getUptime()).thenReturn(123.0); - - // Execute - var result = healthCheckController.checkHealth(); - - // Assert - assertNotNull(result); - assertTrue(result.containsKey("uptimeInSeconds")); - assertEquals(123.0, result.get("uptimeInSeconds")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java deleted file mode 100644 index bf5e0bf8..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import com.RDS.skilltree.Skill.SkillDTO; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.Skill.SkillsServiceImpl; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; - -@ExtendWith(MockitoExtension.class) -public class SkillsServiceTest { - - @Mock private SkillRepository skillRepository; - - @InjectMocks @Autowired private SkillsServiceImpl skillService; - - @Test - public void testGetSkillById() { - UUID skillId = UUID.randomUUID(); - SkillModel skillModel = SkillModel.builder().id(skillId).build(); - - when(skillRepository.findById(skillId)).thenReturn(Optional.of(skillModel)); - - SkillDTO result = skillService.getSkillById(skillId); - assertNotNull(result); - assertEquals(skillId, result.getId(), "The skill Id doesn't matches the expected skillId"); - } - - @Test - public void testGetSkillsByName() { - String skillName = "Java"; - SkillModel skillModel = SkillModel.builder().name("Java").build(); - - when(skillRepository.findByName(skillName)).thenReturn(Optional.of(skillModel)); - - SkillDTO result = skillService.getSkillByName("Java"); - assertNotNull(result); - assertEquals( - skillName, result.getName(), "The skill name doesn't match the expected skill name"); - } - - @Test - public void testGetAllSkills() { - SkillModel skillJava = SkillModel.builder().name("Java").build(); - - SkillModel skillGo = SkillModel.builder().name("Go").build(); - - List skillModelList = Arrays.asList(skillJava, skillGo); - - when(skillRepository.findAll((Pageable) any(Pageable.class))) - .thenReturn(new PageImpl<>(skillModelList)); - - Pageable pageable = PageRequest.of(2, 1); - Page resultPage = skillService.getAllSkills(pageable); - assertNotNull(resultPage); - assertEquals( - skillModelList.size(), - resultPage.getTotalElements(), - "The number of elements returned is not equal to the expected size"); - assertEquals( - skillModelList.size(), - resultPage.getContent().size(), - "The content returned is not equal to the expected content"); - assertEquals( - "Java", - resultPage.getContent().get(0).getName(), - "The returned skill on page 0 doesn't match the actual skill"); - assertEquals( - "Go", - resultPage.getContent().get(1).getName(), - "The returned skill on page 0 doesn't match the actual skill"); - } -}