From acf33ca7f89be9ba6dc0709b319be9dac713411f Mon Sep 17 00:00:00 2001 From: Kevin Day Date: Mon, 1 Aug 2022 16:54:24 -0500 Subject: [PATCH 01/26] Begin updating incompletely migrated code. Fix easy to solve test problems. Begin cleaning up the application.yml files. Begin setting up the logging system. Fix a bug where non-static logging is causing NULL pointer exceptions. --- .../ActiveSprintsScheduledCacheService.java | 2 +- .../ProductsStatsScheduledCacheService.java | 2 +- .../RemoteProjectsScheduledCacheService.java | 2 +- .../app/controller/ProductController.java | 4 +-- .../controller/RemoteProjectController.java | 21 ++-------------- .../RemoteProjectManagerController.java | 4 +-- .../impl/RemoteProjectManagerRepoImpl.java | 2 +- .../service/manager/VersionOneService.java | 2 +- .../registry/ManagementBeanRegistry.java | 2 +- src/main/resources/application.yml | 19 ++++++++------ src/main/resources/log4j.properties | 17 ------------- .../app/cache/ActiveSprintsCacheTest.java | 18 ++++++------- .../tamu/app/cache/ProductStatsCacheTest.java | 4 +-- .../app/cache/RemoteProjectsCacheTest.java | 2 +- .../ActiveSprintsCacheControllerTest.java | 18 ++++++------- .../ProductsStatsCacheControllerTest.java | 4 +-- .../RemoteProjectsCacheControllerTest.java | 4 +-- .../edu/tamu/app/cache/model/CardTest.java | 18 ++++++------- .../edu/tamu/app/cache/model/MemberTest.java | 6 ++--- .../app/cache/model/ProductStatsTest.java | 4 +-- .../app/cache/model/RemoteProjectTest.java | 4 +-- .../edu/tamu/app/cache/model/SprintTest.java | 18 ++++++------- ...ctiveSprintsScheduledCacheServiceTest.java | 18 ++++++------- ...roductsStatsScheduledCacheServiceTest.java | 2 +- ...moteProjectsScheduledCacheServiceTest.java | 4 +-- .../InternalRequestControllerTest.java | 2 +- .../app/controller/ProductControllerTest.java | 4 +-- .../app/controller/StatusControllerTest.java | 4 +-- .../mapping/CardTypeMappingServiceTest.java | 2 +- .../app/mapping/StatusMappingServiceTest.java | 2 +- .../edu/tamu/app/model/ServiceTypeTest.java | 2 +- .../tamu/app/model/repo/CardTypeRepoTest.java | 4 +-- .../tamu/app/model/repo/StatusRepoTest.java | 4 +-- .../edu/tamu/app/model/repo/UserRepoTest.java | 10 ++++---- .../app/model/request/FeatureRequetTest.java | 12 ++++----- .../app/model/request/TicketRequetTest.java | 12 ++++----- .../app/rest/TokenAuthRestTemplateTest.java | 2 +- src/test/resources/application.yml | 25 ++++++++++++------- src/test/resources/log4j.properties | 17 ------------- src/test/resources/logback-test.xml | 11 ++++++++ 40 files changed, 143 insertions(+), 171 deletions(-) delete mode 100644 src/main/resources/log4j.properties delete mode 100644 src/test/resources/log4j.properties create mode 100644 src/test/resources/logback-test.xml 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/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/VersionOneService.java b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java index 003c59a1..e4316722 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; 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/ActiveSprintsCacheTest.java b/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java index 71bc43cd..f60e7a37 100644 --- a/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java @@ -43,18 +43,18 @@ public void testGetCache() { List sprints = cache.get(); assertFalse(sprints.isEmpty(), "Cached active sprints was empty!"); assertEquals(1, sprints.size(), "Cached active sprints had incorrect number of sprints!"); - assertEquals("1", sprints.get(0).getId(), "Cached active sprint had incorrect id!"); - assertEquals("Sprint 1", sprints.get(0).getName(), "Cached active sprint had incorrect name!"); - assertEquals("Application", sprints.get(0).getProduct(), "Cached active sprint had incorrect product!"); + assertEquals(sprints.get(0).getId(), "Cached active sprint had incorrect id!", "1"); + assertEquals(sprints.get(0).getName(), "Cached active sprint had incorrect name!", "Sprint 1"); + assertEquals(sprints.get(0).getProduct(), "Cached active sprint had incorrect product!", "Application"); 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/ProductStatsCacheTest.java b/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java index 6472bb4f..54092f28 100644 --- a/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java @@ -44,8 +44,8 @@ public void testGetCache() { assertFalse(remoteProductsCache.isEmpty(), "Cached products stats was empty!"); assertEquals(1, remoteProductsCache.size(), "Cached products stats had incorrect number of products status!"); - assertEquals("0001", remoteProductsCache.get(0).getId(), "Cached product stats had incorrect id!"); - assertEquals("Sprint 1", remoteProductsCache.get(0).getName(), "Cached product stats had incorrect name!"); + assertEquals(remoteProductsCache.get(0).getId(), "Cached product stats had incorrect id!", "0001"); + assertEquals(remoteProductsCache.get(0).getName(), "Cached product stats had incorrect name!", "Sprint 1"); assertEquals(2, remoteProductsCache.get(0).getRequestCount(), "Cached product stats had incorrect number of requests!"); assertEquals(3, remoteProductsCache.get(0).getIssueCount(), "Cached product stats had incorrect number of issues!"); assertEquals(10, remoteProductsCache.get(0).getFeatureCount(), "Cached product stats had incorrect number of features!"); diff --git a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java index 19f60168..a44c11d7 100644 --- a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java @@ -52,7 +52,7 @@ public void testGetCache() { 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("Sprint 1", remoteProductsCache.get(1L).get(0).getName(), "Cached remote project had incorrect name!"); + assertEquals(remoteProductsCache.get(1L).get(0).getName(), "Cached remote project had incorrect name!", "Sprint 1"); 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!"); assertEquals(10, remoteProductsCache.get(1L).get(0).getFeatureCount(), "Cached remote project had incorrect number of features!"); 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/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/InternalRequestControllerTest.java b/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java index 98b433ad..7b5e7aba 100644 --- a/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java @@ -276,7 +276,7 @@ public void testPushWhenRemoteProductManagerBeanFails() throws Exception { apiResponse = internalRequestController.push(TEST_REQUEST_BELLS.getId(), TEST_PRODUCT1.getId(), TEST_REMOTE_PROJECT_MANAGER.getId(), TEST_REMOTE_PROJECT_INFO1.getScopeId()); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Pushing Internal Request when Remote Project Management Bean push fails did not result in an error"); - assertEquals("Error pushing Internal Request to " + TEST_REMOTE_PROJECT_MANAGER.getName() + " for Product " + TEST_PRODUCT1_NAME + "!", apiResponse.getMeta().getMessage(), "Pushing Internal Request did not result in the expected error message"); + assertEquals(apiResponse.getMeta().getMessage(), "Pushing Internal Request did not result in the expected error message", "Error pushing Internal Request to " + TEST_REMOTE_PROJECT_MANAGER.getName() + " for Product " + TEST_PRODUCT1_NAME + "!"); } @Test diff --git a/src/test/java/edu/tamu/app/controller/ProductControllerTest.java b/src/test/java/edu/tamu/app/controller/ProductControllerTest.java index 23725905..d3b6c122 100644 --- a/src/test/java/edu/tamu/app/controller/ProductControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/ProductControllerTest.java @@ -248,7 +248,7 @@ public void testGetAllRemoteProductsForProductWithNoRemoteProductManager() { when(productRepo.findById(any(Long.class))).thenReturn(Optional.of(TEST_PRODUCT1)); apiResponse = productController.getAllRemoteProjectsForProduct(TEST_PRODUCT1.getId()); 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"); + assertEquals(apiResponse.getMeta().getMessage(), "Missing Remote Project Manager did not result in the expected error message", "Error fetching remote projects associated with product " + TEST_PRODUCT1.getName() + "!"); } @Test @@ -301,4 +301,4 @@ public void testGetRemoteProjectByScopeIdWithMissingRemoteProjectManager() { 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/StatusControllerTest.java b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java index dbc9c44f..eb253aa0 100644 --- a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java @@ -62,7 +62,7 @@ public void testRead() { public void testReadById() { ApiResponse apiResponse = statusController.read(noneStatus.getId()); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Request for status was unsuccessful"); - assertEquals("None", ((Status) apiResponse.getPayload().get("Status")).getIdentifier(), "Status read was incorrect"); + assertEquals(((Status) apiResponse.getPayload().get("Status")).getIdentifier(), "Status read was incorrect", "None"); } @Test @@ -83,4 +83,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/mapping/CardTypeMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java index 64ff4db4..7b69e115 100644 --- a/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java +++ b/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java @@ -40,7 +40,7 @@ public void testMap() { @Test public void testHandleUnmapped() { - assertEquals("Defect", cardTypeMappingService.handleUnmapped("Defect"), "Handled unmapped incorrectly!"); + assertEquals(cardTypeMappingService.handleUnmapped("Defect"), "Handled unmapped incorrectly!", "Defect"); } @AfterEach diff --git a/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java index 0393a8eb..03d571b2 100644 --- a/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java +++ b/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java @@ -40,7 +40,7 @@ public void testMap() { @Test public void testHandleUnmapped() { - assertEquals("In Progress", statusMappingService.handleUnmapped("In Progress"), "Handled unmapped incorrectly!"); + assertEquals(statusMappingService.handleUnmapped("In Progress"), "Handled unmapped incorrectly!", "In Progress"); } @AfterEach diff --git a/src/test/java/edu/tamu/app/model/ServiceTypeTest.java b/src/test/java/edu/tamu/app/model/ServiceTypeTest.java index 090d94b2..741a9012 100644 --- a/src/test/java/edu/tamu/app/model/ServiceTypeTest.java +++ b/src/test/java/edu/tamu/app/model/ServiceTypeTest.java @@ -22,7 +22,7 @@ public class ServiceTypeTest { @Test public void testGetGloss() { - assertEquals("Version One", type.getGloss(), "Gloss did not start out as 'Version One'"); + assertEquals(type.getGloss(), "Gloss did not start out as 'Version One'", "Version One"); } @Test 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..d768fbff 100644 --- a/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/CardTypeRepoTest.java @@ -77,7 +77,7 @@ public void testCreate() { CardType cardType = cardTypeRepo.create(newCardType("Feature", "Story", "Feature")); assertNotNull(cardType, "Unable to create card type!"); assertEquals(1, cardTypeRepo.count(), "Card type repo had incorrect number of card types!"); - assertEquals("Feature", cardType.getIdentifier(), "Card type had incorrect identifier!"); + assertEquals(cardType.getIdentifier(), "Card type had incorrect identifier!", "Feature"); assertEquals(2, cardType.getMapping().size(), "Card type had incorrect number of mappings!"); } @@ -95,7 +95,7 @@ public void testUpdate() { cardType.setIdentifier("Feature"); cardType.setMapping(new HashSet(Arrays.asList(new String[] { "Feature", "Story", "Task" }))); cardType = cardTypeRepo.update(cardType); - assertEquals("Feature", cardType.getIdentifier(), "Card type had incorrect identifier!"); + assertEquals(cardType.getIdentifier(), "Card type had incorrect identifier!", "Feature"); assertEquals(3, cardType.getMapping().size(), "Card type had incorrect number of mappings!"); } 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..b2809582 100644 --- a/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/StatusRepoTest.java @@ -77,7 +77,7 @@ public void testCreate() { Status status = statusRepo.create(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); assertNotNull(status, "Unable to create status!"); assertEquals(1, statusRepo.count(), "Status repo had incorrect number of statuses!"); - assertEquals("None", status.getIdentifier(), "Status had incorrect identifier!"); + assertEquals(status.getIdentifier(), "Status had incorrect identifier!", "None"); assertEquals(2, status.getMapping().size(), "Status had incorrect number of mappings!"); } @@ -95,7 +95,7 @@ public void testUpdate() { status.setIdentifier("None"); status.setMapping(new HashSet(Arrays.asList(new String[] { "None", "Future", "NA" }))); status = statusRepo.update(status); - assertEquals("None", status.getIdentifier(), "Status had incorrect identifier!"); + assertEquals(status.getIdentifier(), "Status had incorrect identifier!", "None"); assertEquals(3, status.getMapping().size(), "Status had incorrect number of mappings!"); } 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..21727c5f 100644 --- a/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java +++ b/src/test/java/edu/tamu/app/model/repo/UserRepoTest.java @@ -68,10 +68,10 @@ public void testUpdate() { user = userRepo.update(user); - assertEquals("123456781", user.getUsername(), "User had incorrect username!"); - assertEquals("jaggie@tamu.edu", user.getEmail(), "User had incorrect email!"); - assertEquals("John", user.getFirstName(), "User had incorrect first name!"); - assertEquals("Agriculture", user.getLastName(), "User had incorrect last name!"); + assertEquals(user.getUsername(), "User had incorrect username!", "123456781"); + assertEquals(user.getEmail(), "User had incorrect email!", "jaggie@tamu.edu"); + assertEquals(user.getFirstName(), "User had incorrect first name!", "John"); + assertEquals(user.getLastName(), "User had incorrect last name!", "Agriculture"); assertEquals(Role.valueOf("ROLE_MANAGER"), user.getRole(), "User had incorrect role!"); } @@ -107,7 +107,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/FeatureRequetTest.java b/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java index 4fcd1bef..48297043 100644 --- a/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java +++ b/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java @@ -14,24 +14,24 @@ public class FeatureRequetTest { public void testNewFeatureRequest() { FeatureRequest request = newFeatureRequest(); assertNotNull(request, "Could not instantiate feature request!"); - assertEquals("New Feature", request.getTitle(), "Feature request had incorrect title!"); - assertEquals("I would like to turn off service through API.", request.getDescription(), "Feature request had incorrect description!"); + assertEquals(request.getTitle(), "Feature request had incorrect title!", "New Feature"); + assertEquals(request.getDescription(), "Feature request had incorrect description!", "I would like to turn off service through API."); assertEquals(1L, request.getProductId(), 0, "Feature request had incorrect product id!"); - assertEquals("0001", request.getScopeId(), "Feature request had incorrect scope id!"); + assertEquals(request.getScopeId(), "Feature request had incorrect scope id!", "0001"); } @Test public void testSetTitle() { FeatureRequest request = newFeatureRequest(); request.setTitle("Fix It"); - assertEquals("Fix It", request.getTitle(), "Feature request did not set title!"); + assertEquals(request.getTitle(), "Feature request did not set title!", "Fix It"); } @Test public void testSetDescription() { FeatureRequest request = newFeatureRequest(); request.setDescription("It just doesn't work!"); - assertEquals("It just doesn't work!", request.getDescription(), "Feature request did not set description!"); + assertEquals(request.getDescription(), "Feature request did not set description!", "It just doesn't work!"); } @Test @@ -45,7 +45,7 @@ public void testSetProductId() { public void testSetScopeId() { FeatureRequest request = newFeatureRequest(); request.setScopeId("0002"); - assertEquals("0002", request.getScopeId(), "Feature request did not set scope id!"); + assertEquals(request.getScopeId(), "Feature request did not set scope id!", "0002"); } private FeatureRequest newFeatureRequest() { diff --git a/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java b/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java index 1096487d..1e3099c8 100644 --- a/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java +++ b/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java @@ -30,9 +30,9 @@ public void setup() throws JsonParseException, JsonMappingException, IOException public void testNewTicketRequest() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); assertNotNull(request, "Could not instantiate ticket request!"); - assertEquals("Is This Right", request.getTitle(), "Ticket request had incorrect title!"); - assertEquals("Does this work as expected!", request.getDescription(), "Ticket request had incorrect description!"); - assertEquals("Test Service 1", request.getService(), "Ticket request had incorrect service!"); + assertEquals(request.getTitle(), "Ticket request had incorrect title!", "Is This Right"); + assertEquals(request.getDescription(), "Ticket request had incorrect description!", "Does this work as expected!"); + assertEquals(request.getService(), "Ticket request had incorrect service!", "Test Service 1"); assertEquals(aggieJackCredenitals, request.getCredentials(), "Ticket request had incorrect credentials!"); } @@ -40,21 +40,21 @@ public void testNewTicketRequest() throws JsonParseException, JsonMappingExcepti public void testSetTitle() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setTitle("Is It Good"); - assertEquals("Is It Good", request.getTitle(), "Ticket request did not set title!"); + assertEquals(request.getTitle(), "Ticket request did not set title!", "Is It Good"); } @Test public void testSetDescription() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setDescription("It could be better."); - assertEquals("It could be better.", request.getDescription(), "Ticket request did not set description!"); + assertEquals(request.getDescription(), "Ticket request did not set description!", "It could be better."); } @Test public void testSetService() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setService("Test Service 2"); - assertEquals("Test Service 2", request.getService(), "Ticket request did not set service!"); + assertEquals(request.getService(), "Ticket request did not set service!", "Test Service 2"); } @Test diff --git a/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java b/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java index 84daccba..b06928b8 100644 --- a/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java +++ b/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java @@ -15,7 +15,7 @@ public class TokenAuthRestTemplateTest { public void testNewTokenAuthRestTemplate() { TokenAuthRestTemplate basicAuthRestTemplate = new TokenAuthRestTemplate("token"); assertNotNull(basicAuthRestTemplate, "Unable to create new basic auth rest template!"); - assertEquals("token", basicAuthRestTemplate.getToken(), "Token auth rest template did not have expected token!"); + assertEquals(basicAuthRestTemplate.getToken(), "Token auth rest template did not have expected token!", "token"); } @Test diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 22008419..51809c4b 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 # ############################# 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 @@ + + + + + + + + + + + From 44b873695ef7e5c0640a4b4e97bb8cea38302814 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 08:30:19 -0500 Subject: [PATCH 02/26] fix active sprints cache test assert argument order --- .../tamu/app/cache/ActiveSprintsCacheTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java b/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java index f60e7a37..71bc43cd 100644 --- a/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/ActiveSprintsCacheTest.java @@ -43,18 +43,18 @@ public void testGetCache() { List sprints = cache.get(); assertFalse(sprints.isEmpty(), "Cached active sprints was empty!"); assertEquals(1, sprints.size(), "Cached active sprints had incorrect number of sprints!"); - assertEquals(sprints.get(0).getId(), "Cached active sprint had incorrect id!", "1"); - assertEquals(sprints.get(0).getName(), "Cached active sprint had incorrect name!", "Sprint 1"); - assertEquals(sprints.get(0).getProduct(), "Cached active sprint had incorrect product!", "Application"); + assertEquals("1", sprints.get(0).getId(), "Cached active sprint had incorrect id!"); + assertEquals("Sprint 1", sprints.get(0).getName(), "Cached active sprint had incorrect name!"); + assertEquals("Application", sprints.get(0).getProduct(), "Cached active sprint had incorrect product!"); assertFalse(sprints.get(0).getCards().isEmpty()); assertEquals(1, sprints.get(0).getCards().size()); - 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", 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(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()); From a2c58a4faa7b459ccd83c950621198e03f22f196 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 08:36:13 -0500 Subject: [PATCH 03/26] fix product stats cache test assert argument order --- src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java b/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java index 54092f28..6472bb4f 100644 --- a/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/ProductStatsCacheTest.java @@ -44,8 +44,8 @@ public void testGetCache() { assertFalse(remoteProductsCache.isEmpty(), "Cached products stats was empty!"); assertEquals(1, remoteProductsCache.size(), "Cached products stats had incorrect number of products status!"); - assertEquals(remoteProductsCache.get(0).getId(), "Cached product stats had incorrect id!", "0001"); - assertEquals(remoteProductsCache.get(0).getName(), "Cached product stats had incorrect name!", "Sprint 1"); + assertEquals("0001", remoteProductsCache.get(0).getId(), "Cached product stats had incorrect id!"); + assertEquals("Sprint 1", remoteProductsCache.get(0).getName(), "Cached product stats had incorrect name!"); assertEquals(2, remoteProductsCache.get(0).getRequestCount(), "Cached product stats had incorrect number of requests!"); assertEquals(3, remoteProductsCache.get(0).getIssueCount(), "Cached product stats had incorrect number of issues!"); assertEquals(10, remoteProductsCache.get(0).getFeatureCount(), "Cached product stats had incorrect number of features!"); From 89e9e9784856c661fce9f39af07596ee014eed5c Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 08:38:55 -0500 Subject: [PATCH 04/26] fix remote projects cache test assert argument order --- src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java index a44c11d7..92fc10c3 100644 --- a/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java +++ b/src/test/java/edu/tamu/app/cache/RemoteProjectsCacheTest.java @@ -51,8 +51,8 @@ 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(remoteProductsCache.get(1L).get(0).getName(), "Cached remote project had incorrect name!", "Sprint 1"); + 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!"); assertEquals(10, remoteProductsCache.get(1L).get(0).getFeatureCount(), "Cached remote project had incorrect number of features!"); From e4104ac655054e71a57a8b8e9499498d8b2ea4bc Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 08:40:54 -0500 Subject: [PATCH 05/26] fix internal request controller test assert argument order --- .../edu/tamu/app/controller/InternalRequestControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java b/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java index 7b5e7aba..98b433ad 100644 --- a/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/InternalRequestControllerTest.java @@ -276,7 +276,7 @@ public void testPushWhenRemoteProductManagerBeanFails() throws Exception { apiResponse = internalRequestController.push(TEST_REQUEST_BELLS.getId(), TEST_PRODUCT1.getId(), TEST_REMOTE_PROJECT_MANAGER.getId(), TEST_REMOTE_PROJECT_INFO1.getScopeId()); assertEquals(ERROR, apiResponse.getMeta().getStatus(), "Pushing Internal Request when Remote Project Management Bean push fails did not result in an error"); - assertEquals(apiResponse.getMeta().getMessage(), "Pushing Internal Request did not result in the expected error message", "Error pushing Internal Request to " + TEST_REMOTE_PROJECT_MANAGER.getName() + " for Product " + TEST_PRODUCT1_NAME + "!"); + assertEquals("Error pushing Internal Request to " + TEST_REMOTE_PROJECT_MANAGER.getName() + " for Product " + TEST_PRODUCT1_NAME + "!", apiResponse.getMeta().getMessage(), "Pushing Internal Request did not result in the expected error message"); } @Test From ee6134dec3d6dd9efc1be094d2bae3bdc33749d0 Mon Sep 17 00:00:00 2001 From: Kevin Day Date: Tue, 2 Aug 2022 08:57:35 -0500 Subject: [PATCH 06/26] Update SugarServiceTest. --- .../service/ticketing/SugarServiceTest.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) 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!"); } From 28a41e3f848db624fd3e68864516e7ca68ac5c5e Mon Sep 17 00:00:00 2001 From: Kevin Day Date: Tue, 2 Aug 2022 10:34:13 -0500 Subject: [PATCH 07/26] Fix unit tests for VersonOneService and fix bug in VersonOneService exposed by fixed unit tests. There is an extra "1" being appended to nowhere when calling `restTemplate.exchange()` that is causes the tests to fail. This likely affects the GithubService as well and that service should also be reviewed. --- .../service/manager/VersionOneService.java | 44 +- .../manager/VersionOneServiceTest.java | 548 +++++------------- 2 files changed, 155 insertions(+), 437 deletions(-) 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 e4316722..291a6874 100644 --- a/src/main/java/edu/tamu/app/service/manager/VersionOneService.java +++ b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java @@ -238,35 +238,34 @@ 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)); - if (!avatarUrl.isPresent()) { - storeAvatar(avatarPath); - } + Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + 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; } @@ -324,7 +323,8 @@ private void storeAvatar(String avatarPath) throws IOException { 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/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java b/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java index 0776ef41..81fec740 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,22 @@ 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 +429,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 +446,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 +476,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 +523,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 +537,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 +620,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 +632,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 +672,7 @@ private Member getMockMemberById(String memberId) { } } } + return null; } From a1313e02488c6caaabff70756aa769108be7a3ba Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 10:56:58 -0500 Subject: [PATCH 08/26] fix product controller test --- .../app/controller/ProductControllerTest.java | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/src/test/java/edu/tamu/app/controller/ProductControllerTest.java b/src/test/java/edu/tamu/app/controller/ProductControllerTest.java index d3b6c122..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,18 +248,18 @@ 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(apiResponse.getMeta().getMessage(), "Missing Remote Project Manager did not result in the expected error message", "Error fetching remote projects associated with product " + TEST_PRODUCT1.getName() + "!"); + 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"); } @Test @@ -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,22 +292,22 @@ 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"); } From 882cc938d4221e17e811c8113235efbaa7b06008 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:06:54 -0500 Subject: [PATCH 09/26] fix remote project manager controller test --- .../tamu/app/controller/RemoteProjectManagerControllerTest.java | 2 ++ 1 file changed, 2 insertions(+) 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 From 84278c738ed878fbbda87c37b1236eb516820ab8 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:44:14 -0500 Subject: [PATCH 10/26] fix product controller integration test --- .../ProductControllerIntegrationTest.java | 58 +++++++++++++++---- 1 file changed, 46 insertions(+), 12 deletions(-) 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."), From e7b5c6dffdd87fda629becb6f5494bb1970fa45a Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:46:16 -0500 Subject: [PATCH 11/26] fix card type mapping service test assert argument order --- .../edu/tamu/app/mapping/CardTypeMappingServiceTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/CardTypeMappingServiceTest.java index 7b69e115..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,12 +32,12 @@ public void setup() { @Test public void testMap() { - assertEquals(cardTypeMappingService.map("Story"), "Feature"); + assertEquals("Feature", cardTypeMappingService.map("Story")); } @Test public void testHandleUnmapped() { - assertEquals(cardTypeMappingService.handleUnmapped("Defect"), "Handled unmapped incorrectly!", "Defect"); + assertEquals("Defect", cardTypeMappingService.handleUnmapped("Defect"), "Handled unmapped incorrectly!"); } @AfterEach From a95830df5e6e58e2527442fa613c271957174fff Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:47:09 -0500 Subject: [PATCH 12/26] fix status mapping service test assert argument order --- .../edu/tamu/app/mapping/StatusMappingServiceTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java b/src/test/java/edu/tamu/app/mapping/StatusMappingServiceTest.java index 03d571b2..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,12 +32,12 @@ public void setup() { @Test public void testMap() { - assertEquals(statusMappingService.map("Future"), "None"); + assertEquals("None", statusMappingService.map("Future")); } @Test public void testHandleUnmapped() { - assertEquals(statusMappingService.handleUnmapped("In Progress"), "Handled unmapped incorrectly!", "In Progress"); + assertEquals("In Progress", statusMappingService.handleUnmapped("In Progress"), "Handled unmapped incorrectly!"); } @AfterEach From f76b1afb3ad76bc37faef37354f30361200cf094 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:49:34 -0500 Subject: [PATCH 13/26] fix service type test assert argument order --- src/test/java/edu/tamu/app/model/ServiceTypeTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/edu/tamu/app/model/ServiceTypeTest.java b/src/test/java/edu/tamu/app/model/ServiceTypeTest.java index 741a9012..090d94b2 100644 --- a/src/test/java/edu/tamu/app/model/ServiceTypeTest.java +++ b/src/test/java/edu/tamu/app/model/ServiceTypeTest.java @@ -22,7 +22,7 @@ public class ServiceTypeTest { @Test public void testGetGloss() { - assertEquals(type.getGloss(), "Gloss did not start out as 'Version One'", "Version One"); + assertEquals("Version One", type.getGloss(), "Gloss did not start out as 'Version One'"); } @Test From cb3d1a9157fc7050cd61d408f21baff8818ef263 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:52:14 -0500 Subject: [PATCH 14/26] fix more test assert argument order --- .../edu/tamu/app/model/repo/CardTypeRepoTest.java | 7 ++----- .../java/edu/tamu/app/model/repo/StatusRepoTest.java | 7 ++----- .../java/edu/tamu/app/model/repo/UserRepoTest.java | 11 ++++------- 3 files changed, 8 insertions(+), 17 deletions(-) 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 d768fbff..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 { @@ -77,7 +74,7 @@ public void testCreate() { CardType cardType = cardTypeRepo.create(newCardType("Feature", "Story", "Feature")); assertNotNull(cardType, "Unable to create card type!"); assertEquals(1, cardTypeRepo.count(), "Card type repo had incorrect number of card types!"); - assertEquals(cardType.getIdentifier(), "Card type had incorrect identifier!", "Feature"); + assertEquals("Feature", cardType.getIdentifier(), "Card type had incorrect identifier!"); assertEquals(2, cardType.getMapping().size(), "Card type had incorrect number of mappings!"); } @@ -95,7 +92,7 @@ public void testUpdate() { cardType.setIdentifier("Feature"); cardType.setMapping(new HashSet(Arrays.asList(new String[] { "Feature", "Story", "Task" }))); cardType = cardTypeRepo.update(cardType); - assertEquals(cardType.getIdentifier(), "Card type had incorrect identifier!", "Feature"); + assertEquals("Feature", cardType.getIdentifier(), "Card type had incorrect identifier!"); assertEquals(3, cardType.getMapping().size(), "Card type had incorrect number of mappings!"); } 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 b2809582..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 { @@ -77,7 +74,7 @@ public void testCreate() { Status status = statusRepo.create(new Status("None", new HashSet(Arrays.asList(new String[] { "None", "Future" })))); assertNotNull(status, "Unable to create status!"); assertEquals(1, statusRepo.count(), "Status repo had incorrect number of statuses!"); - assertEquals(status.getIdentifier(), "Status had incorrect identifier!", "None"); + assertEquals("None", status.getIdentifier(), "Status had incorrect identifier!"); assertEquals(2, status.getMapping().size(), "Status had incorrect number of mappings!"); } @@ -95,7 +92,7 @@ public void testUpdate() { status.setIdentifier("None"); status.setMapping(new HashSet(Arrays.asList(new String[] { "None", "Future", "NA" }))); status = statusRepo.update(status); - assertEquals(status.getIdentifier(), "Status had incorrect identifier!", "None"); + assertEquals("None", status.getIdentifier(), "Status had incorrect identifier!"); assertEquals(3, status.getMapping().size(), "Status had incorrect number of mappings!"); } 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 21727c5f..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 { @@ -68,10 +65,10 @@ public void testUpdate() { user = userRepo.update(user); - assertEquals(user.getUsername(), "User had incorrect username!", "123456781"); - assertEquals(user.getEmail(), "User had incorrect email!", "jaggie@tamu.edu"); - assertEquals(user.getFirstName(), "User had incorrect first name!", "John"); - assertEquals(user.getLastName(), "User had incorrect last name!", "Agriculture"); + assertEquals("123456781", user.getUsername(), "User had incorrect username!"); + assertEquals("jaggie@tamu.edu", user.getEmail(), "User had incorrect email!"); + assertEquals("John", user.getFirstName(), "User had incorrect first name!"); + assertEquals("Agriculture", user.getLastName(), "User had incorrect last name!"); assertEquals(Role.valueOf("ROLE_MANAGER"), user.getRole(), "User had incorrect role!"); } From bb417a89a1e4e256eca86f4761d869b2144c60e6 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:55:14 -0500 Subject: [PATCH 15/26] fix even more test assert argument order --- .../tamu/app/model/request/FeatureRequetTest.java | 12 ++++++------ .../edu/tamu/app/model/request/TicketRequetTest.java | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java b/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java index 48297043..4fcd1bef 100644 --- a/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java +++ b/src/test/java/edu/tamu/app/model/request/FeatureRequetTest.java @@ -14,24 +14,24 @@ public class FeatureRequetTest { public void testNewFeatureRequest() { FeatureRequest request = newFeatureRequest(); assertNotNull(request, "Could not instantiate feature request!"); - assertEquals(request.getTitle(), "Feature request had incorrect title!", "New Feature"); - assertEquals(request.getDescription(), "Feature request had incorrect description!", "I would like to turn off service through API."); + assertEquals("New Feature", request.getTitle(), "Feature request had incorrect title!"); + assertEquals("I would like to turn off service through API.", request.getDescription(), "Feature request had incorrect description!"); assertEquals(1L, request.getProductId(), 0, "Feature request had incorrect product id!"); - assertEquals(request.getScopeId(), "Feature request had incorrect scope id!", "0001"); + assertEquals("0001", request.getScopeId(), "Feature request had incorrect scope id!"); } @Test public void testSetTitle() { FeatureRequest request = newFeatureRequest(); request.setTitle("Fix It"); - assertEquals(request.getTitle(), "Feature request did not set title!", "Fix It"); + assertEquals("Fix It", request.getTitle(), "Feature request did not set title!"); } @Test public void testSetDescription() { FeatureRequest request = newFeatureRequest(); request.setDescription("It just doesn't work!"); - assertEquals(request.getDescription(), "Feature request did not set description!", "It just doesn't work!"); + assertEquals("It just doesn't work!", request.getDescription(), "Feature request did not set description!"); } @Test @@ -45,7 +45,7 @@ public void testSetProductId() { public void testSetScopeId() { FeatureRequest request = newFeatureRequest(); request.setScopeId("0002"); - assertEquals(request.getScopeId(), "Feature request did not set scope id!", "0002"); + assertEquals("0002", request.getScopeId(), "Feature request did not set scope id!"); } private FeatureRequest newFeatureRequest() { diff --git a/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java b/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java index 1e3099c8..1096487d 100644 --- a/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java +++ b/src/test/java/edu/tamu/app/model/request/TicketRequetTest.java @@ -30,9 +30,9 @@ public void setup() throws JsonParseException, JsonMappingException, IOException public void testNewTicketRequest() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); assertNotNull(request, "Could not instantiate ticket request!"); - assertEquals(request.getTitle(), "Ticket request had incorrect title!", "Is This Right"); - assertEquals(request.getDescription(), "Ticket request had incorrect description!", "Does this work as expected!"); - assertEquals(request.getService(), "Ticket request had incorrect service!", "Test Service 1"); + assertEquals("Is This Right", request.getTitle(), "Ticket request had incorrect title!"); + assertEquals("Does this work as expected!", request.getDescription(), "Ticket request had incorrect description!"); + assertEquals("Test Service 1", request.getService(), "Ticket request had incorrect service!"); assertEquals(aggieJackCredenitals, request.getCredentials(), "Ticket request had incorrect credentials!"); } @@ -40,21 +40,21 @@ public void testNewTicketRequest() throws JsonParseException, JsonMappingExcepti public void testSetTitle() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setTitle("Is It Good"); - assertEquals(request.getTitle(), "Ticket request did not set title!", "Is It Good"); + assertEquals("Is It Good", request.getTitle(), "Ticket request did not set title!"); } @Test public void testSetDescription() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setDescription("It could be better."); - assertEquals(request.getDescription(), "Ticket request did not set description!", "It could be better."); + assertEquals("It could be better.", request.getDescription(), "Ticket request did not set description!"); } @Test public void testSetService() throws JsonParseException, JsonMappingException, IOException { TicketRequest request = createTicketRequest(); request.setService("Test Service 2"); - assertEquals(request.getService(), "Ticket request did not set service!", "Test Service 2"); + assertEquals("Test Service 2", request.getService(), "Ticket request did not set service!"); } @Test From e4fe31be3f268fdb21f5dea004919927d29c5a4a Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 11:55:47 -0500 Subject: [PATCH 16/26] fix last test assert argument order --- src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java b/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java index b06928b8..84daccba 100644 --- a/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java +++ b/src/test/java/edu/tamu/app/rest/TokenAuthRestTemplateTest.java @@ -15,7 +15,7 @@ public class TokenAuthRestTemplateTest { public void testNewTokenAuthRestTemplate() { TokenAuthRestTemplate basicAuthRestTemplate = new TokenAuthRestTemplate("token"); assertNotNull(basicAuthRestTemplate, "Unable to create new basic auth rest template!"); - assertEquals(basicAuthRestTemplate.getToken(), "Token auth rest template did not have expected token!", "token"); + assertEquals("token", basicAuthRestTemplate.getToken(), "Token auth rest template did not have expected token!"); } @Test From 913f2f87b363897a25e7a0c5db95aa43a71bd4bf Mon Sep 17 00:00:00 2001 From: Kevin Day Date: Tue, 2 Aug 2022 12:36:39 -0500 Subject: [PATCH 17/26] Update the versionone and github dependencies, fixing security issues. --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1e51999d..b6bf8c30 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 From 0f31056642932619066645b5d15c5ca077f6f58d Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 12:45:25 -0500 Subject: [PATCH 18/26] fix status controller test --- .../java/edu/tamu/app/controller/StatusController.java | 2 +- .../java/edu/tamu/app/controller/StatusControllerTest.java | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/edu/tamu/app/controller/StatusController.java b/src/main/java/edu/tamu/app/controller/StatusController.java index e90c8db2..c48e67ef 100644 --- a/src/main/java/edu/tamu/app/controller/StatusController.java +++ b/src/main/java/edu/tamu/app/controller/StatusController.java @@ -37,7 +37,7 @@ public ApiResponse read() { @GetMapping("/{id}") @PreAuthorize("hasRole('ANONYMOUS')") public ApiResponse read(@PathVariable Long id) { - return new ApiResponse(SUCCESS, statusRepo.findById(id)); + return new ApiResponse(SUCCESS, statusRepo.getById(id)); } @PostMapping diff --git a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java index eb253aa0..32968fef 100644 --- a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; -import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -42,10 +41,12 @@ 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); - when(statusRepo.findById(any(Long.class))).thenReturn(Optional.of(noneStatus)); + when(statusRepo.getById(any(Long.class))).thenReturn(noneStatus); doNothing().when(statusRepo).delete(any(Status.class)); } @@ -62,7 +63,7 @@ public void testRead() { public void testReadById() { ApiResponse apiResponse = statusController.read(noneStatus.getId()); assertEquals(SUCCESS, apiResponse.getMeta().getStatus(), "Request for status was unsuccessful"); - assertEquals(((Status) apiResponse.getPayload().get("Status")).getIdentifier(), "Status read was incorrect", "None"); + assertEquals("None", ((Status) apiResponse.getPayload().get("Status")).getIdentifier(), "Status read was incorrect"); } @Test From 770e06f180512469ab6c562ca270859905df64ea Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 12:51:36 -0500 Subject: [PATCH 19/26] fix products stats cache controller integration tests --- .../ProductsStatsCacheControllerIntegrationTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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."), From 5e3e48d5e879c42a01049de07115c643ce51506a Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 12:53:10 -0500 Subject: [PATCH 20/26] fix remote projects stats cache controller integration test --- .../RemoteProjectsStatsCacheControllerIntegrationTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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."), From 36eddb2821889eaf9370eede2631e25d7e44a55c Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 13:07:49 -0500 Subject: [PATCH 21/26] fix status controller and tests --- .../edu/tamu/app/controller/StatusController.java | 10 +++++++++- .../edu/tamu/app/controller/StatusControllerTest.java | 3 ++- .../integration/StatusControllerIntegrationTest.java | 11 ++++++----- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/main/java/edu/tamu/app/controller/StatusController.java b/src/main/java/edu/tamu/app/controller/StatusController.java index c48e67ef..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.getById(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/test/java/edu/tamu/app/controller/StatusControllerTest.java b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java index 32968fef..ff7f8de5 100644 --- a/src/test/java/edu/tamu/app/controller/StatusControllerTest.java +++ b/src/test/java/edu/tamu/app/controller/StatusControllerTest.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -46,7 +47,7 @@ public void setup() { 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); - when(statusRepo.getById(any(Long.class))).thenReturn(noneStatus); + when(statusRepo.findById(any(Long.class))).thenReturn(Optional.of(noneStatus)); doNothing().when(statusRepo).delete(any(Status.class)); } 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.") ) ) ); From 0571ad0d807fbd8c6bef575af922457be353489e Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 13:10:00 -0500 Subject: [PATCH 22/26] fix remote project manager repo test --- .../tamu/app/model/repo/RemoteProjectManagerRepoTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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); From a6590a1925c5f4b8e8aacea52fbfea8e7f83e7fb Mon Sep 17 00:00:00 2001 From: Kevin Day Date: Tue, 2 Aug 2022 13:58:51 -0500 Subject: [PATCH 23/26] Fix unit tests for both Github Services and fix bug in AbstractGitHubService exposed by fixed unit tests. There is an extra "1" being appended to nowhere when calling `restTemplate.exchange()` that is causes the tests to fail. --- .../manager/AbstractGitHubService.java | 34 ++-- .../manager/GitHubMilestoneService.java | 15 +- .../service/manager/GitHubProjectService.java | 14 +- .../service/manager/VersionOneService.java | 7 +- .../manager/GitHubMilestoneServiceTest.java | 160 ++++++++++-------- .../manager/GitHubProjectServiceTest.java | 160 ++++++++++-------- .../manager/VersionOneServiceTest.java | 15 +- 7 files changed, 233 insertions(+), 172 deletions(-) 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..110d3c29 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.isEmpty()) { + 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..be77fc1c 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); } @@ -46,7 +48,6 @@ public List getAdditionalActiveSprints() throws Exception { } 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, 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..e3fa1f65 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); } 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 291a6874..b14864a7 100644 --- a/src/main/java/edu/tamu/app/service/manager/VersionOneService.java +++ b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java @@ -238,7 +238,6 @@ public List getActiveSprintsCards(final String timeboxId) throws Connectio } public Member getMember(final String id) throws ConnectionException, APIException, OidException, IOException { - Optional cachedMember = getCachedMember(id); if (cachedMember.isPresent()) { return cachedMember.get(); @@ -257,9 +256,9 @@ public Member getMember(final String id) throws ConnectionException, APIExceptio 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)); - if (!avatarUrl.isPresent()) { + + if (avatarUrl.isEmpty()) { storeAvatar(avatarPath); } @@ -321,7 +320,9 @@ 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); String url = getUrl() + "/image.img/" + avatarPath; ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class); 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..35836b15 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java @@ -1,18 +1,36 @@ 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.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; +import edu.tamu.app.cache.model.Member; +import edu.tamu.app.cache.model.RemoteProject; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.mapping.CardTypeMappingService; +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; +import edu.tamu.app.model.Status; +import edu.tamu.app.model.repo.CardTypeRepo; +import edu.tamu.app.model.repo.EstimateRepo; +import edu.tamu.app.model.repo.StatusRepo; +import edu.tamu.app.model.request.FeatureRequest; import java.io.IOException; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -22,7 +40,6 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -40,10 +57,14 @@ import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; +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.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; @@ -51,25 +72,10 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import edu.tamu.app.cache.model.Member; -import edu.tamu.app.cache.model.RemoteProject; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.mapping.CardTypeMappingService; -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; -import edu.tamu.app.model.Status; -import edu.tamu.app.model.repo.CardTypeRepo; -import edu.tamu.app.model.repo.EstimateRepo; -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"; @@ -133,9 +139,6 @@ public class GitHubMilestoneServiceTest extends CacheMockTests { 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( @@ -177,40 +180,39 @@ public class GitHubMilestoneServiceTest extends CacheMockTests { 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; + @Value("classpath:images/no_avatar.png") + private Resource mockImage; - private GitHub github; - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + @Mock + private CardTypeRepo cardTypeRepo; + @Mock + private StatusRepo statusRepo; - CardTypeRepo cardTypeRepo = mock(CardTypeRepo.class); - StatusRepo statusRepo = mock(StatusRepo.class); - EstimateRepo estimateRepo = mock(EstimateRepo.class); + @Mock + private EstimateRepo estimateRepo; - CardTypeMappingService cardTypeMappingService = mock(CardTypeMappingService.class, Mockito.CALLS_REAL_METHODS); - - StatusMappingService statusMappingService = mock(StatusMappingService.class, Mockito.CALLS_REAL_METHODS); + @Mock + private GitHubBuilder ghBuilder; - EstimateMappingService estimateMappingService = mock(EstimateMappingService.class, Mockito.CALLS_REAL_METHODS); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private GitHubMilestoneService gitHubMilestoneService; - ghBuilder = mock(GitHubBuilder.class); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private CardTypeMappingService cardTypeMappingService; - gitHubMilestoneService = mock(GitHubMilestoneService.class, Mockito.CALLS_REAL_METHODS); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private StatusMappingService statusMappingService; - github = mock(GitHub.class); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private EstimateMappingService estimateMappingService; - when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.build()).thenReturn(github); + @Mock + private GitHub github; - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + @BeforeEach + public void setUp() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); when(TEST_ORGANIZATION.getRepositories()).thenReturn(TEST_REPOSITORY_MAP); when(TEST_ORGANIZATION.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); @@ -293,17 +295,16 @@ public void setUp() throws Exception { when(TEST_FEATURE_REQUEST.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); when(TEST_FEATURE_REQUEST.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); - when(restTemplate.exchange( - any(String.class), - any(HttpMethod.class), - Mockito.>any(), - Mockito.>any(), - Mockito.anyCollection())) - .thenReturn(response); - - when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); + 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(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 +323,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,15 +351,15 @@ 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" })))); + lenient().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); @@ -379,6 +377,8 @@ public Optional answer(InvocationOnMock invocation) { @Test public void testGetRemoteProjects() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + 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 +389,8 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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 +402,24 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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(TEST_ORGANIZATION); + 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(TEST_REPOSITORY1); + List sprints = gitHubMilestoneService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); sprints.forEach(sprint -> { @@ -421,6 +429,8 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { @Test public void testGetAdditionalActiveSprintsType() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + List sprints = gitHubMilestoneService.getAdditionalActiveSprints(); sprints.forEach(sprint -> { @@ -430,6 +440,8 @@ public void testGetAdditionalActiveSprintsType() throws Exception { @Test public void testPush() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + String id = gitHubMilestoneService.push(TEST_FEATURE_REQUEST); assertNotNull(id); } @@ -444,6 +456,10 @@ public void testGetMember() throws IOException { @Test public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException { + 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_PROJECT_URL1, TEST_PROJECT_TOKEN1); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -457,6 +473,10 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException @Test public void testGetGitHubInstanceWithInvalidToken() throws IOException { + 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_PROJECT_URL1, TEST_PROJECT_TOKEN1); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -470,13 +490,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(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); when(TEST_CARD1.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..1a5fd7cc 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java @@ -1,18 +1,36 @@ 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.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; +import edu.tamu.app.cache.model.Member; +import edu.tamu.app.cache.model.RemoteProject; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.mapping.CardTypeMappingService; +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; +import edu.tamu.app.model.Status; +import edu.tamu.app.model.repo.CardTypeRepo; +import edu.tamu.app.model.repo.EstimateRepo; +import edu.tamu.app.model.repo.StatusRepo; +import edu.tamu.app.model.request.FeatureRequest; import java.io.IOException; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -22,7 +40,6 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -38,9 +55,13 @@ import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; -import org.mockito.Mockito; +import org.mockito.Answers; +import org.mockito.Mock; 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; @@ -48,25 +69,10 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import edu.tamu.app.cache.model.Member; -import edu.tamu.app.cache.model.RemoteProject; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.mapping.CardTypeMappingService; -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; -import edu.tamu.app.model.Status; -import edu.tamu.app.model.repo.CardTypeRepo; -import edu.tamu.app.model.repo.EstimateRepo; -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"; @@ -127,9 +133,6 @@ public class GitHubProjectServiceTest extends CacheMockTests { 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( @@ -171,39 +174,39 @@ public class GitHubProjectServiceTest extends CacheMockTests { 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; + @Value("classpath:images/no_avatar.png") + private Resource mockImage; - private GitHub github; - - @BeforeEach - public void setUp() throws Exception { - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + @Mock + private CardTypeRepo cardTypeRepo; + @Mock + private StatusRepo statusRepo; - CardTypeRepo cardTypeRepo = mock(CardTypeRepo.class); - StatusRepo statusRepo = mock(StatusRepo.class); - EstimateRepo estimateRepo = mock(EstimateRepo.class); + @Mock + private EstimateRepo estimateRepo; - CardTypeMappingService cardTypeMappingService = mock(CardTypeMappingService.class, Mockito.CALLS_REAL_METHODS); - - StatusMappingService statusMappingService = mock(StatusMappingService.class, Mockito.CALLS_REAL_METHODS); + @Mock + private GitHubBuilder ghBuilder; - EstimateMappingService estimateMappingService = mock(EstimateMappingService.class, Mockito.CALLS_REAL_METHODS); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private GitHubProjectService gitHubProjectService; - ghBuilder = mock(GitHubBuilder.class); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private CardTypeMappingService cardTypeMappingService; - gitHubProjectService = mock(GitHubProjectService.class, Mockito.CALLS_REAL_METHODS); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private StatusMappingService statusMappingService; - github = mock(GitHub.class); + @Mock(answer = Answers.CALLS_REAL_METHODS) + private EstimateMappingService estimateMappingService; - when(ghBuilder.withEndpoint(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); - when(ghBuilder.build()).thenReturn(github); + @Mock + private GitHub github; - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + @BeforeEach + public void setUp() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); when(TEST_ORGANIZATION.getRepositories()).thenReturn(TEST_REPOSITORY_MAP); when(TEST_ORGANIZATION.listProjects(any(ProjectStateFilter.class)).asList()).thenReturn(TEST_PROJECTS); @@ -249,7 +252,6 @@ public void setUp() throws Exception { 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); @@ -278,17 +280,16 @@ public void setUp() throws Exception { when(TEST_FEATURE_REQUEST.getTitle()).thenReturn(TEST_FEATURE_REQUEST_TITLE); when(TEST_FEATURE_REQUEST.getDescription()).thenReturn(TEST_FEATURE_REQUEST_DESCRIPTION); - when(restTemplate.exchange( - any(String.class), - any(HttpMethod.class), - Mockito.>any(), - Mockito.>any(), - Mockito.anyCollection())) - .thenReturn(response); - - when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); + 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(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 +308,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,15 +336,15 @@ 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" })))); + lenient().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); @@ -364,6 +362,8 @@ public Optional answer(InvocationOnMock invocation) { @Test public void testGetRemoteProjects() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + 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 +374,8 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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 +387,24 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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(TEST_ORGANIZATION); + 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(TEST_REPOSITORY1); + List sprints = gitHubProjectService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); sprints.forEach(sprint -> { @@ -406,6 +414,8 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { @Test public void testGetAdditionalActiveSprintType() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + List sprints = gitHubProjectService.getAdditionalActiveSprints(); sprints.forEach(sprint -> { @@ -415,6 +425,8 @@ public void testGetAdditionalActiveSprintType() throws Exception { @Test public void testPush() throws Exception { + when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + String id = gitHubProjectService.push(TEST_FEATURE_REQUEST); assertNotNull(id); } @@ -429,6 +441,10 @@ public void testGetMember() throws IOException { @Test public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException { + 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_PROJECT_URL1, TEST_PROJECT_TOKEN1); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -442,6 +458,10 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException @Test public void testGetGitHubInstanceWithInvalidToken() throws IOException { + 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_PROJECT_URL1, TEST_PROJECT_TOKEN1); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -455,13 +475,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(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); when(TEST_CARD1.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 81fec740..54c5f9df 100644 --- a/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/VersionOneServiceTest.java @@ -392,13 +392,14 @@ public void testGetMemberWithAvatarImage() throws JsonParseException, JsonMappin Member mockMember = getMockMemberById("0003"); Asset[] assets = getMockMemberAsset(mockMember, true); - 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(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"); From d8c7f8a645bacc40396322c17d1f42cbaadbbfa3 Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 14:02:22 -0500 Subject: [PATCH 24/26] use optional isPresent to maintain java 8 compatibility --- .../edu/tamu/app/service/manager/AbstractGitHubService.java | 2 +- .../java/edu/tamu/app/service/manager/VersionOneService.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 110d3c29..74ced261 100644 --- a/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java +++ b/src/main/java/edu/tamu/app/service/manager/AbstractGitHubService.java @@ -142,7 +142,7 @@ Member getMember(final GHUser user) throws IOException { final Member member = new Member(memberId, name, avatarPath); final Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); - if (avatarUrl.isEmpty()) { + if (!avatarUrl.isPresent()) { storeAvatar(avatarUrlString); } 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 b14864a7..3e18271d 100644 --- a/src/main/java/edu/tamu/app/service/manager/VersionOneService.java +++ b/src/main/java/edu/tamu/app/service/manager/VersionOneService.java @@ -258,7 +258,7 @@ public Member getMember(final String id) throws ConnectionException, APIExceptio String avatarPath = parseAvatarUrlPath((Oid) asset.getAttribute(avatarAttributeDefinition).getValue()); Optional avatarUrl = Optional.ofNullable(getClass().getResource("/images/" + avatarPath)); - if (avatarUrl.isEmpty()) { + if (!avatarUrl.isPresent()) { storeAvatar(avatarPath); } From 518f25c840cb3df2148f2e26331e7a117ba2ec0c Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Tue, 2 Aug 2022 14:12:35 -0500 Subject: [PATCH 25/26] remove unnecessary annotation --- src/test/java/edu/tamu/app/model/ProductTest.java | 3 --- 1 file changed, 3 deletions(-) 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 { From 08d074a3a1bdd0e1d61796b0684276766c70167c Mon Sep 17 00:00:00 2001 From: William Welling <8352733+wwelling@users.noreply.github.com> Date: Wed, 3 Aug 2022 13:41:57 -0500 Subject: [PATCH 26/26] Fix github service tests (#155) * Testing... * Another test... * Shouldn't really change anything should it? * Trying newer mockito. * Try without deepmock * Remove all deep stubs * Add back limited deep stubs. * Without spring extension. * fix github service tests * instantiate test collections after stubbing * downgrade github-api * increment github-api version * reorder setup again * minor reorder of test properties * replace deep stubs with more mocks * remove redundant extensions * use long primitive for mock value * try doReturn stubbing * doReturn long primitive * remove unused import * add byte buddy dependency back * use string value of for repository get id stubbing * try not using a constant * reinitialize ids before each * revert some changes * trye surefire configuration parallel none * disable fork reuse of maven surefire plugin * Explicitly set default settings. * try with return value * try reflection for repository id * Add some debugging data * revert changes * fix inconsistencies * downgrade github-api * add paged iterable import back * remove debug lines * upgrade github-api version again * use latest bytebuddy dependencies * use latest mockito * try doReturn for getId * return string for id * try thenAnswer * thenAnswer Long for getId * try reflection and call real method * try extraInterfaces * try stubOnly * trry init bytebuddy agent * comment out and disable untestable code * try reflection on ghobject * move getId call real method to test * add polymorphic method to avoid GHObject getId stubbing issue * init mocks before each * try without extension * try waiting a long while * wait a second before each * reorder stubbing * mock properties once * stub once * cleanup * reorder stubbing * replace GHObject removing WithBridgeMethods annotation from getId * add findbugs annotation dependency * replace deprecated asList * use mockito extension and annotation * move GHObject to tests and cleanup pom Co-authored-by: Kevin Day --- pom.xml | 53 +- .../manager/GitHubMilestoneService.java | 8 +- .../service/manager/GitHubProjectService.java | 8 +- ...SprintsCacheControllerIntegrationTest.java | 3 - ...ernalRequestControllerIntegrationTest.java | 9 +- ...ojectManagerControllerIntegrationTest.java | 5 +- .../mapping/EstimateMappingServiceTest.java | 3 - .../tamu/app/model/repo/EstimateRepoTest.java | 3 - .../model/repo/InternalRequestRepoTest.java | 3 - .../tamu/app/model/repo/ProductRepoTest.java | 5 +- .../app/model/request/AbstractRequetTest.java | 1 - .../manager/GitHubMilestoneServiceTest.java | 478 +++++++++--------- .../manager/GitHubProjectServiceTest.java | 466 ++++++++--------- .../java/org/kohsuke/github/GHObject.java | 188 +++++++ src/test/resources/application.yml | 22 + 15 files changed, 724 insertions(+), 531 deletions(-) create mode 100644 src/test/java/org/kohsuke/github/GHObject.java diff --git a/pom.xml b/pom.xml index b6bf8c30..06957e24 100644 --- a/pom.xml +++ b/pom.xml @@ -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/service/manager/GitHubMilestoneService.java b/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java index be77fc1c..beea20f7 100644 --- a/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java +++ b/src/main/java/edu/tamu/app/service/manager/GitHubMilestoneService.java @@ -34,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()); } @@ -42,7 +42,7 @@ 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()); } @@ -55,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 e3fa1f65..53b60953 100644 --- a/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java +++ b/src/main/java/edu/tamu/app/service/manager/GitHubProjectService.java @@ -28,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()); @@ -37,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()); @@ -58,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/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/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/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/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/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/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 35836b15..101c5ab2 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubMilestoneServiceTest.java @@ -6,31 +6,12 @@ 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.lenient; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; -import edu.tamu.app.cache.model.Member; -import edu.tamu.app.cache.model.RemoteProject; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.mapping.CardTypeMappingService; -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; -import edu.tamu.app.model.Status; -import edu.tamu.app.model.repo.CardTypeRepo; -import edu.tamu.app.model.repo.EstimateRepo; -import edu.tamu.app.model.repo.StatusRepo; -import edu.tamu.app.model.request.FeatureRequest; import java.io.IOException; -import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -40,10 +21,12 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; + import org.junit.jupiter.api.BeforeEach; 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; @@ -57,22 +40,36 @@ 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.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 org.springframework.web.client.RestTemplate; -@ExtendWith(SpringExtension.class) +import edu.tamu.app.cache.model.Member; +import edu.tamu.app.cache.model.RemoteProject; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.mapping.CardTypeMappingService; +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; +import edu.tamu.app.model.Status; +import edu.tamu.app.model.repo.CardTypeRepo; +import edu.tamu.app.model.repo.EstimateRepo; +import edu.tamu.app.model.repo.StatusRepo; +import edu.tamu.app.model.request.FeatureRequest; + @ExtendWith(MockitoExtension.class) public class GitHubMilestoneServiceTest extends CacheMockTests { @@ -92,217 +89,211 @@ 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 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; - 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); - - 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])); - - @Value("classpath:images/no_avatar.png") - private Resource mockImage; - - @Mock - private CardTypeRepo cardTypeRepo; - - @Mock - private StatusRepo statusRepo; + @BeforeEach + public void setup() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); - @Mock - private EstimateRepo estimateRepo; + 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])); - @Mock - private GitHubBuilder ghBuilder; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private GitHubMilestoneService gitHubMilestoneService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private CardTypeMappingService cardTypeMappingService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private StatusMappingService statusMappingService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private EstimateMappingService estimateMappingService; + setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); + setField(statusMappingService, "serviceMappingRepo", statusRepo); + setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - @Mock - private GitHub 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); - @BeforeEach - public void setUp() throws Exception { - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); - - 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(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); - } - }); + 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())) + .thenReturn(response); + + lenient().when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); lenient().when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override @@ -360,24 +351,11 @@ public Optional answer(InvocationOnMock invocation) { lenient().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); } @Test public void testGetRemoteProjects() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List remoteProjects = gitHubMilestoneService.getRemoteProject(); assertEquals(2, remoteProjects.size(), "Didn't get all the remote projects"); @@ -389,7 +367,7 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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"); @@ -402,7 +380,7 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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"); @@ -410,7 +388,7 @@ public void testGetActiveSprintsByProjectId() throws Exception { @Test public void testGetAdditionalActiveSprints() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List additionalSprints = gitHubMilestoneService.getAdditionalActiveSprints(); assertEquals(3, additionalSprints.size(), "Didn't get all additional sprints"); @@ -418,7 +396,7 @@ public void testGetAdditionalActiveSprints() throws Exception { @Test public void testGetActiveSprintsByProjectIdType() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); List sprints = gitHubMilestoneService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); @@ -429,7 +407,7 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { @Test public void testGetAdditionalActiveSprintsType() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List sprints = gitHubMilestoneService.getAdditionalActiveSprints(); @@ -440,15 +418,15 @@ public void testGetAdditionalActiveSprintsType() throws Exception { @Test public void testPush() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); - String id = gitHubMilestoneService.push(TEST_FEATURE_REQUEST); + 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"); @@ -460,7 +438,7 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); when(ghBuilder.build()).thenReturn(github); - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -477,7 +455,7 @@ public void testGetGitHubInstanceWithInvalidToken() throws IOException { when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); when(ghBuilder.build()).thenReturn(github); - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubMilestoneService, "managementService", invalidManagementService); @@ -500,8 +478,8 @@ public void testGetGitHubInstanceByToken() throws IOException { @Test public void testGetCardsWithNote() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - 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 1a5fd7cc..da515fcc 100644 --- a/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java +++ b/src/test/java/edu/tamu/app/service/manager/GitHubProjectServiceTest.java @@ -6,31 +6,12 @@ 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.lenient; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.util.ReflectionTestUtils.setField; -import edu.tamu.app.cache.model.Member; -import edu.tamu.app.cache.model.RemoteProject; -import edu.tamu.app.cache.model.Sprint; -import edu.tamu.app.mapping.CardTypeMappingService; -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; -import edu.tamu.app.model.Status; -import edu.tamu.app.model.repo.CardTypeRepo; -import edu.tamu.app.model.repo.EstimateRepo; -import edu.tamu.app.model.repo.StatusRepo; -import edu.tamu.app.model.request.FeatureRequest; import java.io.IOException; -import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -40,12 +21,15 @@ import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; + import org.junit.jupiter.api.BeforeEach; 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; @@ -55,21 +39,36 @@ 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.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 org.springframework.web.client.RestTemplate; -@ExtendWith(SpringExtension.class) +import edu.tamu.app.cache.model.Member; +import edu.tamu.app.cache.model.RemoteProject; +import edu.tamu.app.cache.model.Sprint; +import edu.tamu.app.mapping.CardTypeMappingService; +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; +import edu.tamu.app.model.Status; +import edu.tamu.app.model.repo.CardTypeRepo; +import edu.tamu.app.model.repo.EstimateRepo; +import edu.tamu.app.model.repo.StatusRepo; +import edu.tamu.app.model.request.FeatureRequest; + @ExtendWith(MockitoExtension.class) public class GitHubProjectServiceTest extends CacheMockTests { @@ -84,210 +83,204 @@ 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 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; - 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); - - 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])); - - @Value("classpath:images/no_avatar.png") - private Resource mockImage; - - @Mock - private CardTypeRepo cardTypeRepo; - - @Mock - private StatusRepo statusRepo; + @BeforeEach + public void setup() throws Exception { + ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_MILESTONE, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); - @Mock - private EstimateRepo estimateRepo; + 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])); - @Mock - private GitHubBuilder ghBuilder; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private GitHubProjectService gitHubProjectService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private CardTypeMappingService cardTypeMappingService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private StatusMappingService statusMappingService; + 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 })); - @Mock(answer = Answers.CALLS_REAL_METHODS) - private EstimateMappingService estimateMappingService; + setField(cardTypeMappingService, "serviceMappingRepo", cardTypeRepo); + setField(statusMappingService, "serviceMappingRepo", statusRepo); + setField(estimateMappingService, "serviceMappingRepo", estimateRepo); - @Mock - private GitHub 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); - @BeforeEach - public void setUp() throws Exception { - ManagementService managementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); - - 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(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); - } - }); + 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())) + .thenReturn(response); + + lenient().when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND); lenient().when(cardTypeRepo.findByMapping(any(String.class))).thenAnswer(new Answer>() { @Override @@ -345,24 +338,11 @@ public Optional answer(InvocationOnMock invocation) { lenient().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); } @Test public void testGetRemoteProjects() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List remoteProjects = gitHubProjectService.getRemoteProject(); assertEquals(2, remoteProjects.size(), "Didn't get all the remote projects"); @@ -374,7 +354,7 @@ public void testGetRemoteProjects() throws Exception { @Test public void testGetRemoteProjectByScopeId() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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"); @@ -387,7 +367,7 @@ public void testGetRemoteProjectByScopeId() throws Exception { @Test public void testGetActiveSprintsByProjectId() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + 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"); @@ -395,7 +375,7 @@ public void testGetActiveSprintsByProjectId() throws Exception { @Test public void testGetAdditionalActiveSprints() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List additionalSprints = gitHubProjectService.getAdditionalActiveSprints(); assertEquals(3, additionalSprints.size(), "Didn't get all additional sprints"); @@ -403,7 +383,7 @@ public void testGetAdditionalActiveSprints() throws Exception { @Test public void testGetActiveSprintsByProjectIdType() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); List sprints = gitHubProjectService.getActiveSprintsByScopeId(String.valueOf(TEST_REPOSITORY1_ID)); @@ -413,8 +393,8 @@ public void testGetActiveSprintsByProjectIdType() throws Exception { } @Test - public void testGetAdditionalActiveSprintType() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); + public void testGetAdditionalActiveSprintsType() throws Exception { + when(github.getOrganization(any(String.class))).thenReturn(testOrganization); List sprints = gitHubProjectService.getAdditionalActiveSprints(); @@ -425,15 +405,15 @@ public void testGetAdditionalActiveSprintType() throws Exception { @Test public void testPush() throws Exception { - when(github.getRepositoryById(any(String.class))).thenReturn(TEST_REPOSITORY1); + when(github.getRepositoryById(any(String.class))).thenReturn(testRepository1); - String id = gitHubProjectService.push(TEST_FEATURE_REQUEST); + 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"); @@ -445,7 +425,7 @@ public void testGetGitHubInstanceWithInvalidServiceEndpoint() throws IOException when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); when(ghBuilder.build()).thenReturn(github); - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -462,7 +442,7 @@ public void testGetGitHubInstanceWithInvalidToken() throws IOException { when(ghBuilder.withOAuthToken(any(String.class))).thenReturn(ghBuilder); when(ghBuilder.build()).thenReturn(github); - ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT_URL1, TEST_PROJECT_TOKEN1); + ManagementService invalidManagementService = new RemoteProjectManager("GitHub", ServiceType.GITHUB_PROJECT, TEST_PROJECT1_URL, TEST_PROJECT1_TOKEN); setField(gitHubProjectService, "managementService", invalidManagementService); @@ -485,8 +465,8 @@ public void testGetGitHubInstanceByToken() throws IOException { @Test public void testGetCardsWithNote() throws Exception { - when(github.getOrganization(any(String.class))).thenReturn(TEST_ORGANIZATION); - 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/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 51809c4b..7a33956f 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -131,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