diff --git a/pom.xml b/pom.xml index 1e51999d..06957e24 100644 --- a/pom.xml +++ b/pom.xml @@ -81,13 +81,13 @@ com.versionone VersionOne.SDK.Java.APIClient - 16.1.0 + 16.1.3 org.kohsuke github-api - 1.306 + 1.307 @@ -120,20 +120,67 @@ - org.springframework.restdocs - spring-restdocs-mockmvc - test + org.springframework.restdocs + spring-restdocs-mockmvc + test org.mockito mockito-core + 4.6.1 test + + + net.bytebuddy + byte-buddy + + + net.bytebuddy + byte-buddy-agent + + org.mockito mockito-junit-jupiter + 4.6.1 + test + + + + net.bytebuddy + byte-buddy + 1.12.13 + test + + + + net.bytebuddy + byte-buddy-agent + 1.12.13 + test + + + + com.infradna.tool + bridge-method-annotation + 1.23 + test + + + + com.google.code.findbugs + jsr305 + 3.0.2 + test + + + + com.google.code.findbugs + annotations + 3.0.1 test diff --git a/src/main/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheService.java b/src/main/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheService.java index a9be2042..ab8ef700 100644 --- a/src/main/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheService.java +++ b/src/main/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheService.java @@ -25,7 +25,7 @@ @Service public class ActiveSprintsScheduledCacheService extends AbstractProductScheduledCacheService, ActiveSprintsCache> { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(ActiveSprintsScheduledCacheService.class); @Autowired private ProductRepo productRepo; diff --git a/src/main/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheService.java b/src/main/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheService.java index 0868bd92..6503880c 100644 --- a/src/main/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheService.java +++ b/src/main/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheService.java @@ -26,7 +26,7 @@ @Service public class ProductsStatsScheduledCacheService extends AbstractProductScheduledCacheService, ProductsStatsCache> { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(ProductsStatsScheduledCacheService.class); @Autowired private ProductRepo productRepo; diff --git a/src/main/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheService.java b/src/main/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheService.java index bda9bb10..93b74b3e 100644 --- a/src/main/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheService.java +++ b/src/main/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheService.java @@ -24,7 +24,7 @@ @Service public class RemoteProjectsScheduledCacheService extends AbstractScheduledCacheService>, RemoteProjectsCache> { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(RemoteProjectsScheduledCacheService.class); @Autowired private RemoteProjectManagerRepo remoteProjectManagerRepo; diff --git a/src/main/java/edu/tamu/app/controller/ProductController.java b/src/main/java/edu/tamu/app/controller/ProductController.java index 04ee9ca2..141e8968 100644 --- a/src/main/java/edu/tamu/app/controller/ProductController.java +++ b/src/main/java/edu/tamu/app/controller/ProductController.java @@ -50,6 +50,8 @@ @RequestMapping("/products") public class ProductController { + private static final Logger logger = LoggerFactory.getLogger(ProductController.class); + @Autowired private ProductRepo productRepo; @@ -68,8 +70,6 @@ public class ProductController { @Autowired private InternalRequestRepo internalRequestRepo; - private Logger logger = LoggerFactory.getLogger(this.getClass()); - @GetMapping @JsonView(ApiView.Partial.class) @PreAuthorize("hasRole('ANONYMOUS')") diff --git a/src/main/java/edu/tamu/app/controller/RemoteProjectController.java b/src/main/java/edu/tamu/app/controller/RemoteProjectController.java index c56248ac..93c48ffd 100644 --- a/src/main/java/edu/tamu/app/controller/RemoteProjectController.java +++ b/src/main/java/edu/tamu/app/controller/RemoteProjectController.java @@ -1,28 +1,11 @@ package edu.tamu.app.controller; -import static edu.tamu.weaver.response.ApiStatus.ERROR; -import static edu.tamu.weaver.response.ApiStatus.SUCCESS; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - +import edu.tamu.app.model.repo.ProductRepo; +import edu.tamu.app.service.registry.ManagementBeanRegistry; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import edu.tamu.app.cache.model.RemoteProject; -import edu.tamu.app.model.Product; -import edu.tamu.app.model.RemoteProjectInfo; -import edu.tamu.app.model.RemoteProjectManager; -import edu.tamu.app.model.repo.ProductRepo; -import edu.tamu.app.service.manager.RemoteProjectManagerBean; -import edu.tamu.app.service.registry.ManagementBeanRegistry; -import edu.tamu.weaver.response.ApiResponse; - @RestController @RequestMapping("/projects/remote") public class RemoteProjectController { diff --git a/src/main/java/edu/tamu/app/controller/RemoteProjectManagerController.java b/src/main/java/edu/tamu/app/controller/RemoteProjectManagerController.java index 1214c90c..e4713837 100644 --- a/src/main/java/edu/tamu/app/controller/RemoteProjectManagerController.java +++ b/src/main/java/edu/tamu/app/controller/RemoteProjectManagerController.java @@ -30,14 +30,14 @@ @RequestMapping("/remote-project-manager") public class RemoteProjectManagerController { + private static final Logger logger = LoggerFactory.getLogger(RemoteProjectManagerController.class); + @Autowired private RemoteProjectManagerRepo remoteProjectManagerRepo; @Autowired private ProductRepo productRepo; - private Logger logger = LoggerFactory.getLogger(this.getClass()); - @GetMapping @PreAuthorize("hasRole('USER')") public ApiResponse getAll() { diff --git a/src/main/java/edu/tamu/app/controller/StatusController.java b/src/main/java/edu/tamu/app/controller/StatusController.java index e90c8db2..8c968ef4 100644 --- a/src/main/java/edu/tamu/app/controller/StatusController.java +++ b/src/main/java/edu/tamu/app/controller/StatusController.java @@ -1,10 +1,13 @@ package edu.tamu.app.controller; +import static edu.tamu.weaver.response.ApiStatus.ERROR; import static edu.tamu.weaver.response.ApiStatus.SUCCESS; import static edu.tamu.weaver.validation.model.BusinessValidationType.CREATE; import static edu.tamu.weaver.validation.model.BusinessValidationType.DELETE; import static edu.tamu.weaver.validation.model.BusinessValidationType.UPDATE; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; @@ -37,7 +40,12 @@ public ApiResponse read() { @GetMapping("/{id}") @PreAuthorize("hasRole('ANONYMOUS')") public ApiResponse read(@PathVariable Long id) { - return new ApiResponse(SUCCESS, statusRepo.findById(id)); + Optional status = statusRepo.findById(id); + if (status.isPresent()) { + return new ApiResponse(SUCCESS, status.get()); + } else { + return new ApiResponse(ERROR, String.format("Status with id %d does not exist.", id)); + } } @PostMapping diff --git a/src/main/java/edu/tamu/app/model/repo/impl/RemoteProjectManagerRepoImpl.java b/src/main/java/edu/tamu/app/model/repo/impl/RemoteProjectManagerRepoImpl.java index fa97dccc..73f8ffd0 100644 --- a/src/main/java/edu/tamu/app/model/repo/impl/RemoteProjectManagerRepoImpl.java +++ b/src/main/java/edu/tamu/app/model/repo/impl/RemoteProjectManagerRepoImpl.java @@ -16,7 +16,7 @@ public class RemoteProjectManagerRepoImpl extends AbstractWeaverRepoImpl implements RemoteProjectManagerRepoCustom { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(RemoteProjectManagerRepoImpl.class); @Autowired private RemoteProjectManagerRepo remoteProjectManagerRepo; diff --git a/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java b/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java index 2565644e..74ced261 100644 --- a/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java +++ b/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java @@ -41,7 +41,7 @@ public abstract class AbstractGitHubService extends MappingRemoteProjectManagerBean { - protected Logger logger = LoggerFactory.getLogger(this.getClass()); + protected static Logger logger = LoggerFactory.getLogger(AbstractGitHubService.class); static final String ORGANIZATION = "TAMULib"; static final String SPRINT = "SPRINT"; @@ -129,24 +129,25 @@ GitHub getGitHubInstance() { } Member getMember(final GHUser user) throws IOException { - Member member; final String memberId = String.valueOf(user.getId()); final Optional cachedMember = getCachedMember(memberId); + if (cachedMember.isPresent()) { - member = cachedMember.get(); - } else { - final String name = StringUtils.isEmpty(user.getName()) ? user.getLogin() : user.getName(); - final String avatarUrlString = user.getAvatarUrl(); - final String avatarPath = getAvatarPath(avatarUrlString); - member = new Member(memberId, name, avatarPath); - - final Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); - if (!avatarUrl.isPresent()) { - storeAvatar(avatarUrlString); - } + return cachedMember.get(); + } - cacheMember(memberId, member); + final String name = StringUtils.isEmpty(user.getName()) ? user.getLogin() : user.getName(); + final String avatarUrlString = user.getAvatarUrl(); + final String avatarPath = getAvatarPath(avatarUrlString); + final Member member = new Member(memberId, name, avatarPath); + final Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); + + if (!avatarUrl.isPresent()) { + storeAvatar(avatarUrlString); } + + cacheMember(memberId, member); + return member; } @@ -219,9 +220,12 @@ private String getAvatarPath(final String url) { private void storeAvatar(final String avatarUrl) throws IOException { final URL imagesPath = getClass().getResource("/images/"); final HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM)); + final HttpEntity entity = new HttpEntity(headers); - final ResponseEntity response = restTemplate.exchange(avatarUrl, HttpMethod.GET, entity, byte[].class, "1"); + final ResponseEntity response = restTemplate.exchange(avatarUrl, HttpMethod.GET, entity, byte[].class); + if (response.getStatusCode().equals(HttpStatus.OK)) { final File file = new File(imagesPath.getFile() + getAvatarPath(avatarUrl)); Files.write(file.toPath(), response.getBody()); diff --git a/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java b/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java index e2af0fc2..beea20f7 100644 --- a/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java +++ b/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java @@ -1,5 +1,9 @@ package edu.tamu.app.service.manager; +import edu.tamu.app.cache.model.Card; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.model.ManagementService; +import edu.tamu.app.model.ServiceType; import java.io.IOException; import java.util.List; import java.util.Map; @@ -8,21 +12,19 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.apache.commons.lang3.tuple.Pair; import org.kohsuke.github.GHMilestoneState; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHProject; import org.kohsuke.github.GHProject.ProjectStateFilter; import org.kohsuke.github.GHRepository; - -import edu.tamu.app.cache.model.Card; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.model.ManagementService; -import edu.tamu.app.model.ServiceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GitHubMilestoneService extends AbstractGitHubService { + protected static Logger logger = LoggerFactory.getLogger(GitHubMilestoneService.class); + public GitHubMilestoneService(final ManagementService managementService) { super(managementService); } @@ -32,7 +34,7 @@ public List getActiveSprintsByScopeId(final String scopeId) throws Excep logger.info("Fetching active sprints for remote project with scope id " + scopeId); GHRepository repo = github.getRepositoryById(scopeId); String productName = repo.getName(); - return repo.listProjects(ProjectStateFilter.OPEN).asList().stream() + return repo.listProjects(ProjectStateFilter.OPEN).toList().stream() .flatMap(project -> getActiveSprintsForProject(project, productName)) .collect(Collectors.toList()); } @@ -40,13 +42,12 @@ public List getActiveSprintsByScopeId(final String scopeId) throws Excep @Override public List getAdditionalActiveSprints() throws Exception { GHOrganization organization = github.getOrganization(ORGANIZATION); - return organization.listProjects(ProjectStateFilter.OPEN).asList().stream() + return organization.listProjects(ProjectStateFilter.OPEN).toList().stream() .flatMap(project -> getActiveSprintsForProject(project, toProductName(project))) .collect(Collectors.toList()); } private Stream getActiveSprintsForProject(GHProject project, String product) { - System.err.println("\n\n\nget: " + project + product + "\n\n\n"); AtomicInteger count = new AtomicInteger(); return exceptionHandlerWrapper(project, p -> getCards(p).entrySet()).stream() .map(e -> new Sprint(String.format("%s-%s", project.getId(), count.incrementAndGet()), e.getKey(), product, @@ -54,8 +55,8 @@ private Stream getActiveSprintsForProject(GHProject project, String prod } private Map> getCards(GHProject project) throws IOException { - return project.listColumns().asList().stream() - .flatMap(column -> exceptionHandlerWrapper(column, c -> c.listCards().asList().stream())) + return project.listColumns().toList().stream() + .flatMap(column -> exceptionHandlerWrapper(column, c -> c.listCards().toList().stream())) .map(card -> Pair.of(card, exceptionHandlerWrapper(card, c -> c.getContent()))) // Card without contents is a note .filter(p -> Objects.nonNull(p.getValue())) diff --git a/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java b/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java index 515e2c4a..53b60953 100644 --- a/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java +++ b/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java @@ -1,22 +1,24 @@ package edu.tamu.app.service.manager; +import edu.tamu.app.cache.model.Card; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.model.ManagementService; +import edu.tamu.app.model.ServiceType; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; - import org.apache.commons.lang3.tuple.Pair; import org.kohsuke.github.GHProject; import org.kohsuke.github.GHProject.ProjectStateFilter; import org.kohsuke.github.GHRepository; - -import edu.tamu.app.cache.model.Card; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.model.ManagementService; -import edu.tamu.app.model.ServiceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GitHubProjectService extends AbstractGitHubService { + protected static Logger logger = LoggerFactory.getLogger(GitHubMilestoneService.class); + public GitHubProjectService(final ManagementService managementService) throws IOException { super(managementService); } @@ -26,7 +28,7 @@ public List getActiveSprintsByScopeId(final String scopeId) throws Excep logger.info("Fetching active sprints for remote project with scope id " + scopeId); GHRepository repo = github.getRepositoryById(scopeId); String productName = repo.getName(); - return repo.listProjects(ProjectStateFilter.OPEN).asList().stream() + return repo.listProjects(ProjectStateFilter.OPEN).toList().stream() .filter(this::isSprintProject) .map(p -> toSprint(p, productName)) .collect(Collectors.toList()); @@ -35,7 +37,7 @@ public List getActiveSprintsByScopeId(final String scopeId) throws Excep @Override public List getAdditionalActiveSprints() throws Exception { return github.getOrganization(ORGANIZATION) - .listProjects(ProjectStateFilter.OPEN).asList().stream() + .listProjects(ProjectStateFilter.OPEN).toList().stream() .filter(this::isSprintProject) .map(p -> toSprint(p, ORGANIZATION)) .collect(Collectors.toList()); @@ -56,8 +58,8 @@ private Sprint toSprint(GHProject project, String productName) { } private List getCards(GHProject project) { - return exceptionHandlerWrapper(project, i -> i.listColumns().asList().stream()) - .flatMap(c -> exceptionHandlerWrapper(c, i -> i.listCards().asList().stream())) + return exceptionHandlerWrapper(project, i -> i.listColumns().toList().stream()) + .flatMap(c -> exceptionHandlerWrapper(c, i -> i.listCards().toList().stream())) .map(c -> Pair.of(c, exceptionHandlerWrapper(c, i -> i.getContent()))) // Card without contents is a note .filter(e -> Objects.nonNull(e.getValue())) diff --git a/src/main/java/edu/tamu/app/service/manager/VersionOneService.java b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java index 003c59a1..3e18271d 100644 --- a/src/main/java/edu/tamu/app/service/manager/VersionOneService.java +++ b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java @@ -52,7 +52,7 @@ public class VersionOneService extends MappingRemoteProjectManagerBean { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(VersionOneService.class); private final ManagementService managementService; @@ -238,35 +238,33 @@ public List getActiveSprintsCards(final String timeboxId) throws Connectio } public Member getMember(final String id) throws ConnectionException, APIException, OidException, IOException { - Member member; Optional cachedMember = getCachedMember(id); if (cachedMember.isPresent()) { - member = cachedMember.get(); - } else { - Oid oid = services.getOid("Member:" + id); - IAssetType memberType = services.getMeta().getAssetType("Member"); - IAttributeDefinition nameAttributeDefinition = memberType.getAttributeDefinition("Name"); - IAttributeDefinition avatarAttributeDefinition = memberType.getAttributeDefinition("Avatar"); + return cachedMember.get(); + } - Query query = new Query(oid); - query.getSelection().add(nameAttributeDefinition); - query.getSelection().add(avatarAttributeDefinition); + Oid oid = services.getOid("Member:" + id); + IAssetType memberType = services.getMeta().getAssetType("Member"); + IAttributeDefinition nameAttributeDefinition = memberType.getAttributeDefinition("Name"); + IAttributeDefinition avatarAttributeDefinition = memberType.getAttributeDefinition("Avatar"); - QueryResult result = services.retrieve(query); - Asset asset = result.getAssets()[0]; - String name = asset.getAttribute(nameAttributeDefinition).getValue().toString(); + Query query = new Query(oid); + query.getSelection().add(nameAttributeDefinition); + query.getSelection().add(avatarAttributeDefinition); - String avatarPath = parseAvatarUrlPath((Oid) asset.getAttribute(avatarAttributeDefinition).getValue()); + QueryResult result = services.retrieve(query); + Asset asset = result.getAssets()[0]; + String name = asset.getAttribute(nameAttributeDefinition).getValue().toString(); + String avatarPath = parseAvatarUrlPath((Oid) asset.getAttribute(avatarAttributeDefinition).getValue()); + Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); - Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); - if (!avatarUrl.isPresent()) { - storeAvatar(avatarPath); - } + if (!avatarUrl.isPresent()) { + storeAvatar(avatarPath); + } - member = new Member(id, name, avatarPath); + Member member = new Member(id, name, avatarPath); + cacheMember(id, member); - cacheMember(id, member); - } return member; } @@ -322,9 +320,12 @@ private String parseAvatarUrlPath(Oid imageOid) throws APIException { private void storeAvatar(String avatarPath) throws IOException { URL imagesPath = getClass().getResource("/images"); HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM)); + HttpEntity entity = new HttpEntity(headers); - ResponseEntity response = restTemplate.exchange(getUrl() + "/image.img/" + avatarPath, HttpMethod.GET, entity, byte[].class, "1"); + String url = getUrl() + "/image.img/" + avatarPath; + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class); if (response.getStatusCode().equals(HttpStatus.OK)) { File file = new File(imagesPath.getFile() + "/" + avatarPath); Files.write(file.toPath(), response.getBody()); diff --git a/src/main/java/edu/tamu/app/service/registry/ManagementBeanRegistry.java b/src/main/java/edu/tamu/app/service/registry/ManagementBeanRegistry.java index bad63045..c39187e1 100644 --- a/src/main/java/edu/tamu/app/service/registry/ManagementBeanRegistry.java +++ b/src/main/java/edu/tamu/app/service/registry/ManagementBeanRegistry.java @@ -21,7 +21,7 @@ @Service public class ManagementBeanRegistry { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private static final Logger logger = LoggerFactory.getLogger(ManagementBeanRegistry.class); private static final Map services = new HashMap(); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9b87c4e8..cb498ced 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,17 +2,25 @@ server: port: 9001 contextPath: ---- +# logging logging: + file: + name: logs/project-management-service.log level: + org.tdl: INFO edu.tamu: INFO org.springframework: INFO - file: logs/product-management-service.log + ro: + isdc: + wro: INFO + encoder: + pattern: "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" + rolling: + file-size: 5MB + threshold-level: ALL ---- security.basic.enabled: false ---- spring: main: allow-circular-references: true @@ -48,7 +56,6 @@ spring: show-sql: false hibernate.ddl-auto: create-drop ---- app: cache: default: @@ -101,7 +108,6 @@ app: # edu.tamu.weaver.utility.HttpUtility http.timeout: 10000 ---- ############################# # Framework auth properties # ############################# @@ -115,7 +121,6 @@ auth: # edu.tamu.weaver.token.provider.controller.TokenController path: /auth ---- ############################# # Framework shib properties # ############################# diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties deleted file mode 100644 index e8f3be48..00000000 --- a/src/main/resources/log4j.properties +++ /dev/null @@ -1,17 +0,0 @@ -# Root logger option -log4j.rootLogger=DEBUG, stdout, file - -# Redirect log messages to console -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=logger.info -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file -log4j.appender.file=org.apache.log4j.RollingFileAppender -#outputs to Tomcat home -log4j.appender.file.File=${catalina.home}/logs/myapp.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java index 19f60168..92fc10c3 100644 --- a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java @@ -51,7 +51,7 @@ public void testGetCache() { assertEquals(1, remoteProductsCache.size(), "Cached remote projects had incorrect number of remote projects!"); assertEquals(1, remoteProductsCache.get(1L).size(), "Cached remote projects did not have expected remote projects for a given remote project manager!"); - assertEquals(remoteProductsCache.get(1L).get(0).getId(), "0001", "Cached remote project had incorrect id!"); + assertEquals("0001", remoteProductsCache.get(1L).get(0).getId(), "Cached remote project had incorrect id!"); assertEquals("Sprint 1", remoteProductsCache.get(1L).get(0).getName(), "Cached remote project had incorrect name!"); assertEquals(2, remoteProductsCache.get(1L).get(0).getRequestCount(), "Cached remote project had incorrect number of requests!"); assertEquals(3, remoteProductsCache.get(1L).get(0).getIssueCount(), "Cached remote project had incorrect number of issues!"); diff --git a/src/test/java/edu/tamu/app/cache/controller/ActiveSprintsCacheControllerTest.java b/src/test/java/edu/tamu/app/cache/controller/ActiveSprintsCacheControllerTest.java index 4705a02f..28f2d9ed 100644 --- a/src/test/java/edu/tamu/app/cache/controller/ActiveSprintsCacheControllerTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/ActiveSprintsCacheControllerTest.java @@ -71,18 +71,18 @@ private Sprint getMockSprint() { private void assertSprints(List sprints) { assertFalse(sprints.isEmpty()); assertEquals(1, sprints.size()); - assertEquals("1", sprints.get(0).getId()); - assertEquals("Sprint 1", sprints.get(0).getName()); - assertEquals("Application", sprints.get(0).getProduct()); + assertEquals(sprints.get(0).getId(), "1"); + assertEquals(sprints.get(0).getName(), "Sprint 1"); + assertEquals(sprints.get(0).getProduct(), "Application"); assertEquals(ServiceType.GITHUB_MILESTONE.toString(), sprints.get(0).getType()); assertFalse(sprints.get(0).getCards().isEmpty()); assertEquals(1, sprints.get(0).getCards().size()); - assertEquals("1", sprints.get(0).getCards().get(0).getId()); - assertEquals("B-00001", sprints.get(0).getCards().get(0).getNumber()); - assertEquals("Feature", sprints.get(0).getCards().get(0).getType()); - assertEquals("Do the thing", sprints.get(0).getCards().get(0).getName()); - assertEquals("Do it with these requirements", sprints.get(0).getCards().get(0).getDescription()); - assertEquals("In Progress", sprints.get(0).getCards().get(0).getStatus()); + assertEquals(sprints.get(0).getCards().get(0).getId(), "1"); + assertEquals(sprints.get(0).getCards().get(0).getNumber(), "B-00001"); + assertEquals(sprints.get(0).getCards().get(0).getType(), "Feature"); + assertEquals(sprints.get(0).getCards().get(0).getName(), "Do the thing"); + assertEquals(sprints.get(0).getCards().get(0).getDescription(), "Do it with these requirements"); + assertEquals(sprints.get(0).getCards().get(0).getStatus(), "In Progress"); assertEquals(1.0, sprints.get(0).getCards().get(0).getEstimate(), 0); assertFalse(sprints.get(0).getCards().get(0).getAssignees().isEmpty()); assertEquals(1, sprints.get(0).getCards().get(0).getAssignees().size()); diff --git a/src/test/java/edu/tamu/app/cache/controller/ProductsStatsCacheControllerTest.java b/src/test/java/edu/tamu/app/cache/controller/ProductsStatsCacheControllerTest.java index 4b73696b..1b356498 100644 --- a/src/test/java/edu/tamu/app/cache/controller/ProductsStatsCacheControllerTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/ProductsStatsCacheControllerTest.java @@ -61,8 +61,8 @@ public void testUpdate() { private void assertProductsStats(List productsStatsCache) { assertFalse(productsStatsCache.isEmpty()); assertEquals(1, productsStatsCache.size()); - assertEquals("0001", productsStatsCache.get(0).getId()); - assertEquals("Sprint 1", productsStatsCache.get(0).getName()); + assertEquals(productsStatsCache.get(0).getId(), "0001"); + assertEquals(productsStatsCache.get(0).getName(), "Sprint 1"); assertEquals(2, productsStatsCache.get(0).getRequestCount()); assertEquals(3, productsStatsCache.get(0).getIssueCount()); assertEquals(10, productsStatsCache.get(0).getFeatureCount()); diff --git a/src/test/java/edu/tamu/app/cache/controller/RemoteProjectsCacheControllerTest.java b/src/test/java/edu/tamu/app/cache/controller/RemoteProjectsCacheControllerTest.java index dc724bd0..2e13adb6 100644 --- a/src/test/java/edu/tamu/app/cache/controller/RemoteProjectsCacheControllerTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/RemoteProjectsCacheControllerTest.java @@ -66,8 +66,8 @@ private void assertRemoteProducts(Map> remoteProductsC List remoteProjects = remoteProductsCache.get(1L); assertFalse(remoteProjects.isEmpty()); assertEquals(1, remoteProjects.size()); - assertEquals("0001", remoteProjects.get(0).getId()); - assertEquals("Sprint 1", remoteProjects.get(0).getName()); + assertEquals(remoteProjects.get(0).getId(), "0001"); + assertEquals(remoteProjects.get(0).getName(), "Sprint 1"); assertEquals(2, remoteProjects.get(0).getRequestCount()); assertEquals(3, remoteProjects.get(0).getIssueCount()); assertEquals(10, remoteProjects.get(0).getFeatureCount()); diff --git a/src/test/java/edu/tamu/app/cache/controller/integration/ActiveSprintsCacheControllerIntegrationTest.java b/src/test/java/edu/tamu/app/cache/controller/integration/ActiveSprintsCacheControllerIntegrationTest.java index fcb320fe..09b539fa 100644 --- a/src/test/java/edu/tamu/app/cache/controller/integration/ActiveSprintsCacheControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/integration/ActiveSprintsCacheControllerIntegrationTest.java @@ -15,7 +15,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; @@ -25,7 +24,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import edu.tamu.app.ProductApplication; @@ -41,7 +39,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class ActiveSprintsCacheControllerIntegrationTest extends AbstractRepoTest { private static final String TEST_MEMBER_ID = "Test Member ID"; diff --git a/src/test/java/edu/tamu/app/cache/controller/integration/ProductsStatsCacheControllerIntegrationTest.java b/src/test/java/edu/tamu/app/cache/controller/integration/ProductsStatsCacheControllerIntegrationTest.java index a301be3f..3cc74a47 100644 --- a/src/test/java/edu/tamu/app/cache/controller/integration/ProductsStatsCacheControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/integration/ProductsStatsCacheControllerIntegrationTest.java @@ -15,7 +15,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; @@ -25,7 +24,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import edu.tamu.app.ProductApplication; @@ -38,9 +36,8 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class ProductsStatsCacheControllerIntegrationTest extends AbstractRepoTest { - + private static final String TEST_PRODUCT_STATS_ID = "0010"; private static final String TEST_PRODUCT_STATS_NAME = "Product Name"; @@ -101,6 +98,7 @@ public void testProductStatsCacheGet() throws Exception { fieldWithPath("payload['ArrayList']").description("The array of Product Stats."), fieldWithPath("payload['ArrayList'][0].id").description("The Product Scope ID."), fieldWithPath("payload['ArrayList'][0].name").description("The Product Name."), + fieldWithPath("payload['ArrayList'][0].backlogItemCount").description("The Product total Backlog Items."), fieldWithPath("payload['ArrayList'][0].requestCount").description("The Product total Requests."), fieldWithPath("payload['ArrayList'][0].issueCount").description("The Product total Issues."), fieldWithPath("payload['ArrayList'][0].featureCount").description("The Product total Features."), diff --git a/src/test/java/edu/tamu/app/cache/controller/integration/RemoteProjectsStatsCacheControllerIntegrationTest.java b/src/test/java/edu/tamu/app/cache/controller/integration/RemoteProjectsStatsCacheControllerIntegrationTest.java index 729cd40b..6a5bab0c 100644 --- a/src/test/java/edu/tamu/app/cache/controller/integration/RemoteProjectsStatsCacheControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/cache/controller/integration/RemoteProjectsStatsCacheControllerIntegrationTest.java @@ -17,7 +17,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; @@ -27,7 +26,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import edu.tamu.app.ProductApplication; @@ -40,7 +38,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class RemoteProjectsStatsCacheControllerIntegrationTest extends AbstractRepoTest { private static final String TEST_REMOTE_PROJECTS_ID = "0010"; @@ -107,6 +104,7 @@ public void testRemoteProjectsCacheGet() throws Exception { fieldWithPath("payload.HashMap['1']").description("The array of Remote Project stats."), fieldWithPath("payload.HashMap['1'][0].id").description("The Remote Project Scope ID."), fieldWithPath("payload.HashMap['1'][0].name").description("The Remote Project Name."), + fieldWithPath("payload.HashMap['1'][0].backlogItemCount").description("The Remote Project total Backlog Items."), fieldWithPath("payload.HashMap['1'][0].requestCount").description("The Remote Project total Requests."), fieldWithPath("payload.HashMap['1'][0].issueCount").description("The Remote Project total Issues."), fieldWithPath("payload.HashMap['1'][0].featureCount").description("The Remote Project total Features."), diff --git a/src/test/java/edu/tamu/app/cache/model/CardTest.java b/src/test/java/edu/tamu/app/cache/model/CardTest.java index 97962e59..c3850b6f 100644 --- a/src/test/java/edu/tamu/app/cache/model/CardTest.java +++ b/src/test/java/edu/tamu/app/cache/model/CardTest.java @@ -17,18 +17,18 @@ public class CardTest { public void testNewCard() { List assignees = Arrays.asList(new Member[] { new Member("1", "Bob Boring", "http://gravatar.com/bborring") }); Card card = new Card("1", "B-00001", "Feature", "Do the thing", "Do it with these requirements", "In Progress", 1.0f, assignees); - assertEquals("1", card.getId()); - assertEquals("B-00001", card.getNumber()); - assertEquals("Feature", card.getType()); - assertEquals("Do the thing", card.getName()); - assertEquals("Do it with these requirements", card.getDescription()); - assertEquals("In Progress", card.getStatus()); + assertEquals(card.getId(), "1"); + assertEquals(card.getNumber(), "B-00001"); + assertEquals(card.getType(), "Feature"); + assertEquals(card.getName(), "Do the thing"); + assertEquals(card.getDescription(), "Do it with these requirements"); + assertEquals(card.getStatus(), "In Progress"); assertEquals(1.0, card.getEstimate(), 0); assertFalse(card.getAssignees().isEmpty()); assertEquals(1, card.getAssignees().size()); - assertEquals("1", card.getAssignees().get(0).getId()); - assertEquals("Bob Boring", card.getAssignees().get(0).getName()); - assertEquals("http://gravatar.com/bborring", card.getAssignees().get(0).getAvatar()); + assertEquals(card.getAssignees().get(0).getId(), "1"); + assertEquals(card.getAssignees().get(0).getName(), "Bob Boring"); + assertEquals(card.getAssignees().get(0).getAvatar(), "http://gravatar.com/bborring"); } } diff --git a/src/test/java/edu/tamu/app/cache/model/MemberTest.java b/src/test/java/edu/tamu/app/cache/model/MemberTest.java index 90e3b2f7..c3369ea9 100644 --- a/src/test/java/edu/tamu/app/cache/model/MemberTest.java +++ b/src/test/java/edu/tamu/app/cache/model/MemberTest.java @@ -12,9 +12,9 @@ public class MemberTest { @Test public void testNewAssignee() { Member member = new Member("1", "Bob Boring", "http://gravatar.com/bborring"); - assertEquals("1", member.getId()); - assertEquals("Bob Boring", member.getName()); - assertEquals("http://gravatar.com/bborring", member.getAvatar()); + assertEquals(member.getId(), "1"); + assertEquals(member.getName(), "Bob Boring"); + assertEquals(member.getAvatar(), "http://gravatar.com/bborring"); } } diff --git a/src/test/java/edu/tamu/app/cache/model/ProductStatsTest.java b/src/test/java/edu/tamu/app/cache/model/ProductStatsTest.java index 5f846879..95735b20 100644 --- a/src/test/java/edu/tamu/app/cache/model/ProductStatsTest.java +++ b/src/test/java/edu/tamu/app/cache/model/ProductStatsTest.java @@ -12,8 +12,8 @@ public class ProductStatsTest { @Test public void testNewProductStats() { ProductStats productStats = new ProductStats("0001", "Sprint 1", 2, 3, 10, 3, 1); - assertEquals("0001", productStats.getId()); - assertEquals("Sprint 1", productStats.getName()); + assertEquals(productStats.getId(), "0001"); + assertEquals(productStats.getName(), "Sprint 1"); assertEquals(2, productStats.getRequestCount()); assertEquals(3, productStats.getIssueCount()); assertEquals(10, productStats.getFeatureCount()); diff --git a/src/test/java/edu/tamu/app/cache/model/RemoteProjectTest.java b/src/test/java/edu/tamu/app/cache/model/RemoteProjectTest.java index ac94e602..be2b5c0b 100644 --- a/src/test/java/edu/tamu/app/cache/model/RemoteProjectTest.java +++ b/src/test/java/edu/tamu/app/cache/model/RemoteProjectTest.java @@ -12,8 +12,8 @@ public class RemoteProjectTest { @Test public void testNewRemoteProduct() { RemoteProject remoteProject = new RemoteProject("0001", "Sprint 1", 2, 3, 10, 3, 1); - assertEquals("0001", remoteProject.getId()); - assertEquals("Sprint 1", remoteProject.getName()); + assertEquals(remoteProject.getId(), "0001"); + assertEquals(remoteProject.getName(), "Sprint 1"); assertEquals(2, remoteProject.getRequestCount()); assertEquals(3, remoteProject.getIssueCount()); assertEquals(10, remoteProject.getFeatureCount()); diff --git a/src/test/java/edu/tamu/app/cache/model/SprintTest.java b/src/test/java/edu/tamu/app/cache/model/SprintTest.java index 39e2bc8b..a22e683e 100644 --- a/src/test/java/edu/tamu/app/cache/model/SprintTest.java +++ b/src/test/java/edu/tamu/app/cache/model/SprintTest.java @@ -20,18 +20,18 @@ public void testNewSprint() { List assignees = Arrays.asList(new Member[] { new Member("1", "Bob Boring", "http://gravatar.com/bborring") }); List cards = Arrays.asList(new Card[] { new Card("1", "B-00001", "Feature", "Do the thing", "Do it with these requirements", "In Progress", 1.0f, assignees) }); Sprint sprint = new Sprint("1", "Sprint 1", "Application", ServiceType.GITHUB_MILESTONE.toString(), cards); - assertEquals("1", sprint.getId()); - assertEquals("Sprint 1", sprint.getName()); - assertEquals("Application", sprint.getProduct()); + assertEquals(sprint.getId(), "1"); + assertEquals(sprint.getName(), "Sprint 1"); + assertEquals(sprint.getProduct(), "Application"); assertEquals(ServiceType.GITHUB_MILESTONE.toString(), sprint.getType()); assertFalse(sprint.getCards().isEmpty()); assertEquals(1, sprint.getCards().size()); - assertEquals("1", sprint.getCards().get(0).getId()); - assertEquals("B-00001", sprint.getCards().get(0).getNumber()); - assertEquals("Feature", sprint.getCards().get(0).getType()); - assertEquals("Do the thing", sprint.getCards().get(0).getName()); - assertEquals("Do it with these requirements", sprint.getCards().get(0).getDescription()); - assertEquals("In Progress", sprint.getCards().get(0).getStatus()); + assertEquals(sprint.getCards().get(0).getId(), "1"); + assertEquals(sprint.getCards().get(0).getNumber(), "B-00001"); + assertEquals(sprint.getCards().get(0).getType(), "Feature"); + assertEquals(sprint.getCards().get(0).getName(), "Do the thing"); + assertEquals(sprint.getCards().get(0).getDescription(), "Do it with these requirements"); + assertEquals(sprint.getCards().get(0).getStatus(), "In Progress"); assertEquals(1.0, sprint.getCards().get(0).getEstimate(), 0); assertFalse(sprint.getCards().get(0).getAssignees().isEmpty()); assertEquals(1, sprint.getCards().get(0).getAssignees().size()); diff --git a/src/test/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheServiceTest.java b/src/test/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheServiceTest.java index 1ab9b880..1b807073 100644 --- a/src/test/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheServiceTest.java +++ b/src/test/java/edu/tamu/app/cache/service/ActiveSprintsScheduledCacheServiceTest.java @@ -144,18 +144,18 @@ private Sprint getMockSprint() { private void assertSprints(List sprints) { assertFalse(sprints.isEmpty()); assertEquals(1, sprints.size()); - assertEquals("2000", sprints.get(0).getId()); - assertEquals("Sprint 1", sprints.get(0).getName()); - assertEquals("Test Product", sprints.get(0).getProduct()); + assertEquals(sprints.get(0).getId(), "2000"); + assertEquals(sprints.get(0).getName(), "Sprint 1"); + assertEquals(sprints.get(0).getProduct(), "Test Product"); assertEquals(ServiceType.GITHUB_MILESTONE.toString(), sprints.get(0).getType()); assertFalse(sprints.get(0).getCards().isEmpty()); assertEquals(1, sprints.get(0).getCards().size()); - assertEquals("3000", sprints.get(0).getCards().get(0).getId()); - assertEquals("B-00001", sprints.get(0).getCards().get(0).getNumber()); - assertEquals("Feature", sprints.get(0).getCards().get(0).getType()); - assertEquals("Do the thing", sprints.get(0).getCards().get(0).getName()); - assertEquals("Do it with these requirements", sprints.get(0).getCards().get(0).getDescription()); - assertEquals("In Progress", sprints.get(0).getCards().get(0).getStatus()); + assertEquals(sprints.get(0).getCards().get(0).getId(), "3000"); + assertEquals(sprints.get(0).getCards().get(0).getNumber(), "B-00001"); + assertEquals(sprints.get(0).getCards().get(0).getType(), "Feature"); + assertEquals(sprints.get(0).getCards().get(0).getName(), "Do the thing"); + assertEquals(sprints.get(0).getCards().get(0).getDescription(), "Do it with these requirements"); + assertEquals(sprints.get(0).getCards().get(0).getStatus(), "In Progress"); assertEquals(1.0, sprints.get(0).getCards().get(0).getEstimate(), 0); assertFalse(sprints.get(0).getCards().get(0).getAssignees().isEmpty()); assertEquals(1, sprints.get(0).getCards().get(0).getAssignees().size()); diff --git a/src/test/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheServiceTest.java b/src/test/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheServiceTest.java index 90ab3128..ce66f122 100644 --- a/src/test/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheServiceTest.java +++ b/src/test/java/edu/tamu/app/cache/service/ProductsStatsScheduledCacheServiceTest.java @@ -140,7 +140,7 @@ private RemoteProject getMockRemoteProduct() { private void assertProductsStats(List productStatsCache) { assertFalse(productStatsCache.isEmpty()); assertEquals(1, productStatsCache.size()); - assertEquals("1000", productStatsCache.get(0).getId()); + assertEquals(productStatsCache.get(0).getId(), "1000"); assertEquals(TEST_PRODUCT_NAME, productStatsCache.get(0).getName()); assertEquals(2, productStatsCache.get(0).getRequestCount()); assertEquals(3, productStatsCache.get(0).getIssueCount()); diff --git a/src/test/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheServiceTest.java b/src/test/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheServiceTest.java index 950eb536..ddf3076f 100644 --- a/src/test/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheServiceTest.java +++ b/src/test/java/edu/tamu/app/cache/service/RemoteProjectsScheduledCacheServiceTest.java @@ -134,8 +134,8 @@ private void assertRemoteProducts(Map> remoteProductsC } private void assertRemoteProduct(RemoteProject remoteProject) { - assertEquals("0001", remoteProject.getId()); - assertEquals("Sprint 1", remoteProject.getName()); + assertEquals(remoteProject.getId(), "0001"); + assertEquals(remoteProject.getName(), "Sprint 1"); assertEquals(2, remoteProject.getRequestCount()); assertEquals(3, remoteProject.getIssueCount()); assertEquals(10, remoteProject.getFeatureCount()); diff --git a/src/test/java/edu/tamu/app/controller/ProductControllerTest.java b/src/test/java/edu/tamu/app/controller/ProductControllerTest.java index 23725905..0bc03fe1 100644 --- a/src/test/java/edu/tamu/app/controller/ProductControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/ProductControllerTest.java @@ -48,8 +48,16 @@ @ExtendWith(SpringExtension.class) public class ProductControllerTest { + private static final Long TEST_PRODUCT1_ID = 1L; + private static final Long TEST_PRODUCT2_ID = 2L; + + private static final Long TEST_INVALID_PRODUCT_ID = 3L; + + private static final Long TEST_REMOTE_PROJECT_MANAGER_ONE_ID = 1L; + private static final String TEST_PRODUCT1_NAME = "Test Product 1 Name"; private static final String TEST_PRODUCT2_NAME = "Test Product 2 Name"; + private static final String TEST_PRODUCT3_NAME = "Test Product 3 Name"; private static final String TEST_MODIFIED_PRODUCT_NAME = "Modified Product Name"; @@ -66,9 +74,9 @@ public class ProductControllerTest { private static final String TEST_RMP_ONE_NAME = "Test Remote Project Manager 1"; private static final String INVALID_RPM_ID_ERROR_MESSAGE_FIND_BY_ID = "Error fetching remote project with scope id " + TEST_INVALID_SCOPE + " from " + TEST_RMP_ONE_NAME + "!"; - private static final String INVALID_PRODUCT_ID_ERROR_MESSAGE = "Product with id null not found!"; + private static final String INVALID_PRODUCT_ID_ERROR_MESSAGE = "Product with id " + TEST_INVALID_PRODUCT_ID + " not found!"; private static final String INVALID_RPM_ID_ERROR_MESSAGE = "Error fetching remote projects from " + TEST_RMP_ONE_NAME + "!"; - private static final String MISSING_RPM_ERROR_MESSAGE = "Remote Project Manager with id null not found!"; + private static final String MISSING_RPM_ERROR_MESSAGE = "Remote Project Manager with id " + TEST_REMOTE_PROJECT_MANAGER_ONE_ID + " not found!"; private static final RemoteProjectManager TEST_REMOTE_PROJECT_MANAGER = new RemoteProjectManager("Test Remote Project Manager", ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); @@ -82,6 +90,7 @@ public class ProductControllerTest { private static Product TEST_PRODUCT1 = new Product(TEST_PRODUCT1_NAME, TEST_PRODUCT1_REMOTE_PROJECT_INFO_LIST); private static Product TEST_PRODUCT2 = new Product(TEST_PRODUCT2_NAME); + private static Product TEST_PRODUCT3 = new Product(TEST_PRODUCT3_NAME); private static Product TEST_MODIFIED_PRODUCT = new Product(TEST_MODIFIED_PRODUCT_NAME); private static RemoteProjectManager testRemoteProjectManagerOne = new RemoteProjectManager(TEST_RMP_ONE_NAME, ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); @@ -90,7 +99,7 @@ public class ProductControllerTest { private static TicketRequest TEST_TICKET_REQUEST = new TicketRequest(); - private static FeatureRequest TEST_FEATURE_REQUEST = new FeatureRequest(TEST_FEATURE_REQUEST_TITLE, TEST_FEATURE_REQUEST_DESCRIPTION, TEST_PRODUCT1.getId(), TEST_PROJECT1_SCOPE1); + private static FeatureRequest TEST_FEATURE_REQUEST = new FeatureRequest(TEST_FEATURE_REQUEST_TITLE, TEST_FEATURE_REQUEST_DESCRIPTION, TEST_PRODUCT1_ID, TEST_PROJECT1_SCOPE1); private static List mockProductList = new ArrayList(Arrays.asList(new Product[] { TEST_PRODUCT1, TEST_PRODUCT2 })); @@ -128,15 +137,17 @@ public void setup() throws Exception { MockitoAnnotations.openMocks(this); when(productRepo.findAll()).thenReturn(mockProductList); when(productRepo.create(any(Product.class))).thenReturn(TEST_PRODUCT1); - when(productRepo.findById(any(Long.class))).thenReturn(null); + when(productRepo.findById(any(Long.class))).thenReturn(Optional.empty()); when(productRepo.update(any(Product.class))).thenReturn(TEST_MODIFIED_PRODUCT); when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_REMOTE_PROJECT_MANAGER)); doNothing().when(productRepo).delete(any(Product.class)); when(sugarService.submit(any(TicketRequest.class))).thenReturn("Successfully submitted issue for test service!"); when(internalRequestRepo.create(any(InternalRequest.class))).thenReturn(TEST_REQUEST1); - TEST_PRODUCT1.setId(1L); - TEST_PRODUCT2.setId(2L); + TEST_PRODUCT1.setId(TEST_PRODUCT1_ID); + TEST_PRODUCT2.setId(TEST_PRODUCT2_ID); + + testRemoteProjectManagerOne.setId(TEST_REMOTE_PROJECT_MANAGER_ONE_ID); ProductsStatsScheduledCacheService productsStatsScheduledCacheService = mock(ProductsStatsScheduledCacheService.class); @@ -173,7 +184,7 @@ public void testGetAllProducts() { @Test public void testGetProductById() { when(productRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_PRODUCT1)); - apiResponse = productController.getOne(TEST_PRODUCT1.getId()); + apiResponse = productController.getOne(TEST_PRODUCT1_ID); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Not successful at getting requested Product"); Product product = (Product) apiResponse.getPayload().get("Product"); assertEquals(TEST_PRODUCT1, product, "Did not get the expected Product"); @@ -181,7 +192,7 @@ public void testGetProductById() { @Test public void testCreate() { - apiResponse = productController.createProduct(TEST_PRODUCT1); + apiResponse = productController.createProduct(TEST_PRODUCT3); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Not successful at creating Product"); } @@ -195,7 +206,7 @@ public void testUpdate() { @Test public void testDelete() { - apiResponse = productController.deleteProduct(TEST_PRODUCT1); + apiResponse = productController.deleteProduct(TEST_PRODUCT3); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Not successful at deleting Product"); } @@ -229,7 +240,7 @@ public void testGetAllRemoteProductsForProduct() throws Exception { when(remoteProjectManagementBean.push(TEST_FEATURE_REQUEST)).thenReturn(TEST_FEATURE_REQUEST.getScopeId()); when(managementBeanRegistry.getService(any(String.class))).thenReturn(remoteProjectManagementBean); when(productRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_PRODUCT1)); - apiResponse = productController.getAllRemoteProjectsForProduct(TEST_PRODUCT1.getId()); + apiResponse = productController.getAllRemoteProjectsForProduct(TEST_PRODUCT1_ID); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Remote Project controller unable to get all remote products for the specified product"); } @@ -237,16 +248,16 @@ public void testGetAllRemoteProductsForProduct() throws Exception { public void testGetAllRemoteProductsForProductWithInvalidId() throws Exception { when(remoteProjectManagementBean.push(TEST_FEATURE_REQUEST)).thenReturn(TEST_FEATURE_REQUEST.getScopeId()); when(managementBeanRegistry.getService(any(String.class))).thenReturn(remoteProjectManagementBean); - apiResponse = productController.getAllRemoteProjectsForProduct(null); + apiResponse = productController.getAllRemoteProjectsForProduct(3L); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request with invalid Product id did not result in an error"); assertEquals(INVALID_PRODUCT_ID_ERROR_MESSAGE, apiResponse.getMeta().getMessage(), "Invalid Product id did not result in the expected error message"); } @Test public void testGetAllRemoteProductsForProductWithNoRemoteProductManager() { - when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(null); + when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.empty()); when(productRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_PRODUCT1)); - apiResponse = productController.getAllRemoteProjectsForProduct(TEST_PRODUCT1.getId()); + apiResponse = productController.getAllRemoteProjectsForProduct(TEST_PRODUCT1_ID); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request without Remote Project Manager did not result in an error"); assertEquals("Error fetching remote projects associated with product " + TEST_PRODUCT1.getName() + "!", apiResponse.getMeta().getMessage(), "Missing Remote Project Manager did not result in the expected error message"); } @@ -256,22 +267,22 @@ public void testGetAllRemoteProjects() throws Exception { when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(testRemoteProjectManagerOne)); when(remoteProjectManagementBean.push(TEST_FEATURE_REQUEST)).thenReturn("1"); when(managementBeanRegistry.getService(any(String.class))).thenReturn(remoteProjectManagementBean); - apiResponse = productController.getAllRemoteProjects(testRemoteProjectManagerOne.getId()); + apiResponse = productController.getAllRemoteProjects(TEST_REMOTE_PROJECT_MANAGER_ONE_ID); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Remote Project Manager controller unable to get all remote projects"); } @Test public void testGetAllRemoteProjectsWithInvalidRemoteProjectManager() { when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(testRemoteProjectManagerOne)); - apiResponse = productController.getAllRemoteProjects(testRemoteProjectManagerOne.getId()); + apiResponse = productController.getAllRemoteProjects(TEST_REMOTE_PROJECT_MANAGER_ONE_ID); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request with invalid Remote Project Manager id did not result in an error"); assertEquals(INVALID_RPM_ID_ERROR_MESSAGE, apiResponse.getMeta().getMessage(), "Invalid Remote Project Manager id did not result in the expected error message"); } @Test public void testGetAllRemoteProjectsWithNoRemoteProjectManager() { - when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(null); - apiResponse = productController.getAllRemoteProjects(testRemoteProjectManagerOne.getId()); + when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.empty()); + apiResponse = productController.getAllRemoteProjects(TEST_REMOTE_PROJECT_MANAGER_ONE_ID); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request without Remote Project Manager did not result in an error"); assertEquals(MISSING_RPM_ERROR_MESSAGE, apiResponse.getMeta().getMessage(), "Missing Remote Project Manager did not result in the expected error message"); } @@ -281,24 +292,24 @@ public void testGetRemoteProjectByScopeId() throws Exception { when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(testRemoteProjectManagerOne)); when(remoteProjectManagementBean.getRemoteProjectByScopeId(TEST_PROJECT1_SCOPE1)).thenReturn(new RemoteProject()); when(managementBeanRegistry.getService(any(String.class))).thenReturn(remoteProjectManagementBean); - apiResponse = productController.getRemoteProjectByScopeId(testRemoteProjectManagerOne.getId(), TEST_PROJECT1_SCOPE1); + apiResponse = productController.getRemoteProjectByScopeId(TEST_REMOTE_PROJECT_MANAGER_ONE_ID, TEST_PROJECT1_SCOPE1); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Product controller unable to get remote project by scope id"); } @Test public void testGetRemoteProjectByScopeIdWithInvalidScope() { when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(testRemoteProjectManagerOne)); - apiResponse = productController.getRemoteProjectByScopeId(testRemoteProjectManagerOne.getId(), TEST_INVALID_SCOPE); + apiResponse = productController.getRemoteProjectByScopeId(TEST_REMOTE_PROJECT_MANAGER_ONE_ID, TEST_INVALID_SCOPE); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request with invalid Remote Project Manager id did not result in an error"); assertEquals(INVALID_RPM_ID_ERROR_MESSAGE_FIND_BY_ID, apiResponse.getMeta().getMessage(), "Invalid Remote Project Manager id did not result in the expected error message"); } @Test public void testGetRemoteProjectByScopeIdWithMissingRemoteProjectManager() { - when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(null); - apiResponse = productController.getRemoteProjectByScopeId(testRemoteProjectManagerOne.getId(), TEST_PROJECT1_SCOPE1); + when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.empty()); + apiResponse = productController.getRemoteProjectByScopeId(TEST_REMOTE_PROJECT_MANAGER_ONE_ID, TEST_PROJECT1_SCOPE1); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Request with no Remote Project Manager did not result in an error"); assertEquals(MISSING_RPM_ERROR_MESSAGE, apiResponse.getMeta().getMessage(), "Missing Remote Project Manager did not result in the expected error message"); } -} \ No newline at end of file +} diff --git a/src/test/java/edu/tamu/app/controller/RemoteProjectManagerControllerTest.java b/src/test/java/edu/tamu/app/controller/RemoteProjectManagerControllerTest.java index 2ceb3d26..028b9dc4 100644 --- a/src/test/java/edu/tamu/app/controller/RemoteProjectManagerControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/RemoteProjectManagerControllerTest.java @@ -91,6 +91,8 @@ public void setUp() { when(productRepo.create(any(Product.class))).thenReturn(TEST_PRODUCT1); when(productRepo.findById(any(Long.class))).thenReturn(null); doNothing().when(productRepo).delete(any(Product.class)); + + testRemoteProjectManagerOne.setId(1L); } @Test diff --git a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java index dbc9c44f..ff7f8de5 100644 --- a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java @@ -42,6 +42,8 @@ public void setup() { noneStatus = new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" }))); doneStatus = new Status("Done", new HashSet(Arrays.asList(new String[] { "Done" }))); + noneStatus.setId(1L); + when(statusRepo.findAll()).thenReturn(new ArrayList(Arrays.asList(new Status[] { noneStatus, doneStatus }))); when(statusRepo.create(any(Status.class))).thenReturn(noneStatus); when(statusRepo.update(any(Status.class))).thenReturn(noneStatus); @@ -83,4 +85,4 @@ public void testDelete() { assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Status was not successfully deleted"); } -} \ No newline at end of file +} diff --git a/src/test/java/edu/tamu/app/controller/integration/InternalRequestControllerIntegrationTest.java b/src/test/java/edu/tamu/app/controller/integration/InternalRequestControllerIntegrationTest.java index 814c4118..452f752c 100644 --- a/src/test/java/edu/tamu/app/controller/integration/InternalRequestControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/controller/integration/InternalRequestControllerIntegrationTest.java @@ -27,13 +27,9 @@ import java.util.List; import java.util.Optional; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; @@ -44,10 +40,12 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; + import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; import edu.tamu.app.cache.service.ProductsStatsScheduledCacheService; @@ -69,7 +67,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class InternalRequestControllerIntegrationTest extends AbstractRepoTest { private static long currentId = 0L; diff --git a/src/test/java/edu/tamu/app/controller/integration/ProductControllerIntegrationTest.java b/src/test/java/edu/tamu/app/controller/integration/ProductControllerIntegrationTest.java index ab47a253..92ece79b 100644 --- a/src/test/java/edu/tamu/app/controller/integration/ProductControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/controller/integration/ProductControllerIntegrationTest.java @@ -27,7 +27,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; @@ -40,7 +39,6 @@ import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -57,9 +55,9 @@ import edu.tamu.app.model.RemoteProjectInfo; import edu.tamu.app.model.RemoteProjectManager; import edu.tamu.app.model.ServiceType; +import edu.tamu.app.model.repo.AbstractRepoTest; import edu.tamu.app.model.repo.ProductRepo; import edu.tamu.app.model.repo.RemoteProjectManagerRepo; -import edu.tamu.app.model.repo.AbstractRepoTest; import edu.tamu.app.model.request.FeatureRequest; import edu.tamu.app.model.request.TicketRequest; import edu.tamu.app.service.manager.GitHubProjectService; @@ -74,7 +72,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class ProductControllerIntegrationTest extends AbstractRepoTest { @Value("classpath:mock/credentials/aggiejack.json") @@ -167,6 +164,7 @@ public void setup() { when(remoteProjectManagerRepo.findAll()).thenReturn(TEST_REMOTE_PROJECT_MANAGER_LIST); when(remoteProjectManagerRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_REMOTE_PROJECT_MANAGER)); + when(remoteProjectManagerRepo.getById(any(Long.class))).thenReturn(TEST_REMOTE_PROJECT_MANAGER); doNothing().when(remoteProjectManagerRepo).delete(any(RemoteProjectManager.class)); @@ -205,8 +203,8 @@ public void testGetProducts() throws Exception { .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.id", equalTo((int) TEST_REMOTE_PROJECT_MANAGER_ID))) .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.name", equalTo(TEST_REMOTE_PROJECT_MANAGER.getName()))) .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.type", equalTo(TEST_REMOTE_PROJECT_MANAGER.getType().toString()))) - .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.url").doesNotExist()) - .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.token").doesNotExist()) + .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.url", equalTo(TEST_PROJECT_URL))) + .andExpect(jsonPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.token", equalTo(TEST_PROJECT_TOKEN))) .andDo( document( "products/get-all", @@ -216,7 +214,23 @@ public void testGetProducts() throws Exception { fieldWithPath("meta.action").description("Action of the request."), fieldWithPath("meta.message").description("Message of the response."), fieldWithPath("meta.status").description("Status of the response."), - fieldWithPath("payload").description("API response payload containing the List of Products.") + fieldWithPath("payload").description("API response payload containing the List of Products."), + fieldWithPath("payload.ArrayList[0]").description("The List of Products."), + fieldWithPath("payload.ArrayList[0].id").description("ID of the Product."), + fieldWithPath("payload.ArrayList[0].name").description("Name of the Product."), + fieldWithPath("payload.ArrayList[0].scopeId").description("Scope ID of the Product."), + fieldWithPath("payload.ArrayList[0].devUrl").description("Dev URL of the Product."), + fieldWithPath("payload.ArrayList[0].preUrl").description("Pre URL of the Product."), + fieldWithPath("payload.ArrayList[0].productionUrl").description("Production URL of the Product."), + fieldWithPath("payload.ArrayList[0].wikiUrl").description( "Wiki URL of the Product."), + fieldWithPath("payload.ArrayList[0].otherUrls[0]").description("Other URL of the Product."), + fieldWithPath("payload.ArrayList[0].otherUrls[1]").description("Other URL of the Product."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].scopeId").description("Scope ID of the Remote Project."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.id").description("ID of the Remote Project Manager."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.name").description("Name of the Remote Project Manager."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.type").description("Type of the Remote Project Manager."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.url").description("URL of the Remote Project Manager."), + fieldWithPath("payload.ArrayList[0].remoteProjectInfo[0].remoteProjectManager.token").description("Token of the Remote Project Manager.") ) ) ); @@ -249,8 +263,8 @@ public void testGetProductById() throws Exception { .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.id", equalTo((int) TEST_REMOTE_PROJECT_MANAGER_ID))) .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.name", equalTo(TEST_REMOTE_PROJECT_MANAGER.getName()))) .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.type", equalTo(TEST_REMOTE_PROJECT_MANAGER.getType().toString()))) - .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.url").doesNotExist()) - .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.token").doesNotExist()) + .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.url", equalTo(TEST_PROJECT_URL))) + .andExpect(jsonPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.token", equalTo(TEST_PROJECT_TOKEN))) .andDo( document( "products/get", @@ -274,7 +288,9 @@ public void testGetProductById() throws Exception { fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager").description("The Remote Project Manager."), fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.id").description("The Remote Project Manager ID."), fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.name").description("The Remote Project Manager name."), - fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.type").description("The Remote Project Manager type.") + fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.type").description("The Remote Project Manager type."), + fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.url").description("URL of the Remote Project Manager."), + fieldWithPath("payload.Product.remoteProjectInfo[0].remoteProjectManager.token").description("Token of the Remote Project Manager.") ) ) ); @@ -486,7 +502,17 @@ public void testProductIssue() throws Exception { fieldWithPath("credentials.email").description("The Issue Creator's E-mail."), fieldWithPath("credentials.role").description("The Issue Creator's role."), fieldWithPath("credentials.affiliation").description("The Issue Creator's affiliation."), - fieldWithPath("credentials.allCredentials").description("A map of additional credential information.") + fieldWithPath("credentials.allCredentials").description("A map of additional credential information."), + fieldWithPath("credentials.allCredentials.lastName").description("The Issue Creator's Last Name."), + fieldWithPath("credentials.allCredentials.firstName").description("The Issue Creator's First Name."), + fieldWithPath("credentials.allCredentials.sub").description("The Issue Creator's Sub."), + fieldWithPath("credentials.allCredentials.netid").description("The Issue Creator's Net ID."), + fieldWithPath("credentials.allCredentials.affiliation").description("The Issue Creator's affiliation."), + fieldWithPath("credentials.allCredentials.iss").description("The Issue Creator's Iss."), + fieldWithPath("credentials.allCredentials.uin").description("The Issue Creator's UIN."), + fieldWithPath("credentials.allCredentials.exp").description("The Issue Creator's expiration."), + fieldWithPath("credentials.allCredentials.iat").description("The Issue Creator's Iat."), + fieldWithPath("credentials.allCredentials.email").description("The Issue Creator's E-mail.") ), responseFields( fieldWithPath("meta").description("API response meta."), @@ -534,7 +560,12 @@ public void testProductFeature() throws Exception { fieldWithPath("meta.action").description("Action of the request."), fieldWithPath("meta.message").description("Message of the response."), fieldWithPath("meta.status").description("Status of the response."), - fieldWithPath("payload").description("API response payload containing the response message from the Feature service.") + fieldWithPath("payload").description("API response payload containing the response message from the Feature service."), + fieldWithPath("payload.FeatureRequest").description("The FeatureRequest object."), + fieldWithPath("payload.FeatureRequest.title").description("The Feature Title."), + fieldWithPath("payload.FeatureRequest.description").description("The Feature Description."), + fieldWithPath("payload.FeatureRequest.productId").description("The Product ID associated with this Feature."), + fieldWithPath("payload.FeatureRequest.scopeId").description("The Product Scope ID associated with this Feature.") ) ) ); @@ -570,6 +601,7 @@ public void testProductRemoteProjectsByProductId() throws Exception { fieldWithPath("payload.HashMap").description("An array of Remote Projects associated with the Product."), fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].id").description("The Remote Project Scope ID."), fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].name").description("The Remote Project Name."), + fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].backlogItemCount").description("The total number of Backlog Items in the Remote Project."), fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].requestCount").description("The total number of Requests in the Remote Project."), fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].issueCount").description("The total number of Issues in the Remote Project."), fieldWithPath("payload.HashMap['" + TEST_PROJECT_SCOPE + "'].featureCount").description("The total number of Features in the Remote Project."), @@ -617,6 +649,7 @@ public void testProductRemoteProjectsByRemoteProjectManagerId() throws Exception fieldWithPath("payload['ArrayList'][0]").description("An array of Remote Projects associated with the Remote Project Manager."), fieldWithPath("payload['ArrayList'][0].id").description("The Remote Project Scope ID."), fieldWithPath("payload['ArrayList'][0].name").description("The Remote Project Name."), + fieldWithPath("payload['ArrayList'][0].backlogItemCount").description("The total number of Backlog Items in the Remote Project."), fieldWithPath("payload['ArrayList'][0].requestCount").description("The total number of Requests in the Remote Project."), fieldWithPath("payload['ArrayList'][0].issueCount").description("The total number of Issues in the Remote Project."), fieldWithPath("payload['ArrayList'][0].featureCount").description("The total number of Features in the Remote Project."), @@ -665,6 +698,7 @@ public void testProductRemoteProjectsByScopeId() throws Exception { fieldWithPath("payload.RemoteProject").description("The Remote Project associated with the Remote Project Manager with the given Project Scope ID."), fieldWithPath("payload.RemoteProject.id").description("The Remote Project Scope ID."), fieldWithPath("payload.RemoteProject.name").description("The Remote Project Name."), + fieldWithPath("payload.RemoteProject.backlogItemCount").description("The total number of Backlog Items in the Remote Project."), fieldWithPath("payload.RemoteProject.requestCount").description("The total number of Requests in the Remote Project."), fieldWithPath("payload.RemoteProject.issueCount").description("The total number of Issues in the Remote Project."), fieldWithPath("payload.RemoteProject.featureCount").description("The total number of Features in the Remote Project."), diff --git a/src/test/java/edu/tamu/app/controller/integration/RemoteProjectManagerControllerIntegrationTest.java b/src/test/java/edu/tamu/app/controller/integration/RemoteProjectManagerControllerIntegrationTest.java index 9b47a2d0..b393ec87 100644 --- a/src/test/java/edu/tamu/app/controller/integration/RemoteProjectManagerControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/controller/integration/RemoteProjectManagerControllerIntegrationTest.java @@ -17,7 +17,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +27,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -40,8 +38,8 @@ import edu.tamu.app.cache.service.RemoteProjectsScheduledCacheService; import edu.tamu.app.model.RemoteProjectManager; import edu.tamu.app.model.ServiceType; -import edu.tamu.app.model.repo.RemoteProjectManagerRepo; import edu.tamu.app.model.repo.AbstractRepoTest; +import edu.tamu.app.model.repo.RemoteProjectManagerRepo; import edu.tamu.app.service.manager.GitHubProjectService; import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.weaver.response.ApiResponse; @@ -50,7 +48,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class RemoteProjectManagerControllerIntegrationTest extends AbstractRepoTest { private static long currentId = 0L; diff --git a/src/test/java/edu/tamu/app/controller/integration/StatusControllerIntegrationTest.java b/src/test/java/edu/tamu/app/controller/integration/StatusControllerIntegrationTest.java index 2db8e370..c9806975 100644 --- a/src/test/java/edu/tamu/app/controller/integration/StatusControllerIntegrationTest.java +++ b/src/test/java/edu/tamu/app/controller/integration/StatusControllerIntegrationTest.java @@ -25,7 +25,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; @@ -36,7 +35,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -50,9 +48,9 @@ import edu.tamu.app.model.RemoteProjectManager; import edu.tamu.app.model.ServiceType; import edu.tamu.app.model.Status; +import edu.tamu.app.model.repo.AbstractRepoTest; import edu.tamu.app.model.repo.ProductRepo; import edu.tamu.app.model.repo.RemoteProjectManagerRepo; -import edu.tamu.app.model.repo.AbstractRepoTest; import edu.tamu.app.model.repo.StatusRepo; import edu.tamu.app.service.manager.GitHubProjectService; import edu.tamu.app.service.manager.VersionOneService; @@ -63,7 +61,6 @@ @SpringBootTest(classes = { ProductApplication.class }, webEnvironment=WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @AutoConfigureRestDocs(outputDir = "target/generated-snippets") -@ExtendWith(SpringExtension.class) public class StatusControllerIntegrationTest extends AbstractRepoTest { private static long currentId = 0L; @@ -155,7 +152,11 @@ public void testGetStatuses() throws JsonProcessingException, Exception { fieldWithPath("meta.action").description("Action of the request."), fieldWithPath("meta.message").description("Message of the response."), fieldWithPath("meta.status").description("Status of the response."), - fieldWithPath("payload").description("API response payload containing the List of Status.") + fieldWithPath("payload").description("Payload of the response."), + fieldWithPath("payload['ArrayList']").description("List of statuses."), + fieldWithPath("payload['ArrayList'][0].id").description("ID of the status."), + fieldWithPath("payload['ArrayList'][0].identifier").description("Identifier of the status."), + fieldWithPath("payload['ArrayList'][0].mapping").description("Mapping of the status.") ) ) ); diff --git a/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java index 64ff4db4..ff2bfd3f 100644 --- a/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java +++ b/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java @@ -8,17 +8,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.model.CardType; import edu.tamu.app.model.repo.CardTypeRepo; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class CardTypeMappingServiceTest { @@ -35,7 +32,7 @@ public void setup() { @Test public void testMap() { - assertEquals(cardTypeMappingService.map("Story"), "Feature"); + assertEquals("Feature", cardTypeMappingService.map("Story")); } @Test diff --git a/src/test/java/edu/tamu/app/mapping/EstimateMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/EstimateMappingServiceTest.java index 77bc5fbe..fb2a5cb6 100644 --- a/src/test/java/edu/tamu/app/mapping/EstimateMappingServiceTest.java +++ b/src/test/java/edu/tamu/app/mapping/EstimateMappingServiceTest.java @@ -8,17 +8,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.model.Estimate; import edu.tamu.app.model.repo.EstimateRepo; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class EstimateMappingServiceTest { diff --git a/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java index 0393a8eb..6bd61525 100644 --- a/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java +++ b/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java @@ -8,17 +8,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.model.Status; import edu.tamu.app.model.repo.StatusRepo; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class StatusMappingServiceTest { @@ -35,7 +32,7 @@ public void setup() { @Test public void testMap() { - assertEquals(statusMappingService.map("Future"), "None"); + assertEquals("None", statusMappingService.map("Future")); } @Test diff --git a/src/test/java/edu/tamu/app/model/ProductTest.java b/src/test/java/edu/tamu/app/model/ProductTest.java index b640bf72..13d0fec6 100644 --- a/src/test/java/edu/tamu/app/model/ProductTest.java +++ b/src/test/java/edu/tamu/app/model/ProductTest.java @@ -8,14 +8,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -25,7 +23,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class ProductTest extends AbstractModelTest { diff --git a/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java b/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java index fac0a78b..dd7278ca 100644 --- a/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; @@ -20,7 +19,6 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -31,7 +29,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class CardTypeRepoTest extends AbstractRepoTest { diff --git a/src/test/java/edu/tamu/app/model/repo/EstimateRepoTest.java b/src/test/java/edu/tamu/app/model/repo/EstimateRepoTest.java index 7a41b911..1ff31174 100644 --- a/src/test/java/edu/tamu/app/model/repo/EstimateRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/EstimateRepoTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; @@ -20,7 +19,6 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -31,7 +29,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class EstimateRepoTest extends AbstractRepoTest { diff --git a/src/test/java/edu/tamu/app/model/repo/InternalRequestRepoTest.java b/src/test/java/edu/tamu/app/model/repo/InternalRequestRepoTest.java index 2f98ac74..cbe241f5 100644 --- a/src/test/java/edu/tamu/app/model/repo/InternalRequestRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/InternalRequestRepoTest.java @@ -9,14 +9,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -31,7 +29,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class InternalRequestRepoTest extends AbstractRepoTest { diff --git a/src/test/java/edu/tamu/app/model/repo/ProductRepoTest.java b/src/test/java/edu/tamu/app/model/repo/ProductRepoTest.java index 568dc7a4..7bab0685 100644 --- a/src/test/java/edu/tamu/app/model/repo/ProductRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/ProductRepoTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.Mock; @@ -22,7 +21,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.messaging.simp.SimpMessagingTemplate; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -37,10 +35,9 @@ import edu.tamu.app.service.registry.ManagementBeanRegistry; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class ProductRepoTest extends AbstractRepoTest { - + private static final RemoteProjectManager TEST_REMOTE_PROJECT_MANAGER1 = new RemoteProjectManager(TEST_REMOTE_PROJECT_MANAGER_NAME1, ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); private static final RemoteProjectInfo TEST_REMOTE_PROJECT_INFO1 = new RemoteProjectInfo(TEST_PROJECT_SCOPE1, TEST_REMOTE_PROJECT_MANAGER1); diff --git a/src/test/java/edu/tamu/app/model/repo/RemoteProjectManagerRepoTest.java b/src/test/java/edu/tamu/app/model/repo/RemoteProjectManagerRepoTest.java index 4f07aba9..4ebc497b 100644 --- a/src/test/java/edu/tamu/app/model/repo/RemoteProjectManagerRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/RemoteProjectManagerRepoTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; @@ -18,7 +17,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.transaction.annotation.Transactional; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -32,7 +31,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class RemoteProjectManagerRepoTest extends AbstractRepoTest { @@ -95,6 +93,7 @@ public void testRead() { } @Test + @Transactional public void testUpdate() { RemoteProjectManager remoteProjectManager = remoteProjectManagerRepo.create(new RemoteProjectManager(TEST_REMOTE_PROJECT_MANAGER_NAME1, ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1)); remoteProjectManager.setName(TEST_REMOTE_PROJECT_MANAGER_NAME_ALTERNATE1); diff --git a/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java b/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java index f827d9db..da8ed765 100644 --- a/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.mockito.MockitoAnnotations; @@ -20,7 +19,6 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.test.context.junit.jupiter.SpringExtension; import edu.tamu.app.ProductApplication; import edu.tamu.app.cache.service.ActiveSprintsScheduledCacheService; @@ -31,7 +29,6 @@ import edu.tamu.app.service.manager.VersionOneService; import edu.tamu.app.service.ticketing.SugarService; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class StatusRepoTest extends AbstractRepoTest { diff --git a/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java b/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java index f055e260..1a073cf3 100644 --- a/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java @@ -12,12 +12,10 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.core.GrantedAuthority; -import org.springframework.test.context.junit.jupiter.SpringExtension; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -28,7 +26,6 @@ import edu.tamu.app.model.User; import edu.tamu.weaver.auth.model.Credentials; -@ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ProductApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class UserRepoTest extends AuthMockTests { @@ -107,7 +104,7 @@ public void testUserDetailsMethods() { assertFalse(user.isAccountNonLocked(), "Account non locked was not false!"); assertFalse(user.isCredentialsNonExpired(), "Credentials non expired was not false!"); assertTrue(user.isEnabled(), "Enabled was not true!"); - assertNull("Password was not null!", user.getPassword()); + assertNull(user.getPassword(), "Password was not null!"); } // @After and @Before cannot be safely specified inside a parent class. diff --git a/src/test/java/edu/tamu/app/model/request/AbstractRequetTest.java b/src/test/java/edu/tamu/app/model/request/AbstractRequetTest.java index 5e738216..901fff2a 100644 --- a/src/test/java/edu/tamu/app/model/request/AbstractRequetTest.java +++ b/src/test/java/edu/tamu/app/model/request/AbstractRequetTest.java @@ -9,7 +9,6 @@ import org.mockito.Mockito; import org.springframework.test.context.junit.jupiter.SpringExtension; - @ExtendWith(SpringExtension.class) public class AbstractRequetTest { diff --git a/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java b/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java index a85c9efe..101c5ab2 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java @@ -1,14 +1,13 @@ package edu.tamu.app.service.manager; -import static edu.tamu.app.service.manager.GitHubMilestoneService.DEFECT_LABEL; -import static edu.tamu.app.service.manager.GitHubMilestoneService.FEATURE_LABEL; -import static edu.tamu.app.service.manager.GitHubMilestoneService.ISSUE_LABEL; -import static edu.tamu.app.service.manager.GitHubMilestoneService.REQUEST_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.DEFECT_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.FEATURE_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.ISSUE_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.REQUEST_LABEL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; @@ -27,6 +26,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHIssue; +import org.kohsuke.github.GHIssueBuilder; import org.kohsuke.github.GHIssueState; import org.kohsuke.github.GHLabel; import org.kohsuke.github.GHMilestone; @@ -40,15 +40,17 @@ import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; +import org.kohsuke.github.PagedIterable; +import org.mockito.Answers; +import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; import edu.tamu.app.cache.model.Member; @@ -68,8 +70,9 @@ import edu.tamu.app.model.repo.StatusRepo; import edu.tamu.app.model.request.FeatureRequest; -@ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) public class GitHubMilestoneServiceTest extends CacheMockTests { + private static final String TEST_REPOSITORY1_NAME = "Test repository 1 name"; private static final String TEST_REPOSITORY2_NAME = "Test repository 2 name"; private static final String TEST_UNUSED_LABEL_NAME = "unused"; @@ -86,224 +89,213 @@ public class GitHubMilestoneServiceTest extends CacheMockTests { private static final String TEST_PROJECT3_NAME = "Test Project 3 Name"; private static final String TEST_MILESTONE_TITLE = "Test Milestone Sprint Title"; private static final Long TEST_REPOSITORY1_ID = 1L; + private static final Long TEST_REPOSITORY2_ID = 2L; private static final Long TEST_USER1_ID = 3L; - - private static final String TEST_PROJECT_URL1 = "http://localhost/1"; - - private static final String TEST_PROJECT_TOKEN1 = "0123456789"; - - private static final GHLabel TEST_LABEL1 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL2 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL3 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL4 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL5 = mock(GHLabel.class); - - private static final GHIssue TEST_ISSUE1 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE2 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE3 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE4 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE5 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - - private static final GHUser TEST_USER1 = mock(GHUser.class); - private static final GHUser TEST_USER2 = mock(GHUser.class); - private static final GHUser TEST_USER3 = mock(GHUser.class); - - private static final GHMilestone TEST_MILESTONE = mock(GHMilestone.class); - - private static final GHProjectCard TEST_CARD1 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD2 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD3 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD4 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD5 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - - private static final GHProjectColumn TEST_COLUMN1 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - private static final GHProjectColumn TEST_COLUMN2 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - private static final GHProjectColumn TEST_COLUMN3 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - - private static final GHProject TEST_PROJECT1 = mock(GHProject.class, RETURNS_DEEP_STUBS); - private static final GHProject TEST_PROJECT2 = mock(GHProject.class, RETURNS_DEEP_STUBS); - private static final GHProject TEST_PROJECT3 = mock(GHProject.class, RETURNS_DEEP_STUBS); - - private static final GHRepository TEST_REPOSITORY1 = mock(GHRepository.class, RETURNS_DEEP_STUBS); - private static final GHRepository TEST_REPOSITORY2 = mock(GHRepository.class, RETURNS_DEEP_STUBS); - - private static final GHOrganization TEST_ORGANIZATION = mock(GHOrganization.class, RETURNS_DEEP_STUBS); - - private static final FeatureRequest TEST_FEATURE_REQUEST = mock(FeatureRequest.class); - - private static final RestTemplate restTemplate = mock(RestTemplate.class); - - @SuppressWarnings("unchecked") - private ResponseEntity response = (ResponseEntity) mock(ResponseEntity.class); - - private static final List ALL_TEST_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL1, TEST_LABEL2, TEST_LABEL3, TEST_LABEL4, TEST_LABEL5 })); - private static final List TEST_CARD1_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL1, TEST_LABEL5 })); - private static final List TEST_CARD2_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL2, TEST_LABEL5 })); - private static final List TEST_CARD3_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL3, TEST_LABEL5 })); - private static final List TEST_CARD4_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL4 })); - private static final List TEST_CARD5_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL5 })); - - private static final List TEST_USERS1 = new ArrayList(Arrays.asList(new GHUser[] { TEST_USER1 })); - private static final List TEST_USERS2 = new ArrayList( - Arrays.asList(new GHUser[] { TEST_USER1, TEST_USER2 })); - private static final List TEST_USERS3 = new ArrayList(Arrays.asList(new GHUser[] {})); - private static final List TEST_USERS4 = new ArrayList(Arrays.asList(new GHUser[] { TEST_USER2 })); - private static final List TEST_USERS5 = new ArrayList( - Arrays.asList(new GHUser[] { TEST_USER3, TEST_USER1 })); - - private static final List TEST_COLUMN1_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD1, TEST_CARD2, TEST_CARD3 })); - private static final List TEST_COLUMN2_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD3, TEST_CARD4 })); - private static final List TEST_COLUMN3_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD5 })); - - private static final List TEST_ISSUE_LIST = new ArrayList( - Arrays.asList((new GHIssue[] { TEST_ISSUE1, TEST_ISSUE2, TEST_ISSUE3, TEST_ISSUE4, TEST_ISSUE5 }))); - - private static final List TEST_PROJECT_COLUMNS = new ArrayList( - Arrays.asList(new GHProjectColumn[] { TEST_COLUMN1, TEST_COLUMN2, TEST_COLUMN3 })); - - private static final List TEST_PROJECTS = new ArrayList( - Arrays.asList(new GHProject[] { TEST_PROJECT1, TEST_PROJECT2, TEST_PROJECT3 })); - - private static final Map TEST_REPOSITORY_MAP = Stream.of( - new Object[][] { { TEST_REPOSITORY1_NAME, TEST_REPOSITORY1 }, { TEST_REPOSITORY2_NAME, TEST_REPOSITORY2 } }) - .collect(Collectors.toMap(data -> (String) data[0], data -> (GHRepository) data[1])); - - private GitHubBuilder ghBuilder; - - private GitHubMilestoneService gitHubMilestoneService; - - private GitHub github; + private static final Long TEST_PRODUCT1_ID = 4L; + private static final String TEST_PROJECT1_URL = "http://localhost/1"; + private static final String TEST_PROJECT1_TOKEN = "0123456789"; + + @Mock private GHLabel testLabel1; + @Mock private GHLabel testLabel2; + @Mock private GHLabel testLabel3; + @Mock private GHLabel testLabel4; + @Mock private GHLabel testLabel5; + @Mock private GHIssue testIssue1; + @Mock private GHIssue testIssue2; + @Mock private GHIssue testIssue3; + @Mock private GHIssue testIssue4; + @Mock private GHIssue testIssue5; + @Mock private GHUser testUser1; + @Mock private GHUser testUser2; + @Mock private GHUser testUser3; + @Mock private GHMilestone testMilestone; + @Mock private GHProjectCard testCard1; + @Mock private GHProjectCard testCard2; + @Mock private GHProjectCard testCard3; + @Mock private GHProjectCard testCard4; + @Mock private GHProjectCard testCard5; + @Mock private PagedIterable cardIterable1; + @Mock private PagedIterable cardIterable2; + @Mock private PagedIterable cardIterable3; + @Mock private GHProjectColumn testColumn1; + @Mock private GHProjectColumn testColumn2; + @Mock private GHProjectColumn testColumn3; + @Mock private PagedIterable columnIterable; + @Mock private GHProject testProject1; + @Mock private GHProject testProject2; + @Mock private GHProject testProject3; + @Mock private PagedIterable labelIterable; + @Mock private GHIssueBuilder issueBuilder; + @Mock private GHRepository testRepository1; + @Mock private GHRepository testRepository2; + @Mock private PagedIterable projectIterable; + @Mock private GHOrganization testOrganization; + @Mock private FeatureRequest testFeatureRequest; + @Mock private RestTemplate restTemplate; + @Mock private ResponseEntity response; + @Mock private CardTypeRepo cardTypeRepo; + @Mock private StatusRepo statusRepo; + @Mock private EstimateRepo estimateRepo; + @Mock private GitHubBuilder ghBuilder; + @Mock private GitHub github; + + @Mock(answer = Answers.CALLS_REAL_METHODS) private GitHubMilestoneService gitHubMilestoneService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private CardTypeMappingService cardTypeMappingService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private StatusMappingService statusMappingService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private EstimateMappingService estimateMappingService; @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); - - - CardTypeRepo cardTypeRepo = mock(CardTypeRepo.class); - StatusRepo statusRepo = mock(StatusRepo.class); - EstimateRepo estimateRepo = mock(EstimateRepo.class); + public void setup() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); - CardTypeMappingService cardTypeMappingService = mock(CardTypeMappingService.class, Mockito.CALLS_REAL_METHODS); + Map testRepositoryMap = Stream.of( + new Object[][] { { TEST_REPOSITORY1_NAME, testRepository1 }, { TEST_REPOSITORY2_NAME, testRepository2 } }) + .collect(Collectors.toMap(data -> (String) data[0], data -> (GHRepository) data[1])); - StatusMappingService statusMappingService = mock(StatusMappingService.class, Mockito.CALLS_REAL_METHODS); + List allTestLabels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel1, testLabel2, testLabel3, testLabel4, testLabel5 })); + List testCard1Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel1, testLabel5 })); + List testCard2Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel2, testLabel5 })); + List testCard3Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel3, testLabel5 })); + List testCard4Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel4 })); + List testCard5Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel5 })); - EstimateMappingService estimateMappingService = mock(EstimateMappingService.class, Mockito.CALLS_REAL_METHODS); + List testUsers1 = new ArrayList(Arrays.asList(new GHUser[] { testUser1 })); + List testUsers2 = new ArrayList(Arrays.asList(new GHUser[] { testUser1, testUser2 })); + List testUsers3 = new ArrayList(Arrays.asList(new GHUser[] {})); + List testUsers4 = new ArrayList(Arrays.asList(new GHUser[] { testUser2 })); + List testUsers5 = new ArrayList(Arrays.asList(new GHUser[] { testUser3, testUser1 })); - ghBuilder = mock(GitHubBuilder.class); + List testColumn1Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard1, testCard2, testCard3 })); + List testColumn2Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard3, testCard4 })); + List testColumn3Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard5 })); - gitHubMilestoneService = mock(GitHubMilestoneService.class, Mockito.CALLS_REAL_METHODS); + List testIssueList = new ArrayList(Arrays.asList((new GHIssue[] { testIssue1, testIssue2, testIssue3, testIssue4, testIssue5 }))); + List testProjectColumns = new ArrayList(Arrays.asList(new GHProjectColumn[] { testColumn1, testColumn2, testColumn3 })); + List testProjects = new ArrayList(Arrays.asList(new GHProject[] { testProject1, testProject2, testProject3 })); - github = mock(GitHub.class); + setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); + setField(statusMappingService, "serviceMappingRepo", statusRepo); + setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.build()).thenReturn(github); + setField(gitHubMilestoneService, "ghBuilder", ghBuilder); + setField(gitHubMilestoneService, "managementService", managementService); + setField(gitHubMilestoneService, "cardTypeMappingService", cardTypeMappingService); + setField(gitHubMilestoneService, "statusMappingService", statusMappingService); + setField(gitHubMilestoneService, "estimateMappingService", estimateMappingService); + setField(gitHubMilestoneService, "github", github); + setField(gitHubMilestoneService, "members", new HashMap()); + setField(gitHubMilestoneService, "restTemplate", restTemplate); - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); - - when(TEST_ORGANIZATION.getRepositories()).thenReturn(TEST_REPOSITORY_MAP); - when(TEST_ORGANIZATION.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); - - when(TEST_REPOSITORY1.getId()).thenReturn(TEST_REPOSITORY1_ID); - when(TEST_REPOSITORY1.createIssue(any(String.class)).body(any(String.class)).create()).thenReturn(TEST_ISSUE1); - when(TEST_REPOSITORY1.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.listProjects().asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.getIssues(any(GHIssueState.class))).thenReturn(TEST_ISSUE_LIST); - when(TEST_REPOSITORY1.getName()).thenReturn(TEST_REPOSITORY1_NAME); - when(TEST_REPOSITORY2.getIssues(any(GHIssueState.class))).thenReturn(TEST_ISSUE_LIST); - when(TEST_REPOSITORY2.listProjects().asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.listLabels().asList()).thenReturn(ALL_TEST_LABELS); - when(TEST_REPOSITORY2.listLabels().asList()).thenReturn(ALL_TEST_LABELS); - - when(TEST_PROJECT1.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - when(TEST_PROJECT2.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - when(TEST_PROJECT3.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - - when(TEST_PROJECT1.getName()).thenReturn(TEST_PROJECT1_NAME); - when(TEST_PROJECT2.getName()).thenReturn(TEST_PROJECT2_NAME); - when(TEST_PROJECT3.getName()).thenReturn(TEST_PROJECT3_NAME); - - when(TEST_COLUMN1.listCards().asList()).thenReturn(TEST_COLUMN1_CARDS); - when(TEST_COLUMN2.listCards().asList()).thenReturn(TEST_COLUMN2_CARDS); - when(TEST_COLUMN3.listCards().asList()).thenReturn(TEST_COLUMN3_CARDS); - - when(TEST_MILESTONE.getState()).thenReturn(GHMilestoneState.OPEN); - when(TEST_MILESTONE.getTitle()).thenReturn(TEST_MILESTONE_TITLE); - - when(TEST_CARD1.getId()).thenReturn(1L); - when(TEST_CARD2.getId()).thenReturn(2L); - when(TEST_CARD3.getId()).thenReturn(3L); - when(TEST_CARD4.getId()).thenReturn(4L); - when(TEST_CARD5.getId()).thenReturn(5L); - - when(TEST_CARD1.getContent()).thenReturn(TEST_ISSUE1); - when(TEST_CARD2.getContent()).thenReturn(TEST_ISSUE2); - when(TEST_CARD3.getContent()).thenReturn(TEST_ISSUE3); - when(TEST_CARD4.getContent()).thenReturn(TEST_ISSUE4); - when(TEST_CARD5.getContent()).thenReturn(TEST_ISSUE5); - when(TEST_CARD1.getColumn()).thenReturn(TEST_COLUMN1); - - when(TEST_ISSUE1.getLabels()).thenReturn(TEST_CARD1_LABELS); - when(TEST_ISSUE2.getLabels()).thenReturn(TEST_CARD2_LABELS); - when(TEST_ISSUE3.getLabels()).thenReturn(TEST_CARD3_LABELS); - when(TEST_ISSUE4.getLabels()).thenReturn(TEST_CARD4_LABELS); - when(TEST_ISSUE5.getLabels()).thenReturn(TEST_CARD5_LABELS); - when(TEST_ISSUE1.getAssignees()).thenReturn(TEST_USERS1); - when(TEST_ISSUE1.getMilestone()).thenReturn(TEST_MILESTONE); - when(TEST_ISSUE2.getMilestone()).thenReturn(TEST_MILESTONE); - when(TEST_ISSUE3.getMilestone()).thenReturn(TEST_MILESTONE); - when(TEST_ISSUE4.getMilestone()).thenReturn(TEST_MILESTONE); - when(TEST_ISSUE5.getMilestone()).thenReturn(TEST_MILESTONE); - - when(TEST_COLUMN1.getName()).thenReturn(TEST_COLUMN1_NAME); - - when(TEST_CARD2.getContent().getLabels()).thenReturn(TEST_CARD2_LABELS); - when(TEST_CARD3.getContent().getLabels()).thenReturn(TEST_CARD3_LABELS); - when(TEST_CARD4.getContent().getLabels()).thenReturn(TEST_CARD4_LABELS); - when(TEST_CARD5.getContent().getLabels()).thenReturn(TEST_CARD5_LABELS); - when(TEST_CARD2.getContent().getAssignees()).thenReturn(TEST_USERS2); - when(TEST_CARD3.getContent().getAssignees()).thenReturn(TEST_USERS3); - when(TEST_CARD4.getContent().getAssignees()).thenReturn(TEST_USERS4); - when(TEST_CARD5.getContent().getAssignees()).thenReturn(TEST_USERS5); - - when(TEST_USER1.getId()).thenReturn(TEST_USER1_ID); - when(TEST_USER1.getName()).thenReturn(TEST_USER1_NAME); - when(TEST_USER1.getAvatarUrl()).thenReturn(TEST_USER1_AVATAR_PATH); - when(TEST_USER2.getAvatarUrl()).thenReturn(TEST_USER2_AVATAR_PATH); - when(TEST_USER3.getAvatarUrl()).thenReturn(TEST_USER3_AVATAR_PATH); - - when(TEST_LABEL1.getName()).thenReturn(REQUEST_LABEL); - when(TEST_LABEL2.getName()).thenReturn(ISSUE_LABEL); - when(TEST_LABEL3.getName()).thenReturn(FEATURE_LABEL); - when(TEST_LABEL4.getName()).thenReturn(DEFECT_LABEL); - when(TEST_LABEL5.getName()).thenReturn(TEST_UNUSED_LABEL_NAME); - - when(TEST_FEATURE_REQUEST.getProductId()).thenReturn(TEST_REPOSITORY1_ID); - when(TEST_FEATURE_REQUEST.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); - when(TEST_FEATURE_REQUEST.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); - - when(restTemplate.exchange( + lenient().when(testOrganization.getRepositories()).thenReturn(testRepositoryMap); + + lenient().when(testOrganization.listProjects(any(ProjectStateFilter.class))).thenReturn(projectIterable); + + lenient().when(testRepository1.getId()).thenReturn(TEST_REPOSITORY1_ID); + lenient().when(testRepository1.getName()).thenReturn(TEST_REPOSITORY1_NAME); + lenient().when(testRepository1.listProjects(any(ProjectStateFilter.class))).thenReturn(projectIterable); + lenient().when(testRepository1.listProjects()).thenReturn(projectIterable); + lenient().when(testRepository1.listLabels()).thenReturn(labelIterable); + lenient().when(testRepository1.getIssues(any(GHIssueState.class))).thenReturn(testIssueList); + + lenient().when(testRepository1.createIssue(any(String.class))).thenReturn(issueBuilder); + lenient().when(issueBuilder.body(any(String.class))).thenReturn(issueBuilder); + lenient().when(issueBuilder.create()).thenReturn(testIssue1); + + lenient().when(testRepository2.getId()).thenReturn(TEST_REPOSITORY2_ID); + lenient().when(testRepository2.getName()).thenReturn(TEST_REPOSITORY2_NAME); + lenient().when(testRepository2.getIssues(any(GHIssueState.class))).thenReturn(testIssueList); + lenient().when(testRepository2.listProjects()).thenReturn(projectIterable); + lenient().when(testRepository2.listLabels()).thenReturn(labelIterable); + + lenient().when(testProject1.listColumns()).thenReturn(columnIterable); + lenient().when(testProject2.listColumns()).thenReturn(columnIterable); + lenient().when(testProject3.listColumns()).thenReturn(columnIterable); + + lenient().when(testProject1.getName()).thenReturn(TEST_PROJECT1_NAME); + lenient().when(testProject2.getName()).thenReturn(TEST_PROJECT2_NAME); + lenient().when(testProject3.getName()).thenReturn(TEST_PROJECT3_NAME); + + lenient().when(testColumn1.listCards()).thenReturn(cardIterable1); + lenient().when(testColumn2.listCards()).thenReturn(cardIterable2); + lenient().when(testColumn3.listCards()).thenReturn(cardIterable3); + + lenient().when(testMilestone.getState()).thenReturn(GHMilestoneState.OPEN); + lenient().when(testMilestone.getTitle()).thenReturn(TEST_MILESTONE_TITLE); + + lenient().when(testCard1.getId()).thenReturn(1L); + lenient().when(testCard2.getId()).thenReturn(2L); + lenient().when(testCard3.getId()).thenReturn(3L); + lenient().when(testCard4.getId()).thenReturn(4L); + lenient().when(testCard5.getId()).thenReturn(5L); + + lenient().when(testCard1.getContent()).thenReturn(testIssue1); + lenient().when(testCard2.getContent()).thenReturn(testIssue2); + lenient().when(testCard3.getContent()).thenReturn(testIssue3); + lenient().when(testCard4.getContent()).thenReturn(testIssue4); + lenient().when(testCard5.getContent()).thenReturn(testIssue5); + + lenient().when(testCard1.getColumn()).thenReturn(testColumn1); + lenient().when(testCard2.getColumn()).thenReturn(testColumn1); + lenient().when(testCard3.getColumn()).thenReturn(testColumn1); + lenient().when(testCard4.getColumn()).thenReturn(testColumn1); + lenient().when(testCard5.getColumn()).thenReturn(testColumn1); + + lenient().when(testIssue1.getLabels()).thenReturn(testCard1Labels); + lenient().when(testIssue2.getLabels()).thenReturn(testCard2Labels); + lenient().when(testIssue3.getLabels()).thenReturn(testCard3Labels); + lenient().when(testIssue4.getLabels()).thenReturn(testCard4Labels); + lenient().when(testIssue5.getLabels()).thenReturn(testCard5Labels); + lenient().when(testIssue1.getAssignees()).thenReturn(testUsers1); + lenient().when(testIssue1.getMilestone()).thenReturn(testMilestone); + lenient().when(testIssue2.getMilestone()).thenReturn(testMilestone); + lenient().when(testIssue3.getMilestone()).thenReturn(testMilestone); + lenient().when(testIssue4.getMilestone()).thenReturn(testMilestone); + lenient().when(testIssue5.getMilestone()).thenReturn(testMilestone); + + lenient().when(testColumn1.getName()).thenReturn(TEST_COLUMN1_NAME); + + lenient().when(testCard2.getContent().getLabels()).thenReturn(testCard2Labels); + lenient().when(testCard3.getContent().getLabels()).thenReturn(testCard3Labels); + lenient().when(testCard4.getContent().getLabels()).thenReturn(testCard4Labels); + lenient().when(testCard5.getContent().getLabels()).thenReturn(testCard5Labels); + lenient().when(testCard2.getContent().getAssignees()).thenReturn(testUsers2); + lenient().when(testCard3.getContent().getAssignees()).thenReturn(testUsers3); + lenient().when(testCard4.getContent().getAssignees()).thenReturn(testUsers4); + lenient().when(testCard5.getContent().getAssignees()).thenReturn(testUsers5); + + lenient().when(testUser1.getId()).thenReturn(TEST_USER1_ID); + lenient().when(testUser1.getName()).thenReturn(TEST_USER1_NAME); + lenient().when(testUser1.getAvatarUrl()).thenReturn(TEST_USER1_AVATAR_PATH); + lenient().when(testUser2.getAvatarUrl()).thenReturn(TEST_USER2_AVATAR_PATH); + lenient().when(testUser3.getAvatarUrl()).thenReturn(TEST_USER3_AVATAR_PATH); + + lenient().when(testLabel1.getName()).thenReturn(REQUEST_LABEL); + lenient().when(testLabel2.getName()).thenReturn(ISSUE_LABEL); + lenient().when(testLabel3.getName()).thenReturn(FEATURE_LABEL); + lenient().when(testLabel4.getName()).thenReturn(DEFECT_LABEL); + lenient().when(testLabel5.getName()).thenReturn(TEST_UNUSED_LABEL_NAME); + + lenient().when(testFeatureRequest.getProductId()).thenReturn(TEST_PRODUCT1_ID); + lenient().when(testFeatureRequest.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); + lenient().when(testFeatureRequest.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); + + lenient().when(labelIterable.toList()).thenReturn(allTestLabels); + lenient().when(projectIterable.toList()).thenReturn(testProjects); + lenient().when(columnIterable.toList()).thenReturn(testProjectColumns); + lenient().when(cardIterable1.toList()).thenReturn(testColumn1Cards); + lenient().when(cardIterable2.toList()).thenReturn(testColumn2Cards); + lenient().when(cardIterable3.toList()).thenReturn(testColumn3Cards); + + lenient().when(restTemplate.exchange( any(String.class), any(HttpMethod.class), Mockito.>any(), - Mockito.>any(), - Mockito.anyCollection())) + Mockito.>any())) .thenReturn(response); - when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); + lenient().when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); - when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { String identifier = (String) invocation.getArguments()[0]; @@ -322,10 +314,7 @@ public Optional answer(InvocationOnMock invocation) { } }); - when(cardTypeRepo.findByIdentifier(any(String.class))) - .thenReturn(new CardType("Feature", new HashSet(Arrays.asList(new String[] { "Story" })))); - - when(statusRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(statusRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { String identifier = (String) invocation.getArguments()[0]; @@ -353,32 +342,21 @@ public Optional answer(InvocationOnMock invocation) { } }); - when(estimateRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(estimateRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { return Optional.empty(); } }); - when(statusRepo.findByIdentifier(any(String.class))) - .thenReturn(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); - - setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); - setField(statusMappingService, "serviceMappingRepo", statusRepo); - setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - - setField(gitHubMilestoneService, "ghBuilder", ghBuilder); - setField(gitHubMilestoneService, "managementService", managementService); - setField(gitHubMilestoneService, "cardTypeMappingService", cardTypeMappingService); - setField(gitHubMilestoneService, "statusMappingService", statusMappingService); - setField(gitHubMilestoneService, "estimateMappingService", estimateMappingService); - setField(gitHubMilestoneService, "github", github); - setField(gitHubMilestoneService, "members", new HashMap()); - setField(gitHubMilestoneService, "restTemplate", restTemplate); + lenient().when(statusRepo.findByIdentifier(any(String.class))) + .thenReturn(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); } @Test public void testGetRemoteProjects() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List remoteProjects = gitHubMilestoneService.getRemoteProject(); assertEquals(2, remoteProjects.size(), "Didn't get all the remote projects"); assertEquals(1, remoteProjects.get(0).getRequestCount(), "Number of Requests was incorrect"); @@ -389,6 +367,8 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + RemoteProject project = gitHubMilestoneService.getRemoteProjectByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); assertNotNull(project, "Didn't get the remote project"); assertEquals(String.valueOf(TEST_REPOSITORY1_ID), project.getId(), "Did not get the expected project"); @@ -400,18 +380,24 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + List activeSprints = gitHubMilestoneService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); assertEquals(3, activeSprints.size(), "Didn't get all active sprints"); } @Test public void testGetAdditionalActiveSprints() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List additionalSprints = gitHubMilestoneService.getAdditionalActiveSprints(); assertEquals(3, additionalSprints.size(), "Didn't get all additional sprints"); } @Test public void testGetActiveSprintsByProjectIdType() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + List sprints = gitHubMilestoneService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); sprints.forEach(sprint -> { @@ -421,6 +407,8 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { @Test public void testGetAdditionalActiveSprintsType() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List sprints = gitHubMilestoneService.getAdditionalActiveSprints(); sprints.forEach(sprint -> { @@ -430,13 +418,15 @@ public void testGetAdditionalActiveSprintsType() throws Exception { @Test public void testPush() throws Exception { - String id = gitHubMilestoneService.push(TEST_FEATURE_REQUEST); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + + String id = gitHubMilestoneService.push(testFeatureRequest); assertNotNull(id); } @Test public void testGetMember() throws IOException { - Member member = gitHubMilestoneService.getMember(TEST_USER1); + Member member = gitHubMilestoneService.getMember(testUser1); assertEquals(String.valueOf(TEST_USER1_ID), member.getId(), "Member ID is incorrect"); assertEquals(TEST_USER1_NAME, member.getName(), "Member Name is incorrect"); assertEquals(TEST_USER1_AVATAR_NAME, member.getAvatar(), "Member Avatar URL is incorrect"); @@ -444,7 +434,11 @@ public void testGetMember() throws IOException { @Test public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException { - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -457,7 +451,11 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException @Test public void testGetGitHubInstanceWithInvalidToken() throws IOException { - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -470,13 +468,19 @@ public void testGetGitHubInstanceWithInvalidToken() throws IOException { @Test public void testGetGitHubInstanceByToken() throws IOException { + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + GitHub gitHubInstance = gitHubMilestoneService.getGitHubInstance(); assertNotNull(gitHubInstance, "GitHub object was not created"); } @Test public void testGetCardsWithNote() throws Exception { - when(TEST_CARD1.getContent()).thenReturn(null); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + when(testCard1.getContent()).thenReturn(null); + List sprints = gitHubMilestoneService.getAdditionalActiveSprints(); assertEquals(5, sprints.get(0).getCards().size(), "Didn't get expected number of cards"); } diff --git a/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java b/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java index 8c50822c..da515fcc 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java @@ -1,14 +1,13 @@ package edu.tamu.app.service.manager; -import static edu.tamu.app.service.manager.GitHubProjectService.DEFECT_LABEL; -import static edu.tamu.app.service.manager.GitHubProjectService.FEATURE_LABEL; -import static edu.tamu.app.service.manager.GitHubProjectService.ISSUE_LABEL; -import static edu.tamu.app.service.manager.GitHubProjectService.REQUEST_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.DEFECT_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.FEATURE_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.ISSUE_LABEL; +import static edu.tamu.app.service.manager.AbstractGitHubService.REQUEST_LABEL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; @@ -27,8 +26,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHIssue; +import org.kohsuke.github.GHIssueBuilder; import org.kohsuke.github.GHIssueState; import org.kohsuke.github.GHLabel; +import org.kohsuke.github.GHMilestone; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHProject; import org.kohsuke.github.GHProject.ProjectStateFilter; @@ -38,14 +39,17 @@ import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; +import org.kohsuke.github.PagedIterable; +import org.mockito.Answers; +import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; import edu.tamu.app.cache.model.Member; @@ -65,8 +69,9 @@ import edu.tamu.app.model.repo.StatusRepo; import edu.tamu.app.model.request.FeatureRequest; -@ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) public class GitHubProjectServiceTest extends CacheMockTests { + private static final String TEST_REPOSITORY1_NAME = "Test repository 1 name"; private static final String TEST_REPOSITORY2_NAME = "Test repository 2 name"; private static final String TEST_UNUSED_LABEL_NAME = "unused"; @@ -78,217 +83,206 @@ public class GitHubProjectServiceTest extends CacheMockTests { private static final String TEST_USER3_AVATAR_PATH = "https://avatars2.githubusercontent.com/u/3333333?v=4"; private static final String TEST_USER1_AVATAR_NAME = "1234567"; private static final String TEST_COLUMN1_NAME = "Test Column 1"; - private static final String TEST_PROJECT1_NAME = "Test Project 1 Sprint Name"; - private static final String TEST_PROJECT2_NAME = "Test Project 2 Sprint Name"; - private static final String TEST_PROJECT3_NAME = "Test Project 3 Sprint Name"; private static final Long TEST_REPOSITORY1_ID = 1L; + private static final Long TEST_REPOSITORY2_ID = 2L; private static final Long TEST_USER1_ID = 3L; - - private static final String TEST_PROJECT_URL1 = "http://localhost/1"; - - private static final String TEST_PROJECT_TOKEN1 = "0123456789"; - - private static final GHLabel TEST_LABEL1 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL2 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL3 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL4 = mock(GHLabel.class); - private static final GHLabel TEST_LABEL5 = mock(GHLabel.class); - - private static final GHIssue TEST_ISSUE1 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE2 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE3 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE4 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - private static final GHIssue TEST_ISSUE5 = mock(GHIssue.class, RETURNS_DEEP_STUBS); - - private static final GHUser TEST_USER1 = mock(GHUser.class); - private static final GHUser TEST_USER2 = mock(GHUser.class); - private static final GHUser TEST_USER3 = mock(GHUser.class); - - private static final GHProjectCard TEST_CARD1 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD2 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD3 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD4 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - private static final GHProjectCard TEST_CARD5 = mock(GHProjectCard.class, RETURNS_DEEP_STUBS); - - private static final GHProjectColumn TEST_COLUMN1 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - private static final GHProjectColumn TEST_COLUMN2 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - private static final GHProjectColumn TEST_COLUMN3 = mock(GHProjectColumn.class, RETURNS_DEEP_STUBS); - - private static final GHProject TEST_PROJECT1 = mock(GHProject.class, RETURNS_DEEP_STUBS); - private static final GHProject TEST_PROJECT2 = mock(GHProject.class, RETURNS_DEEP_STUBS); - private static final GHProject TEST_PROJECT3 = mock(GHProject.class, RETURNS_DEEP_STUBS); - - private static final GHRepository TEST_REPOSITORY1 = mock(GHRepository.class, RETURNS_DEEP_STUBS); - private static final GHRepository TEST_REPOSITORY2 = mock(GHRepository.class, RETURNS_DEEP_STUBS); - - private static final GHOrganization TEST_ORGANIZATION = mock(GHOrganization.class, RETURNS_DEEP_STUBS); - - private static final FeatureRequest TEST_FEATURE_REQUEST = mock(FeatureRequest.class); - - private static final RestTemplate restTemplate = mock(RestTemplate.class); - - @SuppressWarnings("unchecked") - private ResponseEntity response = (ResponseEntity) mock(ResponseEntity.class); - - private static final List ALL_TEST_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL1, TEST_LABEL2, TEST_LABEL3, TEST_LABEL4, TEST_LABEL5 })); - private static final List TEST_CARD1_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL1, TEST_LABEL5 })); - private static final List TEST_CARD2_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL2, TEST_LABEL5 })); - private static final List TEST_CARD3_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL3, TEST_LABEL5 })); - private static final List TEST_CARD4_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL4 })); - private static final List TEST_CARD5_LABELS = new ArrayList( - Arrays.asList(new GHLabel[] { TEST_LABEL5 })); - - private static final List TEST_USERS1 = new ArrayList(Arrays.asList(new GHUser[] { TEST_USER1 })); - private static final List TEST_USERS2 = new ArrayList( - Arrays.asList(new GHUser[] { TEST_USER1, TEST_USER2 })); - private static final List TEST_USERS3 = new ArrayList(Arrays.asList(new GHUser[] {})); - private static final List TEST_USERS4 = new ArrayList(Arrays.asList(new GHUser[] { TEST_USER2 })); - private static final List TEST_USERS5 = new ArrayList( - Arrays.asList(new GHUser[] { TEST_USER3, TEST_USER1 })); - - private static final List TEST_COLUMN1_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD1, TEST_CARD2, TEST_CARD3 })); - private static final List TEST_COLUMN2_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD3, TEST_CARD4 })); - private static final List TEST_COLUMN3_CARDS = new ArrayList( - Arrays.asList(new GHProjectCard[] { TEST_CARD5 })); - - private static final List TEST_ISSUE_LIST = new ArrayList( - Arrays.asList((new GHIssue[] { TEST_ISSUE1, TEST_ISSUE2, TEST_ISSUE3, TEST_ISSUE4, TEST_ISSUE5 }))); - - private static final List TEST_PROJECT_COLUMNS = new ArrayList( - Arrays.asList(new GHProjectColumn[] { TEST_COLUMN1, TEST_COLUMN2, TEST_COLUMN3 })); - - private static final List TEST_PROJECTS = new ArrayList( - Arrays.asList(new GHProject[] { TEST_PROJECT1, TEST_PROJECT2, TEST_PROJECT3 })); - - private static final Map TEST_REPOSITORY_MAP = Stream.of( - new Object[][] { { TEST_REPOSITORY1_NAME, TEST_REPOSITORY1 }, { TEST_REPOSITORY2_NAME, TEST_REPOSITORY2 } }) - .collect(Collectors.toMap(data -> (String) data[0], data -> (GHRepository) data[1])); - - private GitHubBuilder ghBuilder; - - private GitHubProjectService gitHubProjectService; - - private GitHub github; + private static final Long TEST_PRODUCT1_ID = 4L; + private static final String TEST_PROJECT1_URL = "http://localhost/1"; + private static final String TEST_PROJECT1_TOKEN = "0123456789"; + + @Mock private GHLabel testLabel1; + @Mock private GHLabel testLabel2; + @Mock private GHLabel testLabel3; + @Mock private GHLabel testLabel4; + @Mock private GHLabel testLabel5; + @Mock private GHIssue testIssue1; + @Mock private GHIssue testIssue2; + @Mock private GHIssue testIssue3; + @Mock private GHIssue testIssue4; + @Mock private GHIssue testIssue5; + @Mock private GHUser testUser1; + @Mock private GHUser testUser2; + @Mock private GHUser testUser3; + @Mock private GHMilestone testMilestone; + @Mock private GHProjectCard testCard1; + @Mock private GHProjectCard testCard2; + @Mock private GHProjectCard testCard3; + @Mock private GHProjectCard testCard4; + @Mock private GHProjectCard testCard5; + @Mock private PagedIterable cardIterable1; + @Mock private PagedIterable cardIterable2; + @Mock private PagedIterable cardIterable3; + @Mock private GHProjectColumn testColumn1; + @Mock private GHProjectColumn testColumn2; + @Mock private GHProjectColumn testColumn3; + @Mock private PagedIterable columnIterable; + @Mock private GHProject testProject1; + @Mock private GHProject testProject2; + @Mock private GHProject testProject3; + @Mock private PagedIterable labelIterable; + @Mock private GHIssueBuilder issueBuilder; + @Mock private GHRepository testRepository1; + @Mock private GHRepository testRepository2; + @Mock private PagedIterable projectIterable; + @Mock private GHOrganization testOrganization; + @Mock private FeatureRequest testFeatureRequest; + @Mock private RestTemplate restTemplate; + @Mock private ResponseEntity response; + @Mock private CardTypeRepo cardTypeRepo; + @Mock private StatusRepo statusRepo; + @Mock private EstimateRepo estimateRepo; + @Mock private GitHubBuilder ghBuilder; + @Mock private GitHub github; + + @Mock(answer = Answers.CALLS_REAL_METHODS) private GitHubProjectService gitHubProjectService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private CardTypeMappingService cardTypeMappingService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private StatusMappingService statusMappingService; + @Mock(answer = Answers.CALLS_REAL_METHODS) private EstimateMappingService estimateMappingService; @BeforeEach - public void setUp() throws Exception { - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); - - - CardTypeRepo cardTypeRepo = mock(CardTypeRepo.class); - StatusRepo statusRepo = mock(StatusRepo.class); - EstimateRepo estimateRepo = mock(EstimateRepo.class); + public void setup() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); - CardTypeMappingService cardTypeMappingService = mock(CardTypeMappingService.class, Mockito.CALLS_REAL_METHODS); + Map testRepositoryMap = Stream.of( + new Object[][] { { TEST_REPOSITORY1_NAME, testRepository1 }, { TEST_REPOSITORY2_NAME, testRepository2 } }) + .collect(Collectors.toMap(data -> (String) data[0], data -> (GHRepository) data[1])); - StatusMappingService statusMappingService = mock(StatusMappingService.class, Mockito.CALLS_REAL_METHODS); + List allTestLabels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel1, testLabel2, testLabel3, testLabel4, testLabel5 })); + List testCard1Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel1, testLabel5 })); + List testCard2Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel2, testLabel5 })); + List testCard3Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel3, testLabel5 })); + List testCard4Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel4 })); + List testCard5Labels = new ArrayList(Arrays.asList(new GHLabel[] { testLabel5 })); - EstimateMappingService estimateMappingService = mock(EstimateMappingService.class, Mockito.CALLS_REAL_METHODS); + List testUsers1 = new ArrayList(Arrays.asList(new GHUser[] { testUser1 })); + List testUsers2 = new ArrayList(Arrays.asList(new GHUser[] { testUser1, testUser2 })); + List testUsers3 = new ArrayList(Arrays.asList(new GHUser[] {})); + List testUsers4 = new ArrayList(Arrays.asList(new GHUser[] { testUser2 })); + List testUsers5 = new ArrayList(Arrays.asList(new GHUser[] { testUser3, testUser1 })); - ghBuilder = mock(GitHubBuilder.class); + List testColumn1Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard1, testCard2, testCard3 })); + List testColumn2Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard3, testCard4 })); + List testColumn3Cards = new ArrayList(Arrays.asList(new GHProjectCard[] { testCard5 })); - gitHubProjectService = mock(GitHubProjectService.class, Mockito.CALLS_REAL_METHODS); + List testIssueList = new ArrayList(Arrays.asList((new GHIssue[] { testIssue1, testIssue2, testIssue3, testIssue4, testIssue5 }))); + List testProjectColumns = new ArrayList(Arrays.asList(new GHProjectColumn[] { testColumn1, testColumn2, testColumn3 })); + List testProjects = new ArrayList(Arrays.asList(new GHProject[] { testProject1, testProject2, testProject3 })); - github = mock(GitHub.class); + setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); + setField(statusMappingService, "serviceMappingRepo", statusRepo); + setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.build()).thenReturn(github); + setField(gitHubProjectService, "ghBuilder", ghBuilder); + setField(gitHubProjectService, "managementService", managementService); + setField(gitHubProjectService, "cardTypeMappingService", cardTypeMappingService); + setField(gitHubProjectService, "statusMappingService", statusMappingService); + setField(gitHubProjectService, "estimateMappingService", estimateMappingService); + setField(gitHubProjectService, "github", github); + setField(gitHubProjectService, "members", new HashMap()); + setField(gitHubProjectService, "restTemplate", restTemplate); - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); - - when(TEST_ORGANIZATION.getRepositories()).thenReturn(TEST_REPOSITORY_MAP); - when(TEST_ORGANIZATION.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); - - when(TEST_REPOSITORY1.getId()).thenReturn(TEST_REPOSITORY1_ID); - when(TEST_REPOSITORY1.createIssue(any(String.class)).body(any(String.class)).create()).thenReturn(TEST_ISSUE1); - when(TEST_REPOSITORY1.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.listProjects().asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.getIssues(any(GHIssueState.class))).thenReturn(TEST_ISSUE_LIST); - when(TEST_REPOSITORY2.getIssues(any(GHIssueState.class))).thenReturn(TEST_ISSUE_LIST); - when(TEST_REPOSITORY2.listProjects().asList()).thenReturn(TEST_PROJECTS); - when(TEST_REPOSITORY1.listLabels().asList()).thenReturn(ALL_TEST_LABELS); - when(TEST_REPOSITORY2.listLabels().asList()).thenReturn(ALL_TEST_LABELS); - - when(TEST_PROJECT1.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - when(TEST_PROJECT2.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - when(TEST_PROJECT3.listColumns().asList()).thenReturn(TEST_PROJECT_COLUMNS); - - when(TEST_PROJECT1.getName()).thenReturn(TEST_PROJECT1_NAME); - when(TEST_PROJECT2.getName()).thenReturn(TEST_PROJECT2_NAME); - when(TEST_PROJECT3.getName()).thenReturn(TEST_PROJECT3_NAME); - - when(TEST_COLUMN1.listCards().asList()).thenReturn(TEST_COLUMN1_CARDS); - when(TEST_COLUMN2.listCards().asList()).thenReturn(TEST_COLUMN2_CARDS); - when(TEST_COLUMN3.listCards().asList()).thenReturn(TEST_COLUMN3_CARDS); - - when(TEST_CARD1.getId()).thenReturn(1L); - when(TEST_CARD2.getId()).thenReturn(2L); - when(TEST_CARD3.getId()).thenReturn(3L); - when(TEST_CARD4.getId()).thenReturn(4L); - when(TEST_CARD5.getId()).thenReturn(5L); - - when(TEST_CARD1.getContent()).thenReturn(TEST_ISSUE1); - when(TEST_CARD2.getContent()).thenReturn(TEST_ISSUE2); - when(TEST_CARD3.getContent()).thenReturn(TEST_ISSUE3); - when(TEST_CARD4.getContent()).thenReturn(TEST_ISSUE4); - when(TEST_CARD5.getContent()).thenReturn(TEST_ISSUE5); - when(TEST_CARD1.getColumn()).thenReturn(TEST_COLUMN1); - - when(TEST_ISSUE1.getLabels()).thenReturn(TEST_CARD1_LABELS); - when(TEST_ISSUE2.getLabels()).thenReturn(TEST_CARD2_LABELS); - when(TEST_ISSUE3.getLabels()).thenReturn(TEST_CARD3_LABELS); - when(TEST_ISSUE4.getLabels()).thenReturn(TEST_CARD4_LABELS); - when(TEST_ISSUE5.getLabels()).thenReturn(TEST_CARD5_LABELS); - when(TEST_ISSUE1.getAssignees()).thenReturn(TEST_USERS1); - - - when(TEST_COLUMN1.getName()).thenReturn(TEST_COLUMN1_NAME); - - when(TEST_CARD2.getContent().getLabels()).thenReturn(TEST_CARD2_LABELS); - when(TEST_CARD3.getContent().getLabels()).thenReturn(TEST_CARD3_LABELS); - when(TEST_CARD4.getContent().getLabels()).thenReturn(TEST_CARD4_LABELS); - when(TEST_CARD5.getContent().getLabels()).thenReturn(TEST_CARD5_LABELS); - when(TEST_CARD2.getContent().getAssignees()).thenReturn(TEST_USERS2); - when(TEST_CARD3.getContent().getAssignees()).thenReturn(TEST_USERS3); - when(TEST_CARD4.getContent().getAssignees()).thenReturn(TEST_USERS4); - when(TEST_CARD5.getContent().getAssignees()).thenReturn(TEST_USERS5); - - when(TEST_USER1.getId()).thenReturn(TEST_USER1_ID); - when(TEST_USER1.getName()).thenReturn(TEST_USER1_NAME); - when(TEST_USER1.getAvatarUrl()).thenReturn(TEST_USER1_AVATAR_PATH); - when(TEST_USER2.getAvatarUrl()).thenReturn(TEST_USER2_AVATAR_PATH); - when(TEST_USER3.getAvatarUrl()).thenReturn(TEST_USER3_AVATAR_PATH); - - when(TEST_LABEL1.getName()).thenReturn(REQUEST_LABEL); - when(TEST_LABEL2.getName()).thenReturn(ISSUE_LABEL); - when(TEST_LABEL3.getName()).thenReturn(FEATURE_LABEL); - when(TEST_LABEL4.getName()).thenReturn(DEFECT_LABEL); - when(TEST_LABEL5.getName()).thenReturn(TEST_UNUSED_LABEL_NAME); - - when(TEST_FEATURE_REQUEST.getProductId()).thenReturn(TEST_REPOSITORY1_ID); - when(TEST_FEATURE_REQUEST.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); - when(TEST_FEATURE_REQUEST.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); - - when(restTemplate.exchange( + lenient().when(testOrganization.getRepositories()).thenReturn(testRepositoryMap); + + lenient().when(testOrganization.listProjects(any(ProjectStateFilter.class))).thenReturn(projectIterable); + + lenient().when(testRepository1.getId()).thenReturn(TEST_REPOSITORY1_ID); + lenient().when(testRepository1.getName()).thenReturn(TEST_REPOSITORY1_NAME); + lenient().when(testRepository1.listProjects(any(ProjectStateFilter.class))).thenReturn(projectIterable); + lenient().when(testRepository1.listProjects()).thenReturn(projectIterable); + lenient().when(testRepository1.listLabels()).thenReturn(labelIterable); + lenient().when(testRepository1.getIssues(any(GHIssueState.class))).thenReturn(testIssueList); + + lenient().when(testRepository1.createIssue(any(String.class))).thenReturn(issueBuilder); + lenient().when(issueBuilder.body(any(String.class))).thenReturn(issueBuilder); + lenient().when(issueBuilder.create()).thenReturn(testIssue1); + + lenient().when(testRepository2.getId()).thenReturn(TEST_REPOSITORY2_ID); + lenient().when(testRepository2.getName()).thenReturn(TEST_REPOSITORY2_NAME); + lenient().when(testRepository2.getIssues(any(GHIssueState.class))).thenReturn(testIssueList); + lenient().when(testRepository2.listProjects()).thenReturn(projectIterable); + lenient().when(testRepository2.listLabels()).thenReturn(labelIterable); + + lenient().when(testProject1.listColumns()).thenReturn(columnIterable); + lenient().when(testProject2.listColumns()).thenReturn(columnIterable); + lenient().when(testProject3.listColumns()).thenReturn(columnIterable); + + lenient().when(testProject1.getName()).thenReturn(AbstractGitHubService.SPRINT); + lenient().when(testProject2.getName()).thenReturn(AbstractGitHubService.SPRINT); + lenient().when(testProject3.getName()).thenReturn(AbstractGitHubService.SPRINT); + + lenient().when(testColumn1.listCards()).thenReturn(cardIterable1); + lenient().when(testColumn2.listCards()).thenReturn(cardIterable2); + lenient().when(testColumn3.listCards()).thenReturn(cardIterable3); + + lenient().when(testCard1.getId()).thenReturn(1L); + lenient().when(testCard2.getId()).thenReturn(2L); + lenient().when(testCard3.getId()).thenReturn(3L); + lenient().when(testCard4.getId()).thenReturn(4L); + lenient().when(testCard5.getId()).thenReturn(5L); + + lenient().when(testCard1.getContent()).thenReturn(testIssue1); + lenient().when(testCard2.getContent()).thenReturn(testIssue2); + lenient().when(testCard3.getContent()).thenReturn(testIssue3); + lenient().when(testCard4.getContent()).thenReturn(testIssue4); + lenient().when(testCard5.getContent()).thenReturn(testIssue5); + + lenient().when(testCard1.getColumn()).thenReturn(testColumn1); + lenient().when(testCard2.getColumn()).thenReturn(testColumn1); + lenient().when(testCard3.getColumn()).thenReturn(testColumn1); + lenient().when(testCard4.getColumn()).thenReturn(testColumn1); + lenient().when(testCard5.getColumn()).thenReturn(testColumn1); + + lenient().when(testIssue1.getLabels()).thenReturn(testCard1Labels); + lenient().when(testIssue2.getLabels()).thenReturn(testCard2Labels); + lenient().when(testIssue3.getLabels()).thenReturn(testCard3Labels); + lenient().when(testIssue4.getLabels()).thenReturn(testCard4Labels); + lenient().when(testIssue5.getLabels()).thenReturn(testCard5Labels); + lenient().when(testIssue1.getAssignees()).thenReturn(testUsers1); + + lenient().when(testColumn1.getName()).thenReturn(TEST_COLUMN1_NAME); + + lenient().when(testCard2.getContent().getLabels()).thenReturn(testCard2Labels); + lenient().when(testCard3.getContent().getLabels()).thenReturn(testCard3Labels); + lenient().when(testCard4.getContent().getLabels()).thenReturn(testCard4Labels); + lenient().when(testCard5.getContent().getLabels()).thenReturn(testCard5Labels); + lenient().when(testCard2.getContent().getAssignees()).thenReturn(testUsers2); + lenient().when(testCard3.getContent().getAssignees()).thenReturn(testUsers3); + lenient().when(testCard4.getContent().getAssignees()).thenReturn(testUsers4); + lenient().when(testCard5.getContent().getAssignees()).thenReturn(testUsers5); + + lenient().when(testUser1.getId()).thenReturn(TEST_USER1_ID); + lenient().when(testUser1.getName()).thenReturn(TEST_USER1_NAME); + lenient().when(testUser1.getAvatarUrl()).thenReturn(TEST_USER1_AVATAR_PATH); + lenient().when(testUser2.getAvatarUrl()).thenReturn(TEST_USER2_AVATAR_PATH); + lenient().when(testUser3.getAvatarUrl()).thenReturn(TEST_USER3_AVATAR_PATH); + + lenient().when(testLabel1.getName()).thenReturn(REQUEST_LABEL); + lenient().when(testLabel2.getName()).thenReturn(ISSUE_LABEL); + lenient().when(testLabel3.getName()).thenReturn(FEATURE_LABEL); + lenient().when(testLabel4.getName()).thenReturn(DEFECT_LABEL); + lenient().when(testLabel5.getName()).thenReturn(TEST_UNUSED_LABEL_NAME); + + lenient().when(testFeatureRequest.getProductId()).thenReturn(TEST_PRODUCT1_ID); + lenient().when(testFeatureRequest.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); + lenient().when(testFeatureRequest.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); + + lenient().when(labelIterable.toList()).thenReturn(allTestLabels); + lenient().when(projectIterable.toList()).thenReturn(testProjects); + lenient().when(columnIterable.toList()).thenReturn(testProjectColumns); + lenient().when(cardIterable1.toList()).thenReturn(testColumn1Cards); + lenient().when(cardIterable2.toList()).thenReturn(testColumn2Cards); + lenient().when(cardIterable3.toList()).thenReturn(testColumn3Cards); + + lenient().when(restTemplate.exchange( any(String.class), any(HttpMethod.class), Mockito.>any(), - Mockito.>any(), - Mockito.anyCollection())) + Mockito.>any())) .thenReturn(response); - when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); + lenient().when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); - when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { String identifier = (String) invocation.getArguments()[0]; @@ -307,10 +301,7 @@ public Optional answer(InvocationOnMock invocation) { } }); - when(cardTypeRepo.findByIdentifier(any(String.class))) - .thenReturn(new CardType("Feature", new HashSet(Arrays.asList(new String[] { "Story" })))); - - when(statusRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(statusRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { String identifier = (String) invocation.getArguments()[0]; @@ -338,32 +329,21 @@ public Optional answer(InvocationOnMock invocation) { } }); - when(estimateRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { + lenient().when(estimateRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override public Optional answer(InvocationOnMock invocation) { return Optional.empty(); } }); - when(statusRepo.findByIdentifier(any(String.class))) - .thenReturn(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); - - setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); - setField(statusMappingService, "serviceMappingRepo", statusRepo); - setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - - setField(gitHubProjectService, "ghBuilder", ghBuilder); - setField(gitHubProjectService, "managementService", managementService); - setField(gitHubProjectService, "cardTypeMappingService", cardTypeMappingService); - setField(gitHubProjectService, "statusMappingService", statusMappingService); - setField(gitHubProjectService, "estimateMappingService", estimateMappingService); - setField(gitHubProjectService, "github", github); - setField(gitHubProjectService, "members", new HashMap()); - setField(gitHubProjectService, "restTemplate", restTemplate); + lenient().when(statusRepo.findByIdentifier(any(String.class))) + .thenReturn(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); } @Test public void testGetRemoteProjects() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List remoteProjects = gitHubProjectService.getRemoteProject(); assertEquals(2, remoteProjects.size(), "Didn't get all the remote projects"); assertEquals(1, remoteProjects.get(0).getRequestCount(), "Number of Requests was incorrect"); @@ -374,6 +354,8 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + RemoteProject project = gitHubProjectService.getRemoteProjectByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); assertNotNull(project, "Didn't get the remote project"); assertEquals(String.valueOf(TEST_REPOSITORY1_ID), project.getId(), "Did not get the expected project"); @@ -385,18 +367,24 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + List activeSprints = gitHubProjectService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); assertEquals(3, activeSprints.size(), "Didn't get all active sprints"); } @Test public void testGetAdditionalActiveSprints() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List additionalSprints = gitHubProjectService.getAdditionalActiveSprints(); assertEquals(3, additionalSprints.size(), "Didn't get all additional sprints"); } @Test public void testGetActiveSprintsByProjectIdType() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + List sprints = gitHubProjectService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); sprints.forEach(sprint -> { @@ -405,7 +393,9 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { } @Test - public void testGetAdditionalActiveSprintType() throws Exception { + public void testGetAdditionalActiveSprintsType() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + List sprints = gitHubProjectService.getAdditionalActiveSprints(); sprints.forEach(sprint -> { @@ -415,13 +405,15 @@ public void testGetAdditionalActiveSprintType() throws Exception { @Test public void testPush() throws Exception { - String id = gitHubProjectService.push(TEST_FEATURE_REQUEST); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); + + String id = gitHubProjectService.push(testFeatureRequest); assertNotNull(id); } @Test public void testGetMember() throws IOException { - Member member = gitHubProjectService.getMember(TEST_USER1); + Member member = gitHubProjectService.getMember(testUser1); assertEquals(String.valueOf(TEST_USER1_ID), member.getId(), "Member ID is incorrect"); assertEquals(TEST_USER1_NAME, member.getName(), "Member Name is incorrect"); assertEquals(TEST_USER1_AVATAR_NAME, member.getAvatar(), "Member Avatar URL is incorrect"); @@ -429,7 +421,11 @@ public void testGetMember() throws IOException { @Test public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException { - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -442,7 +438,11 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException @Test public void testGetGitHubInstanceWithInvalidToken() throws IOException { - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -455,13 +455,19 @@ public void testGetGitHubInstanceWithInvalidToken() throws IOException { @Test public void testGetGitHubInstanceByToken() throws IOException { + when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); + when(ghBuilder.build()).thenReturn(github); + GitHub gitHubInstance = gitHubProjectService.getGitHubInstance(); assertNotNull(gitHubInstance, "GitHub object was not created"); } @Test public void testGetCardsWithNote() throws Exception { - when(TEST_CARD1.getContent()).thenReturn(null); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); + when(testCard1.getContent()).thenReturn(null); + List sprints = gitHubProjectService.getAdditionalActiveSprints(); assertEquals(5, sprints.get(0).getCards().size(), "Didn't get expected number of cards"); } diff --git a/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java b/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java index 0776ef41..54c5f9df 100644 --- a/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java @@ -3,6 +3,7 @@ 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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.matches; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; @@ -11,31 +12,6 @@ import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.Answer; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit.jupiter.SpringExtension; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.versionone.Oid; @@ -51,7 +27,6 @@ import com.versionone.apiclient.interfaces.IMetaModel; import com.versionone.apiclient.interfaces.IServices; import com.versionone.apiclient.services.QueryResult; - import edu.tamu.app.cache.model.Card; import edu.tamu.app.cache.model.Member; import edu.tamu.app.cache.model.RemoteProject; @@ -60,7 +35,6 @@ import edu.tamu.app.mapping.EstimateMappingService; import edu.tamu.app.mapping.StatusMappingService; import edu.tamu.app.model.CardType; -import edu.tamu.app.model.Estimate; import edu.tamu.app.model.ManagementService; import edu.tamu.app.model.RemoteProjectManager; import edu.tamu.app.model.ServiceType; @@ -70,8 +44,33 @@ import edu.tamu.app.model.repo.StatusRepo; import edu.tamu.app.model.request.FeatureRequest; import edu.tamu.app.rest.TokenAuthRestTemplate; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Answers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.Answer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) public class VersionOneServiceTest extends CacheMockTests { private static final String TEST_PROJECT_URL1 = "http://localhost/1"; @@ -81,99 +80,36 @@ public class VersionOneServiceTest extends CacheMockTests { @Value("classpath:images/no_avatar.png") private Resource mockImage; + private List mockRemoteProjects; + + private List mockActiveSprints; + + @Mock(answer = Answers.CALLS_REAL_METHODS) private VersionOneService versionOneService; + @Mock + private TokenAuthRestTemplate restTemplate; + + @Mock private IServices services; - private TokenAuthRestTemplate restTemplate; + @Mock + private StatusRepo statusRepo; - private List mockRemoteProjects; + @Mock + private CardTypeRepo cardTypeRepo; - private List mockActiveSprints; + @Mock + private EstimateRepo estimateRepo; @BeforeEach - @SuppressWarnings("unchecked") public void setup() throws JsonParseException, JsonMappingException, IOException, V1Exception { - MockitoAnnotations.openMocks(this); - - ManagementService managementService = new RemoteProjectManager("Version One", ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); - - CardTypeRepo cardTypeRepo = mock(CardTypeRepo.class); - StatusRepo statusRepo = mock(StatusRepo.class); - EstimateRepo estimateRepo = mock(EstimateRepo.class); + ManagementService managementService = new RemoteProjectManager("Version One", ServiceType.VERSION_ONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); CardTypeMappingService cardTypeMappingService = mock(CardTypeMappingService.class, Mockito.CALLS_REAL_METHODS); - StatusMappingService statusMappingService = mock(StatusMappingService.class, Mockito.CALLS_REAL_METHODS); - EstimateMappingService estimateMappingService = mock(EstimateMappingService.class, Mockito.CALLS_REAL_METHODS); - versionOneService = mock(VersionOneService.class, Mockito.CALLS_REAL_METHODS); - - services = mock(IServices.class); - - restTemplate = mock(TokenAuthRestTemplate.class); - - when(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class), any(Object[].class))).thenAnswer(new Answer>() { - @Override - public ResponseEntity answer(InvocationOnMock invocation) throws IOException { - byte[] bytes = Files.readAllBytes(mockImage.getFile().toPath()); - return new ResponseEntity(bytes, HttpStatus.OK); - } - }); - - when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { - @Override - public Optional answer(InvocationOnMock invocation) { - String identifier = (String) invocation.getArguments()[0]; - Optional cardType = Optional.empty(); - switch (identifier) { - case "Story": - cardType = Optional.of(new CardType("Feature", new HashSet(Arrays.asList(new String[] { "Story" })))); - break; - case "Defect": - cardType = Optional.of(new CardType("Defect", new HashSet(Arrays.asList(new String[] { "Defect" })))); - break; - } - return cardType; - } - }); - - when(cardTypeRepo.findByIdentifier(any(String.class))).thenReturn(new CardType("Feature", new HashSet(Arrays.asList(new String[] { "Story" })))); - - when(statusRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { - @Override - public Optional answer(InvocationOnMock invocation) { - String identifier = (String) invocation.getArguments()[0]; - Optional status = Optional.empty(); - switch (identifier) { - case "None": - case "Feature": - status = Optional.of(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); - break; - case "In Progress": - status = Optional.of(new Status("In Progress", new HashSet(Arrays.asList(new String[] { "In Progress" })))); - break; - case "Done": - status = Optional.of(new Status("Done", new HashSet(Arrays.asList(new String[] { "Done" })))); - break; - case "Accepted": - status = Optional.of(new Status("Accepted", new HashSet(Arrays.asList(new String[] { "Accepted" })))); - break; - } - return status; - } - }); - - when(estimateRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { - @Override - public Optional answer(InvocationOnMock invocation) { - return Optional.empty(); - } - }); - - when(statusRepo.findByIdentifier(any(String.class))).thenReturn(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); - setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); setField(statusMappingService, "serviceMappingRepo", statusRepo); setField(estimateMappingService, "serviceMappingRepo", estimateRepo); @@ -206,15 +142,6 @@ public void testGetRemoteProducts() throws ConnectionException, APIException, Oi Asset[] assets = getMockRemoteProductAssets(); - when(scopeType.getDisplayName()).thenReturn("AssetType'Scope"); - when(scopeType.getToken()).thenReturn("Scope"); - - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Scope"); - when(nameAttributeDefinition.getToken()).thenReturn("Scope.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(scopeType); - when(result.getAssets()).thenReturn(assets); when(scopeType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); @@ -224,10 +151,10 @@ public void testGetRemoteProducts() throws ConnectionException, APIException, Oi when(services.getMeta()).thenReturn(metaModel); when(services.retrieve(any(Query.class))).thenReturn(result); - doReturn(2).when(versionOneService).getPrimaryWorkItemCount(matches("Request"), any(String.class)); - doReturn(3).when(versionOneService).getPrimaryWorkItemCount(matches("Issue"), any(String.class)); - doReturn(4).when(versionOneService).getPrimaryWorkItemCount(matches("Story"), any(String.class)); - doReturn(1).when(versionOneService).getPrimaryWorkItemCount(matches("Defect"), any(String.class)); + doReturn(2).when(versionOneService).getPrimaryWorkItemCount(matches("Request"), anyString()); + doReturn(3).when(versionOneService).getPrimaryWorkItemCount(matches("Issue"), anyString()); + doReturn(4).when(versionOneService).getPrimaryWorkItemCount(matches("Story"), anyString()); + doReturn(1).when(versionOneService).getPrimaryWorkItemCount(matches("Defect"), anyString()); assertRemoteProducts(versionOneService.getRemoteProject()); } @@ -243,22 +170,13 @@ public void testGetRemoteProductByScopeId() throws ConnectionException, APIExcep Asset[] assets = getMockRemoteProductAssetByScopeId("1934"); - when(scopeType.getDisplayName()).thenReturn("AssetType'Scope"); - when(scopeType.getToken()).thenReturn("Scope"); - - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Scope"); - when(nameAttributeDefinition.getToken()).thenReturn("Scope.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(scopeType); - when(result.getAssets()).thenReturn(assets); when(scopeType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); when(metaModel.getAssetType("Scope")).thenReturn(scopeType); - when(services.getOid(any(String.class))).thenReturn(oid); + when(services.getOid(anyString())).thenReturn(oid); when(services.getMeta()).thenReturn(metaModel); when(services.retrieve(any(Query.class))).thenReturn(result); @@ -280,43 +198,6 @@ public void testGetPrimaryWorkItemCount() throws ConnectionException, APIExcepti testGetPrimaryWorkItemCount("Defect"); } - private void testGetPrimaryWorkItemCount(String type) throws ConnectionException, APIException, OidException, JsonParseException, JsonMappingException, IOException { - QueryResult result = mock(QueryResult.class); - IMetaModel metaModel = mock(IMetaModel.class); - IAssetType assetType = mock(IAssetType.class); - IAttributeDefinition scopeAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition assetStateAttributeDefinition = mock(IAttributeDefinition.class); - - Asset[] assets = new Asset[0]; - - when(assetType.getDisplayName()).thenReturn("AssetType'" + type); - when(assetType.getToken()).thenReturn(type); - - when(scopeAttributeDefinition.getName()).thenReturn("Scope"); - when(scopeAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Scope'" + type); - when(scopeAttributeDefinition.getToken()).thenReturn(type + "Scope"); - when(scopeAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(scopeAttributeDefinition.getAssetType()).thenReturn(assetType); - - when(assetStateAttributeDefinition.getName()).thenReturn("AssetState"); - when(assetStateAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'AssetState'" + type); - when(assetStateAttributeDefinition.getToken()).thenReturn(type + "AssetState"); - when(assetStateAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(assetStateAttributeDefinition.getAssetType()).thenReturn(assetType); - - when(assetType.getAttributeDefinition("Scope")).thenReturn(scopeAttributeDefinition); - when(assetType.getAttributeDefinition("AssetState")).thenReturn(assetStateAttributeDefinition); - - when(metaModel.getAssetType(type)).thenReturn(assetType); - - when(result.getAssets()).thenReturn(assets); - - when(services.getMeta()).thenReturn(metaModel); - when(services.retrieve(any(Query.class))).thenReturn(result); - - assertEquals(0, versionOneService.getPrimaryWorkItemCount(type, "1934"), "Incorrect number of " + type); - } - @Test public void testGetActiveSprintsByProductId() throws ConnectionException, APIException, OidException, IOException { QueryResult result = mock(QueryResult.class); @@ -332,32 +213,11 @@ public void testGetActiveSprintsByProductId() throws ConnectionException, APIExc Asset[] assets = getMockActiveSprintAssets("0001"); - when(timeboxType.getDisplayName()).thenReturn("AssetType'Timebox"); - when(timeboxType.getToken()).thenReturn("Timebox"); - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Timebox"); - when(nameAttributeDefinition.getToken()).thenReturn("Timebox.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(timeboxType); - - when(stateCodeAttributeeDefinition.getName()).thenReturn("State.Code"); - when(stateCodeAttributeeDefinition.getDisplayName()).thenReturn("AttributeDefinition'State.Code'Timebox"); - when(stateCodeAttributeeDefinition.getToken()).thenReturn("Timebox.State.Code"); - when(stateCodeAttributeeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(stateCodeAttributeeDefinition.getAssetType()).thenReturn(timeboxType); when(scheduleScheduledScopesAttributeeDefinition.getName()).thenReturn("Schedule.ScheduledScopes"); - when(scheduleScheduledScopesAttributeeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Schedule.ScheduledScopes'Timebox"); - when(scheduleScheduledScopesAttributeeDefinition.getToken()).thenReturn("Timebox.Schedule.ScheduledScopes"); - when(scheduleScheduledScopesAttributeeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(scheduleScheduledScopesAttributeeDefinition.getAssetType()).thenReturn(timeboxType); when(scheduleScheduledScopesNameAttributeeDefinition.getName()).thenReturn("Schedule.ScheduledScopes.Name"); - when(scheduleScheduledScopesNameAttributeeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Schedule.ScheduledScopes.Name'Timebox"); - when(scheduleScheduledScopesNameAttributeeDefinition.getToken()).thenReturn("Timebox.Schedule.ScheduledScopes.Name"); - when(scheduleScheduledScopesNameAttributeeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(scheduleScheduledScopesNameAttributeeDefinition.getAssetType()).thenReturn(timeboxType); when(timeboxType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); when(timeboxType.getAttributeDefinition("State.Code")).thenReturn(stateCodeAttributeeDefinition); @@ -386,7 +246,6 @@ public void testGetActiveSprintsCards() throws JsonParseException, JsonMappingEx QueryResult result = mock(QueryResult.class); IMetaModel metaModel = mock(IMetaModel.class); - IAssetType primaryWorkitemType = mock(IAssetType.class); IAttributeDefinition nameAttributeDefinition = mock(IAttributeDefinition.class); @@ -400,65 +259,58 @@ public void testGetActiveSprintsCards() throws JsonParseException, JsonMappingEx IAttributeDefinition timboxAttributeDefinition = mock(IAttributeDefinition.class); IAttributeDefinition assetStateAttributeDefinition = mock(IAttributeDefinition.class); + when(cardTypeRepo.findByMapping(anyString())).thenAnswer(new Answer>() { + @Override + public Optional answer(InvocationOnMock invocation) { + String identifier = (String) invocation.getArguments()[0]; + Optional cardType = Optional.empty(); + switch (identifier) { + case "Story": + cardType = Optional.of(new CardType("Feature", new HashSet(Arrays.asList(new String[] { "Story" })))); + break; + case "Defect": + cardType = Optional.of(new CardType("Defect", new HashSet(Arrays.asList(new String[] { "Defect" })))); + break; + } + return cardType; + } + }); + + when(statusRepo.findByMapping(anyString())).thenAnswer(new Answer>() { + @Override + public Optional answer(InvocationOnMock invocation) { + String identifier = (String) invocation.getArguments()[0]; + Optional status = Optional.empty(); + switch (identifier) { + case "None": + case "Feature": + status = Optional.of(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); + break; + case "In Progress": + status = Optional.of(new Status("In Progress", new HashSet(Arrays.asList(new String[] { "In Progress" })))); + break; + case "Done": + status = Optional.of(new Status("Done", new HashSet(Arrays.asList(new String[] { "Done" })))); + break; + case "Accepted": + status = Optional.of(new Status("Accepted", new HashSet(Arrays.asList(new String[] { "Accepted" })))); + break; + } + return status; + } + }); + List mocKSprint1Cards = mockActiveSprints.get(0).getCards(); Asset[] assets = getMockActiveSprintCardAssets(mocKSprint1Cards); - when(primaryWorkitemType.getDisplayName()).thenReturn("AssetType'PrimaryWorkitem"); - when(primaryWorkitemType.getToken()).thenReturn("PrimaryWorkitem"); - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'PrimaryWorkitem"); - when(nameAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); when(numberAttributeDefinition.getName()).thenReturn("Number"); - when(numberAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Number'PrimaryWorkitem"); - when(numberAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Number"); - when(numberAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(numberAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - when(assetTypeAttributeDefinition.getName()).thenReturn("AssetType"); - when(assetTypeAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'AssetType'PrimaryWorkitem"); - when(assetTypeAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.AssetType"); - when(assetTypeAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.AssetType); - when(assetTypeAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - when(descriptionAttributeDefinition.getName()).thenReturn("Description"); - when(descriptionAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Description'PrimaryWorkitem"); - when(descriptionAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Description"); - when(descriptionAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(descriptionAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - when(statusNameAttributeDefinition.getName()).thenReturn("Status.Name"); - when(statusNameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Status.Name'PrimaryWorkitem"); - when(statusNameAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Status.Name"); - when(statusNameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(statusNameAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - when(estimateAttributeDefinition.getName()).thenReturn("Estimate"); - when(estimateAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Estimate'PrimaryWorkitem"); - when(estimateAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Estimate"); - when(estimateAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Numeric); - when(estimateAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - when(ownersAttributeDefinition.getName()).thenReturn("Owners"); - when(ownersAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Owners'PrimaryWorkitem"); - when(ownersAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Owners"); - when(ownersAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(ownersAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(timboxAttributeDefinition.getName()).thenReturn("Timebox"); - when(timboxAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Timebox'PrimaryWorkitem"); - when(timboxAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Timebox"); - when(timboxAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(timboxAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(assetStateAttributeDefinition.getName()).thenReturn("AssetState"); - when(assetStateAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'AssetState'PrimaryWorkitem"); - when(assetStateAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.AssetState"); - when(assetStateAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.State); - when(assetStateAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); when(primaryWorkitemType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); when(primaryWorkitemType.getAttributeDefinition("Number")).thenReturn(numberAttributeDefinition); @@ -482,10 +334,14 @@ public void testGetActiveSprintsCards() throws JsonParseException, JsonMappingEx doAnswer(new Answer() { @Override public Member answer(InvocationOnMock invocation) { - String memberId = (String) invocation.getArguments()[0]; - return getMockMemberById(memberId); + if (invocation.getArguments().length > 0) { + String memberId = (String) invocation.getArguments()[0]; + return getMockMemberById(memberId); + } + + return null; } - }).when(versionOneService).getMember(any(String.class)); + }).when(versionOneService).getMember(anyString()); List cards = versionOneService.getActiveSprintsCards("0001"); @@ -495,7 +351,6 @@ public Member answer(InvocationOnMock invocation) { @Test public void testGetMember() throws JsonParseException, JsonMappingException, APIException, IOException, OidException, ConnectionException { Oid oid = mock(Oid.class); - QueryResult result = mock(QueryResult.class); IMetaModel metaModel = mock(IMetaModel.class); IAssetType memberType = mock(IAssetType.class); @@ -506,29 +361,13 @@ public void testGetMember() throws JsonParseException, JsonMappingException, API Asset[] assets = getMockMemberAsset(mockMember, false); when(result.getAssets()).thenReturn(assets); - - when(memberType.getDisplayName()).thenReturn("AssetType'Member"); - when(memberType.getToken()).thenReturn("Member"); - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Member"); - when(nameAttributeDefinition.getToken()).thenReturn("Member.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(memberType); - when(avatarAttributeDefinition.getName()).thenReturn("Avatar"); - when(avatarAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Avatar'Member"); - when(avatarAttributeDefinition.getToken()).thenReturn("Member.Avatar"); - when(avatarAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(avatarAttributeDefinition.getAssetType()).thenReturn(memberType); - when(memberType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); when(memberType.getAttributeDefinition("Avatar")).thenReturn(avatarAttributeDefinition); - when(metaModel.getAssetType("Member")).thenReturn(memberType); when(services.getOid("Member:0001")).thenReturn(oid); - when(services.getMeta()).thenReturn(metaModel); when(services.retrieve(any(Query.class))).thenReturn(result); @@ -540,9 +379,10 @@ public void testGetMember() throws JsonParseException, JsonMappingException, API } @Test + @SuppressWarnings("unchecked") public void testGetMemberWithAvatarImage() throws JsonParseException, JsonMappingException, APIException, IOException, OidException, ConnectionException { - Oid oid = mock(Oid.class); + Oid oid = mock(Oid.class); QueryResult result = mock(QueryResult.class); IMetaModel metaModel = mock(IMetaModel.class); IAssetType memberType = mock(IAssetType.class); @@ -552,30 +392,23 @@ public void testGetMemberWithAvatarImage() throws JsonParseException, JsonMappin Member mockMember = getMockMemberById("0003"); Asset[] assets = getMockMemberAsset(mockMember, true); - when(result.getAssets()).thenReturn(assets); - - when(memberType.getDisplayName()).thenReturn("AssetType'Member"); - when(memberType.getToken()).thenReturn("Member"); + when(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))) + .thenAnswer(new Answer>() { + @Override + public ResponseEntity answer(InvocationOnMock invocation) throws IOException { + byte[] bytes = Files.readAllBytes(mockImage.getFile().toPath()); + return new ResponseEntity(bytes, HttpStatus.OK); + } + }); + when(result.getAssets()).thenReturn(assets); when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Member"); - when(nameAttributeDefinition.getToken()).thenReturn("Member.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(memberType); - when(avatarAttributeDefinition.getName()).thenReturn("Avatar"); - when(avatarAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Avatar'Member"); - when(avatarAttributeDefinition.getToken()).thenReturn("Member.Avatar"); - when(avatarAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(avatarAttributeDefinition.getAssetType()).thenReturn(memberType); - when(memberType.getAttributeDefinition("Name")).thenReturn(nameAttributeDefinition); when(memberType.getAttributeDefinition("Avatar")).thenReturn(avatarAttributeDefinition); - when(metaModel.getAssetType("Member")).thenReturn(memberType); when(services.getOid("Member:0003")).thenReturn(oid); - when(services.getMeta()).thenReturn(metaModel); when(services.retrieve(any(Query.class))).thenReturn(result); @@ -597,10 +430,10 @@ public void testPush() throws V1Exception { Asset mockAsset = mock(Asset.class); - when(assetType.getAttributeDefinition(any(String.class))).thenReturn(attributeDefinition); - when(metaModel.getAssetType(any(String.class))).thenReturn(assetType); + when(assetType.getAttributeDefinition(anyString())).thenReturn(attributeDefinition); + when(metaModel.getAssetType(anyString())).thenReturn(assetType); - when(services.getOid(any(String.class))).thenReturn(oid); + when(services.getOid(anyString())).thenReturn(oid); when(services.getMeta()).thenReturn(metaModel); when(services.createNew(any(IAssetType.class), any(Oid.class))).thenReturn(mockAsset); @@ -614,6 +447,28 @@ public void testPush() throws V1Exception { assertNotNull(request); } + private void testGetPrimaryWorkItemCount(String type) throws ConnectionException, APIException, OidException, JsonParseException, JsonMappingException, IOException { + QueryResult result = mock(QueryResult.class); + IMetaModel metaModel = mock(IMetaModel.class); + IAssetType assetType = mock(IAssetType.class); + IAttributeDefinition scopeAttributeDefinition = mock(IAttributeDefinition.class); + IAttributeDefinition assetStateAttributeDefinition = mock(IAttributeDefinition.class); + + Asset[] assets = new Asset[0]; + + when(assetType.getAttributeDefinition("Scope")).thenReturn(scopeAttributeDefinition); + when(assetType.getAttributeDefinition("AssetState")).thenReturn(assetStateAttributeDefinition); + + when(metaModel.getAssetType(type)).thenReturn(assetType); + + when(result.getAssets()).thenReturn(assets); + + when(services.getMeta()).thenReturn(metaModel); + when(services.retrieve(any(Query.class))).thenReturn(result); + + assertEquals(0, versionOneService.getPrimaryWorkItemCount(type, "1934"), "Incorrect number of " + type); + } + private Asset[] getMockActiveSprintAssets(String scopeId) throws JsonParseException, JsonMappingException, IOException, APIException { List mockAssets = new ArrayList(); for (Sprint activeSprint : mockActiveSprints) { @@ -622,46 +477,16 @@ private Asset[] getMockActiveSprintAssets(String scopeId) throws JsonParseExcept Oid mockOid = mock(Oid.class); - IAssetType timeboxType = mock(IAssetType.class); - - IAttributeDefinition nameAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition scheduleScheduledScopesAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition scheduledScopesNameAttributeDefinition = mock(IAttributeDefinition.class); - Attribute mockNameAttribute = mock(Attribute.class); Attribute mockScheduledScopesAttribute = mock(Attribute.class); Attribute mockScheduledScopesNameAttribute = mock(Attribute.class); when(mockOid.toString()).thenReturn("Timebox:" + activeSprint.getId()); - when(timeboxType.getDisplayName()).thenReturn("AssetType'Timebox"); - when(timeboxType.getToken()).thenReturn("Timebox"); - - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Timebox"); - when(nameAttributeDefinition.getToken()).thenReturn("Timebox.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(timeboxType); - - when(mockNameAttribute.getDefinition()).thenReturn(nameAttributeDefinition); when(mockNameAttribute.getValue()).thenReturn(activeSprint.getName()); - when(scheduleScheduledScopesAttributeDefinition.getName()).thenReturn("Schedule.ScheduledScopes.Name"); - when(scheduleScheduledScopesAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Schedule.ScheduledScopes.Name'Timebox"); - when(scheduleScheduledScopesAttributeDefinition.getToken()).thenReturn("Timebox.Schedule.ScheduledScopes.Name"); - when(scheduleScheduledScopesAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(scheduleScheduledScopesAttributeDefinition.getAssetType()).thenReturn(timeboxType); - - when(mockScheduledScopesAttribute.getDefinition()).thenReturn(scheduleScheduledScopesAttributeDefinition); when(mockScheduledScopesAttribute.getValues()).thenReturn(new String[] { "Scope:" + scopeId }); - when(scheduledScopesNameAttributeDefinition.getName()).thenReturn("Schedule.ScheduledScopes.Name"); - when(scheduledScopesNameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Schedule.ScheduledScopes.Name'Timebox"); - when(scheduledScopesNameAttributeDefinition.getToken()).thenReturn("Timebox.Schedule.ScheduledScopes.Name"); - when(scheduledScopesNameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(scheduledScopesNameAttributeDefinition.getAssetType()).thenReturn(timeboxType); - - when(mockScheduledScopesNameAttribute.getDefinition()).thenReturn(scheduledScopesNameAttributeDefinition); when(mockScheduledScopesNameAttribute.getValues()).thenReturn(new String[] { activeSprint.getProduct() }); when(mockAsset.getOid()).thenReturn(mockOid); @@ -699,18 +524,9 @@ private Asset[] getMockActiveSprintCardAssets(List mockSprintCards) throws for (Card card : mockSprintCards) { Asset mockAsset = mock(Asset.class); - Oid mockOid = mock(Oid.class); - IAssetType primaryWorkitemType = mock(IAssetType.class); - - IAttributeDefinition nameAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition numberAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition assetTypeAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition descriptionAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition statusNameAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition estimateAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition ownersAttributeDefinition = mock(IAttributeDefinition.class); + IAssetType storyAssetType = mock(IAssetType.class); Attribute mockNameAttribute = mock(Attribute.class); Attribute mockNumberAttribute = mock(Attribute.class); @@ -722,77 +538,15 @@ private Asset[] getMockActiveSprintCardAssets(List mockSprintCards) throws when(mockOid.toString()).thenReturn("PrimaryWorkitem:" + card.getId()); - when(primaryWorkitemType.getDisplayName()).thenReturn("AssetType'PrimaryWorkitem"); - when(primaryWorkitemType.getToken()).thenReturn("PrimaryWorkitem"); - - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'PrimaryWorkitem"); - when(nameAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockNameAttribute.getDefinition()).thenReturn(nameAttributeDefinition); when(mockNameAttribute.getValue()).thenReturn(card.getName()); - - when(numberAttributeDefinition.getName()).thenReturn("Number"); - when(numberAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Number'PrimaryWorkitem"); - when(numberAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Number"); - when(numberAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(numberAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockNumberAttribute.getDefinition()).thenReturn(numberAttributeDefinition); when(mockNumberAttribute.getValue()).thenReturn(card.getNumber()); - - when(assetTypeAttributeDefinition.getName()).thenReturn("AssetType"); - when(assetTypeAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'AssetType'PrimaryWorkitem"); - when(assetTypeAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.AssetType"); - when(assetTypeAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.AssetType); - when(assetTypeAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockAssetTypeAttribute.getDefinition()).thenReturn(assetTypeAttributeDefinition); - - IAssetType storyAssetType = mock(IAssetType.class); - when(storyAssetType.getDisplayName()).thenReturn("AssetType'Story"); - when(storyAssetType.getToken()).thenReturn(card.getStatus().equals("Feature") ? "Story" : "Defect"); when(mockAssetTypeAttribute.getValue()).thenReturn(storyAssetType); - - when(descriptionAttributeDefinition.getName()).thenReturn("Description"); - when(descriptionAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Description'PrimaryWorkitem"); - when(descriptionAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Description"); - when(descriptionAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(descriptionAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockDescriptionAttribute.getDefinition()).thenReturn(descriptionAttributeDefinition); when(mockDescriptionAttribute.getValue()).thenReturn(card.getDescription()); - - when(statusNameAttributeDefinition.getName()).thenReturn("Status.Name"); - when(statusNameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Status.Name'PrimaryWorkitem"); - when(statusNameAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Status.Name"); - when(statusNameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(statusNameAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockStatusNameAttribute.getDefinition()).thenReturn(statusNameAttributeDefinition); when(mockStatusNameAttribute.getValue()).thenReturn(card.getStatus()); - - when(estimateAttributeDefinition.getName()).thenReturn("Estimate"); - when(estimateAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Estimate'PrimaryWorkitem"); - when(estimateAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Estimate"); - when(estimateAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Numeric); - when(estimateAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockEstimateAttribute.getDefinition()).thenReturn(estimateAttributeDefinition); when(mockEstimateAttribute.getValue()).thenReturn(card.getEstimate()); - when(ownersAttributeDefinition.getName()).thenReturn("Owners"); - when(ownersAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Owners'PrimaryWorkitem"); - when(ownersAttributeDefinition.getToken()).thenReturn("PrimaryWorkitem.Owners"); - when(ownersAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(ownersAttributeDefinition.getAssetType()).thenReturn(primaryWorkitemType); - - when(mockOwnersAttribute.getDefinition()).thenReturn(ownersAttributeDefinition); - Object[] mockMemberObjects = getMockMemberAssetsWithIdOnly(card.getAssignees()); when(mockOwnersAttribute.getValues()).thenReturn(mockMemberObjects); @@ -867,11 +621,8 @@ private Asset[] getMockRemoteProductAssetByScopeId(String scopeId) throws JsonPa for (RemoteProject remoteProject : mockRemoteProjects) { if (remoteProject.getId().equals(scopeId)) { Asset mockAsset = mock(Asset.class); - Oid mockOid = mock(Oid.class); Attribute mockNameAttribute = mock(Attribute.class); when(mockNameAttribute.getValue()).thenReturn(remoteProject.getName()); - when(mockOid.toString()).thenReturn("Scope:" + remoteProject.getId()); - when(mockAsset.getOid()).thenReturn(mockOid); when(mockAsset.getAttribute(any(IAttributeDefinition.class))).thenReturn(mockNameAttribute); mockAssets.add(mockAsset); break; @@ -882,47 +633,14 @@ private Asset[] getMockRemoteProductAssetByScopeId(String scopeId) throws JsonPa private Asset[] getMockMemberAsset(Member member, boolean withImage) throws APIException { Asset mockAsset = mock(Asset.class); - Oid mockOid = mock(Oid.class); - - IAssetType memberType = mock(IAssetType.class); - - IAttributeDefinition nameAttributeDefinition = mock(IAttributeDefinition.class); - IAttributeDefinition avatarAttributeDefinition = mock(IAttributeDefinition.class); - Attribute mockNameAttribute = mock(Attribute.class); Attribute mockAvatarAttribute = mock(Attribute.class); - - when(mockOid.toString()).thenReturn("Member:" + member.getId()); - - when(memberType.getDisplayName()).thenReturn("AssetType'Member"); - when(memberType.getToken()).thenReturn("Member"); - - when(nameAttributeDefinition.getName()).thenReturn("Name"); - when(nameAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Name'Member"); - when(nameAttributeDefinition.getToken()).thenReturn("Member.Name"); - when(nameAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Text); - when(nameAttributeDefinition.getAssetType()).thenReturn(memberType); - - when(mockNameAttribute.getDefinition()).thenReturn(nameAttributeDefinition); - when(mockNameAttribute.getValue()).thenReturn(member.getName()); - - when(avatarAttributeDefinition.getName()).thenReturn("Avatar"); - when(avatarAttributeDefinition.getDisplayName()).thenReturn("AttributeDefinition'Avatar'Member"); - when(avatarAttributeDefinition.getToken()).thenReturn("Member.Avatar"); - when(avatarAttributeDefinition.getAttributeType()).thenReturn(IAttributeDefinition.AttributeType.Relation); - when(avatarAttributeDefinition.getAssetType()).thenReturn(memberType); - - when(mockAvatarAttribute.getDefinition()).thenReturn(avatarAttributeDefinition); - Oid oid = mock(Oid.class); - Oid assetOid = mock(Oid.class); + when(mockNameAttribute.getValue()).thenReturn(member.getName()); when(oid.toString()).thenReturn(withImage ? "Image:" + member.getId() : "NULL"); when(mockAvatarAttribute.getValue()).thenReturn(oid); - when(mockAsset.getOid()).thenReturn(assetOid); - when(assetOid.getToken()).thenReturn("token:assetOid"); - when(mockAsset.getAttribute(any(IAttributeDefinition.class))).thenAnswer(new Answer() { @Override public Attribute answer(InvocationOnMock invocation) { @@ -955,6 +673,7 @@ private Member getMockMemberById(String memberId) { } } } + return null; } diff --git a/src/test/java/edu/tamu/app/service/ticketing/SugarServiceTest.java b/src/test/java/edu/tamu/app/service/ticketing/SugarServiceTest.java index a218c39a..7bc38b14 100644 --- a/src/test/java/edu/tamu/app/service/ticketing/SugarServiceTest.java +++ b/src/test/java/edu/tamu/app/service/ticketing/SugarServiceTest.java @@ -1,26 +1,23 @@ package edu.tamu.app.service.ticketing; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import edu.tamu.app.model.request.TicketRequest; +import edu.tamu.weaver.auth.model.Credentials; +import edu.tamu.weaver.email.service.EmailSender; import javax.mail.MessagingException; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.context.TestPropertySource; import org.springframework.test.util.ReflectionTestUtils; -import edu.tamu.app.model.request.TicketRequest; -import edu.tamu.weaver.auth.model.Credentials; -import edu.tamu.weaver.email.service.EmailSender; - @TestPropertySource @ExtendWith(MockitoExtension.class) public class SugarServiceTest { @@ -51,20 +48,21 @@ public class SugarServiceTest { @BeforeEach public void setup() { - MockitoAnnotations.openMocks(this); ReflectionTestUtils.setField(sugarService, "sugarEmail", "helpdesk@library.tamu.edu"); } @Test public void testSubmit() throws MessagingException { - doNothing().when(emailService).sendEmail(any(String.class), any(String.class), any(String.class)); + doNothing().when(emailService).sendEmail(anyString(), anyString(), anyString()); + String result = sugarService.submit(TEST_REQUEST); assertEquals(SUCCESSFUL_SUBMIT_TICKET_MESSAGE, result, "Results were not as expected!"); } @Test public void testInvalidEmail() throws MessagingException { - doThrow(MessagingException.class).when(emailService).sendEmail(any(String.class), any(String.class), any(String.class)); + doThrow(MessagingException.class).when(emailService).sendEmail(anyString(), anyString(), anyString()); + String result = sugarService.submit(TEST_REQUEST); assertEquals(SUBMIT_TICKET_ERROR_MESSAGE, result, "Results were not as expected!"); } diff --git a/src/test/java/org/kohsuke/github/GHObject.java b/src/test/java/org/kohsuke/github/GHObject.java new file mode 100644 index 00000000..99f84eca --- /dev/null +++ b/src/test/java/org/kohsuke/github/GHObject.java @@ -0,0 +1,188 @@ +package org.kohsuke.github; + +import com.fasterxml.jackson.annotation.JacksonInject; +import com.infradna.tool.bridge_method_injector.WithBridgeMethods; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.kohsuke.github.connector.GitHubConnectorResponse; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URL; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.annotation.CheckForNull; + +/** + * Most (all?) domain objects in GitHub seems to have these 4 properties. + */ +@SuppressFBWarnings(value = { "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD" }, + justification = "JSON API") +public abstract class GHObject extends GitHubInteractiveObject { + /** + * Capture response HTTP headers on the state object. + */ + protected transient Map> responseHeaderFields; + + private String url; + + private long id; + private String nodeId; + private String createdAt; + private String updatedAt; + + GHObject() { + } + + /** + * Called by Jackson + * + * @param connectorResponse + * the {@link GitHubConnectorResponse} to get headers from. + */ + @JacksonInject + protected void setResponseHeaderFields(@CheckForNull GitHubConnectorResponse connectorResponse) { + if (connectorResponse != null) { + responseHeaderFields = connectorResponse.allHeaders(); + } + } + + /** + * Returns the HTTP response headers given along with the state of this object. + * + *

+ * Some of the HTTP headers have nothing to do with the object, for example "Cache-Control" and others are different + * depending on how this object was retrieved. + *

+ * This method was added as a kind of hack to allow the caller to retrieve OAuth scopes and such. Use with caution. + * The method might be removed in the future. + * + * @return a map of header names to value lists + */ + @CheckForNull + @Deprecated + public Map> getResponseHeaderFields() { + return GitHubClient.unmodifiableMapOrNull(responseHeaderFields); + } + + /** + * When was this resource created? + * + * @return date created + * @throws IOException + * on error + */ + @WithBridgeMethods(value = String.class, adapterMethod = "createdAtStr") + public Date getCreatedAt() throws IOException { + return GitHubClient.parseDate(createdAt); + } + + @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "Bridge method of getCreatedAt") + private Object createdAtStr(Date id, Class type) { + return createdAt; + } + + /** + * Gets url. + * + * @return API URL of this object. + */ + @WithBridgeMethods(value = String.class, adapterMethod = "urlToString") + public URL getUrl() { + return GitHubClient.parseURL(url); + } + + /** + * Gets html url. + * + * @return URL of this object for humans, which renders some HTML. + * @throws IOException + * on error + */ + @WithBridgeMethods(value = String.class, adapterMethod = "urlToString") + public abstract URL getHtmlUrl() throws IOException; + + /** + * When was this resource last updated? + * + * @return updated date + * @throws IOException + * on error + */ + public Date getUpdatedAt() throws IOException { + return GitHubClient.parseDate(updatedAt); + } + + /** + * Get Global node_id from Github object. + * + * @see Using Global Node IDs + * + * @return Global Node ID. + */ + public String getNodeId() { + return nodeId; + } + + /** + * Gets id. + * + * @return Unique ID number of this resource. + */ + // @WithBridgeMethods(value = { String.class, int.class }, adapterMethod = "longToStringOrInt") + public long getId() { + return id; + } + + @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "Bridge method of getId") + private Object longToStringOrInt(long id, Class type) { + if (type == String.class) + return String.valueOf(id); + if (type == int.class) + return (int) id; + throw new AssertionError("Unexpected type: " + type); + } + + @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "Bridge method of getHtmlUrl") + private Object urlToString(URL url, Class type) { + return url == null ? null : url.toString(); + } + + /** + * String representation to assist debugging and inspection. The output format of this string is not a committed + * part of the API and is subject to change. + */ + @Override + public String toString() { + return new ReflectionToStringBuilder(this, TOSTRING_STYLE, null, null, false, false) { + @Override + protected boolean accept(Field field) { + return super.accept(field) && !field.isAnnotationPresent(SkipFromToString.class); + } + }.toString(); + } + + private static final ToStringStyle TOSTRING_STYLE = new ToStringStyle() { + { + this.setUseShortClassName(true); + } + + @Override + public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { + // skip unimportant properties. '_' is a heuristics as important properties tend to have short names + if (fieldName.contains("_")) + return; + // avoid recursing other GHObject + if (value instanceof GHObject) + return; + // likewise no point in showing root + if (value instanceof GitHub) + return; + + super.append(buffer, fieldName, value, fullDetail); + } + }; +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 22008419..7a33956f 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -2,17 +2,27 @@ server: port: 9101 contextPath: ---- +# logging logging: + file: + name: logs/project-management-service.log level: - edu.tamu: INFO - org.springframework: WARN - file: logs/product-management-service.log + edu: + tamu: ERROR + org: + tdl: ERROR + springframework: ERROR + hibernate: OFF + ro: + isdc: + wro: ERROR + com: + zaxxer: ERROR + encoder: + pattern: "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" ---- security.basic.enabled: false ---- spring: main: allow-circular-references: true @@ -43,7 +53,6 @@ spring: show-sql: false hibernate.ddl-auto: create-drop ---- app: cache: default: @@ -97,7 +106,6 @@ app: # edu.tamu.weaver.utility.HttpUtility http.timeout: 10000 ---- ############################# # Framework auth properties # ############################# @@ -111,7 +119,6 @@ auth: # edu.tamu.weaver.token.provider.controller.TokenController path: /auth ---- ############################# # Framework shib properties # ############################# @@ -124,3 +131,25 @@ shib: lastName: tdl-sn firstName: tdl-givenname email: tdl-mail + +# For unit testing. +junit: + jupiter: + + execution: + parallel: + enabled: false + + mode: + default: same_thread + classes: + default: same_thread + + testinstance: + + # Possibilities: per_class, per_method. + lifecycle:default: per_method + + extensions: + autodetection: + enabled: false diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties deleted file mode 100644 index cd31af2c..00000000 --- a/src/test/resources/log4j.properties +++ /dev/null @@ -1,17 +0,0 @@ -# Root logger option -log4j.rootLogger=WARN, stdout, file - -# Redirect log messages to console -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=logger.info -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - -# Redirect log messages to a log file -log4j.appender.file=org.apache.log4j.RollingFileAppender -#outputs to Tomcat home -log4j.appender.file.File=${catalina.home}/logs/myapp.log -log4j.appender.file.MaxFileSize=5MB -log4j.appender.file.MaxBackupIndex=10 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 00000000..ff2a2b03 --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,11 @@ + + + + + + + + + + +