From 86c5e8123e4f418f08aca2f9b7e94ecf264f1d94 Mon Sep 17 00:00:00 2001 From: zeliu Date: Thu, 7 Mar 2019 10:22:08 -0700 Subject: [PATCH 01/44] Here is the JSP file for hoempage --- ...damonium-theorem-prover.main.kotlin_module | Bin 16 -> 0 bytes src/main/webapp/index.jsp | 20 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) delete mode 100644 out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module diff --git a/out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module b/out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module deleted file mode 100644 index 8fb60192d378759239a3ecbf60eac8c8de446e9c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16 RcmZQzU|?ooU|@t|UH|}6022TJ diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp index f8d618c..0efda13 100644 --- a/src/main/webapp/index.jsp +++ b/src/main/webapp/index.jsp @@ -5,12 +5,18 @@ Time: 8:03 PM To change this template use File | Settings | File Templates. --%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> - - $Title$ - - - $END$ - + + Test page + + + +

Test stuffs

+test hyperlink +
+ +
+ + From ba37ffeb5793efd6be3f2aa0a869e5e27c5e5cb2 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 15:55:43 -0600 Subject: [PATCH 02/44] PAN-15 Created initial UserService implementation and initial integration tests --- .../tsp/services/ServicesTestConfig.java | 17 ++++++++ .../services/UserServiceIntegrationTest.java | 43 +++++++++++++++++++ .../integrationTest/resources/test.properties | 3 ++ .../msudenver/tsp/services/ServiceConfig.java | 14 ++++++ .../msudenver/tsp/services/UserService.java | 4 +- .../msudenver/tsp/services/dto/Account.java | 8 ++-- .../tsp/services/parser/ParserService.java | 18 -------- .../src/main/resources/application.properties | 6 +-- 8 files changed, 86 insertions(+), 27 deletions(-) create mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java create mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java create mode 100644 services/src/integrationTest/resources/test.properties create mode 100644 services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java new file mode 100644 index 0000000..4c9e2b4 --- /dev/null +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java @@ -0,0 +1,17 @@ +package edu.msudenver.tsp.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +public class ServicesTestConfig { + + @Bean + @Autowired + public UserService userService(final RestService restService) { + return new UserService(restService); + } +} diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java new file mode 100644 index 0000000..e434d64 --- /dev/null +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -0,0 +1,43 @@ +package edu.msudenver.tsp.services; + +import edu.msudenver.tsp.services.dto.Account; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.text.ParseException; +import java.util.Date; +import java.util.Optional; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ServicesTestConfig.class) +@TestPropertySource("classpath:test.properties") +public class UserServiceIntegrationTest { + @Autowired + @Qualifier("userService") + private UserService userService; + + @Test + public void testCreateNewUser() throws ParseException { + final Account testAccount = new Account(); + testAccount.setUsername("test user"); + testAccount.setPassword("test password"); + testAccount.setAdministratorStatus(false); + testAccount.setLastLogin(new Date()); + + final Optional testCreatedAccount = userService.createNewAccount(testAccount); + + assertTrue(testCreatedAccount.isPresent()); + final Account returnedAccount = testCreatedAccount.get(); + Assert.assertEquals("test user", returnedAccount.getUsername()); + Assert.assertEquals("test password", returnedAccount.getPassword()); + Assert.assertEquals(false, returnedAccount.isAdministratorStatus()); + } +} diff --git a/services/src/integrationTest/resources/test.properties b/services/src/integrationTest/resources/test.properties new file mode 100644 index 0000000..3690a57 --- /dev/null +++ b/services/src/integrationTest/resources/test.properties @@ -0,0 +1,3 @@ +persistence.api.connection.timeout.milliseconds=5000 +persistence.api.socket.timeout.milliseconds=10000 +persistence.api.base.url=http://localhost:8090/ diff --git a/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java new file mode 100644 index 0000000..db65cc6 --- /dev/null +++ b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java @@ -0,0 +1,14 @@ +package edu.msudenver.tsp.services; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration(exclude = {DevToolsDataSourceAutoConfiguration.class, + HibernateJpaAutoConfiguration.class, + DataSourceAutoConfiguration.class}) +public class ServiceConfig { +} diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index f119441..0862ae5 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -34,8 +34,8 @@ public class UserService { try { final TypeToken typeToken = new TypeToken() {}; - final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "/accounts/", - new GsonBuilder().create().toJson(account), + final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "accounts/", + new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds); diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index c82731a..b7135ec 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -1,19 +1,19 @@ package edu.msudenver.tsp.services.dto; import com.google.gson.annotations.SerializedName; -import edu.msudenver.tsp.persistence.dto.AccountDto; +import lombok.Data; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Date; +@Data public class Account extends BaseDto implements Serializable { - @NotBlank(groups = AccountDto.Insert.class, message = "A username must be specified") @Size(max = 50) private String username; - @NotBlank(groups = AccountDto.Insert.class, message = "A password must be specified") @Size(max = 256) private String password; + @Size(max = 50) private String username; + @Size(max = 256) private String password; @NotNull @SerializedName("administrator_status") private boolean administratorStatus; @Temporal(TemporalType.DATE) @SerializedName("last_login") private Date lastLogin; diff --git a/services/src/main/java/edu/msudenver/tsp/services/parser/ParserService.java b/services/src/main/java/edu/msudenver/tsp/services/parser/ParserService.java index 0106b8b..5bebbc1 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/parser/ParserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/parser/ParserService.java @@ -1,10 +1,5 @@ package edu.msudenver.tsp.services.parser; -import edu.msudenver.tsp.persistence.controller.DefinitionController; -import edu.msudenver.tsp.persistence.controller.NotationController; -import edu.msudenver.tsp.persistence.controller.ProofController; -import edu.msudenver.tsp.persistence.controller.TheoremController; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -12,21 +7,8 @@ import java.util.List; @Service class ParserService { - private final DefinitionController definitionController; - private final TheoremController theoremController; - private final NotationController notationController; - private final ProofController proofController; private Node root; - @Autowired - public ParserService(final DefinitionController definitionController, final TheoremController theoremController, - final NotationController notationController, final ProofController proofController) { - this.definitionController = definitionController; - this.theoremController = theoremController; - this.notationController = notationController; - this.proofController = proofController; - } - public boolean parseUserInput(final String userInput) { try { diff --git a/services/src/main/resources/application.properties b/services/src/main/resources/application.properties index ff86c7e..710f97b 100644 --- a/services/src/main/resources/application.properties +++ b/services/src/main/resources/application.properties @@ -1,3 +1,3 @@ -persistence.api.connection.timeout.milliseconds = 5000 -persistence.api.socket.timeout.milliseconds = 10000 -persistence.api.base.url = http://localhost:8090/ \ No newline at end of file +persistence.api.connection.timeout.milliseconds=5000 +persistence.api.socket.timeout.milliseconds=10000 +persistence.api.base.url=http://localhost:8090/ \ No newline at end of file From 10b0a09690020b5bdd47ebb998a50c3a50166e3f Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 16:18:19 -0600 Subject: [PATCH 03/44] PAN-15 Updated the gradle dependencies --- services/build.gradle | 7 +++++- .../msudenver/tsp/services/dto/Account.java | 2 ++ .../services/parser/ParserServiceTest.java | 23 +++++++------------ 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/services/build.gradle b/services/build.gradle index 05efbeb..00a0119 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -18,11 +18,16 @@ repositories { } dependencies { - compile project(':persistence') compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.11' compile group: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.7' + compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2' + compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final' + compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: '2.1.3.RELEASE' + compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.1.3.RELEASE' + compile group: 'org.springframework', name: 'spring-web', version: '5.1.5.RELEASE' compile group: 'com.google.code.gson', name: 'gson', version: '2.7' compile fileTree(dir: 'lib', include: '**/*.jar') testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'org.springframework', name: 'spring-test', version: '5.1.5.RELEASE' } diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index b7135ec..1190dd8 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -2,6 +2,7 @@ package edu.msudenver.tsp.services.dto; import com.google.gson.annotations.SerializedName; import lombok.Data; +import lombok.EqualsAndHashCode; import javax.persistence.Temporal; import javax.persistence.TemporalType; @@ -11,6 +12,7 @@ import java.io.Serializable; import java.util.Date; @Data +@EqualsAndHashCode(callSuper = true) public class Account extends BaseDto implements Serializable { @Size(max = 50) private String username; @Size(max = 256) private String password; diff --git a/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java index 829a02a..1b23d95 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java @@ -1,9 +1,8 @@ package edu.msudenver.tsp.services.parser; -import edu.msudenver.tsp.persistence.controller.DefinitionController; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; +import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; @@ -12,18 +11,12 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ParserServiceTest { - private final DefinitionController definitionControllerMock = mock(DefinitionController.class); - private final ParserService mockParserService = mock(ParserService.class); - - @InjectMocks - private final ParserService parserService = new ParserService(definitionControllerMock, null, - null, null); + @Spy private ParserService parserService; @Test public void testEmptyStringEqualsEmptyString() { @@ -106,8 +99,8 @@ public class ParserServiceTest { final List expectedList = new ArrayList<>(); expectedList.add(""); - when(mockParserService.parseRawInput(anyString())).thenReturn(new Node("", null)); - final List actualList = parserService.retrieveStatements(mockParserService.parseRawInput("")); + when(parserService.parseRawInput(anyString())).thenReturn(new Node("", null)); + final List actualList = parserService.retrieveStatements(parserService.parseRawInput("")); assertEquals(expectedList, actualList); } @@ -124,8 +117,8 @@ public class ParserServiceTest { testNode.setRight(new Node("then", testNode)); testNode.getRight().setCenter(new Node(" x^2 is even", testNode.getRight())); - when(mockParserService.parseRawInput(anyString())).thenReturn(testNode); - final List actualList = parserService.retrieveStatements(mockParserService.parseRawInput("baseCase")); + when(parserService.parseRawInput(anyString())).thenReturn(testNode); + final List actualList = parserService.retrieveStatements(parserService.parseRawInput("baseCase")); assertEquals(expectedList, actualList); } @@ -133,8 +126,8 @@ public class ParserServiceTest { @Test public void testDriveParseUserInput() { final Node testNode = new Node("", null); - when(mockParserService.parseRawInput(anyString())).thenReturn(testNode); - when(mockParserService.retrieveStatements(testNode)).thenReturn(new ArrayList<>()); + when(parserService.parseRawInput(anyString())).thenReturn(testNode); + when(parserService.retrieveStatements(testNode)).thenReturn(new ArrayList<>()); final boolean successfulTestDrive = parserService.parseUserInput(""); From 238908f4facf34e91949a9a61283e90dfe1f1a98 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 17:03:50 -0600 Subject: [PATCH 04/44] PAN-15 Updated tests --- .../services/UserServiceIntegrationTest.java | 9 ++++---- .../msudenver/tsp/services/dto/Account.java | 2 ++ .../services/parser/ParserServiceTest.java | 23 +++++++------------ 3 files changed, 14 insertions(+), 20 deletions(-) diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index e434d64..c3a71d0 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -1,7 +1,6 @@ package edu.msudenver.tsp.services; import edu.msudenver.tsp.services.dto.Account; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,7 +13,7 @@ import java.text.ParseException; import java.util.Date; import java.util.Optional; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ServicesTestConfig.class) @@ -36,8 +35,8 @@ public class UserServiceIntegrationTest { assertTrue(testCreatedAccount.isPresent()); final Account returnedAccount = testCreatedAccount.get(); - Assert.assertEquals("test user", returnedAccount.getUsername()); - Assert.assertEquals("test password", returnedAccount.getPassword()); - Assert.assertEquals(false, returnedAccount.isAdministratorStatus()); + assertEquals("test user", returnedAccount.getUsername()); + assertEquals("test password", returnedAccount.getPassword()); + assertFalse(returnedAccount.isAdministratorStatus()); } } diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index b7135ec..1190dd8 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -2,6 +2,7 @@ package edu.msudenver.tsp.services.dto; import com.google.gson.annotations.SerializedName; import lombok.Data; +import lombok.EqualsAndHashCode; import javax.persistence.Temporal; import javax.persistence.TemporalType; @@ -11,6 +12,7 @@ import java.io.Serializable; import java.util.Date; @Data +@EqualsAndHashCode(callSuper = true) public class Account extends BaseDto implements Serializable { @Size(max = 50) private String username; @Size(max = 256) private String password; diff --git a/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java index 829a02a..1b23d95 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java @@ -1,9 +1,8 @@ package edu.msudenver.tsp.services.parser; -import edu.msudenver.tsp.persistence.controller.DefinitionController; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; +import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; @@ -12,18 +11,12 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ParserServiceTest { - private final DefinitionController definitionControllerMock = mock(DefinitionController.class); - private final ParserService mockParserService = mock(ParserService.class); - - @InjectMocks - private final ParserService parserService = new ParserService(definitionControllerMock, null, - null, null); + @Spy private ParserService parserService; @Test public void testEmptyStringEqualsEmptyString() { @@ -106,8 +99,8 @@ public class ParserServiceTest { final List expectedList = new ArrayList<>(); expectedList.add(""); - when(mockParserService.parseRawInput(anyString())).thenReturn(new Node("", null)); - final List actualList = parserService.retrieveStatements(mockParserService.parseRawInput("")); + when(parserService.parseRawInput(anyString())).thenReturn(new Node("", null)); + final List actualList = parserService.retrieveStatements(parserService.parseRawInput("")); assertEquals(expectedList, actualList); } @@ -124,8 +117,8 @@ public class ParserServiceTest { testNode.setRight(new Node("then", testNode)); testNode.getRight().setCenter(new Node(" x^2 is even", testNode.getRight())); - when(mockParserService.parseRawInput(anyString())).thenReturn(testNode); - final List actualList = parserService.retrieveStatements(mockParserService.parseRawInput("baseCase")); + when(parserService.parseRawInput(anyString())).thenReturn(testNode); + final List actualList = parserService.retrieveStatements(parserService.parseRawInput("baseCase")); assertEquals(expectedList, actualList); } @@ -133,8 +126,8 @@ public class ParserServiceTest { @Test public void testDriveParseUserInput() { final Node testNode = new Node("", null); - when(mockParserService.parseRawInput(anyString())).thenReturn(testNode); - when(mockParserService.retrieveStatements(testNode)).thenReturn(new ArrayList<>()); + when(parserService.parseRawInput(anyString())).thenReturn(testNode); + when(parserService.retrieveStatements(testNode)).thenReturn(new ArrayList<>()); final boolean successfulTestDrive = parserService.parseUserInput(""); From 5d429b2c8ea9f4bde67c1f7ee33db09dc5799a14 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 17:06:47 -0600 Subject: [PATCH 05/44] PAN-15 Updated tests --- services/build.gradle | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/services/build.gradle b/services/build.gradle index 00a0119..05efbeb 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -18,16 +18,11 @@ repositories { } dependencies { + compile project(':persistence') compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.11' compile group: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.7' - compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2' - compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final' - compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: '2.1.3.RELEASE' - compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.1.3.RELEASE' - compile group: 'org.springframework', name: 'spring-web', version: '5.1.5.RELEASE' compile group: 'com.google.code.gson', name: 'gson', version: '2.7' compile fileTree(dir: 'lib', include: '**/*.jar') testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.springframework', name: 'spring-test', version: '5.1.5.RELEASE' } From ffaf020b8005651688ca877ad35a7a6fb3b5dc1a Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 17:21:32 -0600 Subject: [PATCH 06/44] PAN-15 WORKING AND WITH TRAVIS!!! --- services/build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/services/build.gradle b/services/build.gradle index 05efbeb..fd28275 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -25,4 +25,5 @@ dependencies { compile fileTree(dir: 'lib', include: '**/*.jar') testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'org.springframework', name: 'spring-test', version: '5.1.5.RELEASE' } From 46122cbafd1c7211635b07723d0324c2a50790ee Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 10 Mar 2019 19:58:04 -0600 Subject: [PATCH 07/44] PAN-15 Created gradle tasks to start the persistence API and to start the API asynchronously --- build.gradle | 26 +++++++++++++++++++++----- persistence/build.gradle | 11 +++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 6690226..6c4a792 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,20 @@ +import java.util.concurrent.Callable +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +class RunAsyncTask extends DefaultTask { + String taskToExecute = ':persistence:startPersistenceApi' + @TaskAction + def startAsync() { + ExecutorService es = Executors.newSingleThreadExecutor() + es.submit({taskToExecute.execute()} as Callable) + } +} + buildscript { repositories { mavenCentral() + maven { url 'http://dl.bintray.com/vermeulen-mp/gradle-plugins' } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE") @@ -15,6 +29,7 @@ plugins { id "org.sonarqube" version "2.6" id 'org.unbroken-dome.test-sets' version '1.4.5' id 'war' + id "com.wiredforcode.spawn" version "0.8.2" } apply plugin: 'org.springframework.boot' @@ -87,11 +102,6 @@ subprojects { } } -bootJar { - baseName = 'gs-spring-boot' - version = '0.1.0' -} - sourceCompatibility = 1.8 targetCompatibility = 1.8 @@ -136,6 +146,12 @@ testSets { integrationTest } +task startApi(type: RunAsyncTask) { + dependsOn ':persistence:loadDb' + dependsOn 'build' + taskToExecute = ':persistence:startPersistenceApi' +} + compileKotlin { kotlinOptions.jvmTarget = "1.8" } diff --git a/persistence/build.gradle b/persistence/build.gradle index b832e7e..4672194 100644 --- a/persistence/build.gradle +++ b/persistence/build.gradle @@ -3,6 +3,9 @@ plugins { id 'java' } +apply plugin: 'io.spring.dependency-management' +apply plugin: 'org.springframework.boot' + description = 'Provides database access and connectivity' group 'edu.msudenver.tsp' version '1.0' @@ -50,3 +53,11 @@ task loadDb(type: Exec, group: 'Verification', description: 'Reloads the local d commandLine=['cmd','/c','loaddb.bat'] } } + +task startPersistenceApi(type: JavaExec, description: 'Starts the Persistence API') { + dependsOn 'loadDb' + dependsOn 'build' + classpath = files('build/libs/persistence-1.0.jar') + classpath += sourceSets.main.runtimeClasspath + main = 'edu.msudenver.tsp.persistence.PersistenceApi' +} From 3853911b3c54cb5790e0979a1a35303e78e17225 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 17 Mar 2019 21:09:07 -0600 Subject: [PATCH 08/44] PAN-11 corrected build.gradle inter-project dependencies --- services/build.gradle | 4 +- .../DefinitionServiceIntegrationTest.java | 55 ++++++++++++ .../tsp/services/ServiceTestConfig.java | 21 +++++ .../integrationTest/resources/test.properties | 3 + .../tsp/services/DefinitionService.java | 59 +++++++++++++ .../msudenver/tsp/services/ServiceConfig.java | 9 ++ .../tsp/services/dto/Definition.java | 24 ++++++ .../tsp/services/DefinitionServiceTest.java | 86 +++++++++++++++++++ 8 files changed, 260 insertions(+), 1 deletion(-) create mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java create mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java create mode 100644 services/src/integrationTest/resources/test.properties create mode 100644 services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java create mode 100644 services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java create mode 100644 services/src/main/java/edu/msudenver/tsp/services/dto/Definition.java create mode 100644 services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java diff --git a/services/build.gradle b/services/build.gradle index 551f2b2..2d22968 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -18,12 +18,14 @@ repositories { } dependencies { - compile project(':persistence') compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.11' compile group: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.7' compile group: 'com.google.code.gson', name: 'gson', version: '2.7' + compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.5.RELEASE' + compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.5.RELEASE' compile fileTree(dir: 'lib', include: '**/*.jar') testCompile "org.springframework:spring-test:5.0.9.RELEASE" + testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE' testCompile group: 'junit', name: 'junit', version: '4.12' } diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java new file mode 100644 index 0000000..f7e2d59 --- /dev/null +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java @@ -0,0 +1,55 @@ +package edu.msudenver.tsp.services; + +import edu.msudenver.tsp.services.dto.Definition; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import static org.mockito.AdditionalMatchers.not; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ServiceTestConfig.class) +public class DefinitionServiceIntegrationTest { + @Autowired private DefinitionService definitionService; + + @Test + public void testCreateNewDefinition() { + final Definition testDefinition = createDefinition(); + final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + + assertNotNull(createdDefinition); + assertTrue(createdDefinition.isPresent()); + assertThat(createdDefinition.get().getId(), is(not(0))); + assertThat(createdDefinition.get().getVersion(), is(0)); + assertThat(createdDefinition.get().getName(), is("Test Name")); + assertNotNull(createdDefinition.get().getDefinition()); + assertThat(createdDefinition.get().getDefinition().size(), is(1)); + assertThat(createdDefinition.get().getDefinition().get(0), is("Test definition 1")); + assertNotNull(createdDefinition.get().getNotation()); + assertThat(createdDefinition.get().getNotation().size(), is(1)); + assertThat(createdDefinition.get().getNotation().get(0), is("\\testLaTeX")); + } + + private Definition createDefinition() { + final List definitionList = new ArrayList<>(); + definitionList.add("Test definition 1"); + + final List notationList = new ArrayList<>(); + notationList.add("\\testLaTeX"); + + final Definition definition = new Definition(); + definition.setName("Test Name"); + definition.setDefinition(definitionList); + definition.setNotation(notationList); + + return definition; + } +} diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java new file mode 100644 index 0000000..724e5c8 --- /dev/null +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java @@ -0,0 +1,21 @@ +package edu.msudenver.tsp.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.TestPropertySource; + +@Configuration +@ComponentScan +@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) +@TestPropertySource("classpath:test.properties") +public class ServiceTestConfig { + + @Bean + @Autowired public DefinitionService definitionService(final RestService restService) { + return new DefinitionService(restService); + } +} diff --git a/services/src/integrationTest/resources/test.properties b/services/src/integrationTest/resources/test.properties new file mode 100644 index 0000000..ff86c7e --- /dev/null +++ b/services/src/integrationTest/resources/test.properties @@ -0,0 +1,3 @@ +persistence.api.connection.timeout.milliseconds = 5000 +persistence.api.socket.timeout.milliseconds = 10000 +persistence.api.base.url = http://localhost:8090/ \ No newline at end of file diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java new file mode 100644 index 0000000..425d329 --- /dev/null +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -0,0 +1,59 @@ +package edu.msudenver.tsp.services; + +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import edu.msudenver.tsp.services.dto.Definition; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; + +@Slf4j +@Service +@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true) +public class DefinitionService { + private final RestService restService; + @Value("${persistence.api.connection.timeout.milliseconds}") private int connectionTimeoutMilliseconds; + @Value("${persistence.api.socket.timeout.milliseconds}") private int socketTimeoutMilliseconds; + @Value("${persistence.api.base.url}") private String persistenceApiBaseUrl; + + @Autowired + public DefinitionService(final RestService restService) { + this.restService = restService; + } + + public Optional createNewDefinition(final Definition definition) { + if (definition == null) { + LOG.error("Given null definition, returning {}"); + return Optional.empty(); + } + final Instant start = Instant.now(); + + try { + final TypeToken definitionTypeToken = new TypeToken() {}; + final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "/", + new GsonBuilder().create().toJson(definition), + definitionTypeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds); + + if(persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to create new definition {}", definition.toString()); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error creating new definition {}", e); + return Optional.empty(); + } finally { + LOG.info("Create new definition request took {}ms", Duration.between(start, Instant.now()).toMillis()); + } + } +} diff --git a/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java new file mode 100644 index 0000000..b80e2da --- /dev/null +++ b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java @@ -0,0 +1,9 @@ +package edu.msudenver.tsp.services; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration +public class ServiceConfig { +} diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Definition.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Definition.java new file mode 100644 index 0000000..a208e83 --- /dev/null +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Definition.java @@ -0,0 +1,24 @@ +package edu.msudenver.tsp.services.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.List; + +@Data +@EqualsAndHashCode(callSuper = true) +public class Definition extends BaseDto implements Serializable { + @NotBlank(groups = Insert.class, message = "A name must be specified") + @Size(min = 1, max = 200, message = "Must be between 1 and 200 characters") + private String name; + @NotBlank(groups = Insert.class, message = "At least one (1) definition must be specified") + private List definition; + private List notation; + + private static final long serialVersionUID = 3412178112996807691L; + + public interface Insert {} +} diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java new file mode 100644 index 0000000..b712ccd --- /dev/null +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -0,0 +1,86 @@ +package edu.msudenver.tsp.services; + +import com.google.gson.GsonBuilder; +import edu.msudenver.tsp.services.dto.Definition; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DefinitionServiceTest { + @Mock private RestService restService; + @InjectMocks private DefinitionService definitionService; + + @Test + public void testCreateNewDefinition() { + final Definition testDefinition = createDefinition(); + final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); + + when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenReturn(Optional.of(testDefinition)); + + final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + + assertNotNull(createdDefinition); + assertTrue(createdDefinition.isPresent()); + assertEquals(testDefinition, createdDefinition.get()); + verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt()); + } + + @Test + public void testCreateNewDefinition_unableToCreateNewDefinition() { + final Definition testDefinition = createDefinition(); + final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); + + when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenReturn(Optional.empty()); + + final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + + assertNotNull(createdDefinition); + assertFalse(createdDefinition.isPresent()); + verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt()); + } + + @Test + public void testCreateNewDefinition_restServiceThrowsException() { + final Definition testDefinition = createDefinition(); + final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); + + when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenThrow(new UnsupportedOperationException("test exception")); + + final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + + assertNotNull(createdDefinition); + assertFalse(createdDefinition.isPresent()); + verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt()); + } + + private Definition createDefinition() { + final List definitionList = new ArrayList<>(); + definitionList.add("Test definition 1"); + + final List notationList = new ArrayList<>(); + notationList.add("\\testLaTeX"); + + final Definition definition = new Definition(); + definition.setName("Test Name"); + definition.setDefinition(definitionList); + definition.setNotation(notationList); + + return definition; + } +} \ No newline at end of file From b48094ba26642e359232e1f924fd074a8b947ad5 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 17 Mar 2019 22:02:00 -0600 Subject: [PATCH 09/44] PAN-11 Stuck trying to get the integration tests to be configured correctly --- .../tsp/services/DefinitionServiceIntegrationTest.java | 2 ++ .../edu/msudenver/tsp/services/ServiceTestConfig.java | 9 ++++----- .../edu/msudenver/tsp/services/DefinitionService.java | 2 -- .../java/edu/msudenver/tsp/services/dto/Account.java | 9 ++++----- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java index f7e2d59..3e4bc99 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; @@ -17,6 +18,7 @@ import static org.mockito.AdditionalMatchers.not; @RunWith(SpringRunner.class) @ContextConfiguration(classes = ServiceTestConfig.class) +@TestPropertySource(locations = "classpath:test.properties") public class DefinitionServiceIntegrationTest { @Autowired private DefinitionService definitionService; diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java index 724e5c8..93ae8e1 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java @@ -1,17 +1,16 @@ package edu.msudenver.tsp.services; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.TestPropertySource; +import org.springframework.context.annotation.FilterType; @Configuration -@ComponentScan -@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) -@TestPropertySource("classpath:test.properties") +@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class)) +@EnableAutoConfiguration public class ServiceTestConfig { @Bean diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index 425d329..23b177a 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -6,7 +6,6 @@ import edu.msudenver.tsp.services.dto.Definition; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import java.time.Duration; @@ -15,7 +14,6 @@ import java.util.Optional; @Slf4j @Service -@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true) public class DefinitionService { private final RestService restService; @Value("${persistence.api.connection.timeout.milliseconds}") private int connectionTimeoutMilliseconds; diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index 139cd41..99ca0cd 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -4,8 +4,6 @@ import com.google.gson.annotations.SerializedName; import lombok.Data; import lombok.EqualsAndHashCode; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @@ -15,11 +13,12 @@ import java.util.Date; @Data @EqualsAndHashCode(callSuper = true) public class Account extends BaseDto implements Serializable { - @NotBlank(groups = edu.msudenver.tsp.persistence.dto.Account.Insert.class, message = "A username must be specified") @Size(max = 50) private String username; - @NotBlank(groups = edu.msudenver.tsp.persistence.dto.Account.Insert.class, message = "A password must be specified") @Size(max = 256) private String password; + @NotBlank(groups = Insert.class, message = "A username must be specified") @Size(max = 50) private String username; + @NotBlank(groups = Insert.class, message = "A password must be specified") @Size(max = 256) private String password; @NotNull @SerializedName("administrator_status") private boolean administratorStatus; - @Temporal(TemporalType.DATE) @SerializedName("last_login") private Date lastLogin; + @SerializedName("last_login") private Date lastLogin; private static final long serialVersionUID = 7095627971593953734L; + public interface Insert {} } From 860e5379e6f70ad11be3fc83597cce1c8b78f54e Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Wed, 20 Mar 2019 16:06:24 -0600 Subject: [PATCH 10/44] PAN-15 UserService.java and completed UserSservice integration test --- ...damonium-theorem-prover.main.kotlin_module | Bin 16 -> 0 bytes .../scripts/mysql/local_development.sql | 1 + .../repository/AccountsRepository.java | 3 + .../controller/AccountControllerTest.java | 1 + .../services/UserServiceIntegrationTest.java | 24 +++- .../msudenver/tsp/services/RestService.java | 9 +- .../msudenver/tsp/services/UserService.java | 115 +++++++++++++++++- .../msudenver/tsp/services/dto/Account.java | 1 + .../tsp/services/factory/RequestFactory.java | 4 + 9 files changed, 148 insertions(+), 10 deletions(-) delete mode 100644 out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module diff --git a/out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module b/out/production/classes/META-INF/edu.msudenver.tsp.pandamonium-theorem-prover.main.kotlin_module deleted file mode 100644 index 8fb60192d378759239a3ecbf60eac8c8de446e9c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16 RcmZQzU|?ooU|@t|UH|}6022TJ diff --git a/persistence/scripts/mysql/local_development.sql b/persistence/scripts/mysql/local_development.sql index 1f885cc..eb1549c 100644 --- a/persistence/scripts/mysql/local_development.sql +++ b/persistence/scripts/mysql/local_development.sql @@ -16,6 +16,7 @@ values ('admin', 'secret', true), ('BrittanyBi', 'secret', true), ('lanlanzeliu', 'secret', true), ('tramanh305', 'secret', true); + create table definitions ( id int not null auto_increment primary key unique, name varchar(200) not null, diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/repository/AccountsRepository.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/repository/AccountsRepository.java index 454cd77..542ffe8 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/repository/AccountsRepository.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/repository/AccountsRepository.java @@ -6,4 +6,7 @@ import org.springframework.stereotype.Repository; @Repository public interface AccountsRepository extends CrudRepository { + + + } diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java index 0b88630..8dd69ca 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java @@ -33,6 +33,7 @@ public class AccountControllerTest { @Test public void testGetAllAccounts() { + final AccountDto accountDto = createAccount(); final List accountDtoList = new ArrayList<>(); accountDtoList.add(accountDto); diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index c3a71d0..c006236 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -9,7 +9,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.text.ParseException; import java.util.Date; import java.util.Optional; @@ -24,7 +23,7 @@ public class UserServiceIntegrationTest { private UserService userService; @Test - public void testCreateNewUser() throws ParseException { + public void testUserService(){ final Account testAccount = new Account(); testAccount.setUsername("test user"); testAccount.setPassword("test password"); @@ -38,5 +37,26 @@ public class UserServiceIntegrationTest { assertEquals("test user", returnedAccount.getUsername()); assertEquals("test password", returnedAccount.getPassword()); assertFalse(returnedAccount.isAdministratorStatus()); + + final Optional updatePasswordTestCreatedAccount = userService.updatePassword(returnedAccount, "password"); + + assertTrue(updatePasswordTestCreatedAccount.isPresent()); + final Account returnedUpdatedPasswordAccount = updatePasswordTestCreatedAccount.get(); + assertEquals("test user", returnedUpdatedPasswordAccount.getUsername()); + assertEquals("password", returnedUpdatedPasswordAccount.getPassword()); + assertFalse(returnedAccount.isAdministratorStatus()); + + final Optional updateUsernameTestCreatedAccount = userService.updateUsername(returnedUpdatedPasswordAccount, "user"); + + assertTrue(updateUsernameTestCreatedAccount.isPresent()); + final Account returnedUpdatedUsernameAccount = updateUsernameTestCreatedAccount.get(); + assertEquals("user", returnedUpdatedUsernameAccount.getUsername()); + assertEquals("password", returnedUpdatedUsernameAccount.getPassword()); + assertFalse(returnedAccount.isAdministratorStatus()); + + final boolean result = userService.deleteAccount(returnedUpdatedUsernameAccount); + + assertTrue(result); } + } diff --git a/services/src/main/java/edu/msudenver/tsp/services/RestService.java b/services/src/main/java/edu/msudenver/tsp/services/RestService.java index 78f0cb9..a8d043a 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/RestService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/RestService.java @@ -43,16 +43,21 @@ public class RestService { return send(requestFactory.post(uri, requestJson), null, connectionTimeout, socketTimeout, type); } + Optional patch(final String uri, final String requestJson, final TypeToken type, final Integer connectionTimeout, final Integer socketTimeout) { + LOG.info("Sending Patch {} with body: {}", uri, requestJson); + return send(requestFactory.patch(uri, requestJson), null, connectionTimeout, socketTimeout, type); + } Optional post(final String uri, final String requestJson, final Integer connectionTimeout, final Integer socketTimeout) { LOG.info("Sending POST {} with body: {}", uri, requestJson); return send(requestFactory.post(uri, requestJson), null, connectionTimeout, socketTimeout); } - Optional put(final String uri, final String requestJson, final TypeToken type, final Integer connectionTimeout, final Integer socketTimeout, final String auth) { + Optional put(final String uri, final String requestJson, final TypeToken type, final Integer connectionTimeout, final Integer socketTimeout) { LOG.info("Sending PUT {} with body: {}", uri, requestJson); - return send(requestFactory.put(uri, requestJson), auth, connectionTimeout, socketTimeout, type); + return send(requestFactory.put(uri, requestJson), null, connectionTimeout, socketTimeout, type); } + private Optional send(final Request request, final String auth, final Integer connectionTimeout, final Integer socketTimeout, final TypeToken type) { try { final Optional optionalHttpResponse = send(request, auth, connectionTimeout, socketTimeout); diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index 0862ae5..9cb0b46 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -6,6 +6,7 @@ import edu.msudenver.tsp.services.dto.Account; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.time.Duration; @@ -16,16 +17,19 @@ import java.util.Optional; @Service public class UserService { private final RestService restService; - @Value("${persistence.api.connection.timeout.milliseconds}") private int connectionTimeoutMilliseconds; - @Value("${persistence.api.socket.timeout.milliseconds}") private int socketTimeoutMilliseconds; - @Value("${persistence.api.base.url}") private String persistenceApiBaseUrl; + @Value("${persistence.api.connection.timeout.milliseconds}") + private int connectionTimeoutMilliseconds; + @Value("${persistence.api.socket.timeout.milliseconds}") + private int socketTimeoutMilliseconds; + @Value("${persistence.api.base.url}") + private String persistenceApiBaseUrl; @Autowired public UserService(final RestService restService) { this.restService = restService; } - public Optional createNewAccount(final Account account) { + public Optional createNewAccount(final Account account) { if (account == null) { LOG.error("Given null account, returning {}"); return Optional.empty(); @@ -33,7 +37,8 @@ public class UserService { final Instant start = Instant.now(); try { - final TypeToken typeToken = new TypeToken() {}; + final TypeToken typeToken = new TypeToken() { + }; final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "accounts/", new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, @@ -41,7 +46,7 @@ public class UserService { socketTimeoutMilliseconds); if (persistenceApiResponse.isPresent()) { - LOG.info("Returning {}", persistenceApiResponse.get()); + LOG.info("Returning {}", persistenceApiResponse); } else { LOG.info("Unable to create new account {}", account.toString()); } @@ -54,4 +59,102 @@ public class UserService { LOG.info("Create new account request took {} ms", Duration.between(start, Instant.now()).toMillis()); } } + + public Optional updatePassword(final Account account , final String password){ + + if(account ==null){ + LOG.error("user not exist, returning{}"); + return Optional.empty(); + } + + final Integer id = account.getId(); + account.setPassword(password); + final Instant start = Instant.now(); + + try{ + final String auth = ""; + final TypeToken typeToken = new TypeToken(){}; + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, + new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to update password for account {}",account.toString()); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error updating account {}", e); + return Optional.empty(); + } finally { + LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } + + public Optional updateUsername(final Account account , final String username){ + + if(account ==null){ + LOG.error("user not exist, returning{}"); + return Optional.empty(); + } + + final Integer id = account.getId(); + account.setUsername(username); + final Instant start = Instant.now(); + + try{ + final String auth = ""; + final TypeToken typeToken = new TypeToken(){}; + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, + new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to update username for account {}",account.toString()); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error updating account {}", e); + return Optional.empty(); + } finally { + LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } + public boolean deleteAccount(final Account account){ + if(account ==null){ + LOG.error("Username not exist, returning{}"); + return false; + } + final Integer id = account.getId(); + final Instant start = Instant.now(); + + try{ + + final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl +"/accounts/"+id, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds, HttpStatus.NO_CONTENT ); + if(persistenceApiResponse){ + LOG.info("return {}", persistenceApiResponse); + } + else { + LOG.info("Unable to delete user {}",account.toString()); + } + + return persistenceApiResponse; + }catch (final Exception e) { + LOG.error("Error deleting user {}", e); + return false; + } finally { + LOG.info("delete user request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } } diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index 1190dd8..b1a04d9 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -21,4 +21,5 @@ public class Account extends BaseDto implements Serializable { private static final long serialVersionUID = 7095627971593953734L; + } diff --git a/services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java b/services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java index 726b9a8..e108cd1 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java +++ b/services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java @@ -22,4 +22,8 @@ public class RequestFactory { public Request put(final String uri, final String requestJson) { return StringUtils.isNotBlank(requestJson) ? Request.Put(uri).bodyString(requestJson, ContentType.APPLICATION_JSON) : Request.Put(uri); } + + public Request patch(final String uri, final String requestJson) { + return StringUtils.isNotBlank(requestJson) ? Request.Patch(uri).bodyString(requestJson, ContentType.APPLICATION_JSON) : Request.Patch(uri); + } } \ No newline at end of file From f5f959b4530cf351436d02d94586d7e556fe9852 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Wed, 20 Mar 2019 22:28:51 -0600 Subject: [PATCH 11/44] Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15 # Conflicts: # services/build.gradle --- persistence/build.gradle | 3 -- .../scripts/mysql/local_development.sql | 1 - .../msudenver/tsp/services/UserService.java | 33 +++++++++---------- 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/persistence/build.gradle b/persistence/build.gradle index 4672194..811725d 100644 --- a/persistence/build.gradle +++ b/persistence/build.gradle @@ -3,9 +3,6 @@ plugins { id 'java' } -apply plugin: 'io.spring.dependency-management' -apply plugin: 'org.springframework.boot' - description = 'Provides database access and connectivity' group 'edu.msudenver.tsp' version '1.0' diff --git a/persistence/scripts/mysql/local_development.sql b/persistence/scripts/mysql/local_development.sql index e8acdaf..52480e5 100644 --- a/persistence/scripts/mysql/local_development.sql +++ b/persistence/scripts/mysql/local_development.sql @@ -16,7 +16,6 @@ values ('admin', 'secret', true), ('BrittanyBi', 'secret', true), ('lanlanzeliu', 'secret', true), ('tramanh305', 'secret', true); - create table definitions ( id int not null auto_increment primary key unique, name varchar(200) not null, diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index 9cb0b46..7382653 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -17,19 +17,16 @@ import java.util.Optional; @Service public class UserService { private final RestService restService; - @Value("${persistence.api.connection.timeout.milliseconds}") - private int connectionTimeoutMilliseconds; - @Value("${persistence.api.socket.timeout.milliseconds}") - private int socketTimeoutMilliseconds; - @Value("${persistence.api.base.url}") - private String persistenceApiBaseUrl; + @Value("${persistence.api.connection.timeout.milliseconds}") private int connectionTimeoutMilliseconds; + @Value("${persistence.api.socket.timeout.milliseconds}") private int socketTimeoutMilliseconds; + @Value("${persistence.api.base.url}") private String persistenceApiBaseUrl; @Autowired public UserService(final RestService restService) { this.restService = restService; } - public Optional createNewAccount(final Account account) { + public Optional createNewAccount(final Account account) { if (account == null) { LOG.error("Given null account, returning {}"); return Optional.empty(); @@ -37,8 +34,7 @@ public class UserService { final Instant start = Instant.now(); try { - final TypeToken typeToken = new TypeToken() { - }; + final TypeToken typeToken = new TypeToken() {}; final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "accounts/", new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, @@ -46,7 +42,7 @@ public class UserService { socketTimeoutMilliseconds); if (persistenceApiResponse.isPresent()) { - LOG.info("Returning {}", persistenceApiResponse); + LOG.info("Returning {}", persistenceApiResponse.get()); } else { LOG.info("Unable to create new account {}", account.toString()); } @@ -74,7 +70,7 @@ public class UserService { try{ final String auth = ""; final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/id?id=" + id, new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, connectionTimeoutMilliseconds, @@ -93,7 +89,7 @@ public class UserService { } finally { LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); } - } + } public Optional updateUsername(final Account account , final String username){ @@ -109,7 +105,7 @@ public class UserService { try{ final String auth = ""; final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/id?id="+id, new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, connectionTimeoutMilliseconds, @@ -129,9 +125,10 @@ public class UserService { LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); } } - public boolean deleteAccount(final Account account){ - if(account ==null){ - LOG.error("Username not exist, returning{}"); + + public boolean deleteAccount(final Account account) { + if(account == null){ + LOG.error("Username does not exist, returning {}"); return false; } final Integer id = account.getId(); @@ -139,14 +136,14 @@ public class UserService { try{ - final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl +"/accounts/"+id, + final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "/accounts/id?id=" + id, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, HttpStatus.NO_CONTENT ); if(persistenceApiResponse){ LOG.info("return {}", persistenceApiResponse); } else { - LOG.info("Unable to delete user {}",account.toString()); + LOG.info("Unable to delete user {}", account.toString()); } return persistenceApiResponse; From 9695f5082ad34a47f3551e778adaeff20c1704f5 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Wed, 20 Mar 2019 22:30:11 -0600 Subject: [PATCH 12/44] Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15 # Conflicts: # services/build.gradle --- .../main/java/edu/msudenver/tsp/services/UserService.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index 7382653..ffb78a5 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -70,7 +70,7 @@ public class UserService { try{ final String auth = ""; final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/id?id=" + id, + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/" + id, new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, connectionTimeoutMilliseconds, @@ -105,7 +105,7 @@ public class UserService { try{ final String auth = ""; final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/id?id="+id, + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), typeToken, connectionTimeoutMilliseconds, @@ -136,7 +136,7 @@ public class UserService { try{ - final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "/accounts/id?id=" + id, + final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "/accounts/" + id, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, HttpStatus.NO_CONTENT ); if(persistenceApiResponse){ From 89f1c55f51a4f4d8c8c6bb32271115c4df29c00c Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 24 Mar 2019 14:54:06 -0600 Subject: [PATCH 13/44] PAN-15 Fixed unit tests --- build.gradle | 6 ++- .../msudenver/tsp/services/UserService.java | 24 +++++----- .../tsp/services/UserServiceTest.java | 47 +++++++++++++++++++ .../msudenver/tsp/website/Application.java | 19 +------- src/main/webapp/index.jsp | 15 ++++-- 5 files changed, 79 insertions(+), 32 deletions(-) create mode 100644 services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java diff --git a/build.gradle b/build.gradle index cc21aa1..e00bb1b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,3 +1,4 @@ + buildscript { repositories { mavenCentral() @@ -70,7 +71,6 @@ subprojects { testCompile group: 'junit', name: 'junit', version: '4.11' testCompile group: 'junit', name: 'junit', version: '4.12' testCompile('org.mockito:mockito-core:1.10.19') {exclude(group: 'org.hamcrest')} - } test { @@ -107,7 +107,11 @@ dependencies { compile 'org.slf4j:slf4j-api:1.7.22' compile "joda-time:joda-time:2.2" compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.5.RELEASE' + compile('org.springframework.boot:spring-boot-starter-web','org.apache.tomcat.embed:tomcat-embed-jasper' + ,'javax.servlet:jstl') + testCompile 'javax.el:javax.el-api:3.0.0' + testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.3.RELEASE' testCompile group: 'junit', name: 'junit', version: '4.12' testCompile "org.springframework:spring-test:5.0.9.RELEASE" testCompile('org.mockito:mockito-core:1.10.19') {exclude(group: 'org.hamcrest')} diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index ffb78a5..d717e2b 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -56,19 +56,21 @@ public class UserService { } } - public Optional updatePassword(final Account account , final String password){ - - if(account ==null){ - LOG.error("user not exist, returning{}"); + public Optional updateAccount(final Account account) { + if (account == null) { + LOG.error("User does not exist, returning {}"); return Optional.empty(); } - final Integer id = account.getId(); - account.setPassword(password); + if (account.getId() == 0) { + LOG.error("No user ID specified! Returning {}"); + return Optional.empty(); + } + + final int id = account.getId(); final Instant start = Instant.now(); - try{ - final String auth = ""; + try { final TypeToken typeToken = new TypeToken(){}; final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/" + id, new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), @@ -79,15 +81,15 @@ public class UserService { if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to update password for account {}",account.toString()); + LOG.info("Unable to update user {} with id", account.getId()); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error updating account {}", e); + LOG.error("Error updating user {}", e); return Optional.empty(); } finally { - LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Update user request took {} ms", Duration.between(start, Instant.now()).toMillis()); } } diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java new file mode 100644 index 0000000..52379b0 --- /dev/null +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -0,0 +1,47 @@ +package edu.msudenver.tsp.services; + +import com.google.gson.reflect.TypeToken; +import edu.msudenver.tsp.services.dto.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.text.ParseException; +import java.util.Date; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.when; + + + + +@RunWith(MockitoJUnitRunner.class) +public class UserServiceTest { + @Mock + private RestService restService; + @InjectMocks + private UserService userService; + + @Test + public void testCreateNewAccount() throws ParseException { + + final Account account = new Account(); + account.setUsername("Test username"); + account.setPassword("test password"); + account.setAdministratorStatus(false); + account.setLastLogin(new Date()); + + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + .thenReturn(Optional.of(account)); + + final Optional response = userService.createNewAccount(account); + + assertTrue(response.isPresent()); + assertEquals(account, response.get()); + } +} \ No newline at end of file diff --git a/src/main/java/edu/msudenver/tsp/website/Application.java b/src/main/java/edu/msudenver/tsp/website/Application.java index c8f0854..3339429 100644 --- a/src/main/java/edu/msudenver/tsp/website/Application.java +++ b/src/main/java/edu/msudenver/tsp/website/Application.java @@ -1,15 +1,9 @@ package edu.msudenver.tsp.website; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import java.util.Arrays; -@Slf4j @SpringBootApplication public class Application { @@ -17,17 +11,8 @@ public class Application { SpringApplication.run(Application.class, args); } - @Bean - public CommandLineRunner commandLineRunner(final ApplicationContext ctx) { - return args -> { - LOG.info("Beans provided by Spring Boot:"); - final String[] beanNames = ctx.getBeanDefinitionNames(); - Arrays.sort(beanNames); - for (final String beanName : beanNames) { - LOG.info(beanName); - } - }; - } + + } diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp index f8d618c..6417074 100644 --- a/src/main/webapp/index.jsp +++ b/src/main/webapp/index.jsp @@ -5,12 +5,21 @@ Time: 8:03 PM To change this template use File | Settings | File Templates. --%> -<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> + - $Title$ + + Theroem Prover - $END$ +
+
+

Theorem Prover

+

Hello! ${message}

+ + Click on this link to visit theorem entering page. +
+
From 94440faa4d748f8792b764bd0a95645f3929c0fd Mon Sep 17 00:00:00 2001 From: zeliu Date: Sun, 24 Mar 2019 15:21:25 -0600 Subject: [PATCH 14/44] PAN-18 Here is the JSP file for hoempage --- .../resources/application.properties | 3 +-- src/main/webapp/index.jsp | 25 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/out/production/resources/application.properties b/out/production/resources/application.properties index a8a0755..f3ce324 100644 --- a/out/production/resources/application.properties +++ b/out/production/resources/application.properties @@ -1,3 +1,2 @@ spring.mvc.view.prefix:/WEB-INF/jsp/ -spring.mvc.view.suffix:.jsp -server.port=8090 \ No newline at end of file +spring.mvc.view.suffix:.jsp \ No newline at end of file diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp index 0efda13..eaf742c 100644 --- a/src/main/webapp/index.jsp +++ b/src/main/webapp/index.jsp @@ -5,18 +5,23 @@ Time: 8:03 PM To change this template use File | Settings | File Templates. --%> -<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> + + +<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> + - Test page + + Theroem Prover - -

Test stuffs

-test hyperlink -
- -
- - +
+
+

Theorem Prover

+

Hello! ${message}

+ Click on this link to visit theorem entering page. +
+
+ + \ No newline at end of file From 3b4753215c0064158cf72af4a72104632dba1c0f Mon Sep 17 00:00:00 2001 From: zeliu Date: Sun, 24 Mar 2019 15:26:08 -0600 Subject: [PATCH 15/44] PAN-18 Refactored the HomeController --- .../resources/application.properties | 2 -- .../website/controller/HomeController.java | 28 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) delete mode 100644 out/production/resources/application.properties create mode 100644 src/main/java/edu/msudenver/tsp/website/controller/HomeController.java diff --git a/out/production/resources/application.properties b/out/production/resources/application.properties deleted file mode 100644 index f3ce324..0000000 --- a/out/production/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.mvc.view.prefix:/WEB-INF/jsp/ -spring.mvc.view.suffix:.jsp \ No newline at end of file diff --git a/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java b/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java new file mode 100644 index 0000000..128ca0c --- /dev/null +++ b/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java @@ -0,0 +1,28 @@ +package edu.msudenver.tsp.website.controller; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.Map; + +@Slf4j +@Controller +@AllArgsConstructor +@RequestMapping("/") +public class HomeController { + + @GetMapping("") + public String home(Map model) { + model.put("message", "Welcome to Theorem Prover !!"); + return "index"; + } + + @RequestMapping("/next") + public String next(Map model) { + model.put("message", "You are in new page !!"); + return "Theorem"; + } +} From 98f6b9e2b7551ba19bb94f13bb864e54c37ec038 Mon Sep 17 00:00:00 2001 From: zeliu Date: Sun, 24 Mar 2019 17:02:50 -0600 Subject: [PATCH 16/44] PAN-18 WORKING HOMEPAGE --- build.gradle | 2 +- .../website/controller/HomeController.java | 28 ------------------- src/main/webapp/{ => WEB-INF/jsp}/index.jsp | 8 +++--- 3 files changed, 5 insertions(+), 33 deletions(-) delete mode 100644 src/main/java/edu/msudenver/tsp/website/controller/HomeController.java rename src/main/webapp/{ => WEB-INF/jsp}/index.jsp (63%) diff --git a/build.gradle b/build.gradle index 1402ea7..d2d9c24 100644 --- a/build.gradle +++ b/build.gradle @@ -99,7 +99,7 @@ repositories { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8" + compile group: 'org.jacoco', name: 'org.jacoco.core', version: '0.8.3' compile 'org.codehaus.groovy:groovy-all:2.3.11' compile 'org.apache.commons:commons-lang3:3.5' // The production code uses the SLF4J logging API at compile time diff --git a/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java b/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java deleted file mode 100644 index 128ca0c..0000000 --- a/src/main/java/edu/msudenver/tsp/website/controller/HomeController.java +++ /dev/null @@ -1,28 +0,0 @@ -package edu.msudenver.tsp.website.controller; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import java.util.Map; - -@Slf4j -@Controller -@AllArgsConstructor -@RequestMapping("/") -public class HomeController { - - @GetMapping("") - public String home(Map model) { - model.put("message", "Welcome to Theorem Prover !!"); - return "index"; - } - - @RequestMapping("/next") - public String next(Map model) { - model.put("message", "You are in new page !!"); - return "Theorem"; - } -} diff --git a/src/main/webapp/index.jsp b/src/main/webapp/WEB-INF/jsp/index.jsp similarity index 63% rename from src/main/webapp/index.jsp rename to src/main/webapp/WEB-INF/jsp/index.jsp index eaf742c..54f56bb 100644 --- a/src/main/webapp/index.jsp +++ b/src/main/webapp/WEB-INF/jsp/index.jsp @@ -7,20 +7,20 @@ --%> -<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %> +<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %> - Theroem Prover + Theorem Prover

Theorem Prover

-

Hello! ${message}

+

Hello! Welcome to Theorem Prover !!

- Click on this link to visit theorem entering page. + Click on this link to visit theorem entering page.
From 8f2968bc2b0529c4dbb6f73b8c13df73cf26de77 Mon Sep 17 00:00:00 2001 From: zeliu Date: Sun, 24 Mar 2019 17:17:04 -0600 Subject: [PATCH 17/44] PAN-18 WORKING HOMEPAGE --- src/main/webapp/WEB-INF/jsp/index.jsp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/WEB-INF/jsp/index.jsp b/src/main/webapp/WEB-INF/jsp/index.jsp index 54f56bb..a31785b 100644 --- a/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/src/main/webapp/WEB-INF/jsp/index.jsp @@ -12,13 +12,13 @@ - Theorem Prover + Pandamoniumâ„¢ Theorem Prover

Theorem Prover

-

Hello! Welcome to Theorem Prover !!

+

Hello! Welcome to Pandamoniumâ„¢ Theorem Prover!!

Click on this link to visit theorem entering page.
From 6791f6c61fe64cfa1cc96d65669da3def5c31e61 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Sun, 24 Mar 2019 17:31:40 -0600 Subject: [PATCH 18/44] Merge branch 'master' of https://github.com/atusa17/ptp into PAN-15 # Conflicts: # src/main/java/edu/msudenver/tsp/website/Application.java --- .../services/UserServiceIntegrationTest.java | 38 +++++++-------- .../msudenver/tsp/services/UserService.java | 41 +++------------- .../tsp/services/UserServiceTest.java | 47 ++++++++++++++++--- 3 files changed, 66 insertions(+), 60 deletions(-) diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index e8abd0b..be372fc 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -24,11 +24,7 @@ public class UserServiceIntegrationTest { @Test public void testUserService(){ - final Account testAccount = new Account(); - testAccount.setUsername("test user"); - testAccount.setPassword("test password"); - testAccount.setAdministratorStatus(false); - testAccount.setLastLogin(new Date()); + final Account testAccount = creatAccount(); final Optional testCreatedAccount = userService.createNewAccount(testAccount); @@ -38,25 +34,29 @@ public class UserServiceIntegrationTest { assertEquals("test password", returnedAccount.getPassword()); assertFalse(returnedAccount.isAdministratorStatus()); - final Optional updatePasswordTestCreatedAccount = userService.updateAccount(returnedAccount); + returnedAccount.setUsername("test updatedUser"); + returnedAccount.setPassword("test updatedPassword"); - assertTrue(updatePasswordTestCreatedAccount.isPresent()); - final Account returnedUpdatedPasswordAccount = updatePasswordTestCreatedAccount.get(); - assertEquals("test user", returnedUpdatedPasswordAccount.getUsername()); - assertEquals("password", returnedUpdatedPasswordAccount.getPassword()); - assertFalse(returnedAccount.isAdministratorStatus()); + final Optional updatedTestCreatedAccount = userService.updateAccount(returnedAccount); - final Optional updateUsernameTestCreatedAccount = userService.updateUsername(returnedUpdatedPasswordAccount, "user"); + assertTrue(updatedTestCreatedAccount .isPresent()); + final Account returnedUpdatedAccount = updatedTestCreatedAccount.get(); + assertEquals("test updatedUser", returnedUpdatedAccount.getUsername()); + assertEquals("test updatedPassword", returnedUpdatedAccount.getPassword()); + assertFalse(returnedUpdatedAccount.isAdministratorStatus()); - assertTrue(updateUsernameTestCreatedAccount.isPresent()); - final Account returnedUpdatedUsernameAccount = updateUsernameTestCreatedAccount.get(); - assertEquals("user", returnedUpdatedUsernameAccount.getUsername()); - assertEquals("password", returnedUpdatedUsernameAccount.getPassword()); - assertFalse(returnedAccount.isAdministratorStatus()); - - final boolean result = userService.deleteAccount(returnedUpdatedUsernameAccount); + final boolean result = userService.deleteAccount(returnedUpdatedAccount); assertTrue(result); } + private Account creatAccount(){ + final Account testAccount = new Account(); + testAccount.setUsername("test user"); + testAccount.setPassword("test password"); + testAccount.setAdministratorStatus(false); + testAccount.setLastLogin(new Date()); + + return testAccount; + } } diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index d717e2b..2e7a468 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -93,47 +93,18 @@ public class UserService { } } - public Optional updateUsername(final Account account , final String username){ - - if(account ==null){ - LOG.error("user not exist, returning{}"); - return Optional.empty(); - } - - final Integer id = account.getId(); - account.setUsername(username); - final Instant start = Instant.now(); - - try{ - final String auth = ""; - final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "accounts/"+id, - new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account), - typeToken, - connectionTimeoutMilliseconds, - socketTimeoutMilliseconds); - - if (persistenceApiResponse.isPresent()) { - LOG.info("Returning {}", persistenceApiResponse.get()); - } else { - LOG.info("Unable to update username for account {}",account.toString()); - } - - return persistenceApiResponse; - } catch (final Exception e) { - LOG.error("Error updating account {}", e); - return Optional.empty(); - } finally { - LOG.info("Update account request took {} ms", Duration.between(start, Instant.now()).toMillis()); - } - } public boolean deleteAccount(final Account account) { if(account == null){ LOG.error("Username does not exist, returning {}"); return false; } - final Integer id = account.getId(); + + if (account.getId() == 0) { + LOG.error("No user ID specified! Returning {}"); + return false; + } + final int id = account.getId(); final Instant start = Instant.now(); try{ diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index ab1f321..1fb9dda 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -27,11 +27,7 @@ public class UserServiceTest { @Test public void testCreateNewAccount() throws ParseException { - final Account account = new Account(); - account.setUsername("Test username"); - account.setPassword("test password"); - account.setAdministratorStatus(false); - account.setLastLogin(new Date()); + final Account account = createAccount(); when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) .thenReturn(Optional.of(account)); @@ -41,4 +37,43 @@ public class UserServiceTest { assertTrue(response.isPresent()); assertEquals(account, response.get()); } -} \ No newline at end of file + + @Test + public void testUpdateAccount() throws ParseException { + final Account account = createAccount(); + account.setId(1); + + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + .thenReturn(Optional.of(account)); + + final Optional response = userService.updateAccount(account); + + assertTrue(response.isPresent()); + assertEquals(account, response.get()); + } + + @Test + public void testDeleteAccount() throws ParseException { + final boolean response= true; + final Account account = createAccount(); + account.setId(1); + + when(restService.delete(anyString(), anyInt(), anyInt(), any())) + .thenReturn(response); + + final boolean persistenceApiResponse = userService.deleteAccount(account); + + assertTrue(persistenceApiResponse ); + assertEquals(response, persistenceApiResponse ); + } + + + private Account createAccount() { + final Account account = new Account(); + account.setUsername("Test username"); + account.setPassword("test password"); + account.setAdministratorStatus(true); + account.setLastLogin(new Date()); + return account; + } +} From 0bc56f57e6978cd5634e06a4c3f7c724303102e7 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 17:49:07 -0600 Subject: [PATCH 19/44] PAN-15 Merged with master --- build.gradle | 1 - .../msudenver/tsp/services/UserServiceIntegrationTest.java | 1 + .../java/edu/msudenver/tsp/services/UserServiceTest.java | 6 ++---- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 2dfd518..d2d9c24 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,3 @@ - buildscript { repositories { mavenCentral() diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index be372fc..88da28f 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -49,6 +49,7 @@ public class UserServiceIntegrationTest { assertTrue(result); } + private Account creatAccount(){ final Account testAccount = new Account(); testAccount.setUsername("test user"); diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index 1fb9dda..7f19401 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -19,10 +19,8 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { - @Mock - private RestService restService; - @InjectMocks - private UserService userService; + @Mock private RestService restService; + @InjectMocks private UserService userService; @Test public void testCreateNewAccount() throws ParseException { From 978b58fe2cf5991ebb5ce6b2f1465d2705ca3519 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 20:48:25 -0600 Subject: [PATCH 20/44] PAN-11 wrote the GetAllDefinitions() method --- .../scripts/mysql/local_development.sql | 23 ++++++------ .../persistence/ProofsIntegrationTest.java | 3 +- .../DefinitionServiceIntegrationTest.java | 8 ++--- .../tsp/services/ServiceTestConfig.java | 9 ++--- .../tsp/services/DefinitionService.java | 35 ++++++++++++++++--- .../tsp/services/DefinitionServiceTest.java | 12 +++---- 6 files changed, 56 insertions(+), 34 deletions(-) diff --git a/persistence/scripts/mysql/local_development.sql b/persistence/scripts/mysql/local_development.sql index 27005d4..fbd9dac 100644 --- a/persistence/scripts/mysql/local_development.sql +++ b/persistence/scripts/mysql/local_development.sql @@ -34,17 +34,16 @@ referenced_theorems json, proven_status boolean default false, version int default 1 ); -CREATE TABLE proofs +create table proofs ( - id INT NOT NULL AUTO_INCREMENT, - theorem_name VARCHAR(512) NOT NULL, - proof VARCHAR(4096) NOT NULL, - branch VARCHAR(512) NOT NULL, - theorem INT NOT NULL, - referenced_definitions JSON, - referenced_theorems JSON, - date_added DATE, - last_updated DATE, - version INT DEFAULT 1, - PRIMARY KEY (id) + id int not null auto_increment primary key unique, + theorem_name varchar(512) not null, + proof varchar(4096) not null, + branch varchar(512) not null, + theorem int not null, + referenced_definitions json, + referenced_theorems json, + date_added date, + last_updated date, + version int default 1 ); \ No newline at end of file diff --git a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java index b18c47d..9fa7edb 100644 --- a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java +++ b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java @@ -18,8 +18,7 @@ import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = PersistenceTestConfig.class) public class ProofsIntegrationTest { - @Autowired - private ProofRepository proofRepository; + @Autowired private ProofRepository proofRepository; @Test public void testCRUDFunctionality() { diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java index 3e4bc99..7f424e3 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.List; @@ -16,16 +16,16 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.AdditionalMatchers.not; -@RunWith(SpringRunner.class) +@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ServiceTestConfig.class) @TestPropertySource(locations = "classpath:test.properties") public class DefinitionServiceIntegrationTest { @Autowired private DefinitionService definitionService; @Test - public void testCreateNewDefinition() { + public void testCreateDefinition() { final Definition testDefinition = createDefinition(); - final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + final Optional createdDefinition = definitionService.createDefinition(testDefinition); assertNotNull(createdDefinition); assertTrue(createdDefinition.isPresent()); diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java index 93ae8e1..1d9d54e 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java @@ -1,20 +1,17 @@ package edu.msudenver.tsp.services; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; @Configuration -@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class)) -@EnableAutoConfiguration +@ComponentScan public class ServiceTestConfig { @Bean - @Autowired public DefinitionService definitionService(final RestService restService) { + @Autowired + public DefinitionService definitionService(final RestService restService) { return new DefinitionService(restService); } } diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index 23b177a..f4bd91a 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -10,6 +10,7 @@ import org.springframework.stereotype.Service; import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Optional; @Slf4j @@ -25,25 +26,51 @@ public class DefinitionService { this.restService = restService; } - public Optional createNewDefinition(final Definition definition) { + public Optional> getAllDefinitions() { + final Instant start = Instant.now(); + + try { + final TypeToken> typeToken = new TypeToken>(){}; + final Optional> persistenceApiResponse = + restService.get(persistenceApiBaseUrl + "definitions/", + typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, null); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to get list of definitions"); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error getting list of definitions! {}", e); + return Optional.empty(); + } finally { + LOG.info("Get all definitions request took {}ms", Duration.between(start, Instant.now()).toMillis()); + } + } + + public Optional createDefinition(final Definition definition) { if (definition == null) { LOG.error("Given null definition, returning {}"); return Optional.empty(); } + + LOG.info("Sending request to insert definition {}", definition); final Instant start = Instant.now(); try { final TypeToken definitionTypeToken = new TypeToken() {}; - final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "/", + final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "definitions/", new GsonBuilder().create().toJson(definition), definitionTypeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds); - if(persistenceApiResponse.isPresent()) { + if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to create new definition {}", definition.toString()); + LOG.info("Unable to create new definition {}", definition); } return persistenceApiResponse; diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index b712ccd..673affd 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -24,14 +24,14 @@ public class DefinitionServiceTest { @InjectMocks private DefinitionService definitionService; @Test - public void testCreateNewDefinition() { + public void testCreateDefinition() { final Definition testDefinition = createDefinition(); final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) .thenReturn(Optional.of(testDefinition)); - final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + final Optional createdDefinition = definitionService.createDefinition(testDefinition); assertNotNull(createdDefinition); assertTrue(createdDefinition.isPresent()); @@ -40,14 +40,14 @@ public class DefinitionServiceTest { } @Test - public void testCreateNewDefinition_unableToCreateNewDefinition() { + public void testCreateDefinition_unableToCreateDefinition() { final Definition testDefinition = createDefinition(); final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) .thenReturn(Optional.empty()); - final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + final Optional createdDefinition = definitionService.createDefinition(testDefinition); assertNotNull(createdDefinition); assertFalse(createdDefinition.isPresent()); @@ -55,14 +55,14 @@ public class DefinitionServiceTest { } @Test - public void testCreateNewDefinition_restServiceThrowsException() { + public void testCreateDefinition_restServiceThrowsException() { final Definition testDefinition = createDefinition(); final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); when(restService.post(anyString(), anyString(), any(), anyInt(), anyInt())) .thenThrow(new UnsupportedOperationException("test exception")); - final Optional createdDefinition = definitionService.createNewDefinition(testDefinition); + final Optional createdDefinition = definitionService.createDefinition(testDefinition); assertNotNull(createdDefinition); assertFalse(createdDefinition.isPresent()); From 92bea81ae5ac0f3b0a247d3ababd9a0baafff7f5 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 21:23:03 -0600 Subject: [PATCH 21/44] PAN-11 Wrote unit tests for getAllDefinitions() --- .../msudenver/tsp/services/ServiceConfig.java | 7 +++- .../tsp/services/DefinitionServiceTest.java | 40 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java index b80e2da..db65cc6 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java +++ b/services/src/main/java/edu/msudenver/tsp/services/ServiceConfig.java @@ -1,9 +1,14 @@ package edu.msudenver.tsp.services; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration; import org.springframework.context.annotation.Configuration; @Configuration -@EnableAutoConfiguration +@EnableAutoConfiguration(exclude = {DevToolsDataSourceAutoConfiguration.class, + HibernateJpaAutoConfiguration.class, + DataSourceAutoConfiguration.class}) public class ServiceConfig { } diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index 673affd..23cd626 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -1,6 +1,7 @@ package edu.msudenver.tsp.services; import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; import edu.msudenver.tsp.services.dto.Definition; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,6 +14,8 @@ import java.util.List; import java.util.Optional; import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.verify; @@ -23,6 +26,43 @@ public class DefinitionServiceTest { @Mock private RestService restService; @InjectMocks private DefinitionService definitionService; + @Test + public void testGetAllDefinitions() { + final List definitionList = new ArrayList<>(); + final Definition testDefinition = createDefinition(); + definitionList.add(testDefinition); + definitionList.add(testDefinition); + + when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + .thenReturn(Optional.of(definitionList)); + + final Optional> listOfDefinitions = definitionService.getAllDefinitions(); + + assertTrue(listOfDefinitions.isPresent()); + assertThat(listOfDefinitions.get().size(), is(2)); + listOfDefinitions.get().forEach(definition -> assertThat(definition, equalTo(testDefinition))); + } + + @Test + public void testGetAllDefinitions_ReturnsEmptyOptional() { + when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + .thenReturn(Optional.empty()); + + final Optional> listOfDefinitions = definitionService.getAllDefinitions(); + + assertFalse(listOfDefinitions.isPresent()); + } + + @Test + public void testGetAllDefinitions_ExceptionThrown() { + when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + .thenThrow(new UnsupportedOperationException("Test exception")); + + final Optional> listOfDefinitions = definitionService.getAllDefinitions(); + + assertFalse(listOfDefinitions.isPresent()); + } + @Test public void testCreateDefinition() { final Definition testDefinition = createDefinition(); From bc0d631e6c4c496fb97baac10ba1fe31517f987a Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 21:29:49 -0600 Subject: [PATCH 22/44] PAN-11 Wrote the findById method --- .../tsp/services/DefinitionService.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index f4bd91a..7279ccd 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -50,6 +50,35 @@ public class DefinitionService { } } + public Optional findById(final int id) { + if (id == 0) { + LOG.error("Null id specified; returning {}"); + return Optional.empty(); + } + + LOG.info("Sending request to find definition by id {}", id); + final Instant start = Instant.now(); + + try { + final TypeToken typeToken = new TypeToken(){}; + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "/" + id, + typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, null); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to find definition with id {}", id); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error finding definition by id", e); + return Optional.empty(); + } finally { + LOG.info("Find by id request took {}ms", Duration.between(start, Instant.now()).toMillis()); + } + } + public Optional createDefinition(final Definition definition) { if (definition == null) { LOG.error("Given null definition, returning {}"); From ae88fd356d607878b192ce1ae535b7ef42479bf8 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 21:41:16 -0600 Subject: [PATCH 23/44] PAN-11 Wrote unit tests for the findById method --- .../tsp/services/DefinitionServiceTest.java | 60 ++++++++++++++++--- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index 23cd626..0631854 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -1,7 +1,6 @@ package edu.msudenver.tsp.services; import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; import edu.msudenver.tsp.services.dto.Definition; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,8 +17,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; import static org.mockito.Matchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class DefinitionServiceTest { @@ -33,7 +31,7 @@ public class DefinitionServiceTest { definitionList.add(testDefinition); definitionList.add(testDefinition); - when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) .thenReturn(Optional.of(definitionList)); final Optional> listOfDefinitions = definitionService.getAllDefinitions(); @@ -41,26 +39,73 @@ public class DefinitionServiceTest { assertTrue(listOfDefinitions.isPresent()); assertThat(listOfDefinitions.get().size(), is(2)); listOfDefinitions.get().forEach(definition -> assertThat(definition, equalTo(testDefinition))); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); } @Test public void testGetAllDefinitions_ReturnsEmptyOptional() { - when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) .thenReturn(Optional.empty()); final Optional> listOfDefinitions = definitionService.getAllDefinitions(); assertFalse(listOfDefinitions.isPresent()); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); } @Test - public void testGetAllDefinitions_ExceptionThrown() { - when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())) + public void testGetAllDefinitions_ExceptionThrownWhenSendingRequest() { + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) .thenThrow(new UnsupportedOperationException("Test exception")); final Optional> listOfDefinitions = definitionService.getAllDefinitions(); assertFalse(listOfDefinitions.isPresent()); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); + } + + @Test + public void testFindById() { + final Definition testDefinition = createDefinition(); + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) + .thenReturn(Optional.of(testDefinition)); + + final Optional foundDefinition = definitionService.findById(testDefinition.getId()); + + assertTrue(foundDefinition.isPresent()); + assertThat(foundDefinition.get().getId(), is(1)); + assertThat(foundDefinition.get(), is(equalTo(testDefinition))); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); + } + + @Test + public void testFindById_ReturnsEmptyOptional() { + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) + .thenReturn(Optional.empty()); + + final Optional nonExistentDefinition = definitionService.findById(1); + + assertFalse(nonExistentDefinition.isPresent()); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); + } + + @Test + public void testFindById_ExceptionThrownWhenSendingRequest() { + when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) + .thenThrow(new UnsupportedOperationException("test exception")); + + final Optional exceptionThrowingDefinition = definitionService.findById(1); + + assertFalse(exceptionThrowingDefinition.isPresent()); + verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString()); + } + + @Test + public void testFindById_IdIsZero() { + final Optional impossibleDefinition = definitionService.findById(0); + + assertFalse(impossibleDefinition.isPresent()); + verifyZeroInteractions(restService); } @Test @@ -120,6 +165,7 @@ public class DefinitionServiceTest { definition.setName("Test Name"); definition.setDefinition(definitionList); definition.setNotation(notationList); + definition.setId(1); return definition; } From 69726a46a4305bd76c6bd87c220289d22a36e778 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 21:51:10 -0600 Subject: [PATCH 24/44] PAN-11 created the updateDefinition method --- .../tsp/services/DefinitionService.java | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index 7279ccd..dec86a3 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -89,10 +89,10 @@ public class DefinitionService { final Instant start = Instant.now(); try { - final TypeToken definitionTypeToken = new TypeToken() {}; + final TypeToken typeToken = new TypeToken() {}; final Optional persistenceApiResponse = restService.post(persistenceApiBaseUrl + "definitions/", new GsonBuilder().create().toJson(definition), - definitionTypeToken, + typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds); @@ -110,4 +110,36 @@ public class DefinitionService { LOG.info("Create new definition request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } + + public Optional updateDefinition(final Definition definition) { + if (definition == null) { + LOG.error("Given null definition, returning {}"); + return Optional.empty(); + } + + LOG.info("Sending request to update definition {}", definition); + final Instant start = Instant.now(); + + try { + final TypeToken typeToken = new TypeToken(){}; + final Optional persistenceApiResposne = restService.patch(persistenceApiBaseUrl + "/" + definition.getId(), + new GsonBuilder().create().toJson(definition), + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds); + + if (persistenceApiResposne.isPresent()) { + LOG.info("Returning {}", persistenceApiResposne.get()); + } else { + LOG.info("Unable to update definition {}", definition); + } + + return persistenceApiResposne; + } catch (final Exception e) { + LOG.error("Error updating definition {}", e); + return Optional.empty(); + } finally { + LOG.info("Update definition request took {}ms", Duration.between(start, Instant.now()).toMillis()); + } + } } From 6d1db048c8d84c7f695c455f08440453185f39c6 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 21:51:36 -0600 Subject: [PATCH 25/44] PAN-11 created the updateDefinition method --- .../edu/msudenver/tsp/services/DefinitionService.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index dec86a3..6ffa013 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -122,19 +122,19 @@ public class DefinitionService { try { final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResposne = restService.patch(persistenceApiBaseUrl + "/" + definition.getId(), + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "/" + definition.getId(), new GsonBuilder().create().toJson(definition), typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds); - if (persistenceApiResposne.isPresent()) { - LOG.info("Returning {}", persistenceApiResposne.get()); + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); } else { LOG.info("Unable to update definition {}", definition); } - return persistenceApiResposne; + return persistenceApiResponse; } catch (final Exception e) { LOG.error("Error updating definition {}", e); return Optional.empty(); From 5a44b5b79300e56a054a0d526e1cfef09363be40 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 22:12:34 -0600 Subject: [PATCH 26/44] PAN-11 wrote unit tests for the updateDefinition method --- .../tsp/services/DefinitionService.java | 5 ++ .../tsp/services/DefinitionServiceTest.java | 66 +++++++++++++++++-- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index 6ffa013..e8ec3a2 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -117,6 +117,11 @@ public class DefinitionService { return Optional.empty(); } + if (definition.getId() == 0) { + LOG.error("Given invalid id 0, returning {}"); + return Optional.empty(); + } + LOG.info("Sending request to update definition {}", definition); final Instant start = Instant.now(); diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index 0631854..e7b423f 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -43,7 +43,7 @@ public class DefinitionServiceTest { } @Test - public void testGetAllDefinitions_ReturnsEmptyOptional() { + public void testGetAllDefinitions_RequestReturnsEmptyOptional() { when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) .thenReturn(Optional.empty()); @@ -79,7 +79,7 @@ public class DefinitionServiceTest { } @Test - public void testFindById_ReturnsEmptyOptional() { + public void testFindById_RequestReturnsEmptyOptional() { when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString())) .thenReturn(Optional.empty()); @@ -125,7 +125,7 @@ public class DefinitionServiceTest { } @Test - public void testCreateDefinition_unableToCreateDefinition() { + public void testCreateDefinition_UnableToCreateDefinition() { final Definition testDefinition = createDefinition(); final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); @@ -140,7 +140,7 @@ public class DefinitionServiceTest { } @Test - public void testCreateDefinition_restServiceThrowsException() { + public void testCreateDefinition_RestServiceThrowsException() { final Definition testDefinition = createDefinition(); final String testDefinitionJson = new GsonBuilder().create().toJson(testDefinition); @@ -154,6 +154,64 @@ public class DefinitionServiceTest { verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt()); } + @Test + public void testUpdateDefinition() { + when(restService.patch(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenReturn(Optional.of(createDefinition().setName("Test update"))); + + final Definition testDefinition = new Definition(); + testDefinition.setName("Test update"); + testDefinition.setId(1); + + final Optional updatedDefinition = definitionService.updateDefinition(testDefinition); + + assertTrue(updatedDefinition.isPresent()); + assertThat(updatedDefinition.get().getId(), is(1)); + assertThat(updatedDefinition.get().getName(), is(equalTo("Test update"))); + verify(restService).patch(anyString(), anyString(), any(), anyInt(), anyInt()); + } + + @Test + public void testUpdateDefinition_nullDefinition() { + final Optional testUpdate = definitionService.updateDefinition(null); + + assertFalse(testUpdate.isPresent()); + verifyZeroInteractions(restService); + } + + @Test + public void testUpdateDefinition_IdIsZero() { + final Definition impossibleDefinition = createDefinition(); + impossibleDefinition.setId(0); + + final Optional testUpdate = definitionService.updateDefinition(impossibleDefinition); + + assertFalse(testUpdate.isPresent()); + verifyZeroInteractions(restService); + } + + @Test + public void testUpdateDefinition_RequestReturnsEmptyOptional() { + when(restService.patch(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenReturn(Optional.empty()); + + final Optional nonExistentDefinition = definitionService.updateDefinition(createDefinition()); + + assertFalse(nonExistentDefinition.isPresent()); + verify(restService).patch(anyString(), anyString(), any(), anyInt(), anyInt()); + } + + @Test + public void testUpdateDefinition_ExceptionThrownWhenSendingRequest() { + when(restService.patch(anyString(), anyString(), any(), anyInt(), anyInt())) + .thenThrow(new UnsupportedOperationException("test exception")); + + final Optional exceptionThrowingDefinition = definitionService.updateDefinition(createDefinition()); + + assertFalse(exceptionThrowingDefinition.isPresent()); + verify(restService).patch(anyString(), anyString(), any(), anyInt(), anyInt()); + } + private Definition createDefinition() { final List definitionList = new ArrayList<>(); definitionList.add("Test definition 1"); From 8724d6c2f83cabca8ae0e44f75adab4403918add Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 22:27:27 -0600 Subject: [PATCH 27/44] PAN-11 created the deleteDefinition method --- .../tsp/services/DefinitionService.java | 40 ++++++++++++++++++- .../tsp/services/DefinitionServiceTest.java | 8 ++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index e8ec3a2..eec2324 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -6,6 +6,7 @@ import edu.msudenver.tsp.services.dto.Definition; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.time.Duration; @@ -97,7 +98,7 @@ public class DefinitionService { socketTimeoutMilliseconds); if (persistenceApiResponse.isPresent()) { - LOG.info("Returning {}", persistenceApiResponse.get()); + LOG.info("Creation successful. Returning {}", persistenceApiResponse.get()); } else { LOG.info("Unable to create new definition {}", definition); } @@ -134,7 +135,7 @@ public class DefinitionService { socketTimeoutMilliseconds); if (persistenceApiResponse.isPresent()) { - LOG.info("Returning {}", persistenceApiResponse.get()); + LOG.info("Update successful. Returning {}", persistenceApiResponse.get()); } else { LOG.info("Unable to update definition {}", definition); } @@ -147,4 +148,39 @@ public class DefinitionService { LOG.info("Update definition request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } + + public boolean deleteDefinition(final Definition definition) { + if (definition == null) { + LOG.error("Given null definition, returning false"); + return false; + } + + if (definition.getId() == 0) { + LOG.error("Given invalid id 0, returning false"); + return false; + } + + LOG.info("Sending request to delete definition {}", definition); + final Instant start = Instant.now(); + + try { + final boolean deleteIsSuccessful = restService.delete(persistenceApiBaseUrl + "/" + definition.getId(), + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds, + HttpStatus.NO_CONTENT); + + if (deleteIsSuccessful) { + LOG.info("Deletion successful. Returning true"); + } else { + LOG.info("Unable to delete definition {}", definition); + } + + return deleteIsSuccessful; + } catch (final Exception e) { + LOG.error("Error when deleting definition {}", e); + return false; + } finally { + LOG.info("Delete definition request took {}ms", Duration.between(start, Instant.now()).toMillis()); + } + } } diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index e7b423f..e18e54a 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -124,6 +124,14 @@ public class DefinitionServiceTest { verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt()); } + @Test + public void testCreateDefinition_NullDefinition() { + final Optional nullDefinition = definitionService.createDefinition(null); + + assertFalse(nullDefinition.isPresent()); + verifyZeroInteractions(restService); + } + @Test public void testCreateDefinition_UnableToCreateDefinition() { final Definition testDefinition = createDefinition(); From 765d8283d97e7273f9c924a95217aeb193d5034e Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 24 Mar 2019 22:36:10 -0600 Subject: [PATCH 28/44] PAN-11 wrote unit tests for deleteDefinition --- .../tsp/services/DefinitionServiceTest.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index e18e54a..38597d8 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -220,6 +220,58 @@ public class DefinitionServiceTest { verify(restService).patch(anyString(), anyString(), any(), anyInt(), anyInt()); } + @Test + public void testDeleteDefinition() { + when(restService.delete(anyString(), anyInt(), anyInt(), any())) + .thenReturn(true); + + final boolean deleteIsSuccessful = definitionService.deleteDefinition(createDefinition()); + + assertTrue(deleteIsSuccessful); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteDefinition_NullDefinition() { + final boolean deleteIsSuccessful = definitionService.deleteDefinition(null); + + assertFalse(deleteIsSuccessful); + verifyZeroInteractions(restService); + } + + @Test + public void testDeleteDefinition_IdIsZero() { + final Definition testDefinition = createDefinition(); + testDefinition.setId(0); + + final boolean deleteIsSuccessful = definitionService.deleteDefinition(testDefinition); + + assertFalse(deleteIsSuccessful); + verifyZeroInteractions(restService); + } + + @Test + public void testDeleteDefinition_RequestReturnsFalse() { + when(restService.delete(anyString(), anyInt(), anyInt(), any())) + .thenReturn(false); + + final boolean deleteIsSuccessful = definitionService.deleteDefinition(createDefinition()); + + assertFalse(deleteIsSuccessful); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteDefinition_ExceptionThrownWhenSendingRequest() { + when(restService.delete(anyString(), anyInt(), anyInt(), any())) + .thenThrow(new UnsupportedOperationException("test exception")); + + final boolean deleteIsSuccessful = definitionService.deleteDefinition(createDefinition()); + + assertFalse(deleteIsSuccessful); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); + } + private Definition createDefinition() { final List definitionList = new ArrayList<>(); definitionList.add("Test definition 1"); From b1d4ed9719c74b14d7ca0769be51ac9a4157e043 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Wed, 27 Mar 2019 12:18:12 -0600 Subject: [PATCH 29/44] PAN-15 fix the request changes --- .../services/UserServiceIntegrationTest.java | 43 ++++--- .../msudenver/tsp/services/UserService.java | 114 ++++++++++++++++-- .../tsp/services/UserServiceTest.java | 56 +++++++-- .../website/controller/LogInController.java | 35 ++++++ 4 files changed, 212 insertions(+), 36 deletions(-) create mode 100644 src/main/java/edu/msudenver/tsp/website/controller/LogInController.java diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index 88da28f..b3a547d 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -24,36 +24,47 @@ public class UserServiceIntegrationTest { @Test public void testUserService(){ - final Account testAccount = creatAccount(); - - final Optional testCreatedAccount = userService.createNewAccount(testAccount); + final Account testAccount = createAccount(); + final Optional testCreatedAccount = userService.createAccount(testAccount); assertTrue(testCreatedAccount.isPresent()); final Account returnedAccount = testCreatedAccount.get(); - assertEquals("test user", returnedAccount.getUsername()); - assertEquals("test password", returnedAccount.getPassword()); + assertEquals("test_user", returnedAccount.getUsername()); + assertEquals("test_password", returnedAccount.getPassword()); assertFalse(returnedAccount.isAdministratorStatus()); - returnedAccount.setUsername("test updatedUser"); - returnedAccount.setPassword("test updatedPassword"); + final Optional getAccountById = userService.getAccountById(returnedAccount.getId()); + assertTrue(getAccountById.isPresent()); + final Account returnedAccountById = getAccountById.get(); + assertEquals("test_user", returnedAccountById.getUsername()); + assertEquals("test_password", returnedAccountById.getPassword()); + assertFalse(returnedAccountById.isAdministratorStatus()); - final Optional updatedTestCreatedAccount = userService.updateAccount(returnedAccount); + final Optional getAccountByUsername = userService.getAccountByUsername(returnedAccount.getUsername()); + assertTrue(getAccountByUsername.isPresent()); + final Account returnedAccountByUsername = getAccountByUsername.get(); + assertEquals("test_user", returnedAccountByUsername.getUsername()); + assertEquals("test_password", returnedAccountByUsername.getPassword()); + assertFalse(returnedAccountById.isAdministratorStatus()); - assertTrue(updatedTestCreatedAccount .isPresent()); - final Account returnedUpdatedAccount = updatedTestCreatedAccount.get(); - assertEquals("test updatedUser", returnedUpdatedAccount.getUsername()); - assertEquals("test updatedPassword", returnedUpdatedAccount.getPassword()); + returnedAccount.setUsername("test_updatedUser"); + returnedAccount.setPassword("test_updatedPassword"); + + final Optional updatedAccount = userService.updateAccount(returnedAccount); + assertTrue(updatedAccount .isPresent()); + final Account returnedUpdatedAccount = updatedAccount.get(); + assertEquals("test_updatedUser", returnedUpdatedAccount.getUsername()); + assertEquals("test_updatedPassword", returnedUpdatedAccount.getPassword()); assertFalse(returnedUpdatedAccount.isAdministratorStatus()); final boolean result = userService.deleteAccount(returnedUpdatedAccount); - assertTrue(result); } - private Account creatAccount(){ + private Account createAccount(){ final Account testAccount = new Account(); - testAccount.setUsername("test user"); - testAccount.setPassword("test password"); + testAccount.setUsername("test_user"); + testAccount.setPassword("test_password"); testAccount.setAdministratorStatus(false); testAccount.setLastLogin(new Date()); diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index 2e7a468..593b0d9 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -26,7 +26,99 @@ public class UserService { this.restService = restService; } - public Optional createNewAccount(final Account account) { + public Optional getListOfAccount(){ + final String auth = ""; + final Instant start = Instant.now(); + + try { + final TypeToken typeToken = new TypeToken() {}; + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/", + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds, + auth); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to get the list of accounts"); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error getting the list of accounts {}", e); + return Optional.empty(); + } finally { + LOG.info("Getting the list of accounts request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } + + public Optional getAccountById(final int id) { + + if (id == 0) { + LOG.error("No user ID specified! Returning {}"); + return Optional.empty(); + } + + final String auth = ""; + final Instant start = Instant.now(); + + try { + final TypeToken typeToken = new TypeToken() {}; + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/id?id="+id, + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds, + auth); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to find account with id {}", id); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error getting account by id {}", e); + return Optional.empty(); + } finally { + LOG.info("Getting account by ID request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } + + public Optional getAccountByUsername(final String username) { + if (username == null) { + LOG.error("No username specified! Returning {}"); + return Optional.empty(); + } + + final String auth = ""; + final Instant start = Instant.now(); + + try { + final TypeToken typeToken = new TypeToken() {}; + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/username?username="+username, + typeToken, + connectionTimeoutMilliseconds, + socketTimeoutMilliseconds, + auth); + + if (persistenceApiResponse.isPresent()) { + LOG.info("Returning {}", persistenceApiResponse.get()); + } else { + LOG.info("Unable to GET account with username{}", username); + } + + return persistenceApiResponse; + } catch (final Exception e) { + LOG.error("Error getting account by username {}", e); + return Optional.empty(); + } finally { + LOG.info("Getting account by username request took {} ms", Duration.between(start, Instant.now()).toMillis()); + } + } + + public Optional createAccount(final Account account) { if (account == null) { LOG.error("Given null account, returning {}"); return Optional.empty(); @@ -58,7 +150,7 @@ public class UserService { public Optional updateAccount(final Account account) { if (account == null) { - LOG.error("User does not exist, returning {}"); + LOG.error("Specified account is null; returning {}"); return Optional.empty(); } @@ -81,7 +173,7 @@ public class UserService { if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to update user {} with id", account.getId()); + LOG.info("Unable to update user with id {}", account.getId()); } return persistenceApiResponse; @@ -95,8 +187,8 @@ public class UserService { public boolean deleteAccount(final Account account) { - if(account == null){ - LOG.error("Username does not exist, returning {}"); + if (account == null){ + LOG.error("Specified account is null; returning {}"); return false; } @@ -107,13 +199,13 @@ public class UserService { final int id = account.getId(); final Instant start = Instant.now(); - try{ + try { - final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "/accounts/" + id, + final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "accounts/" + id, connectionTimeoutMilliseconds, - socketTimeoutMilliseconds, HttpStatus.NO_CONTENT ); - if(persistenceApiResponse){ - LOG.info("return {}", persistenceApiResponse); + socketTimeoutMilliseconds, HttpStatus.NO_CONTENT); + if (persistenceApiResponse){ + LOG.info("Returning {}", persistenceApiResponse); } else { LOG.info("Unable to delete user {}", account.toString()); @@ -124,7 +216,7 @@ public class UserService { LOG.error("Error deleting user {}", e); return false; } finally { - LOG.info("delete user request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Delete user request took {} ms", Duration.between(start, Instant.now()).toMillis()); } } } diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index 7f19401..4a478d9 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -8,8 +8,9 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.text.ParseException; +import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; @@ -23,27 +24,65 @@ public class UserServiceTest { @InjectMocks private UserService userService; @Test - public void testCreateNewAccount() throws ParseException { + public void testGetListOfAccounts(){ + final Account account1 = createAccount(); + final Account account2 = createAccount(); + final List accountList = new ArrayList<>(); + accountList.add(account1); + accountList.add(account2); + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenReturn(Optional.of(accountList)); + final Optional response = userService.getListOfAccount(); + + assertTrue(response.isPresent()); + assertEquals(accountList, response.get()); + } + + @Test + public void testGetAccountById(){ final Account account = createAccount(); + account.setId(1); - when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) .thenReturn(Optional.of(account)); - - final Optional response = userService.createNewAccount(account); + final Optional response = userService.getAccountById(1); assertTrue(response.isPresent()); assertEquals(account, response.get()); } @Test - public void testUpdateAccount() throws ParseException { + public void testGetAccountByUsername(){ + final Account account = createAccount(); + final String username = account.getUsername(); + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenReturn(Optional.of(account)); + final Optional response = userService.getAccountByUsername(username); + + assertTrue(response.isPresent()); + assertEquals(account, response.get()); + } + @Test + public void testCreateAccount(){ + final Account account = createAccount(); + + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + .thenReturn(Optional.of(account)); + final Optional response = userService.createAccount(account); + + assertTrue(response.isPresent()); + assertEquals(account, response.get()); + } + + @Test + public void testUpdateAccount(){ final Account account = createAccount(); account.setId(1); when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) .thenReturn(Optional.of(account)); - final Optional response = userService.updateAccount(account); assertTrue(response.isPresent()); @@ -51,14 +90,13 @@ public class UserServiceTest { } @Test - public void testDeleteAccount() throws ParseException { + public void testDeleteAccount(){ final boolean response= true; final Account account = createAccount(); account.setId(1); when(restService.delete(anyString(), anyInt(), anyInt(), any())) .thenReturn(response); - final boolean persistenceApiResponse = userService.deleteAccount(account); assertTrue(persistenceApiResponse ); diff --git a/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java b/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java new file mode 100644 index 0000000..70247ff --- /dev/null +++ b/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java @@ -0,0 +1,35 @@ +package edu.msudenver.tsp.website.controller; + +import edu.msudenver.tsp.website.forms.TheoremForm; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + + + @Slf4j + @Controller + @AllArgsConstructor + @RequestMapping("/login") + public class LogInController { + @GetMapping({"/",""}) + public ModelAndView enterTheoremPage() { + LOG.info("Received request to display the theorem entry page: returning model with name 'Theorem'"); + return new ModelAndView("Theorem"); + } + + @PostMapping({"/",""}) + public String saveTheorem(@Validated final TheoremForm theoremForm, final Model model) { + model.addAttribute("theoremName", theoremForm.getTheoremName()); + model.addAttribute("theorem", theoremForm.getTheorem()); + LOG.info("Saving theorem {}...", theoremForm); + + return "success"; + } + } +} From adbcd786f0cd20caca30f4621150678f769730c6 Mon Sep 17 00:00:00 2001 From: dantanxiaotian Date: Tue, 2 Apr 2019 16:38:54 -0600 Subject: [PATCH 30/44] PAN-15 fix the request changes --- .../msudenver/tsp/services/UserService.java | 8 +- .../tsp/services/UserServiceTest.java | 221 +++++++++++++++++- .../website/controller/LogInController.java | 35 --- 3 files changed, 216 insertions(+), 48 deletions(-) delete mode 100644 src/main/java/edu/msudenver/tsp/website/controller/LogInController.java diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index 593b0d9..d5333f0 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -27,7 +27,7 @@ public class UserService { } public Optional getListOfAccount(){ - final String auth = ""; + final String auth = null; final Instant start = Instant.now(); try { @@ -60,7 +60,7 @@ public class UserService { return Optional.empty(); } - final String auth = ""; + final String auth = null; final Instant start = Instant.now(); try { @@ -92,7 +92,7 @@ public class UserService { return Optional.empty(); } - final String auth = ""; + final String auth = null; final Instant start = Instant.now(); try { @@ -208,7 +208,7 @@ public class UserService { LOG.info("Returning {}", persistenceApiResponse); } else { - LOG.info("Unable to delete user {}", account.toString()); + LOG.info("Unable to delete user {}"); } return persistenceApiResponse; diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index 4a478d9..6debc4a 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -13,10 +13,8 @@ import java.util.Date; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @@ -39,10 +37,41 @@ public class UserServiceTest { assertEquals(accountList, response.get()); } + @Test + public void testGetListOfAccounts_persistenceApiResponseIsNotPresent(){ + final Account account1 = createAccount(); + final Account account2 = createAccount(); + final List accountList = new ArrayList<>(); + accountList.add(account1); + accountList.add(account2); + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenReturn(Optional.empty()); + final Optional response = userService.getListOfAccount(); + + assertFalse(response.isPresent()); + } + + @Test + public void testGetListOfAccounts_catchException(){ + final Account account1 = createAccount(); + final Account account2 = createAccount(); + final List accountList = new ArrayList<>(); + accountList.add(account1); + accountList.add(account2); + final Exception e = new Exception(); + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenThrow(Exception.class); + final Optional response = userService.getListOfAccount(); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + } + @Test public void testGetAccountById(){ final Account account = createAccount(); - account.setId(1); when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) .thenReturn(Optional.of(account)); @@ -50,20 +79,74 @@ public class UserServiceTest { assertTrue(response.isPresent()); assertEquals(account, response.get()); + verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); + } + + @Test + public void testGetAccountById_nullId() { + final Optional response = userService.getAccountById(0); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + verifyZeroInteractions(restService); + } + + @Test + public void testGetAccountById_persistenceApiResponseIsNotPresent(){ + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenReturn(Optional.empty()); + final Optional response = userService.getAccountById(1); + + assertFalse(response.isPresent()); + verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); + } + + @Test + public void testGetAccountById_catchException(){ + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenThrow(Exception.class); + final Optional response = userService.getAccountById(1); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); } @Test public void testGetAccountByUsername(){ final Account account = createAccount(); - final String username = account.getUsername(); when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) .thenReturn(Optional.of(account)); - final Optional response = userService.getAccountByUsername(username); + final Optional response = userService.getAccountByUsername(account.getUsername()); assertTrue(response.isPresent()); assertEquals(account, response.get()); + verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); } + + @Test + public void testGetAccountByUsername_nullUsername(){ + final Optional response = userService.getAccountByUsername(null); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + verifyZeroInteractions(restService); + } + + @Test + public void testGetAccountByUsername_persistenceApiResponseIsNotPresent(){ + final Account account = createAccount(); + + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) + .thenReturn(Optional.empty()); + final Optional response = userService.getAccountByUsername(account.getUsername()); + + assertFalse(response.isPresent()); + verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); + } + @Test public void testCreateAccount(){ final Account account = createAccount(); @@ -74,6 +157,27 @@ public class UserServiceTest { assertTrue(response.isPresent()); assertEquals(account, response.get()); + verify(restService).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testCreateAccount_NoAccountFound() { + final Optional response = userService.createAccount(null); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + verify(restService, times(0)).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testCreateAccount_catchException(){ + final Account account = createAccount(); + + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class); + final Optional response = userService.createAccount(account); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); } @Test @@ -87,6 +191,54 @@ public class UserServiceTest { assertTrue(response.isPresent()); assertEquals(account, response.get()); + verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testUpdateAccount_nullAccount(){ + final Optional response = userService.updateAccount(null); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + verify(restService, times(0)).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testUpdateAccount_nullId(){ + final Account account = createAccount(); + account.setId(0); + + final Optional response = userService.updateAccount(account); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + verify(restService, times(0)).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testUpdateAccount_PersistenceApiResponseIsNotPresent(){ + final Account account = createAccount(); + account.setId(1); + + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + .thenReturn(Optional.empty()); + final Optional response = userService.updateAccount(account); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); + } + + @Test + public void testUpdateAccount_catchException(){ + final Account account = createAccount(); + account.setId(1); + + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) + .thenThrow(Exception.class); + final Optional response = userService.updateAccount(account); + + assertFalse(response.isPresent()); + assertEquals(Optional.empty(), response); } @Test @@ -99,8 +251,59 @@ public class UserServiceTest { .thenReturn(response); final boolean persistenceApiResponse = userService.deleteAccount(account); - assertTrue(persistenceApiResponse ); - assertEquals(response, persistenceApiResponse ); + assertNotNull(persistenceApiResponse); + assertTrue(persistenceApiResponse); + assertEquals(response, persistenceApiResponse); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteAccount_nullAccount(){ + final boolean persistenceApiResponse = userService.deleteAccount(null); + + assertNotNull(persistenceApiResponse); + assertFalse(persistenceApiResponse); + verify(restService, times(0)).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteAccount_nullId(){ + final Account account = createAccount(); + account.setId(0); + + final boolean persistenceApiResponse = userService.deleteAccount(account); + + assertNotNull(persistenceApiResponse); + assertFalse(persistenceApiResponse); + verify(restService, times(0)).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteAccount_persistenceApiResponseIsNotPresent(){ + final boolean response= false; + final Account account = createAccount(); + account.setId(1); + + when(restService.delete(anyString(), anyInt(), anyInt(), any())) + .thenReturn(response); + final boolean persistenceApiResponse = userService.deleteAccount(account); + + assertNotNull(persistenceApiResponse); + assertFalse(persistenceApiResponse); + assertEquals(response, persistenceApiResponse); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); + } + + @Test + public void testDeleteAccount_catchException(){ + final Account account = createAccount(); + account.setId(1); + + when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenThrow(Exception.class); + final boolean persistenceApiResponse = userService.deleteAccount(account); + + assertNotNull(persistenceApiResponse); + assertFalse(persistenceApiResponse); } diff --git a/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java b/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java deleted file mode 100644 index 70247ff..0000000 --- a/src/main/java/edu/msudenver/tsp/website/controller/LogInController.java +++ /dev/null @@ -1,35 +0,0 @@ -package edu.msudenver.tsp.website.controller; - -import edu.msudenver.tsp.website.forms.TheoremForm; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; - - - @Slf4j - @Controller - @AllArgsConstructor - @RequestMapping("/login") - public class LogInController { - @GetMapping({"/",""}) - public ModelAndView enterTheoremPage() { - LOG.info("Received request to display the theorem entry page: returning model with name 'Theorem'"); - return new ModelAndView("Theorem"); - } - - @PostMapping({"/",""}) - public String saveTheorem(@Validated final TheoremForm theoremForm, final Model model) { - model.addAttribute("theoremName", theoremForm.getTheoremName()); - model.addAttribute("theorem", theoremForm.getTheorem()); - LOG.info("Saving theorem {}...", theoremForm); - - return "success"; - } - } -} From 36036b710de0ccc24e3977a11e1f677ce167231a Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 15:18:19 -0600 Subject: [PATCH 31/44] PAN-15 Finished Unit Tests --- .../services/UserServiceIntegrationTest.java | 6 +- .../msudenver/tsp/services/UserService.java | 63 +++--- .../tsp/services/UserServiceTest.java | 209 +++++++++--------- 3 files changed, 136 insertions(+), 142 deletions(-) diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index b3a547d..be36c25 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -33,14 +33,14 @@ public class UserServiceIntegrationTest { assertEquals("test_password", returnedAccount.getPassword()); assertFalse(returnedAccount.isAdministratorStatus()); - final Optional getAccountById = userService.getAccountById(returnedAccount.getId()); + final Optional getAccountById = userService.findAccountById(returnedAccount.getId()); assertTrue(getAccountById.isPresent()); final Account returnedAccountById = getAccountById.get(); assertEquals("test_user", returnedAccountById.getUsername()); assertEquals("test_password", returnedAccountById.getPassword()); assertFalse(returnedAccountById.isAdministratorStatus()); - final Optional getAccountByUsername = userService.getAccountByUsername(returnedAccount.getUsername()); + final Optional getAccountByUsername = userService.findAccountByUsername(returnedAccount.getUsername()); assertTrue(getAccountByUsername.isPresent()); final Account returnedAccountByUsername = getAccountByUsername.get(); assertEquals("test_user", returnedAccountByUsername.getUsername()); @@ -61,7 +61,7 @@ public class UserServiceIntegrationTest { assertTrue(result); } - private Account createAccount(){ + private Account createAccount() { final Account testAccount = new Account(); testAccount.setUsername("test_user"); testAccount.setPassword("test_password"); diff --git a/services/src/main/java/edu/msudenver/tsp/services/UserService.java b/services/src/main/java/edu/msudenver/tsp/services/UserService.java index d5333f0..3125824 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/UserService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/UserService.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Service; import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Optional; @Slf4j @@ -26,95 +27,92 @@ public class UserService { this.restService = restService; } - public Optional getListOfAccount(){ - final String auth = null; + public Optional> getListOfAccounts() { final Instant start = Instant.now(); try { - final TypeToken typeToken = new TypeToken() {}; - final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/", + final TypeToken> typeToken = new TypeToken>() {}; + final Optional> persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/", typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, - auth); + null); if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to get the list of accounts"); + LOG.warn("Unable to get the list of accounts"); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error getting the list of accounts {}", e); + LOG.error("Error getting the list of accounts", e); return Optional.empty(); } finally { - LOG.info("Getting the list of accounts request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Get the list of accounts request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } - public Optional getAccountById(final int id) { + public Optional findAccountById(final int id) { if (id == 0) { LOG.error("No user ID specified! Returning {}"); return Optional.empty(); } - final String auth = null; final Instant start = Instant.now(); try { final TypeToken typeToken = new TypeToken() {}; - final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/id?id="+id, + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/id?id=" + id, typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, - auth); + null); if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to find account with id {}", id); + LOG.warn("Unable to find account with id {}", id); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error getting account by id {}", e); + LOG.error("Error finding account by id", e); return Optional.empty(); } finally { - LOG.info("Getting account by ID request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Find account by ID request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } - public Optional getAccountByUsername(final String username) { + public Optional findAccountByUsername(final String username) { if (username == null) { LOG.error("No username specified! Returning {}"); return Optional.empty(); } - final String auth = null; final Instant start = Instant.now(); try { final TypeToken typeToken = new TypeToken() {}; - final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/username?username="+username, + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/username?username=" + username, typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, - auth); + null); if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to GET account with username{}", username); + LOG.warn("Unable to GET account with username {}", username); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error getting account by username {}", e); + LOG.error("Error finding account by username", e); return Optional.empty(); } finally { - LOG.info("Getting account by username request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Find account by username request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } @@ -136,15 +134,15 @@ public class UserService { if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to create new account {}", account.toString()); + LOG.warn("Unable to create new account {}", account.toString()); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error creating new account {}", e); + LOG.error("Error creating new account", e); return Optional.empty(); } finally { - LOG.info("Create new account request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Create new account request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } @@ -173,15 +171,15 @@ public class UserService { if (persistenceApiResponse.isPresent()) { LOG.info("Returning {}", persistenceApiResponse.get()); } else { - LOG.info("Unable to update user with id {}", account.getId()); + LOG.warn("Unable to update user with id {}", account.getId()); } return persistenceApiResponse; } catch (final Exception e) { - LOG.error("Error updating user {}", e); + LOG.error("Error updating user", e); return Optional.empty(); } finally { - LOG.info("Update user request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Update user request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } @@ -196,6 +194,7 @@ public class UserService { LOG.error("No user ID specified! Returning {}"); return false; } + final int id = account.getId(); final Instant start = Instant.now(); @@ -204,19 +203,19 @@ public class UserService { final boolean persistenceApiResponse = restService.delete(persistenceApiBaseUrl + "accounts/" + id, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, HttpStatus.NO_CONTENT); - if (persistenceApiResponse){ + if (persistenceApiResponse) { LOG.info("Returning {}", persistenceApiResponse); } else { - LOG.info("Unable to delete user {}"); + LOG.error("Unable to delete user {}", account); } return persistenceApiResponse; }catch (final Exception e) { - LOG.error("Error deleting user {}", e); + LOG.error("Error deleting user", e); return false; } finally { - LOG.info("Delete user request took {} ms", Duration.between(start, Instant.now()).toMillis()); + LOG.info("Delete user request took {}ms", Duration.between(start, Instant.now()).toMillis()); } } } diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index 6debc4a..1d42311 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -22,60 +22,47 @@ public class UserServiceTest { @InjectMocks private UserService userService; @Test - public void testGetListOfAccounts(){ - final Account account1 = createAccount(); - final Account account2 = createAccount(); + public void testGetListOfAccounts() { final List accountList = new ArrayList<>(); - accountList.add(account1); - accountList.add(account2); + accountList.add(createAccount()); + accountList.add(createAccount()); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.of(accountList)); - final Optional response = userService.getListOfAccount(); + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(), anyString())).thenReturn(Optional.of(accountList)); + + final Optional> response = userService.getListOfAccounts(); assertTrue(response.isPresent()); assertEquals(accountList, response.get()); + verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString()); } @Test - public void testGetListOfAccounts_persistenceApiResponseIsNotPresent(){ - final Account account1 = createAccount(); - final Account account2 = createAccount(); - final List accountList = new ArrayList<>(); - accountList.add(account1); - accountList.add(account2); + public void testGetListOfAccounts_PersistenceApiResponseIsEmpty() { + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty()); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.empty()); - final Optional response = userService.getListOfAccount(); + final Optional> response = userService.getListOfAccounts(); assertFalse(response.isPresent()); + verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString()); } @Test - public void testGetListOfAccounts_catchException(){ - final Account account1 = createAccount(); - final Account account2 = createAccount(); - final List accountList = new ArrayList<>(); - accountList.add(account1); - accountList.add(account2); - final Exception e = new Exception(); + public void testGetListOfAccounts_RestServiceThrowsException() { + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenThrow(Exception.class); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenThrow(Exception.class); - final Optional response = userService.getListOfAccount(); + final Optional> response = userService.getListOfAccounts(); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); + verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString()); } @Test - public void testGetAccountById(){ + public void testFindAccountById() { final Account account = createAccount(); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.of(account)); - final Optional response = userService.getAccountById(1); + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.of(account)); + + final Optional response = userService.findAccountById(1); assertTrue(response.isPresent()); assertEquals(account, response.get()); @@ -83,8 +70,8 @@ public class UserServiceTest { } @Test - public void testGetAccountById_nullId() { - final Optional response = userService.getAccountById(0); + public void testFindAccountById_IdEqualsZero() { + final Optional response = userService.findAccountById(0); assertFalse(response.isPresent()); assertEquals(Optional.empty(), response); @@ -92,34 +79,32 @@ public class UserServiceTest { } @Test - public void testGetAccountById_persistenceApiResponseIsNotPresent(){ + public void testFindAccountById_PersistenceApiResponseIsEmpty() { + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty()); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.empty()); - final Optional response = userService.getAccountById(1); + final Optional response = userService.findAccountById(1); assertFalse(response.isPresent()); verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); } @Test - public void testGetAccountById_catchException(){ + public void testFindAccountById_RestServiceThrowsException() { + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenThrow(Exception.class); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenThrow(Exception.class); - final Optional response = userService.getAccountById(1); + final Optional response = userService.findAccountById(1); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); + verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString()); } @Test - public void testGetAccountByUsername(){ + public void testFindAccountByUsername() { final Account account = createAccount(); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.of(account)); - final Optional response = userService.getAccountByUsername(account.getUsername()); + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.of(account)); + + final Optional response = userService.findAccountByUsername(account.getUsername()); assertTrue(response.isPresent()); assertEquals(account, response.get()); @@ -127,8 +112,8 @@ public class UserServiceTest { } @Test - public void testGetAccountByUsername_nullUsername(){ - final Optional response = userService.getAccountByUsername(null); + public void testFindAccountByUsername_NullUsername() { + final Optional response = userService.findAccountByUsername(null); assertFalse(response.isPresent()); assertEquals(Optional.empty(), response); @@ -136,23 +121,33 @@ public class UserServiceTest { } @Test - public void testGetAccountByUsername_persistenceApiResponseIsNotPresent(){ + public void testFindAccountByUsername_PersistenceApiResponseIsEmpty() { final Account account = createAccount(); - when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())) - .thenReturn(Optional.empty()); - final Optional response = userService.getAccountByUsername(account.getUsername()); + when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty()); + + final Optional response = userService.findAccountByUsername(account.getUsername()); assertFalse(response.isPresent()); verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString()); } @Test - public void testCreateAccount(){ + public void testFindAccountByUsername_RestServiceThrowsException() { + when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())).thenThrow(Exception.class); + + final Optional response = userService.findAccountByUsername("test"); + + assertFalse(response.isPresent()); + verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString()); + } + + @Test + public void testCreateAccount() { final Account account = createAccount(); - when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) - .thenReturn(Optional.of(account)); + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.of(account)); + final Optional response = userService.createAccount(account); assertTrue(response.isPresent()); @@ -161,7 +156,7 @@ public class UserServiceTest { } @Test - public void testCreateAccount_NoAccountFound() { + public void testCreateAccount_NullAccount() { final Optional response = userService.createAccount(null); assertFalse(response.isPresent()); @@ -170,23 +165,32 @@ public class UserServiceTest { } @Test - public void testCreateAccount_catchException(){ - final Account account = createAccount(); + public void testCreateAccount_AccountCouldNotBeCreated() { + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.empty()); - when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class); - final Optional response = userService.createAccount(account); + final Optional response = userService.createAccount(createAccount()); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); + verify(restService).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); } @Test - public void testUpdateAccount(){ + public void testCreateAccount_RestServiceThrowsException() { + when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class); + + final Optional response = userService.createAccount(createAccount()); + + assertFalse(response.isPresent()); + verify(restService).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + } + + @Test + public void testUpdateAccount() { final Account account = createAccount(); account.setId(1); - when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) - .thenReturn(Optional.of(account)); + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.of(account)); + final Optional response = userService.updateAccount(account); assertTrue(response.isPresent()); @@ -195,115 +199,106 @@ public class UserServiceTest { } @Test - public void testUpdateAccount_nullAccount(){ + public void testUpdateAccount_NullAccount() { final Optional response = userService.updateAccount(null); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); - verify(restService, times(0)).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + verifyZeroInteractions(restService); } @Test - public void testUpdateAccount_nullId(){ + public void testUpdateAccount_IdEqualsZero() { final Account account = createAccount(); account.setId(0); final Optional response = userService.updateAccount(account); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); - verify(restService, times(0)).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); + verifyZeroInteractions(restService); } @Test - public void testUpdateAccount_PersistenceApiResponseIsNotPresent(){ + public void testUpdateAccount_PersistenceApiResponseIsEmpty() { final Account account = createAccount(); account.setId(1); - when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) - .thenReturn(Optional.empty()); + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.empty()); + final Optional response = userService.updateAccount(account); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); + verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); } @Test - public void testUpdateAccount_catchException(){ + public void testUpdateAccount_RestServiceThrowsException() { final Account account = createAccount(); account.setId(1); - when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())) - .thenThrow(Exception.class); + when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class); + final Optional response = userService.updateAccount(account); assertFalse(response.isPresent()); - assertEquals(Optional.empty(), response); + verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt()); } @Test - public void testDeleteAccount(){ - final boolean response= true; + public void testDeleteAccount() { final Account account = createAccount(); account.setId(1); - when(restService.delete(anyString(), anyInt(), anyInt(), any())) - .thenReturn(response); - final boolean persistenceApiResponse = userService.deleteAccount(account); + when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenReturn(true); - assertNotNull(persistenceApiResponse); - assertTrue(persistenceApiResponse); - assertEquals(response, persistenceApiResponse); + final boolean isDeleteSuccessful = userService.deleteAccount(account); + + assertTrue(isDeleteSuccessful); verify(restService).delete(anyString(), anyInt(), anyInt(), any()); } @Test - public void testDeleteAccount_nullAccount(){ - final boolean persistenceApiResponse = userService.deleteAccount(null); + public void testDeleteAccount_NullAccount() { + final boolean isDeleteSuccessful = userService.deleteAccount(null); - assertNotNull(persistenceApiResponse); - assertFalse(persistenceApiResponse); - verify(restService, times(0)).delete(anyString(), anyInt(), anyInt(), any()); + assertFalse(isDeleteSuccessful); + verifyZeroInteractions(restService); } @Test - public void testDeleteAccount_nullId(){ + public void testDeleteAccount_IdEqualsZero() { final Account account = createAccount(); account.setId(0); - final boolean persistenceApiResponse = userService.deleteAccount(account); + final boolean isDeleteSuccessful = userService.deleteAccount(account); - assertNotNull(persistenceApiResponse); - assertFalse(persistenceApiResponse); - verify(restService, times(0)).delete(anyString(), anyInt(), anyInt(), any()); + assertFalse(isDeleteSuccessful); + verifyZeroInteractions(restService); } @Test - public void testDeleteAccount_persistenceApiResponseIsNotPresent(){ - final boolean response= false; + public void testDeleteAccount_PersistenceApiResponseIsEmpty() { final Account account = createAccount(); account.setId(1); - when(restService.delete(anyString(), anyInt(), anyInt(), any())) - .thenReturn(response); - final boolean persistenceApiResponse = userService.deleteAccount(account); + when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenReturn(false); - assertNotNull(persistenceApiResponse); - assertFalse(persistenceApiResponse); - assertEquals(response, persistenceApiResponse); + final boolean isDeleteSuccessful = userService.deleteAccount(account); + + assertFalse(isDeleteSuccessful); verify(restService).delete(anyString(), anyInt(), anyInt(), any()); } @Test - public void testDeleteAccount_catchException(){ + public void testDeleteAccount_RestServiceThrowsException() { final Account account = createAccount(); account.setId(1); when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenThrow(Exception.class); + final boolean persistenceApiResponse = userService.deleteAccount(account); - assertNotNull(persistenceApiResponse); assertFalse(persistenceApiResponse); + verify(restService).delete(anyString(), anyInt(), anyInt(), any()); } From 609f018f9f8c9f1837d2610dbb9346320df3d569 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 16:21:18 -0600 Subject: [PATCH 32/44] PAN-11 Fixed integration tests --- .../tsp/persistence/AccountsIntegrationTest.java | 4 ++-- .../edu/msudenver/tsp/persistence/dto/Account.java | 12 +----------- .../controller/AccountControllerTest.java | 6 ++---- 3 files changed, 5 insertions(+), 17 deletions(-) diff --git a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java index fbb3a21..7cd5abd 100644 --- a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java +++ b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java @@ -29,7 +29,7 @@ public class AccountsIntegrationTest { assertEquals("Test username", savedAccount.getUsername()); assertEquals("test password", savedAccount.getPassword()); - assertTrue(savedAccount.getAdministrator()); + assertTrue(savedAccount.isAdministrator()); savedAccount.setPassword("Test Update"); @@ -37,7 +37,7 @@ public class AccountsIntegrationTest { assertEquals("Test username", savedAccount.getUsername()); assertEquals("Test Update", savedAccount.getPassword()); - assertTrue(savedAccount.getAdministrator()); + assertTrue(savedAccount.isAdministrator()); assertEquals(updatedAccount.getId(), id); accountsRepository.delete(account); diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java index 14141f1..674d83b 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java @@ -19,21 +19,11 @@ import java.util.Date; public class Account extends BaseDto implements Serializable { @NotBlank(groups = Insert.class, message = "A username must be specified") @Size(max = 50) private String username; @NotBlank(groups = Insert.class, message = "A password must be specified") @Size(max = 256) private String password; - @NotNull @Column(name = "administrator") private boolean administrator; + @NotNull private boolean administrator; @Temporal(TemporalType.DATE) @Column(name = "last_login") private Date lastLogin; private static final long serialVersionUID = 7095627971593953734L; - @JsonProperty("administrator_status") - public boolean getAdministrator() { - return administrator; - } - - @JsonProperty("administrator_status") - public void setAdministrator(final boolean administrator) { - this.administrator = administrator; - } - @JsonProperty("last_login") public Date getLastLogin() { return lastLogin; diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java index 446e10b..4ffd766 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java @@ -25,10 +25,8 @@ import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) @WebMvcTest(controllers = AccountController.class) public class AccountControllerTest { - @Mock - private AccountsRepository accountsRepository; - @InjectMocks - private AccountController accountController; + @Mock private AccountsRepository accountsRepository; + @InjectMocks private AccountController accountController; @Mock private BindingResult bindingResult; @Test From c75b243df89e6ce2567ffce44f0079929f235f4a Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 16:51:36 -0600 Subject: [PATCH 33/44] PAN-11 Fixed integration tests --- .../DefinitionServiceIntegrationTest.java | 2 +- .../tsp/services/ServiceTestConfig.java | 17 ----------------- .../tsp/services/ServicesTestConfig.java | 6 ++++++ .../services/UserServiceIntegrationTest.java | 2 +- 4 files changed, 8 insertions(+), 19 deletions(-) delete mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java index a8a137f..5bd042d 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java @@ -18,7 +18,7 @@ import static org.junit.Assert.*; import static org.mockito.AdditionalMatchers.not; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ServiceTestConfig.class) +@ContextConfiguration(classes = ServicesTestConfig.class) @TestPropertySource(locations = "classpath:test.properties") public class DefinitionServiceIntegrationTest { @Autowired private DefinitionService definitionService; diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java deleted file mode 100644 index 1d9d54e..0000000 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServiceTestConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package edu.msudenver.tsp.services; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan -public class ServiceTestConfig { - - @Bean - @Autowired - public DefinitionService definitionService(final RestService restService) { - return new DefinitionService(restService); - } -} diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java index 4c9e2b4..40fd162 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java @@ -14,4 +14,10 @@ public class ServicesTestConfig { public UserService userService(final RestService restService) { return new UserService(restService); } + + @Bean + @Autowired + public DefinitionService definitionService(final RestService restService) { + return new DefinitionService(restService); + } } diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index bb7a4e8..64fd7ad 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -23,7 +23,7 @@ public class UserServiceIntegrationTest { private UserService userService; @Test - public void testUserService(){ + public void testCRUD() { final Account testAccount = createAccount(); final Optional testCreatedAccount = userService.createAccount(testAccount); From 67f77d6c9ede188ff556ff1b781cbda182c32b38 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 17:06:43 -0600 Subject: [PATCH 34/44] PAN-11 Fixed integration tests --- .../DefinitionServiceIntegrationTest.java | 86 ------------------- 1 file changed, 86 deletions(-) delete mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java deleted file mode 100644 index 5bd042d..0000000 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package edu.msudenver.tsp.services; - -import edu.msudenver.tsp.services.dto.Definition; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; -import static org.mockito.AdditionalMatchers.not; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ServicesTestConfig.class) -@TestPropertySource(locations = "classpath:test.properties") -public class DefinitionServiceIntegrationTest { - @Autowired private DefinitionService definitionService; - - @Test - public void testCRUD() { - final Definition testDefinition = createDefinition(); - final Optional createdDefinition = definitionService.createDefinition(testDefinition); - - assertTrue(createdDefinition.isPresent()); - assertThat(createdDefinition.get().getId(), is(not(0))); - assertThat(createdDefinition.get().getVersion(), is(0)); - assertThat(createdDefinition.get().getName(), is("Test Name")); - assertNotNull(createdDefinition.get().getDefinition()); - assertThat(createdDefinition.get().getDefinition().size(), is(1)); - assertThat(createdDefinition.get().getDefinition().get(0), is("Test definition 1")); - assertNotNull(createdDefinition.get().getNotation()); - assertThat(createdDefinition.get().getNotation().size(), is(1)); - assertThat(createdDefinition.get().getNotation().get(0), is("\\testLaTeX")); - - final Optional definitionFoundById = definitionService.findById(createdDefinition.get().getId()); - - assertThat(definitionFoundById.get(), is(equalTo(createdDefinition.get()))); - - final Definition definitionUpdate = new Definition(); - definitionUpdate.setId(createdDefinition.get().getId()); - definitionUpdate.setName("Test Update"); - - final Optional updatedDefinition = definitionService.updateDefinition(definitionUpdate); - - assertTrue(updatedDefinition.isPresent()); - assertThat(updatedDefinition.get().getId(), is(not(0))); - assertThat(updatedDefinition.get().getVersion(), is(1)); - assertThat(updatedDefinition.get().getName(), is("Test Update")); - assertNotNull(updatedDefinition.get().getDefinition()); - assertThat(updatedDefinition.get().getDefinition().size(), is(1)); - assertThat(updatedDefinition.get().getDefinition().get(0), is("Test definition 1")); - assertNotNull(updatedDefinition.get().getNotation()); - assertThat(updatedDefinition.get().getNotation().size(), is(1)); - assertThat(updatedDefinition.get().getNotation().get(0), is("\\testLaTeX")); - - final boolean deletionWasSuccessful = definitionService.deleteDefinition(updatedDefinition.get()); - - assertThat(deletionWasSuccessful, is(true)); - - final Optional deletedDefinitionFoundById = definitionService.findById(createdDefinition.get().getId()); - - assertFalse(deletedDefinitionFoundById.isPresent()); - } - - private Definition createDefinition() { - final List definitionList = new ArrayList<>(); - definitionList.add("Test definition 1"); - - final List notationList = new ArrayList<>(); - notationList.add("\\testLaTeX"); - - final Definition definition = new Definition(); - definition.setName("Test Name"); - definition.setDefinition(definitionList); - definition.setNotation(notationList); - - return definition; - } -} From 091215f1eb617ac83a74a6a781334e32350ad27f Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 17:22:08 -0600 Subject: [PATCH 35/44] PAN-11 Fixed integration tests --- .../java/edu/msudenver/tsp/services/ServicesTestConfig.java | 6 ------ services/src/integrationTest/resources/test.properties | 6 +++--- .../main/java/edu/msudenver/tsp/services/dto/Account.java | 4 +++- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java index 40fd162..4c9e2b4 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/ServicesTestConfig.java @@ -14,10 +14,4 @@ public class ServicesTestConfig { public UserService userService(final RestService restService) { return new UserService(restService); } - - @Bean - @Autowired - public DefinitionService definitionService(final RestService restService) { - return new DefinitionService(restService); - } } diff --git a/services/src/integrationTest/resources/test.properties b/services/src/integrationTest/resources/test.properties index ff86c7e..3690a57 100644 --- a/services/src/integrationTest/resources/test.properties +++ b/services/src/integrationTest/resources/test.properties @@ -1,3 +1,3 @@ -persistence.api.connection.timeout.milliseconds = 5000 -persistence.api.socket.timeout.milliseconds = 10000 -persistence.api.base.url = http://localhost:8090/ \ No newline at end of file +persistence.api.connection.timeout.milliseconds=5000 +persistence.api.socket.timeout.milliseconds=10000 +persistence.api.base.url=http://localhost:8090/ diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index 54127ba..f04a108 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -4,6 +4,8 @@ import com.google.gson.annotations.SerializedName; import lombok.Data; import lombok.EqualsAndHashCode; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; @@ -15,7 +17,7 @@ public class Account extends BaseDto implements Serializable { @Size(max = 50) private String username; @Size(max = 256) private String password; @NotNull private boolean administrator; - @SerializedName("last_login") private Date lastLogin; + @Temporal(TemporalType.DATE) @SerializedName("last_login") private Date lastLogin; private static final long serialVersionUID = 7095627971593953734L; } From c8600b8bb45565693127e5cd254cae7f52c8405d Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 17:30:34 -0600 Subject: [PATCH 36/44] PAN-11 Fixed integration tests --- services/build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/services/build.gradle b/services/build.gradle index 2d22968..4b57a8d 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -23,6 +23,7 @@ dependencies { compile group: 'com.google.code.gson', name: 'gson', version: '2.7' compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.5.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.5.RELEASE' + compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2' compile fileTree(dir: 'lib', include: '**/*.jar') testCompile "org.springframework:spring-test:5.0.9.RELEASE" From 12f7d7f35925a7167aa6ae8ac092b7b3bfd1c675 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 18:00:12 -0600 Subject: [PATCH 37/44] PAN-11 fixed all integration tests --- .../scripts/mysql/local_development.sql | 5 +- services/build.gradle | 2 +- .../DefinitionServiceIntegrationTest.java | 85 +++++++++++++++++++ .../tsp/services/DefinitionService.java | 6 +- .../tsp/services/DefinitionServiceTest.java | 4 +- 5 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java diff --git a/persistence/scripts/mysql/local_development.sql b/persistence/scripts/mysql/local_development.sql index bfb1811..9650f22 100644 --- a/persistence/scripts/mysql/local_development.sql +++ b/persistence/scripts/mysql/local_development.sql @@ -36,7 +36,7 @@ version int default 1 ); create table proofs ( - id int not null auto_increment primary key unique, + id int not null auto_increment, theorem_name varchar(512) not null, proof varchar(4096) not null, branch varchar(512) not null, @@ -45,5 +45,6 @@ create table proofs referenced_theorems json, date_added date, last_updated date, - version int default 1 + version int default 1, + primary key (id) ); \ No newline at end of file diff --git a/services/build.gradle b/services/build.gradle index 4b57a8d..0873510 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -27,6 +27,6 @@ dependencies { compile fileTree(dir: 'lib', include: '**/*.jar') testCompile "org.springframework:spring-test:5.0.9.RELEASE" - testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE' testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'org.springframework', name: 'spring-test', version: '5.1.5.RELEASE' } diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java new file mode 100644 index 0000000..9aff2fc --- /dev/null +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/DefinitionServiceIntegrationTest.java @@ -0,0 +1,85 @@ +package edu.msudenver.tsp.services; + +import edu.msudenver.tsp.services.dto.Definition; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ServicesTestConfig.class) +@TestPropertySource(locations = "classpath:test.properties") +public class DefinitionServiceIntegrationTest { + @Autowired private DefinitionService definitionService; + + @Test + public void testCRUD() { + final Definition testDefinition = createDefinition(); + final Optional createdDefinition = definitionService.createDefinition(testDefinition); + + assertTrue(createdDefinition.isPresent()); + assertNotEquals(0, createdDefinition.get().getId()); + assertThat(createdDefinition.get().getVersion(), is(0)); + assertThat(createdDefinition.get().getName(), is("Test Name")); + assertNotNull(createdDefinition.get().getDefinition()); + assertThat(createdDefinition.get().getDefinition().size(), is(1)); + assertThat(createdDefinition.get().getDefinition().get(0), is("Test definition 1")); + assertNotNull(createdDefinition.get().getNotation()); + assertThat(createdDefinition.get().getNotation().size(), is(1)); + assertThat(createdDefinition.get().getNotation().get(0), is("\\testLaTeX")); + + final Optional definitionFoundById = definitionService.findById(createdDefinition.get().getId()); + + assertThat(definitionFoundById.get(), is(equalTo(createdDefinition.get()))); + + final Definition definitionUpdate = new Definition(); + definitionUpdate.setId(createdDefinition.get().getId()); + definitionUpdate.setName("Test Update"); + + final Optional updatedDefinition = definitionService.updateDefinition(definitionUpdate); + + assertTrue(updatedDefinition.isPresent()); + assertNotEquals(0, updatedDefinition.get().getId()); + assertThat(updatedDefinition.get().getVersion(), is(1)); + assertThat(updatedDefinition.get().getName(), is("Test Update")); + assertNotNull(updatedDefinition.get().getDefinition()); + assertThat(updatedDefinition.get().getDefinition().size(), is(1)); + assertThat(updatedDefinition.get().getDefinition().get(0), is("Test definition 1")); + assertNotNull(updatedDefinition.get().getNotation()); + assertThat(updatedDefinition.get().getNotation().size(), is(1)); + assertThat(updatedDefinition.get().getNotation().get(0), is("\\testLaTeX")); + + final boolean deletionWasSuccessful = definitionService.deleteDefinition(updatedDefinition.get()); + + assertThat(deletionWasSuccessful, is(true)); + + final Optional deletedDefinitionFoundById = definitionService.findById(createdDefinition.get().getId()); + + assertFalse(deletedDefinitionFoundById.isPresent()); + } + + private Definition createDefinition() { + final List definitionList = new ArrayList<>(); + definitionList.add("Test definition 1"); + + final List notationList = new ArrayList<>(); + notationList.add("\\testLaTeX"); + + final Definition definition = new Definition(); + definition.setName("Test Name"); + definition.setDefinition(definitionList); + definition.setNotation(notationList); + + return definition; + } +} diff --git a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java index 967e0c6..68472ea 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java +++ b/services/src/main/java/edu/msudenver/tsp/services/DefinitionService.java @@ -62,7 +62,7 @@ public class DefinitionService { try { final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "/" + id, + final Optional persistenceApiResponse = restService.get(persistenceApiBaseUrl + "definitions/" + id, typeToken, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, null); if (persistenceApiResponse.isPresent()) { @@ -128,7 +128,7 @@ public class DefinitionService { try { final TypeToken typeToken = new TypeToken(){}; - final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "/" + definition.getId(), + final Optional persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "definitions/" + definition.getId(), new GsonBuilder().create().toJson(definition), typeToken, connectionTimeoutMilliseconds, @@ -164,7 +164,7 @@ public class DefinitionService { final Instant start = Instant.now(); try { - final boolean deleteIsSuccessful = restService.delete(persistenceApiBaseUrl + "/" + definition.getId(), + final boolean deleteIsSuccessful = restService.delete(persistenceApiBaseUrl + "definitions/" + definition.getId(), connectionTimeoutMilliseconds, socketTimeoutMilliseconds, HttpStatus.NO_CONTENT); diff --git a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java index 38597d8..c9c8f42 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/DefinitionServiceTest.java @@ -13,8 +13,8 @@ import java.util.List; import java.util.Optional; import static junit.framework.TestCase.assertTrue; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; From 8127cb1647a2cc89ab0d705070fc6a7e5669c45b Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 20:25:33 -0600 Subject: [PATCH 38/44] PAN-46 Added validation to the AccountController --- .../controller/AccountController.java | 31 ++--- .../ExceptionHandlingController.java | 74 ++++++++++++ .../exception/BadRequestException.java | 20 ++++ .../UnprocessableEntityException.java | 21 ++++ .../controller/AccountControllerTest.java | 107 ++++++------------ 5 files changed, 170 insertions(+), 83 deletions(-) create mode 100644 persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingController.java create mode 100644 persistence/src/main/java/edu/msudenver/tsp/persistence/exception/BadRequestException.java create mode 100644 persistence/src/main/java/edu/msudenver/tsp/persistence/exception/UnprocessableEntityException.java diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/AccountController.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/AccountController.java index 3301f65..f94eb99 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/AccountController.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/AccountController.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Account; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.AccountsRepository; import edu.msudenver.tsp.utilities.PersistenceUtilities; import lombok.AllArgsConstructor; @@ -23,6 +25,7 @@ import java.util.Optional; @RestController @AllArgsConstructor @RequestMapping("/accounts") +@Validated public class AccountController { private final AccountsRepository accountsRepository; @@ -48,11 +51,11 @@ public class AccountController { @GetMapping("/id") public @ResponseBody - ResponseEntity getAccountById(@RequestParam("id") final Integer id) { + ResponseEntity getAccountById(@RequestParam("id") final Integer id) throws BadRequestException { LOG.info("Received request to query for account with id {}", id); if (id == null) { LOG.error("ERROR: ID was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("ERROR: ID cannot be null"); } LOG.debug("Querying for account with id {}", id); @@ -77,11 +80,11 @@ public class AccountController { @GetMapping("/username") public @ResponseBody - ResponseEntity getAccountByUsername(@RequestParam("username") final String username) { + ResponseEntity getAccountByUsername(@RequestParam("username") final String username) throws BadRequestException { LOG.info("Received request to query for account with username {}", username); if (username == null) { LOG.error("ERROR: username was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("ERROR: Username cannot be null"); } LOG.debug("Querying for account with username {}", username); @@ -107,17 +110,18 @@ public class AccountController { @PostMapping({"","/"}) @Validated({Account.Insert.class, Default.class}) public @ResponseBody ResponseEntity insertAccount( - @Valid @RequestBody final Account account, final BindingResult bindingResult) { + @Valid @RequestBody final Account account, final BindingResult bindingResult) + throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to insert a new account"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (account == null) { LOG.error("Passed account is unprocessable"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed account is unprocessable"); } LOG.info("Checking for any existing users with username {}", account.getUsername()); @@ -152,22 +156,23 @@ public class AccountController { @PatchMapping("/{id}") public @ResponseBody ResponseEntity updateAccount( @PathVariable("id") final Integer id, - @RequestBody final Account account, final BindingResult bindingResult) { + @RequestBody final Account account, final BindingResult bindingResult) + throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to update an account"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (account == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed account is null"); } if (id == null) { LOG.error("Account ID must be specified"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Account ID must be specified"); } LOG.debug("Checking for existence of account with id {}", id); @@ -204,11 +209,11 @@ public class AccountController { } @DeleteMapping("/{id}") - public @ResponseBody ResponseEntity deleteAccountById(@PathVariable("id") final Integer id) { + public @ResponseBody ResponseEntity deleteAccountById(@PathVariable("id") final Integer id) throws BadRequestException { LOG.info("Received request to delete account with id {}", id); if (id == null) { LOG.error("Specified Id is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Deleting account with id {}", id); diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingController.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingController.java new file mode 100644 index 0000000..737298f --- /dev/null +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingController.java @@ -0,0 +1,74 @@ +package edu.msudenver.tsp.persistence.controller; + +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.ValidationException; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Slf4j +@RestControllerAdvice +public class ExceptionHandlingController { + + @ExceptionHandler(HttpMessageNotReadableException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public void handleMessageNotReadableException(final HttpServletRequest request, final HttpMessageNotReadableException e) { + LOG.error("Unable to bind post data sent to: {} \nCaught Exception: {}", request.getRequestURI(), e.getMessage()); + } + + @ExceptionHandler(ValidationException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public String handleMessageInvalidRequest(final HttpServletRequest request, final ValidationException e) { + LOG.error("Request did not validate. Experienced the following error: {}", e.getMessage()); + return "Request did not evaluate. Experienced the following error: " + e.getMessage(); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) + public void handleHttpRequestMethodNotSupported(final HttpServletRequest request) { + LOG.error("Unsupported request method ({}) for URL: {}", request.getMethod(), request.getRequestURI()); + } + + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + public void handleHttpMediaTypeNotSupportedException(final HttpServletRequest request, final HttpMediaTypeNotSupportedException e) { + LOG.error("Unsupported media type ({}) for URL: {}", e.getContentType(), request.getRequestURI()); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public void handleException(final HttpServletRequest request, final Exception e) { + LOG.error("Exception caught for URL: {}", request.getRequestURI(), e); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public List handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) { + LOG.error("Request did not evaluate. Experienced the following error: {}", e.getMessage()); + return e.getBindingResult().getFieldErrors().stream().map(x -> x.getField() + " " + x.getDefaultMessage()).collect(Collectors.toList()); + } + + @ExceptionHandler(BadRequestException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public List handleBadRequestException(final BadRequestException e) { + return e.getErrors(); + } + + @ExceptionHandler(UnprocessableEntityException.class) + @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) + public List handleUnprocessableEntityException(final UnprocessableEntityException e) { + return Collections.singletonList("Request did not evaluate. Experienced the following error: " + e.getMessage()); + } +} diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/BadRequestException.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/BadRequestException.java new file mode 100644 index 0000000..ec37a6d --- /dev/null +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/BadRequestException.java @@ -0,0 +1,20 @@ +package edu.msudenver.tsp.persistence.exception; + +import lombok.Getter; + +import java.util.Collections; +import java.util.List; + +public class BadRequestException extends Exception { + @Getter private final List errors; + + public BadRequestException(final String message) { + super(message); + errors = Collections.singletonList(message); + } + + public BadRequestException(final List errorMessages) { + super(String.join(" ", errorMessages)); + errors = errorMessages; + } +} diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/UnprocessableEntityException.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/UnprocessableEntityException.java new file mode 100644 index 0000000..758e33e --- /dev/null +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/exception/UnprocessableEntityException.java @@ -0,0 +1,21 @@ +package edu.msudenver.tsp.persistence.exception; + +import lombok.Getter; + +import java.util.Collections; +import java.util.List; + +public class UnprocessableEntityException extends Exception { + @Getter + private final List errors; + + public UnprocessableEntityException(final String message) { + super(message); + errors = Collections.singletonList(message); + } + + public UnprocessableEntityException(final List errorMessages) { + super(String.join(" ", errorMessages)); + errors = errorMessages; + } +} diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java index 503e2f6..11a099c 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Account; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.AccountsRepository; import org.junit.Test; import org.junit.runner.RunWith; @@ -51,7 +53,7 @@ public class AccountControllerTest { } @Test - public void testGetAccountById() { + public void testGetAccountById() throws BadRequestException { final Account account = createAccount(); when(accountsRepository.findById(anyInt())).thenReturn(Optional.ofNullable(account)); @@ -65,18 +67,13 @@ public class AccountControllerTest { verify(accountsRepository).findById(anyInt()); } - @Test - public void testGetAccountById_nullId() { - final ResponseEntity responseEntity = accountController.getAccountById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); + @Test(expected = BadRequestException.class) + public void testGetAccountById_nullId() throws BadRequestException { + accountController.getAccountById(null); } @Test - public void testGetAccountById_noAccountFound() { + public void testGetAccountById_noAccountFound() throws BadRequestException { when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = accountController.getAccountById(1); @@ -88,7 +85,7 @@ public class AccountControllerTest { } @Test - public void testGetAccountByUsername() { + public void testGetAccountByUsername() throws BadRequestException { final Account account = createAccount(); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.ofNullable(account)); @@ -102,18 +99,13 @@ public class AccountControllerTest { verify(accountsRepository).findByUsername(anyString()); } - @Test - public void testGetAccountById_nullUsername() { - final ResponseEntity responseEntity = accountController.getAccountByUsername(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); + @Test(expected = BadRequestException.class) + public void testGetAccountById_nullUsername() throws BadRequestException { + accountController.getAccountByUsername(null); } @Test - public void testGetAccountByUsername_noAccountFound() { + public void testGetAccountByUsername_noAccountFound() throws BadRequestException { when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = accountController.getAccountByUsername("Test username"); @@ -125,7 +117,7 @@ public class AccountControllerTest { } @Test - public void testInsertAccount() { + public void testInsertAccount() throws UnprocessableEntityException, BadRequestException { final Account account = createAccount(); when(accountsRepository.save(any(Account.class))).thenReturn(account); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty()); @@ -141,7 +133,7 @@ public class AccountControllerTest { } @Test - public void testInsertAccount_usernameAlreadyExists() { + public void testInsertAccount_usernameAlreadyExists() throws UnprocessableEntityException, BadRequestException { final Account account = createAccount(); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.of(account)); @@ -154,8 +146,8 @@ public class AccountControllerTest { verify(accountsRepository, times(0)).save(any(Account.class)); } - @Test - public void testInsertAccount_accountsDtoIsNull() { + @Test(expected = BadRequestException.class) + public void testInsertAccount_accountsDtoIsNull() throws UnprocessableEntityException, BadRequestException { final ResponseEntity responseEntity = accountController.insertAccount(null, bindingResult); assertNotNull(responseEntity); @@ -164,21 +156,16 @@ public class AccountControllerTest { verifyZeroInteractions(accountsRepository); } - @Test - public void testInsertAccount_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testInsertAccount_bindingResultHasErrors() throws UnprocessableEntityException, BadRequestException { final Account account = createAccount(); when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = accountController.insertAccount(account, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); + accountController.insertAccount(account, bindingResult); } @Test - public void testUpdateAccount() { + public void testUpdateAccount() throws UnprocessableEntityException, BadRequestException { final Account existingAccount = createAccount(); existingAccount.setId(1); existingAccount.setVersion(1); @@ -199,40 +186,25 @@ public class AccountControllerTest { verify(accountsRepository).save(any(Account.class)); } - @Test - public void testUpdateAccount_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testUpdateAccount_bindingResultHasErrors() throws UnprocessableEntityException, BadRequestException { when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = accountController.updateAccount(1, createAccount(), bindingResult); + accountController.updateAccount(1, createAccount(), bindingResult); + } - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); + @Test(expected = BadRequestException.class) + public void testUpdateAccount_accountsDtoIsNull() throws UnprocessableEntityException, BadRequestException { + accountController.updateAccount(1, null, bindingResult); + } + + @Test(expected = BadRequestException.class) + public void testUpdateAccount_idIsNull() throws UnprocessableEntityException, BadRequestException { + accountController.updateAccount(null, createAccount(), bindingResult); } @Test - public void testUpdateAccount_accountsDtoIsNull() { - final ResponseEntity responseEntity = accountController.updateAccount(1, null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); - } - - @Test - public void testUpdateAccount_idIsNull() { - final ResponseEntity responseEntity = accountController.updateAccount(null, createAccount(), bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); - } - - @Test - public void testUpdateAccount_accountDoesNotExist() { + public void testUpdateAccount_accountDoesNotExist() throws UnprocessableEntityException, BadRequestException { when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = accountController.updateAccount(1, createAccount(), bindingResult); @@ -244,7 +216,7 @@ public class AccountControllerTest { } @Test - public void testDeleteAccountById() { + public void testDeleteAccountById() throws BadRequestException { doNothing().when(accountsRepository).deleteById(anyInt()); final ResponseEntity responseEntity = accountController.deleteAccountById(1); @@ -255,14 +227,9 @@ public class AccountControllerTest { verify(accountsRepository).deleteById(anyInt()); } - @Test - public void testDeleteAccountById_idIsNull() { - final ResponseEntity responseEntity = accountController.deleteAccountById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(accountsRepository); + @Test(expected = BadRequestException.class) + public void testDeleteAccountById_idIsNull() throws BadRequestException { + accountController.deleteAccountById(null); } private Account createAccount() { From 9dd7fb66f505bc21fd1abacaa5d9a5ef13b813d6 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 20:35:57 -0600 Subject: [PATCH 39/44] PAN-46 Added validation to the DefinitionController --- .../controller/DefinitionController.java | 31 +++--- .../controller/DefinitionControllerTest.java | 99 +++++++------------ 2 files changed, 51 insertions(+), 79 deletions(-) diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/DefinitionController.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/DefinitionController.java index 720e5df..b89f5b7 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/DefinitionController.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/DefinitionController.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Definition; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.DefinitionRepository; import edu.msudenver.tsp.utilities.PersistenceUtilities; import lombok.AllArgsConstructor; @@ -21,6 +23,7 @@ import java.util.Optional; @RestController @AllArgsConstructor @RequestMapping(path = "/definitions") +@Validated public class DefinitionController { private final DefinitionRepository definitionRepository; @@ -45,11 +48,12 @@ public class DefinitionController { @GetMapping("/{id}") public @ResponseBody - ResponseEntity getDefinitionById(@PathVariable("id") final Integer id) { + ResponseEntity getDefinitionById(@PathVariable("id") final Integer id) + throws BadRequestException { LOG.info("Received request to query for definition with id {}", id); if (id == null) { - LOG.error("ERROR: ID was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + LOG.error("ERROR: ID cannot be null"); + throw new BadRequestException("ERROR: ID cannot be null"); } LOG.debug("Querying for definition with id {}", id); @@ -77,16 +81,17 @@ public class DefinitionController { @Validated({Definition.Insert.class, Default.class}) public @ResponseBody ResponseEntity insertDefinition( @Valid @RequestBody final Definition definition, - final BindingResult bindingResult) { + final BindingResult bindingResult) + throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to insert a new definition"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (definition == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed definition is be null"); } LOG.debug("Saving new definition"); @@ -106,22 +111,22 @@ public class DefinitionController { @PatchMapping("/{id}") public @ResponseBody ResponseEntity updateDefinition( @PathVariable("id") final Integer id, - @RequestBody final Definition definition, final BindingResult bindingResult) { + @RequestBody final Definition definition, final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to update an account"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (definition == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed definition is null"); } if (id == null) { LOG.error("Definition ID must be specified"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Definition ID must be specified"); } LOG.debug("Checking for existence of definition with id {}", id); @@ -137,7 +142,7 @@ public class DefinitionController { if (!existingDefinition.isPresent()) { LOG.error("No definition associated with id {}", id); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PersistenceUtilities.copyNonNullProperties(definition, existingDefinition.get()); @@ -158,11 +163,11 @@ public class DefinitionController { } @DeleteMapping("/{id}") - public @ResponseBody ResponseEntity deleteDefinitionById(@PathVariable("id") final Integer id) { + public @ResponseBody ResponseEntity deleteDefinitionById(@PathVariable("id") final Integer id) throws BadRequestException { LOG.info("Received request to delete definition with id {}", id); if (id == null) { LOG.error("Specified id is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Deleting definition with id {}", id); diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/DefinitionControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/DefinitionControllerTest.java index 4b7fa77..492002f 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/DefinitionControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/DefinitionControllerTest.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Definition; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.DefinitionRepository; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,7 +50,7 @@ public class DefinitionControllerTest { } @Test - public void testGetDefinitionsById() { + public void testGetDefinitionsById() throws BadRequestException { final Definition definition = createDefinition(); when(definitionRepository.findById(anyInt())).thenReturn(Optional.ofNullable(definition)); @@ -62,18 +64,13 @@ public class DefinitionControllerTest { verify(definitionRepository).findById(anyInt()); } - @Test - public void testGetDefinitionById_nullId() { - final ResponseEntity responseEntity = definitionController.getDefinitionById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); + @Test(expected = BadRequestException.class) + public void testGetDefinitionById_nullId() throws BadRequestException { + definitionController.getDefinitionById(null); } @Test - public void testGetDefinitionById_noDefinitionFound() { + public void testGetDefinitionById_noDefinitionFound() throws BadRequestException { when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = definitionController.getDefinitionById(1); @@ -85,7 +82,7 @@ public class DefinitionControllerTest { } @Test - public void testInsertDefinition() { + public void testInsertDefinition() throws BadRequestException, UnprocessableEntityException { final Definition definition = createDefinition(); when(definitionRepository.save(any(Definition.class))).thenReturn(definition); @@ -99,31 +96,21 @@ public class DefinitionControllerTest { verify(definitionRepository).save(any(Definition.class)); } - @Test - public void testInsertDefinition_definitionDtoIsNull() { - final ResponseEntity responseEntity = definitionController.insertDefinition(null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); + @Test(expected = BadRequestException.class) + public void testInsertDefinition_definitionDtoIsNull() throws BadRequestException, UnprocessableEntityException { + definitionController.insertDefinition(null, bindingResult); } - @Test - public void testInsertDefinition_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testInsertDefinition_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException { final Definition definition = createDefinition(); when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = definitionController.insertDefinition(definition, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); + definitionController.insertDefinition(definition, bindingResult); } @Test - public void testUpdateDefinition() { + public void testUpdateDefinition() throws BadRequestException, UnprocessableEntityException { final Definition existingDefinition = createDefinition(); existingDefinition.setId(1); existingDefinition.setVersion(1); @@ -144,52 +131,37 @@ public class DefinitionControllerTest { verify(definitionRepository).save(any(Definition.class)); } - @Test - public void testUpdateDefinition_bindingResultErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testUpdateDefinition_bindingResultErrors() throws BadRequestException, UnprocessableEntityException { when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = definitionController.updateDefinition(1, createDefinition(), bindingResult); + definitionController.updateDefinition(1, createDefinition(), bindingResult); + } - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); + @Test(expected = BadRequestException.class) + public void testUpdateDefinition_definitionDtoIsNull() throws BadRequestException, UnprocessableEntityException { + definitionController.updateDefinition(1, null, bindingResult); + } + + @Test(expected = BadRequestException.class) + public void testUpdateDefinition_idIsNull() throws BadRequestException, UnprocessableEntityException { + definitionController.updateDefinition(null, createDefinition(), bindingResult); } @Test - public void testUpdateDefinition_definitionDtoIsNull() { - final ResponseEntity responseEntity = definitionController.updateDefinition(1, null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); - } - - @Test - public void testUpdateDefinition_idIsNull() { - final ResponseEntity responseEntity = definitionController.updateDefinition(null, createDefinition(), bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); - } - - @Test - public void testUpdateDefinition_definitionDoesntExist() { + public void testUpdateDefinition_definitionDoesntExist() throws BadRequestException, UnprocessableEntityException { when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = definitionController.updateDefinition(1, createDefinition(), bindingResult); assertNotNull(responseEntity); assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); verify(definitionRepository, times(0)).save(any(Definition.class)); } @Test - public void testDeleteDefinitionById() { + public void testDeleteDefinitionById() throws BadRequestException { doNothing().when(definitionRepository).deleteById(anyInt()); final ResponseEntity responseEntity = definitionController.deleteDefinitionById(1); @@ -200,14 +172,9 @@ public class DefinitionControllerTest { verify(definitionRepository).deleteById(anyInt()); } - @Test - public void testDeleteDefinitionById_nullId() { - final ResponseEntity responseEntity = definitionController.deleteDefinitionById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(definitionRepository); + @Test(expected = BadRequestException.class) + public void testDeleteDefinitionById_nullId() throws BadRequestException { + definitionController.deleteDefinitionById(null); } private Definition createDefinition() { From 61c4b3de42b1bac9494a9d3462fd156c7e5fb6b1 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 21:32:43 -0600 Subject: [PATCH 40/44] PAN-46 Added validation to ProofController --- .../controller/ProofController.java | 37 ++--- .../controller/ProofControllerTest.java | 129 ++++++------------ 2 files changed, 64 insertions(+), 102 deletions(-) diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ProofController.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ProofController.java index d682c32..77a9dc7 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ProofController.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/ProofController.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Proof; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.ProofRepository; import edu.msudenver.tsp.utilities.PersistenceUtilities; import lombok.AllArgsConstructor; @@ -45,11 +47,11 @@ public class ProofController { @GetMapping("/id") public @ResponseBody - ResponseEntity getProofById(@RequestParam("id") final Integer id) { + ResponseEntity getProofById(@RequestParam("id") final Integer id) throws BadRequestException { LOG.info("Received request to query for proof with id {}", id); if (id == null) { LOG.error("ERROR: ID was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Querying for proof with id {}", id); @@ -75,11 +77,12 @@ public class ProofController { @GetMapping("/branch") public @ResponseBody - ResponseEntity> getAllProofsByBranch(@RequestParam("branch") String branch) { + ResponseEntity> getAllProofsByBranch(@RequestParam("branch") String branch) + throws BadRequestException { LOG.info("Received request to query for proofs related to the {} branch of mathematics", branch); if (branch == null) { LOG.error("ERROR: branch was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified branch is null"); } if (branch.contains("_") || branch.contains("-")) { @@ -110,11 +113,12 @@ public class ProofController { @GetMapping("/theorem_name") public @ResponseBody - ResponseEntity> getAllProofsByTheoremName(@RequestParam("theorem_name") String theoremName) { + ResponseEntity> getAllProofsByTheoremName(@RequestParam("theorem_name") String theoremName) + throws BadRequestException { LOG.info("Received request to query for proofs of the theorem {}", theoremName); if (theoremName == null) { LOG.error("ERROR: theorem name was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified theorem name is null"); } if (theoremName.contains("_") || theoremName.contains("-")) { @@ -147,16 +151,16 @@ public class ProofController { @Validated({Proof.Insert.class, Default.class}) public @ResponseBody ResponseEntity insertProof( @Valid @RequestBody final Proof proof, - final BindingResult bindingResult) { + final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to insert a new proof"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (proof == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed proof is null"); } LOG.debug("Saving new proof"); @@ -176,22 +180,23 @@ public class ProofController { @PatchMapping("/{id}") public @ResponseBody ResponseEntity updateProof( @PathVariable("id") final Integer id, - @RequestBody final Proof proof, final BindingResult bindingResult) { + @RequestBody final Proof proof, final BindingResult bindingResult) + throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to update a proof"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (proof == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed proof is null"); } if (id == null) { LOG.error("Proof ID must be specified"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Checking for existence of proof with id {}", id); @@ -207,7 +212,7 @@ public class ProofController { if (!existingProof.isPresent()) { LOG.error("No proof associated with id {}", id); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PersistenceUtilities.copyNonNullProperties(proof, existingProof.get()); @@ -228,11 +233,11 @@ public class ProofController { } @DeleteMapping("/{id}") - public @ResponseBody ResponseEntity deleteProofById(@PathVariable("id") final Integer id) { + public @ResponseBody ResponseEntity deleteProofById(@PathVariable("id") final Integer id) throws BadRequestException { LOG.info("Received request to delete proof with id {}", id); if (id == null) { LOG.error("Specified id is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Deleting proof with id {}", id); diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ProofControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ProofControllerTest.java index 14c2482..6953b0a 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ProofControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ProofControllerTest.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Proof; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.ProofRepository; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,7 +47,7 @@ public class ProofControllerTest { } @Test - public void testGetAllProofsByBranch() { + public void testGetAllProofsByBranch() throws BadRequestException { final Proof proofDto = createProof(); final List listOfProofs = new ArrayList<>(); listOfProofs.add(proofDto); @@ -63,18 +65,13 @@ public class ProofControllerTest { responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof)); } - @Test - public void testGetAllProfsByBranch_nullBranch() { - final ResponseEntity> responseEntity = proofController.getAllProofsByBranch(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testGetAllProfsByBranch_nullBranch() throws BadRequestException { + proofController.getAllProofsByBranch(null); } @Test - public void testGetAllProofsByBranch_noProofsFound() { + public void testGetAllProofsByBranch_noProofsFound() throws BadRequestException { when(proofRepository.findByBranch(anyString())).thenReturn(Collections.emptyList()); final ResponseEntity> responseEntity = proofController.getAllProofsByBranch("test-nonexistent-branch"); @@ -85,7 +82,7 @@ public class ProofControllerTest { } @Test - public void testGetAllProofsByTheoremName() { + public void testGetAllProofsByTheoremName() throws BadRequestException { final Proof proofDto = createProof(); final List listOfProofs = new ArrayList<>(); listOfProofs.add(proofDto); @@ -103,18 +100,13 @@ public class ProofControllerTest { responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof)); } - @Test - public void testGetAllProofsByTheoremName_nullTheoremName() { - final ResponseEntity> responseEntity = proofController.getAllProofsByTheoremName(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testGetAllProofsByTheoremName_nullTheoremName() throws BadRequestException { + proofController.getAllProofsByTheoremName(null); } @Test - public void testGetAllProofsByTheoremName_noProofsFound() { + public void testGetAllProofsByTheoremName_noProofsFound() throws BadRequestException { when(proofRepository.findByTheoremName(anyString())).thenReturn(Collections.emptyList()); final ResponseEntity> responseEntity = proofController.getAllProofsByTheoremName("test-nonexistent-proof"); @@ -125,7 +117,7 @@ public class ProofControllerTest { } @Test - public void testGetProofById() { + public void testGetProofById() throws BadRequestException { final Proof proof = createProof(); when(proofRepository.findById(anyInt())).thenReturn(Optional.ofNullable(proof)); @@ -139,18 +131,13 @@ public class ProofControllerTest { verify(proofRepository).findById(anyInt()); } - @Test - public void testGetProofById_nullId() { - final ResponseEntity responseEntity = proofController.getProofById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testGetProofById_nullId() throws BadRequestException { + proofController.getProofById(null); } @Test - public void testGetProofById_noProofFound() { + public void testGetProofById_noProofFound() throws BadRequestException { when(proofRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = proofController.getProofById(1); @@ -162,7 +149,7 @@ public class ProofControllerTest { } @Test - public void testInsertProof() { + public void testInsertProof() throws BadRequestException, UnprocessableEntityException { final Proof proof = createProof(); when(proofRepository.save(any(Proof.class))).thenReturn(proof); @@ -176,31 +163,21 @@ public class ProofControllerTest { verify(proofRepository).save(any(Proof.class)); } - @Test - public void testInsertProof_proofDtoIsNull() { - final ResponseEntity responseEntity = proofController.insertProof(null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testInsertProof_proofDtoIsNull() throws BadRequestException, UnprocessableEntityException { + proofController.insertProof(null, bindingResult); } - @Test - public void testInsertProof_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testInsertProof_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException { final Proof proof = createProof(); when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = proofController.insertProof(proof, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + proofController.insertProof(proof, bindingResult); } @Test - public void testUpdateProof() { + public void testUpdateProof() throws BadRequestException, UnprocessableEntityException { final Proof existingProof = createProof(); existingProof.setId(1); existingProof.setVersion(1); @@ -221,52 +198,37 @@ public class ProofControllerTest { verify(proofRepository).save(any(Proof.class)); } - @Test - public void testUpdateProof_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testUpdateProof_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException { when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = proofController.updateProof(1, createProof(), bindingResult); + proofController.updateProof(1, createProof(), bindingResult); + } - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testUpdateProof_proofDtoIsNull() throws BadRequestException, UnprocessableEntityException { + proofController.updateProof(1, null, bindingResult); + } + + @Test(expected = BadRequestException.class) + public void testUpdateProof_idIsNull() throws BadRequestException, UnprocessableEntityException { + proofController.updateProof(null, createProof(), bindingResult); } @Test - public void testUpdateProof_proofDtoIsNull() { - final ResponseEntity responseEntity = proofController.updateProof(1, null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); - } - - @Test - public void testUpdateProof_idIsNull() { - final ResponseEntity responseEntity = proofController.updateProof(null, createProof(), bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); - } - - @Test - public void testUpdateProof_theoremDoesNotExist() { + public void testUpdateProof_theoremDoesNotExist() throws BadRequestException, UnprocessableEntityException { when(proofRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = proofController.updateProof(1, createProof(), bindingResult); assertNotNull(responseEntity); assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); verify(proofRepository, times(0)).save(any(Proof.class)); } @Test - public void testDeleteProofById() { + public void testDeleteProofById() throws BadRequestException { doNothing().when(proofRepository).deleteById(anyInt()); final ResponseEntity responseEntity = proofController.deleteProofById(1); @@ -277,14 +239,9 @@ public class ProofControllerTest { verify(proofRepository).deleteById(anyInt()); } - @Test - public void testDeleteProofById_idIsNull() { - final ResponseEntity responseEntity = proofController.deleteProofById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(proofRepository); + @Test(expected = BadRequestException.class) + public void testDeleteProofById_idIsNull() throws BadRequestException { + proofController.deleteProofById(null); } private Proof createProof() { From c5727c8d1ad9d1ce333a6a1a6ebc8f117059b8ef Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 21:40:09 -0600 Subject: [PATCH 41/44] PAN-46 Added validation to TheoremController --- .../controller/TheoremController.java | 38 ++--- .../controller/TheoremControllerTest.java | 146 ++++++------------ 2 files changed, 69 insertions(+), 115 deletions(-) diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/TheoremController.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/TheoremController.java index 457ac10..fc78e77 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/TheoremController.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/controller/TheoremController.java @@ -1,6 +1,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Theorem; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.TheoremRepository; import edu.msudenver.tsp.utilities.PersistenceUtilities; import lombok.AllArgsConstructor; @@ -45,11 +47,11 @@ public class TheoremController { @GetMapping("/branch") public @ResponseBody - ResponseEntity> getAllTheoremsByBranch(@RequestParam("branch") String branch) { + ResponseEntity> getAllTheoremsByBranch(@RequestParam("branch") String branch) throws BadRequestException { LOG.info("Received request to query for theorems related to the {} branch of mathematics", branch); if (branch == null) { LOG.error("ERROR: branch was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified branch is null"); } if (branch.contains("_") || branch.contains("-")) { @@ -80,11 +82,11 @@ public class TheoremController { @GetMapping("/proven_status") public @ResponseBody - ResponseEntity> getAllTheoremsByProvenStatus(@RequestParam("proven_status") final String provenStatus) { + ResponseEntity> getAllTheoremsByProvenStatus(@RequestParam("proven_status") final String provenStatus) throws BadRequestException { LOG.info("Received request to query for theorems whose proven status is {}", provenStatus); if (provenStatus == null) { LOG.error("ERROR: status was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified status is null"); } final Boolean isProven = Boolean.parseBoolean(provenStatus); @@ -112,11 +114,11 @@ public class TheoremController { @GetMapping("/name") public @ResponseBody - ResponseEntity> getAllTheoremsByName(@RequestParam("name") String name) { + ResponseEntity> getAllTheoremsByName(@RequestParam("name") String name) throws BadRequestException { LOG.info("Received request to query for theorems whose name is {}", name); if (name == null) { LOG.error("ERROR: name was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified name is null"); } if (name.contains("_") || name.contains("-")) { @@ -147,11 +149,11 @@ public class TheoremController { @GetMapping("/id") public @ResponseBody - ResponseEntity getTheoremById(@RequestParam("id") final Integer id) { + ResponseEntity getTheoremById(@RequestParam("id") final Integer id) throws BadRequestException { LOG.info("Received request to query for theorem with id {}", id); if (id == null) { LOG.error("ERROR: ID was null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Querying for theorem with id {}", id); @@ -179,16 +181,16 @@ public class TheoremController { @Validated({Theorem.Insert.class, Default.class}) public @ResponseBody ResponseEntity insertTheorem( @Valid @RequestBody final Theorem theorem, - final BindingResult bindingResult) { + final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to insert a new theorem"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (theorem == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed theorem is null"); } LOG.debug("Saving new theorem"); @@ -208,22 +210,22 @@ public class TheoremController { @PatchMapping("/{id}") public @ResponseBody ResponseEntity updateTheorem( @PathVariable("id") final Integer id, - @RequestBody final Theorem theorem, final BindingResult bindingResult) { + @RequestBody final Theorem theorem, final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException { LOG.info("Received request to update a theorem"); if (bindingResult.hasErrors()) { LOG.error("Binding result is unprocessable"); - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + throw new UnprocessableEntityException(bindingResult.getAllErrors().toString()); } if (theorem == null) { LOG.error("Passed entity is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Passed theorem is null"); } if (id == null) { LOG.error("Theorem ID must be specified"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Checking for existence of theorem with id {}", id); @@ -239,7 +241,7 @@ public class TheoremController { if (!existingTheorem.isPresent()) { LOG.error("No theorem associated with id {}", id); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PersistenceUtilities.copyNonNullProperties(theorem, existingTheorem.get()); @@ -260,11 +262,11 @@ public class TheoremController { } @DeleteMapping("/{id}") - public @ResponseBody ResponseEntity deleteTheoremById(@PathVariable("id") final Integer id) { + public @ResponseBody ResponseEntity deleteTheoremById(@PathVariable("id") final Integer id) throws BadRequestException { LOG.info("Received request to delete theorem with id {}", id); if (id == null) { LOG.error("Specified id is null"); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new BadRequestException("Specified ID is null"); } LOG.debug("Deleting theorem with id {}", id); diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/TheoremControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/TheoremControllerTest.java index a667d0a..7fee5c8 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/TheoremControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/TheoremControllerTest.java @@ -2,6 +2,8 @@ package edu.msudenver.tsp.persistence.controller; import edu.msudenver.tsp.persistence.dto.Theorem; import edu.msudenver.tsp.persistence.dto.TheoremType; +import edu.msudenver.tsp.persistence.exception.BadRequestException; +import edu.msudenver.tsp.persistence.exception.UnprocessableEntityException; import edu.msudenver.tsp.persistence.repository.TheoremRepository; import org.junit.Test; import org.junit.runner.RunWith; @@ -50,7 +52,7 @@ public class TheoremControllerTest { } @Test - public void testGetTheoremById() { + public void testGetTheoremById() throws BadRequestException { final Theorem theorem = createTheorem(); when(theoremRepository.findById(anyInt())).thenReturn(Optional.ofNullable(theorem)); @@ -64,18 +66,13 @@ public class TheoremControllerTest { verify(theoremRepository).findById(anyInt()); } - @Test - public void testGetTheoremById_nullId() { - final ResponseEntity responseEntity = theoremController.getTheoremById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testGetTheoremById_nullId() throws BadRequestException { + theoremController.getTheoremById(null); } @Test - public void testGetTheoremById_noTheoremFound() { + public void testGetTheoremById_noTheoremFound() throws BadRequestException { when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = theoremController.getTheoremById(1); @@ -87,7 +84,7 @@ public class TheoremControllerTest { } @Test - public void testGetAllTheoremsByBranch() { + public void testGetAllTheoremsByBranch() throws BadRequestException { final Theorem theoremDto = createTheorem(); final List listOfTheorems = new ArrayList<>(); listOfTheorems.add(theoremDto); @@ -105,18 +102,13 @@ public class TheoremControllerTest { responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); } - @Test - public void testGetAllTheoremsByBranch_nullBranch() { - final ResponseEntity> responseEntity = theoremController.getAllTheoremsByBranch(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testGetAllTheoremsByBranch_nullBranch() throws BadRequestException { + theoremController.getAllTheoremsByBranch(null); } @Test - public void testGetAllTheoremsByBranch_noTheoremsFound() { + public void testGetAllTheoremsByBranch_noTheoremsFound() throws BadRequestException { when(theoremRepository.findByBranch(anyString())).thenReturn(Collections.emptyList()); final ResponseEntity> responseEntity = theoremController.getAllTheoremsByBranch("test_nonexistent_branch"); @@ -127,7 +119,7 @@ public class TheoremControllerTest { } @Test - public void testGetAllTheoremsByProvenStatus() { + public void testGetAllTheoremsByProvenStatus() throws BadRequestException { final Theorem theoremDto = createTheorem(); final List listOfTheorems = new ArrayList<>(); listOfTheorems.add(theoremDto); @@ -145,18 +137,13 @@ public class TheoremControllerTest { responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); } - @Test - public void testGetAllTheoremsByProvenStatus_nullProvenStatus() { - final ResponseEntity> responseEntity = theoremController.getAllTheoremsByProvenStatus(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testGetAllTheoremsByProvenStatus_nullProvenStatus() throws BadRequestException { + theoremController.getAllTheoremsByProvenStatus(null); } @Test - public void testGetAllTheoremsByProvenStatus_invalidProvenStatus() { + public void testGetAllTheoremsByProvenStatus_invalidProvenStatus() throws BadRequestException { final ResponseEntity> responseEntity = theoremController.getAllTheoremsByProvenStatus("test"); assertNotNull(responseEntity); @@ -165,7 +152,7 @@ public class TheoremControllerTest { } @Test - public void testGetAllTheoremsByProvenStatus_noTheoremsFound() { + public void testGetAllTheoremsByProvenStatus_noTheoremsFound() throws BadRequestException { when(theoremRepository.findByProvenStatus(anyBoolean())).thenReturn(Collections.emptyList()); final ResponseEntity> responseEntity = theoremController.getAllTheoremsByProvenStatus("false"); @@ -176,7 +163,7 @@ public class TheoremControllerTest { } @Test - public void testGetAllTheoremsByName() { + public void testGetAllTheoremsByName() throws BadRequestException { final Theorem theoremDto = createTheorem(); final List listOfTheorems = new ArrayList<>(); listOfTheorems.add(theoremDto); @@ -194,18 +181,13 @@ public class TheoremControllerTest { responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); } - @Test - public void testGetAllTheoremsByName_nullName() { - final ResponseEntity> responseEntity = theoremController.getAllTheoremsByName(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testGetAllTheoremsByName_nullName() throws BadRequestException { + theoremController.getAllTheoremsByName(null); } @Test - public void testGetAllTheoremsByName_noNameFound() { + public void testGetAllTheoremsByName_noNameFound() throws BadRequestException { when(theoremRepository.findByName(anyString())).thenReturn(Collections.emptyList()); final ResponseEntity> responseEntity = theoremController.getAllTheoremsByName("No-name"); @@ -216,7 +198,7 @@ public class TheoremControllerTest { } @Test - public void testInsertTheorem() { + public void testInsertTheorem() throws BadRequestException, UnprocessableEntityException { final Theorem theorem = createTheorem(); when(theoremRepository.save(any(Theorem.class))).thenReturn(theorem); @@ -230,31 +212,21 @@ public class TheoremControllerTest { verify(theoremRepository).save(any(Theorem.class)); } - @Test - public void testInsertTheorem_theoremDtoIsNull() { - final ResponseEntity responseEntity = theoremController.insertTheorem(null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testInsertTheorem_theoremDtoIsNull() throws BadRequestException, UnprocessableEntityException { + theoremController.insertTheorem(null, bindingResult); } - @Test - public void testInsertTheorem_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testInsertTheorem_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException { final Theorem theorem = createTheorem(); when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = theoremController.insertTheorem(theorem, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + theoremController.insertTheorem(theorem, bindingResult); } @Test - public void testUpdateTheorem() { + public void testUpdateTheorem() throws BadRequestException, UnprocessableEntityException { final Theorem existingTheorem = createTheorem(); existingTheorem.setId(1); existingTheorem.setVersion(1); @@ -275,52 +247,37 @@ public class TheoremControllerTest { verify(theoremRepository).save(any(Theorem.class)); } - @Test - public void testUpdateTheorem_bindingResultHasErrors() { + @Test(expected = UnprocessableEntityException.class) + public void testUpdateTheorem_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException { when(bindingResult.hasErrors()).thenReturn(true); - final ResponseEntity responseEntity = theoremController.updateTheorem(1, createTheorem(), bindingResult); + theoremController.updateTheorem(1, createTheorem(), bindingResult); + } - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testUpdateTheorem_theoremDtoIsNull() throws BadRequestException, UnprocessableEntityException { + theoremController.updateTheorem(1, null, bindingResult); + } + + @Test(expected = BadRequestException.class) + public void testUpdateTheorem_idIsNull() throws BadRequestException, UnprocessableEntityException { + theoremController.updateTheorem(null, createTheorem(), bindingResult); } @Test - public void testUpdateTheorem_theoremDtoIsNull() { - final ResponseEntity responseEntity = theoremController.updateTheorem(1, null, bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); - } - - @Test - public void testUpdateTheorem_idIsNull() { - final ResponseEntity responseEntity = theoremController.updateTheorem(null, createTheorem(), bindingResult); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); - } - - @Test - public void testUpdateTheorem_theoremDoesNotExist() { + public void testUpdateTheorem_theoremDoesNotExist() throws BadRequestException, UnprocessableEntityException { when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty()); final ResponseEntity responseEntity = theoremController.updateTheorem(1, createTheorem(), bindingResult); assertNotNull(responseEntity); assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); verify(theoremRepository, times(0)).save(any(Theorem.class)); } @Test - public void testDeleteTheoremById() { + public void testDeleteTheoremById() throws BadRequestException { doNothing().when(theoremRepository).deleteById(anyInt()); final ResponseEntity responseEntity = theoremController.deleteTheoremById(1); @@ -331,14 +288,9 @@ public class TheoremControllerTest { verify(theoremRepository).deleteById(anyInt()); } - @Test - public void testDeleteTheoremById_idIsNull() { - final ResponseEntity responseEntity = theoremController.deleteTheoremById(null); - - assertNotNull(responseEntity); - assertFalse(responseEntity.hasBody()); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - verifyZeroInteractions(theoremRepository); + @Test(expected = BadRequestException.class) + public void testDeleteTheoremById_idIsNull() throws BadRequestException { + theoremController.deleteTheoremById(null); } private Theorem createTheorem() { From 93774e7e11536bd2a9f0aac4b157ece7f4bfb771 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Sun, 7 Apr 2019 21:56:23 -0600 Subject: [PATCH 42/44] PAN-46 Wrote unit tests for the ExceptionHandlingController --- .../ExceptionHandlingControllerTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingControllerTest.java diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingControllerTest.java new file mode 100644 index 0000000..217bcbf --- /dev/null +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/ExceptionHandlingControllerTest.java @@ -0,0 +1,54 @@ +package edu.msudenver.tsp.persistence.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Matchers.any; + +@RunWith(MockitoJUnitRunner.class) +public class ExceptionHandlingControllerTest { + @Mock + ExceptionHandlingController exceptionHandlingController; + + @Test + public void testHandleMessageNotReadableException() { + exceptionHandlingController.handleMessageNotReadableException(any(), any()); + } + + @Test + public void testHandleMessageInvalidRequestException() { + exceptionHandlingController.handleMessageInvalidRequest(any(), any()); + } + + @Test + public void testHandleHttpRequestMethodNotSupportedException() { + exceptionHandlingController.handleHttpRequestMethodNotSupported(any()); + } + + @Test + public void testHandleHttpMediaTypeNotSupportedException() { + exceptionHandlingController.handleHttpMediaTypeNotSupportedException(any(), any()); + } + + @Test + public void testHandleException() { + exceptionHandlingController.handleException(any(), any()); + } + + @Test + public void testHandleMethodArgumentNotValidException() { + exceptionHandlingController.handleMethodArgumentNotValidException(any()); + } + + @Test + public void testHandleBadRequestException() { + exceptionHandlingController.handleBadRequestException(any()); + } + + @Test + public void testHandleUnprocessableEntityException() { + exceptionHandlingController.handleUnprocessableEntityException(any()); + } +} \ No newline at end of file From 7305f444f873dfbecc7d5630071aee6fc2b0a596 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Thu, 11 Apr 2019 20:57:20 -0600 Subject: [PATCH 43/44] PAN-46 Merged with Master --- .../scripts/mysql/local_development.sql | 28 +++++++++---------- .../persistence/AccountsIntegrationTest.java | 6 ++-- .../persistence/ProofsIntegrationTest.java | 3 +- .../tsp/persistence/dto/Account.java | 12 +------- .../controller/AccountControllerTest.java | 2 +- services/build.gradle | 4 ++- .../services/UserServiceIntegrationTest.java | 12 ++++---- .../msudenver/tsp/services/dto/Account.java | 2 +- .../tsp/services/UserServiceTest.java | 2 +- 9 files changed, 31 insertions(+), 40 deletions(-) diff --git a/persistence/scripts/mysql/local_development.sql b/persistence/scripts/mysql/local_development.sql index 27005d4..9650f22 100644 --- a/persistence/scripts/mysql/local_development.sql +++ b/persistence/scripts/mysql/local_development.sql @@ -5,11 +5,11 @@ create table accounts ( id int not null auto_increment primary key unique, username varchar(50) not null unique, password varchar(256) not null, -administrator_status boolean default false, +administrator boolean default false, last_login date, version int default 1 ); -insert into accounts (username, password, administrator_status) +insert into accounts (username, password, administrator) values ('admin', 'secret', true), ('atusa', 'secret', true), ('dantanxiaotian', 'secret', true), @@ -34,17 +34,17 @@ referenced_theorems json, proven_status boolean default false, version int default 1 ); -CREATE TABLE proofs +create table proofs ( - id INT NOT NULL AUTO_INCREMENT, - theorem_name VARCHAR(512) NOT NULL, - proof VARCHAR(4096) NOT NULL, - branch VARCHAR(512) NOT NULL, - theorem INT NOT NULL, - referenced_definitions JSON, - referenced_theorems JSON, - date_added DATE, - last_updated DATE, - version INT DEFAULT 1, - PRIMARY KEY (id) + id int not null auto_increment, + theorem_name varchar(512) not null, + proof varchar(4096) not null, + branch varchar(512) not null, + theorem int not null, + referenced_definitions json, + referenced_theorems json, + date_added date, + last_updated date, + version int default 1, + primary key (id) ); \ No newline at end of file diff --git a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java index 42cce04..7cd5abd 100644 --- a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java +++ b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/AccountsIntegrationTest.java @@ -29,7 +29,7 @@ public class AccountsIntegrationTest { assertEquals("Test username", savedAccount.getUsername()); assertEquals("test password", savedAccount.getPassword()); - assertTrue(savedAccount.getAdministratorStatus()); + assertTrue(savedAccount.isAdministrator()); savedAccount.setPassword("Test Update"); @@ -37,7 +37,7 @@ public class AccountsIntegrationTest { assertEquals("Test username", savedAccount.getUsername()); assertEquals("Test Update", savedAccount.getPassword()); - assertTrue(savedAccount.getAdministratorStatus()); + assertTrue(savedAccount.isAdministrator()); assertEquals(updatedAccount.getId(), id); accountsRepository.delete(account); @@ -49,7 +49,7 @@ public class AccountsIntegrationTest { final Account account = new Account(); account.setUsername("Test username"); account.setPassword("test password"); - account.setAdministratorStatus(true); + account.setAdministrator(true); return account; } diff --git a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java index b18c47d..9fa7edb 100644 --- a/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java +++ b/persistence/src/integrationTest/java/edu/msudenver/tsp/persistence/ProofsIntegrationTest.java @@ -18,8 +18,7 @@ import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = PersistenceTestConfig.class) public class ProofsIntegrationTest { - @Autowired - private ProofRepository proofRepository; + @Autowired private ProofRepository proofRepository; @Test public void testCRUDFunctionality() { diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java index a8fa430..674d83b 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Account.java @@ -19,21 +19,11 @@ import java.util.Date; public class Account extends BaseDto implements Serializable { @NotBlank(groups = Insert.class, message = "A username must be specified") @Size(max = 50) private String username; @NotBlank(groups = Insert.class, message = "A password must be specified") @Size(max = 256) private String password; - @NotNull @Column(name = "administrator_status") private boolean administratorStatus; + @NotNull private boolean administrator; @Temporal(TemporalType.DATE) @Column(name = "last_login") private Date lastLogin; private static final long serialVersionUID = 7095627971593953734L; - @JsonProperty("administrator_status") - public boolean getAdministratorStatus() { - return administratorStatus; - } - - @JsonProperty("administrator_status") - public void setAdministratorStatus(final boolean administratorStatus) { - this.administratorStatus = administratorStatus; - } - @JsonProperty("last_login") public Date getLastLogin() { return lastLogin; diff --git a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java index 11a099c..0d07045 100644 --- a/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java +++ b/persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java @@ -236,7 +236,7 @@ public class AccountControllerTest { final Account account = new Account(); account.setUsername("Test username"); account.setPassword("test password"); - account.setAdministratorStatus(true); + account.setAdministrator(true); return account; } diff --git a/services/build.gradle b/services/build.gradle index 95d21d7..0873510 100644 --- a/services/build.gradle +++ b/services/build.gradle @@ -18,10 +18,12 @@ repositories { } dependencies { - compile project(':persistence') compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.11' compile group: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.7' compile group: 'com.google.code.gson', name: 'gson', version: '2.7' + compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.5.RELEASE' + compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.5.RELEASE' + compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2' compile fileTree(dir: 'lib', include: '**/*.jar') testCompile "org.springframework:spring-test:5.0.9.RELEASE" diff --git a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java index be36c25..64fd7ad 100644 --- a/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java +++ b/services/src/integrationTest/java/edu/msudenver/tsp/services/UserServiceIntegrationTest.java @@ -23,7 +23,7 @@ public class UserServiceIntegrationTest { private UserService userService; @Test - public void testUserService(){ + public void testCRUD() { final Account testAccount = createAccount(); final Optional testCreatedAccount = userService.createAccount(testAccount); @@ -31,21 +31,21 @@ public class UserServiceIntegrationTest { final Account returnedAccount = testCreatedAccount.get(); assertEquals("test_user", returnedAccount.getUsername()); assertEquals("test_password", returnedAccount.getPassword()); - assertFalse(returnedAccount.isAdministratorStatus()); + assertFalse(returnedAccount.isAdministrator()); final Optional getAccountById = userService.findAccountById(returnedAccount.getId()); assertTrue(getAccountById.isPresent()); final Account returnedAccountById = getAccountById.get(); assertEquals("test_user", returnedAccountById.getUsername()); assertEquals("test_password", returnedAccountById.getPassword()); - assertFalse(returnedAccountById.isAdministratorStatus()); + assertFalse(returnedAccountById.isAdministrator()); final Optional getAccountByUsername = userService.findAccountByUsername(returnedAccount.getUsername()); assertTrue(getAccountByUsername.isPresent()); final Account returnedAccountByUsername = getAccountByUsername.get(); assertEquals("test_user", returnedAccountByUsername.getUsername()); assertEquals("test_password", returnedAccountByUsername.getPassword()); - assertFalse(returnedAccountById.isAdministratorStatus()); + assertFalse(returnedAccountById.isAdministrator()); returnedAccount.setUsername("test_updatedUser"); returnedAccount.setPassword("test_updatedPassword"); @@ -55,7 +55,7 @@ public class UserServiceIntegrationTest { final Account returnedUpdatedAccount = updatedAccount.get(); assertEquals("test_updatedUser", returnedUpdatedAccount.getUsername()); assertEquals("test_updatedPassword", returnedUpdatedAccount.getPassword()); - assertFalse(returnedUpdatedAccount.isAdministratorStatus()); + assertFalse(returnedUpdatedAccount.isAdministrator()); final boolean result = userService.deleteAccount(returnedUpdatedAccount); assertTrue(result); @@ -65,7 +65,7 @@ public class UserServiceIntegrationTest { final Account testAccount = new Account(); testAccount.setUsername("test_user"); testAccount.setPassword("test_password"); - testAccount.setAdministratorStatus(false); + testAccount.setAdministrator(false); testAccount.setLastLogin(new Date()); return testAccount; diff --git a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java index 05872fc..f04a108 100644 --- a/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java +++ b/services/src/main/java/edu/msudenver/tsp/services/dto/Account.java @@ -16,7 +16,7 @@ import java.util.Date; public class Account extends BaseDto implements Serializable { @Size(max = 50) private String username; @Size(max = 256) private String password; - @NotNull @SerializedName("administrator_status") private boolean administratorStatus; + @NotNull private boolean administrator; @Temporal(TemporalType.DATE) @SerializedName("last_login") private Date lastLogin; private static final long serialVersionUID = 7095627971593953734L; diff --git a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java index 1d42311..1f7812f 100644 --- a/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java +++ b/services/src/test/java/edu/msudenver/tsp/services/UserServiceTest.java @@ -306,7 +306,7 @@ public class UserServiceTest { final Account account = new Account(); account.setUsername("Test username"); account.setPassword("test password"); - account.setAdministratorStatus(true); + account.setAdministrator(true); account.setLastLogin(new Date()); return account; } From 1e7e46fc669bc7c1d3140249a7a3dd4a7aa99953 Mon Sep 17 00:00:00 2001 From: atusa17 Date: Thu, 11 Apr 2019 21:36:21 -0600 Subject: [PATCH 44/44] PAN-46 fixed breaking integration tests --- .../java/edu/msudenver/tsp/persistence/dto/Definition.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Definition.java b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Definition.java index b18d743..43b95f4 100644 --- a/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Definition.java +++ b/persistence/src/main/java/edu/msudenver/tsp/persistence/dto/Definition.java @@ -10,6 +10,7 @@ import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Table; import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.List; @@ -24,7 +25,7 @@ public class Definition extends BaseDto implements Serializable { @Size(min = 1, max = 200, message = "Must be between 1 and 200 characters") private String name; - @NotBlank(groups = Insert.class, message = "At least one (1) definition must be specified") + @NotNull(groups = Insert.class, message = "At least one (1) definition must be specified") @Type(type = "json") @Column(columnDefinition = "jsonb") private List definition; @Type(type = "json") @Column(columnDefinition = "jsonb") private List notation;