61 Commits

Author SHA1 Message Date
Alex Tusa
dd92307cf8 Merge pull request #28 from atusa17/PAN-46
Pan 46
2019-04-11 21:51:52 -06:00
1e7e46fc66 PAN-46 fixed breaking integration tests 2019-04-11 21:36:21 -06:00
53ba34db1e Merge remote-tracking branch 'origin/PAN-46' into PAN-46 2019-04-11 20:57:46 -06:00
7305f444f8 PAN-46 Merged with Master 2019-04-11 20:57:20 -06:00
dantanxiaotian
34c74da321 Merge branch 'master' into PAN-46 2019-04-11 20:31:14 -06:00
Alex Tusa
dd6e98130d Merge pull request #27 from atusa17/PAN-11
Pan 11
2019-04-11 15:18:17 -06:00
93774e7e11 PAN-46 Wrote unit tests for the ExceptionHandlingController 2019-04-07 21:56:23 -06:00
c5727c8d1a PAN-46 Added validation to TheoremController 2019-04-07 21:40:09 -06:00
61c4b3de42 PAN-46 Added validation to ProofController 2019-04-07 21:32:43 -06:00
9dd7fb66f5 PAN-46 Added validation to the DefinitionController 2019-04-07 20:35:57 -06:00
8127cb1647 PAN-46 Added validation to the AccountController 2019-04-07 20:25:33 -06:00
12f7d7f359 PAN-11 fixed all integration tests 2019-04-07 18:00:12 -06:00
c8600b8bb4 PAN-11 Fixed integration tests 2019-04-07 17:30:34 -06:00
091215f1eb PAN-11 Fixed integration tests 2019-04-07 17:22:08 -06:00
67f77d6c9e PAN-11 Fixed integration tests 2019-04-07 17:06:43 -06:00
c75b243df8 PAN-11 Fixed integration tests 2019-04-07 16:51:36 -06:00
609f018f9f PAN-11 Fixed integration tests 2019-04-07 16:21:18 -06:00
7802e25310 Merge branches 'PAN-11' and 'master' of https://github.com/atusa17/ptp into PAN-11
# Conflicts:
#	services/src/integrationTest/resources/test.properties
#	services/src/main/java/edu/msudenver/tsp/services/dto/Account.java
2019-04-07 16:03:36 -06:00
Alex Tusa
1bddb2d646 Merge pull request #24 from atusa17/PAN-15
Pan 15
2019-04-07 15:33:49 -06:00
36036b710d PAN-15 Finished Unit Tests 2019-04-07 15:18:19 -06:00
dantanxiaotian
adbcd786f0 PAN-15 fix the request changes 2019-04-02 16:38:54 -06:00
dantanxiaotian
b1d4ed9719 PAN-15 fix the request changes 2019-03-27 12:18:12 -06:00
765d8283d9 PAN-11 wrote unit tests for deleteDefinition 2019-03-24 22:36:10 -06:00
8724d6c2f8 PAN-11 created the deleteDefinition method 2019-03-24 22:27:27 -06:00
5a44b5b793 PAN-11 wrote unit tests for the updateDefinition method 2019-03-24 22:12:34 -06:00
6d1db048c8 PAN-11 created the updateDefinition method 2019-03-24 21:51:36 -06:00
69726a46a4 PAN-11 created the updateDefinition method 2019-03-24 21:51:10 -06:00
ae88fd356d PAN-11 Wrote unit tests for the findById method 2019-03-24 21:41:16 -06:00
bc0d631e6c PAN-11 Wrote the findById method 2019-03-24 21:29:49 -06:00
92bea81ae5 PAN-11 Wrote unit tests for getAllDefinitions() 2019-03-24 21:23:03 -06:00
978b58fe2c PAN-11 wrote the GetAllDefinitions() method 2019-03-24 20:48:25 -06:00
8a582614f9 Merge branches 'PAN-11' and 'master' of https://github.com/atusa17/ptp into PAN-11 2019-03-24 19:20:38 -06:00
eedc7a3eee Merge remote-tracking branch 'origin/PAN-15' into PAN-15 2019-03-24 17:49:16 -06:00
0bc56f57e6 PAN-15 Merged with master 2019-03-24 17:49:07 -06:00
dantanxiaotian
cc7e6e0ed2 Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15 2019-03-24 17:45:00 -06:00
e2e2b24f3d Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15 2019-03-24 17:44:27 -06:00
Alex Tusa
c715e98e81 Merge pull request #26 from atusa17/PAN-18
Pan 18
2019-03-24 17:34:50 -06:00
dantanxiaotian
6791f6c61f Merge branch 'master' of https://github.com/atusa17/ptp into PAN-15
# Conflicts:
#	src/main/java/edu/msudenver/tsp/website/Application.java
2019-03-24 17:31:40 -06:00
zeliu
8f2968bc2b PAN-18 WORKING HOMEPAGE 2019-03-24 17:17:04 -06:00
zeliu
98f6b9e2b7 PAN-18 WORKING HOMEPAGE 2019-03-24 17:02:50 -06:00
zeliu
3b4753215c PAN-18 Refactored the HomeController 2019-03-24 15:26:08 -06:00
zeliu
94440faa4d PAN-18 Here is the JSP file for hoempage 2019-03-24 15:21:25 -06:00
zeliu
cf5135e5b0 Merge branch 'master' of https://github.com/atusa17/ptp 2019-03-24 15:18:22 -06:00
dantanxiaotian
7060f2e7e3 Merge branch 'master' of https://github.com/atusa17/ptp into PAN-15
# Conflicts:
#	src/main/java/edu/msudenver/tsp/website/Application.java
2019-03-24 15:00:20 -06:00
dantanxiaotian
89f1c55f51 PAN-15 Fixed unit tests 2019-03-24 14:54:06 -06:00
9695f5082a Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15
# Conflicts:
#	services/build.gradle
2019-03-20 22:30:11 -06:00
f5f959b453 Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15
# Conflicts:
#	services/build.gradle
2019-03-20 22:28:51 -06:00
f35777b5a6 Merge remote-tracking branch 'origin/PAN-15' into PAN-15
# Conflicts:
#	services/src/main/java/edu/msudenver/tsp/services/dto/Account.java
#	services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java
2019-03-20 22:17:24 -06:00
748781f10f Merge branches 'PAN-15' and 'master' of https://github.com/atusa17/ptp into PAN-15
# Conflicts:
#	build.gradle
#	persistence/src/main/java/edu/msudenver/tsp/persistence/repository/AccountsRepository.java
#	persistence/src/test/java/edu/msudenver/tsp/persistence/controller/AccountControllerTest.java
#	services/src/main/java/edu/msudenver/tsp/services/RestService.java
#	services/src/main/java/edu/msudenver/tsp/services/dto/Account.java
#	services/src/main/java/edu/msudenver/tsp/services/factory/RequestFactory.java
#	services/src/main/java/edu/msudenver/tsp/services/parser/ParserService.java
#	services/src/test/java/edu/msudenver/tsp/services/parser/ParserServiceTest.java
2019-03-20 22:15:32 -06:00
Alex Tusa
083c149a73 Merge branch 'master' into PAN-15 2019-03-20 22:15:08 -06:00
dantanxiaotian
860e5379e6 PAN-15 UserService.java and completed UserSservice integration test 2019-03-20 16:06:24 -06:00
b48094ba26 PAN-11 Stuck trying to get the integration tests to be configured correctly 2019-03-17 22:02:00 -06:00
3853911b3c PAN-11 corrected build.gradle inter-project dependencies 2019-03-17 21:09:07 -06:00
dantanxiaotian
46122cbafd PAN-15 Created gradle tasks to start the persistence API and to start the API asynchronously 2019-03-10 19:58:04 -06:00
dantanxiaotian
ffaf020b80 PAN-15 WORKING AND WITH TRAVIS!!! 2019-03-10 17:21:32 -06:00
dantanxiaotian
5d429b2c8e PAN-15 Updated tests 2019-03-10 17:06:47 -06:00
dantanxiaotian
ced18dcc97 Merge remote-tracking branch 'origin/PAN-15' into PAN-15 2019-03-10 17:03:59 -06:00
dantanxiaotian
238908f4fa PAN-15 Updated tests 2019-03-10 17:03:50 -06:00
dantanxiaotian
10b0a09690 PAN-15 Updated the gradle dependencies 2019-03-10 16:18:19 -06:00
dantanxiaotian
ba37ffeb57 PAN-15 Created initial UserService implementation and initial integration tests 2019-03-10 15:55:43 -06:00
zeliu
86c5e8123e Here is the JSP file for hoempage 2019-03-07 10:22:08 -07:00
36 changed files with 1647 additions and 452 deletions
+1 -1
View File
@@ -99,7 +99,7 @@ repositories {
} }
dependencies { 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.codehaus.groovy:groovy-all:2.3.11'
compile 'org.apache.commons:commons-lang3:3.5' compile 'org.apache.commons:commons-lang3:3.5'
// The production code uses the SLF4J logging API at compile time // The production code uses the SLF4J logging API at compile time
@@ -1,3 +0,0 @@
spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp
server.port=8090
+14 -14
View File
@@ -5,11 +5,11 @@ create table accounts (
id int not null auto_increment primary key unique, id int not null auto_increment primary key unique,
username varchar(50) not null unique, username varchar(50) not null unique,
password varchar(256) not null, password varchar(256) not null,
administrator_status boolean default false, administrator boolean default false,
last_login date, last_login date,
version int default 1 version int default 1
); );
insert into accounts (username, password, administrator_status) insert into accounts (username, password, administrator)
values ('admin', 'secret', true), values ('admin', 'secret', true),
('atusa', 'secret', true), ('atusa', 'secret', true),
('dantanxiaotian', 'secret', true), ('dantanxiaotian', 'secret', true),
@@ -34,17 +34,17 @@ referenced_theorems json,
proven_status boolean default false, proven_status boolean default false,
version int default 1 version int default 1
); );
CREATE TABLE proofs create table proofs
( (
id INT NOT NULL AUTO_INCREMENT, id int not null auto_increment,
theorem_name VARCHAR(512) NOT NULL, theorem_name varchar(512) not null,
proof VARCHAR(4096) NOT NULL, proof varchar(4096) not null,
branch VARCHAR(512) NOT NULL, branch varchar(512) not null,
theorem INT NOT NULL, theorem int not null,
referenced_definitions JSON, referenced_definitions json,
referenced_theorems JSON, referenced_theorems json,
date_added DATE, date_added date,
last_updated DATE, last_updated date,
version INT DEFAULT 1, version int default 1,
PRIMARY KEY (id) primary key (id)
); );
@@ -29,7 +29,7 @@ public class AccountsIntegrationTest {
assertEquals("Test username", savedAccount.getUsername()); assertEquals("Test username", savedAccount.getUsername());
assertEquals("test password", savedAccount.getPassword()); assertEquals("test password", savedAccount.getPassword());
assertTrue(savedAccount.getAdministratorStatus()); assertTrue(savedAccount.isAdministrator());
savedAccount.setPassword("Test Update"); savedAccount.setPassword("Test Update");
@@ -37,7 +37,7 @@ public class AccountsIntegrationTest {
assertEquals("Test username", savedAccount.getUsername()); assertEquals("Test username", savedAccount.getUsername());
assertEquals("Test Update", savedAccount.getPassword()); assertEquals("Test Update", savedAccount.getPassword());
assertTrue(savedAccount.getAdministratorStatus()); assertTrue(savedAccount.isAdministrator());
assertEquals(updatedAccount.getId(), id); assertEquals(updatedAccount.getId(), id);
accountsRepository.delete(account); accountsRepository.delete(account);
@@ -49,7 +49,7 @@ public class AccountsIntegrationTest {
final Account account = new Account(); final Account account = new Account();
account.setUsername("Test username"); account.setUsername("Test username");
account.setPassword("test password"); account.setPassword("test password");
account.setAdministratorStatus(true); account.setAdministrator(true);
return account; return account;
} }
@@ -18,8 +18,7 @@ import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PersistenceTestConfig.class) @ContextConfiguration(classes = PersistenceTestConfig.class)
public class ProofsIntegrationTest { public class ProofsIntegrationTest {
@Autowired @Autowired private ProofRepository proofRepository;
private ProofRepository proofRepository;
@Test @Test
public void testCRUDFunctionality() { public void testCRUDFunctionality() {
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Account; 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.persistence.repository.AccountsRepository;
import edu.msudenver.tsp.utilities.PersistenceUtilities; import edu.msudenver.tsp.utilities.PersistenceUtilities;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -23,6 +25,7 @@ import java.util.Optional;
@RestController @RestController
@AllArgsConstructor @AllArgsConstructor
@RequestMapping("/accounts") @RequestMapping("/accounts")
@Validated
public class AccountController { public class AccountController {
private final AccountsRepository accountsRepository; private final AccountsRepository accountsRepository;
@@ -48,11 +51,11 @@ public class AccountController {
@GetMapping("/id") @GetMapping("/id")
public @ResponseBody public @ResponseBody
ResponseEntity<Account> getAccountById(@RequestParam("id") final Integer id) { ResponseEntity<Account> getAccountById(@RequestParam("id") final Integer id) throws BadRequestException {
LOG.info("Received request to query for account with id {}", id); LOG.info("Received request to query for account with id {}", id);
if (id == null) { if (id == null) {
LOG.error("ERROR: ID was 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); LOG.debug("Querying for account with id {}", id);
@@ -77,11 +80,11 @@ public class AccountController {
@GetMapping("/username") @GetMapping("/username")
public @ResponseBody public @ResponseBody
ResponseEntity<Account> getAccountByUsername(@RequestParam("username") final String username) { ResponseEntity<Account> getAccountByUsername(@RequestParam("username") final String username) throws BadRequestException {
LOG.info("Received request to query for account with username {}", username); LOG.info("Received request to query for account with username {}", username);
if (username == null) { if (username == null) {
LOG.error("ERROR: username was 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); LOG.debug("Querying for account with username {}", username);
@@ -107,17 +110,18 @@ public class AccountController {
@PostMapping({"","/"}) @PostMapping({"","/"})
@Validated({Account.Insert.class, Default.class}) @Validated({Account.Insert.class, Default.class})
public @ResponseBody ResponseEntity<Account> insertAccount( public @ResponseBody ResponseEntity<Account> 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"); LOG.info("Received request to insert a new account");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (account == null) { if (account == null) {
LOG.error("Passed account is unprocessable"); 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()); LOG.info("Checking for any existing users with username {}", account.getUsername());
@@ -152,22 +156,23 @@ public class AccountController {
@PatchMapping("/{id}") @PatchMapping("/{id}")
public @ResponseBody ResponseEntity<Account> updateAccount( public @ResponseBody ResponseEntity<Account> updateAccount(
@PathVariable("id") final Integer id, @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"); LOG.info("Received request to update an account");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (account == null) { if (account == null) {
LOG.error("Passed entity is null"); LOG.error("Passed entity is null");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("Passed account is null");
} }
if (id == null) { if (id == null) {
LOG.error("Account ID must be specified"); 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); LOG.debug("Checking for existence of account with id {}", id);
@@ -204,11 +209,11 @@ public class AccountController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public @ResponseBody ResponseEntity<Void> deleteAccountById(@PathVariable("id") final Integer id) { public @ResponseBody ResponseEntity<Void> deleteAccountById(@PathVariable("id") final Integer id) throws BadRequestException {
LOG.info("Received request to delete account with id {}", id); LOG.info("Received request to delete account with id {}", id);
if (id == null) { if (id == null) {
LOG.error("Specified Id is 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); LOG.debug("Deleting account with id {}", id);
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Definition; 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.persistence.repository.DefinitionRepository;
import edu.msudenver.tsp.utilities.PersistenceUtilities; import edu.msudenver.tsp.utilities.PersistenceUtilities;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -21,6 +23,7 @@ import java.util.Optional;
@RestController @RestController
@AllArgsConstructor @AllArgsConstructor
@RequestMapping(path = "/definitions") @RequestMapping(path = "/definitions")
@Validated
public class DefinitionController { public class DefinitionController {
private final DefinitionRepository definitionRepository; private final DefinitionRepository definitionRepository;
@@ -45,11 +48,12 @@ public class DefinitionController {
@GetMapping("/{id}") @GetMapping("/{id}")
public @ResponseBody public @ResponseBody
ResponseEntity<Definition> getDefinitionById(@PathVariable("id") final Integer id) { ResponseEntity<Definition> getDefinitionById(@PathVariable("id") final Integer id)
throws BadRequestException {
LOG.info("Received request to query for definition with id {}", id); LOG.info("Received request to query for definition with id {}", id);
if (id == null) { if (id == null) {
LOG.error("ERROR: ID was null"); LOG.error("ERROR: ID cannot be null");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("ERROR: ID cannot be null");
} }
LOG.debug("Querying for definition with id {}", id); LOG.debug("Querying for definition with id {}", id);
@@ -77,16 +81,17 @@ public class DefinitionController {
@Validated({Definition.Insert.class, Default.class}) @Validated({Definition.Insert.class, Default.class})
public @ResponseBody ResponseEntity<Definition> insertDefinition( public @ResponseBody ResponseEntity<Definition> insertDefinition(
@Valid @RequestBody final Definition definition, @Valid @RequestBody final Definition definition,
final BindingResult bindingResult) { final BindingResult bindingResult)
throws UnprocessableEntityException, BadRequestException {
LOG.info("Received request to insert a new definition"); LOG.info("Received request to insert a new definition");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (definition == null) { if (definition == null) {
LOG.error("Passed entity is 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"); LOG.debug("Saving new definition");
@@ -106,22 +111,22 @@ public class DefinitionController {
@PatchMapping("/{id}") @PatchMapping("/{id}")
public @ResponseBody ResponseEntity<Definition> updateDefinition( public @ResponseBody ResponseEntity<Definition> updateDefinition(
@PathVariable("id") final Integer id, @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"); LOG.info("Received request to update an account");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (definition == null) { if (definition == null) {
LOG.error("Passed entity is null"); LOG.error("Passed entity is null");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("Passed definition is null");
} }
if (id == null) { if (id == null) {
LOG.error("Definition ID must be specified"); 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); LOG.debug("Checking for existence of definition with id {}", id);
@@ -137,7 +142,7 @@ public class DefinitionController {
if (!existingDefinition.isPresent()) { if (!existingDefinition.isPresent()) {
LOG.error("No definition associated with id {}", id); 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()); PersistenceUtilities.copyNonNullProperties(definition, existingDefinition.get());
@@ -158,11 +163,11 @@ public class DefinitionController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public @ResponseBody ResponseEntity<Void> deleteDefinitionById(@PathVariable("id") final Integer id) { public @ResponseBody ResponseEntity<Void> deleteDefinitionById(@PathVariable("id") final Integer id) throws BadRequestException {
LOG.info("Received request to delete definition with id {}", id); LOG.info("Received request to delete definition with id {}", id);
if (id == null) { if (id == null) {
LOG.error("Specified id is 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); LOG.debug("Deleting definition with id {}", id);
@@ -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<String> 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<String> handleBadRequestException(final BadRequestException e) {
return e.getErrors();
}
@ExceptionHandler(UnprocessableEntityException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public List<String> handleUnprocessableEntityException(final UnprocessableEntityException e) {
return Collections.singletonList("Request did not evaluate. Experienced the following error: " + e.getMessage());
}
}
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Proof; 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.persistence.repository.ProofRepository;
import edu.msudenver.tsp.utilities.PersistenceUtilities; import edu.msudenver.tsp.utilities.PersistenceUtilities;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -45,11 +47,11 @@ public class ProofController {
@GetMapping("/id") @GetMapping("/id")
public @ResponseBody public @ResponseBody
ResponseEntity<Proof> getProofById(@RequestParam("id") final Integer id) { ResponseEntity<Proof> getProofById(@RequestParam("id") final Integer id) throws BadRequestException {
LOG.info("Received request to query for proof with id {}", id); LOG.info("Received request to query for proof with id {}", id);
if (id == null) { if (id == null) {
LOG.error("ERROR: ID was 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); LOG.debug("Querying for proof with id {}", id);
@@ -75,11 +77,12 @@ public class ProofController {
@GetMapping("/branch") @GetMapping("/branch")
public @ResponseBody public @ResponseBody
ResponseEntity<List<Proof>> getAllProofsByBranch(@RequestParam("branch") String branch) { ResponseEntity<List<Proof>> getAllProofsByBranch(@RequestParam("branch") String branch)
throws BadRequestException {
LOG.info("Received request to query for proofs related to the {} branch of mathematics", branch); LOG.info("Received request to query for proofs related to the {} branch of mathematics", branch);
if (branch == null) { if (branch == null) {
LOG.error("ERROR: branch was 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("-")) { if (branch.contains("_") || branch.contains("-")) {
@@ -110,11 +113,12 @@ public class ProofController {
@GetMapping("/theorem_name") @GetMapping("/theorem_name")
public @ResponseBody public @ResponseBody
ResponseEntity<List<Proof>> getAllProofsByTheoremName(@RequestParam("theorem_name") String theoremName) { ResponseEntity<List<Proof>> getAllProofsByTheoremName(@RequestParam("theorem_name") String theoremName)
throws BadRequestException {
LOG.info("Received request to query for proofs of the theorem {}", theoremName); LOG.info("Received request to query for proofs of the theorem {}", theoremName);
if (theoremName == null) { if (theoremName == null) {
LOG.error("ERROR: theorem name was 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("-")) { if (theoremName.contains("_") || theoremName.contains("-")) {
@@ -147,16 +151,16 @@ public class ProofController {
@Validated({Proof.Insert.class, Default.class}) @Validated({Proof.Insert.class, Default.class})
public @ResponseBody ResponseEntity<Proof> insertProof( public @ResponseBody ResponseEntity<Proof> insertProof(
@Valid @RequestBody final Proof proof, @Valid @RequestBody final Proof proof,
final BindingResult bindingResult) { final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException {
LOG.info("Received request to insert a new proof"); LOG.info("Received request to insert a new proof");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (proof == null) { if (proof == null) {
LOG.error("Passed entity is 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"); LOG.debug("Saving new proof");
@@ -176,22 +180,23 @@ public class ProofController {
@PatchMapping("/{id}") @PatchMapping("/{id}")
public @ResponseBody ResponseEntity<Proof> updateProof( public @ResponseBody ResponseEntity<Proof> updateProof(
@PathVariable("id") final Integer id, @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"); LOG.info("Received request to update a proof");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (proof == null) { if (proof == null) {
LOG.error("Passed entity is null"); LOG.error("Passed entity is null");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("Passed proof is null");
} }
if (id == null) { if (id == null) {
LOG.error("Proof ID must be specified"); 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); LOG.debug("Checking for existence of proof with id {}", id);
@@ -207,7 +212,7 @@ public class ProofController {
if (!existingProof.isPresent()) { if (!existingProof.isPresent()) {
LOG.error("No proof associated with id {}", id); 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()); PersistenceUtilities.copyNonNullProperties(proof, existingProof.get());
@@ -228,11 +233,11 @@ public class ProofController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public @ResponseBody ResponseEntity<Void> deleteProofById(@PathVariable("id") final Integer id) { public @ResponseBody ResponseEntity<Void> deleteProofById(@PathVariable("id") final Integer id) throws BadRequestException {
LOG.info("Received request to delete proof with id {}", id); LOG.info("Received request to delete proof with id {}", id);
if (id == null) { if (id == null) {
LOG.error("Specified id is 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); LOG.debug("Deleting proof with id {}", id);
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Theorem; 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.persistence.repository.TheoremRepository;
import edu.msudenver.tsp.utilities.PersistenceUtilities; import edu.msudenver.tsp.utilities.PersistenceUtilities;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -45,11 +47,11 @@ public class TheoremController {
@GetMapping("/branch") @GetMapping("/branch")
public @ResponseBody public @ResponseBody
ResponseEntity<List<Theorem>> getAllTheoremsByBranch(@RequestParam("branch") String branch) { ResponseEntity<List<Theorem>> getAllTheoremsByBranch(@RequestParam("branch") String branch) throws BadRequestException {
LOG.info("Received request to query for theorems related to the {} branch of mathematics", branch); LOG.info("Received request to query for theorems related to the {} branch of mathematics", branch);
if (branch == null) { if (branch == null) {
LOG.error("ERROR: branch was 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("-")) { if (branch.contains("_") || branch.contains("-")) {
@@ -80,11 +82,11 @@ public class TheoremController {
@GetMapping("/proven_status") @GetMapping("/proven_status")
public @ResponseBody public @ResponseBody
ResponseEntity<List<Theorem>> getAllTheoremsByProvenStatus(@RequestParam("proven_status") final String provenStatus) { ResponseEntity<List<Theorem>> getAllTheoremsByProvenStatus(@RequestParam("proven_status") final String provenStatus) throws BadRequestException {
LOG.info("Received request to query for theorems whose proven status is {}", provenStatus); LOG.info("Received request to query for theorems whose proven status is {}", provenStatus);
if (provenStatus == null) { if (provenStatus == null) {
LOG.error("ERROR: status was 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); final Boolean isProven = Boolean.parseBoolean(provenStatus);
@@ -112,11 +114,11 @@ public class TheoremController {
@GetMapping("/name") @GetMapping("/name")
public @ResponseBody public @ResponseBody
ResponseEntity<List<Theorem>> getAllTheoremsByName(@RequestParam("name") String name) { ResponseEntity<List<Theorem>> getAllTheoremsByName(@RequestParam("name") String name) throws BadRequestException {
LOG.info("Received request to query for theorems whose name is {}", name); LOG.info("Received request to query for theorems whose name is {}", name);
if (name == null) { if (name == null) {
LOG.error("ERROR: name was 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("-")) { if (name.contains("_") || name.contains("-")) {
@@ -147,11 +149,11 @@ public class TheoremController {
@GetMapping("/id") @GetMapping("/id")
public @ResponseBody public @ResponseBody
ResponseEntity<Theorem> getTheoremById(@RequestParam("id") final Integer id) { ResponseEntity<Theorem> getTheoremById(@RequestParam("id") final Integer id) throws BadRequestException {
LOG.info("Received request to query for theorem with id {}", id); LOG.info("Received request to query for theorem with id {}", id);
if (id == null) { if (id == null) {
LOG.error("ERROR: ID was 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); LOG.debug("Querying for theorem with id {}", id);
@@ -179,16 +181,16 @@ public class TheoremController {
@Validated({Theorem.Insert.class, Default.class}) @Validated({Theorem.Insert.class, Default.class})
public @ResponseBody ResponseEntity<Theorem> insertTheorem( public @ResponseBody ResponseEntity<Theorem> insertTheorem(
@Valid @RequestBody final Theorem theorem, @Valid @RequestBody final Theorem theorem,
final BindingResult bindingResult) { final BindingResult bindingResult) throws UnprocessableEntityException, BadRequestException {
LOG.info("Received request to insert a new theorem"); LOG.info("Received request to insert a new theorem");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (theorem == null) { if (theorem == null) {
LOG.error("Passed entity is 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"); LOG.debug("Saving new theorem");
@@ -208,22 +210,22 @@ public class TheoremController {
@PatchMapping("/{id}") @PatchMapping("/{id}")
public @ResponseBody ResponseEntity<Theorem> updateTheorem( public @ResponseBody ResponseEntity<Theorem> updateTheorem(
@PathVariable("id") final Integer id, @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"); LOG.info("Received request to update a theorem");
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
LOG.error("Binding result is unprocessable"); LOG.error("Binding result is unprocessable");
return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); throw new UnprocessableEntityException(bindingResult.getAllErrors().toString());
} }
if (theorem == null) { if (theorem == null) {
LOG.error("Passed entity is null"); LOG.error("Passed entity is null");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("Passed theorem is null");
} }
if (id == null) { if (id == null) {
LOG.error("Theorem ID must be specified"); 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); LOG.debug("Checking for existence of theorem with id {}", id);
@@ -239,7 +241,7 @@ public class TheoremController {
if (!existingTheorem.isPresent()) { if (!existingTheorem.isPresent()) {
LOG.error("No theorem associated with id {}", id); 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()); PersistenceUtilities.copyNonNullProperties(theorem, existingTheorem.get());
@@ -260,11 +262,11 @@ public class TheoremController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public @ResponseBody ResponseEntity<Void> deleteTheoremById(@PathVariable("id") final Integer id) { public @ResponseBody ResponseEntity<Void> deleteTheoremById(@PathVariable("id") final Integer id) throws BadRequestException {
LOG.info("Received request to delete theorem with id {}", id); LOG.info("Received request to delete theorem with id {}", id);
if (id == null) { if (id == null) {
LOG.error("Specified id is 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); LOG.debug("Deleting theorem with id {}", id);
@@ -19,21 +19,11 @@ import java.util.Date;
public class Account extends BaseDto implements Serializable { 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 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; @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; @Temporal(TemporalType.DATE) @Column(name = "last_login") private Date lastLogin;
private static final long serialVersionUID = 7095627971593953734L; 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") @JsonProperty("last_login")
public Date getLastLogin() { public Date getLastLogin() {
return lastLogin; return lastLogin;
@@ -10,6 +10,7 @@ import javax.persistence.Entity;
import javax.persistence.EntityListeners; import javax.persistence.EntityListeners;
import javax.persistence.Table; import javax.persistence.Table;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; 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") @Size(min = 1, max = 200, message = "Must be between 1 and 200 characters")
private String name; 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<String> definition; @Type(type = "json") @Column(columnDefinition = "jsonb") private List<String> definition;
@Type(type = "json") @Column(columnDefinition = "jsonb") private List<String> notation; @Type(type = "json") @Column(columnDefinition = "jsonb") private List<String> notation;
@@ -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<String> errors;
public BadRequestException(final String message) {
super(message);
errors = Collections.singletonList(message);
}
public BadRequestException(final List<String> errorMessages) {
super(String.join(" ", errorMessages));
errors = errorMessages;
}
}
@@ -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<String> errors;
public UnprocessableEntityException(final String message) {
super(message);
errors = Collections.singletonList(message);
}
public UnprocessableEntityException(final List<String> errorMessages) {
super(String.join(" ", errorMessages));
errors = errorMessages;
}
}
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Account; 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.persistence.repository.AccountsRepository;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -25,10 +27,8 @@ import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
@WebMvcTest(controllers = AccountController.class) @WebMvcTest(controllers = AccountController.class)
public class AccountControllerTest { public class AccountControllerTest {
@Mock @Mock private AccountsRepository accountsRepository;
private AccountsRepository accountsRepository; @InjectMocks private AccountController accountController;
@InjectMocks
private AccountController accountController;
@Mock private BindingResult bindingResult; @Mock private BindingResult bindingResult;
@Test @Test
@@ -51,7 +51,7 @@ public class AccountControllerTest {
} }
@Test @Test
public void testGetAccountById() { public void testGetAccountById() throws BadRequestException {
final Account account = createAccount(); final Account account = createAccount();
when(accountsRepository.findById(anyInt())).thenReturn(Optional.ofNullable(account)); when(accountsRepository.findById(anyInt())).thenReturn(Optional.ofNullable(account));
@@ -65,18 +65,13 @@ public class AccountControllerTest {
verify(accountsRepository).findById(anyInt()); verify(accountsRepository).findById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAccountById_nullId() { public void testGetAccountById_nullId() throws BadRequestException {
final ResponseEntity responseEntity = accountController.getAccountById(null); accountController.getAccountById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(accountsRepository);
} }
@Test @Test
public void testGetAccountById_noAccountFound() { public void testGetAccountById_noAccountFound() throws BadRequestException {
when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty()); when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity responseEntity = accountController.getAccountById(1); final ResponseEntity responseEntity = accountController.getAccountById(1);
@@ -88,7 +83,7 @@ public class AccountControllerTest {
} }
@Test @Test
public void testGetAccountByUsername() { public void testGetAccountByUsername() throws BadRequestException {
final Account account = createAccount(); final Account account = createAccount();
when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.ofNullable(account)); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.ofNullable(account));
@@ -102,18 +97,13 @@ public class AccountControllerTest {
verify(accountsRepository).findByUsername(anyString()); verify(accountsRepository).findByUsername(anyString());
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAccountById_nullUsername() { public void testGetAccountById_nullUsername() throws BadRequestException {
final ResponseEntity responseEntity = accountController.getAccountByUsername(null); accountController.getAccountByUsername(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(accountsRepository);
} }
@Test @Test
public void testGetAccountByUsername_noAccountFound() { public void testGetAccountByUsername_noAccountFound() throws BadRequestException {
when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty()); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty());
final ResponseEntity responseEntity = accountController.getAccountByUsername("Test username"); final ResponseEntity responseEntity = accountController.getAccountByUsername("Test username");
@@ -125,7 +115,7 @@ public class AccountControllerTest {
} }
@Test @Test
public void testInsertAccount() { public void testInsertAccount() throws UnprocessableEntityException, BadRequestException {
final Account account = createAccount(); final Account account = createAccount();
when(accountsRepository.save(any(Account.class))).thenReturn(account); when(accountsRepository.save(any(Account.class))).thenReturn(account);
when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty()); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.empty());
@@ -141,7 +131,7 @@ public class AccountControllerTest {
} }
@Test @Test
public void testInsertAccount_usernameAlreadyExists() { public void testInsertAccount_usernameAlreadyExists() throws UnprocessableEntityException, BadRequestException {
final Account account = createAccount(); final Account account = createAccount();
when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.of(account)); when(accountsRepository.findByUsername(anyString())).thenReturn(Optional.of(account));
@@ -154,8 +144,8 @@ public class AccountControllerTest {
verify(accountsRepository, times(0)).save(any(Account.class)); verify(accountsRepository, times(0)).save(any(Account.class));
} }
@Test @Test(expected = BadRequestException.class)
public void testInsertAccount_accountsDtoIsNull() { public void testInsertAccount_accountsDtoIsNull() throws UnprocessableEntityException, BadRequestException {
final ResponseEntity responseEntity = accountController.insertAccount(null, bindingResult); final ResponseEntity responseEntity = accountController.insertAccount(null, bindingResult);
assertNotNull(responseEntity); assertNotNull(responseEntity);
@@ -164,21 +154,16 @@ public class AccountControllerTest {
verifyZeroInteractions(accountsRepository); verifyZeroInteractions(accountsRepository);
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testInsertAccount_bindingResultHasErrors() { public void testInsertAccount_bindingResultHasErrors() throws UnprocessableEntityException, BadRequestException {
final Account account = createAccount(); final Account account = createAccount();
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity responseEntity = accountController.insertAccount(account, bindingResult); accountController.insertAccount(account, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode());
verifyZeroInteractions(accountsRepository);
} }
@Test @Test
public void testUpdateAccount() { public void testUpdateAccount() throws UnprocessableEntityException, BadRequestException {
final Account existingAccount = createAccount(); final Account existingAccount = createAccount();
existingAccount.setId(1); existingAccount.setId(1);
existingAccount.setVersion(1); existingAccount.setVersion(1);
@@ -199,40 +184,25 @@ public class AccountControllerTest {
verify(accountsRepository).save(any(Account.class)); verify(accountsRepository).save(any(Account.class));
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testUpdateAccount_bindingResultHasErrors() { public void testUpdateAccount_bindingResultHasErrors() throws UnprocessableEntityException, BadRequestException {
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity<Account> responseEntity = accountController.updateAccount(1, createAccount(), bindingResult); accountController.updateAccount(1, createAccount(), bindingResult);
}
assertNotNull(responseEntity); @Test(expected = BadRequestException.class)
assertFalse(responseEntity.hasBody()); public void testUpdateAccount_accountsDtoIsNull() throws UnprocessableEntityException, BadRequestException {
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); accountController.updateAccount(1, null, bindingResult);
verifyZeroInteractions(accountsRepository); }
@Test(expected = BadRequestException.class)
public void testUpdateAccount_idIsNull() throws UnprocessableEntityException, BadRequestException {
accountController.updateAccount(null, createAccount(), bindingResult);
} }
@Test @Test
public void testUpdateAccount_accountsDtoIsNull() { public void testUpdateAccount_accountDoesNotExist() throws UnprocessableEntityException, BadRequestException {
final ResponseEntity<Account> 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<Account> responseEntity = accountController.updateAccount(null, createAccount(), bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(accountsRepository);
}
@Test
public void testUpdateAccount_accountDoesNotExist() {
when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty()); when(accountsRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity<Account> responseEntity = accountController.updateAccount(1, createAccount(), bindingResult); final ResponseEntity<Account> responseEntity = accountController.updateAccount(1, createAccount(), bindingResult);
@@ -244,7 +214,7 @@ public class AccountControllerTest {
} }
@Test @Test
public void testDeleteAccountById() { public void testDeleteAccountById() throws BadRequestException {
doNothing().when(accountsRepository).deleteById(anyInt()); doNothing().when(accountsRepository).deleteById(anyInt());
final ResponseEntity responseEntity = accountController.deleteAccountById(1); final ResponseEntity responseEntity = accountController.deleteAccountById(1);
@@ -255,21 +225,16 @@ public class AccountControllerTest {
verify(accountsRepository).deleteById(anyInt()); verify(accountsRepository).deleteById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testDeleteAccountById_idIsNull() { public void testDeleteAccountById_idIsNull() throws BadRequestException {
final ResponseEntity responseEntity = accountController.deleteAccountById(null); accountController.deleteAccountById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(accountsRepository);
} }
private Account createAccount() { private Account createAccount() {
final Account account = new Account(); final Account account = new Account();
account.setUsername("Test username"); account.setUsername("Test username");
account.setPassword("test password"); account.setPassword("test password");
account.setAdministratorStatus(true); account.setAdministrator(true);
return account; return account;
} }
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Definition; 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.persistence.repository.DefinitionRepository;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -48,7 +50,7 @@ public class DefinitionControllerTest {
} }
@Test @Test
public void testGetDefinitionsById() { public void testGetDefinitionsById() throws BadRequestException {
final Definition definition = createDefinition(); final Definition definition = createDefinition();
when(definitionRepository.findById(anyInt())).thenReturn(Optional.ofNullable(definition)); when(definitionRepository.findById(anyInt())).thenReturn(Optional.ofNullable(definition));
@@ -62,18 +64,13 @@ public class DefinitionControllerTest {
verify(definitionRepository).findById(anyInt()); verify(definitionRepository).findById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testGetDefinitionById_nullId() { public void testGetDefinitionById_nullId() throws BadRequestException {
final ResponseEntity responseEntity = definitionController.getDefinitionById(null); definitionController.getDefinitionById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(definitionRepository);
} }
@Test @Test
public void testGetDefinitionById_noDefinitionFound() { public void testGetDefinitionById_noDefinitionFound() throws BadRequestException {
when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty()); when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity responseEntity = definitionController.getDefinitionById(1); final ResponseEntity responseEntity = definitionController.getDefinitionById(1);
@@ -85,7 +82,7 @@ public class DefinitionControllerTest {
} }
@Test @Test
public void testInsertDefinition() { public void testInsertDefinition() throws BadRequestException, UnprocessableEntityException {
final Definition definition = createDefinition(); final Definition definition = createDefinition();
when(definitionRepository.save(any(Definition.class))).thenReturn(definition); when(definitionRepository.save(any(Definition.class))).thenReturn(definition);
@@ -99,31 +96,21 @@ public class DefinitionControllerTest {
verify(definitionRepository).save(any(Definition.class)); verify(definitionRepository).save(any(Definition.class));
} }
@Test @Test(expected = BadRequestException.class)
public void testInsertDefinition_definitionDtoIsNull() { public void testInsertDefinition_definitionDtoIsNull() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity responseEntity = definitionController.insertDefinition(null, bindingResult); definitionController.insertDefinition(null, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(definitionRepository);
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testInsertDefinition_bindingResultHasErrors() { public void testInsertDefinition_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException {
final Definition definition = createDefinition(); final Definition definition = createDefinition();
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity responseEntity = definitionController.insertDefinition(definition, bindingResult); definitionController.insertDefinition(definition, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode());
verifyZeroInteractions(definitionRepository);
} }
@Test @Test
public void testUpdateDefinition() { public void testUpdateDefinition() throws BadRequestException, UnprocessableEntityException {
final Definition existingDefinition = createDefinition(); final Definition existingDefinition = createDefinition();
existingDefinition.setId(1); existingDefinition.setId(1);
existingDefinition.setVersion(1); existingDefinition.setVersion(1);
@@ -144,52 +131,37 @@ public class DefinitionControllerTest {
verify(definitionRepository).save(any(Definition.class)); verify(definitionRepository).save(any(Definition.class));
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testUpdateDefinition_bindingResultErrors() { public void testUpdateDefinition_bindingResultErrors() throws BadRequestException, UnprocessableEntityException {
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity<Definition> responseEntity = definitionController.updateDefinition(1, createDefinition(), bindingResult); definitionController.updateDefinition(1, createDefinition(), bindingResult);
}
assertNotNull(responseEntity); @Test(expected = BadRequestException.class)
assertFalse(responseEntity.hasBody()); public void testUpdateDefinition_definitionDtoIsNull() throws BadRequestException, UnprocessableEntityException {
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); definitionController.updateDefinition(1, null, bindingResult);
verifyZeroInteractions(definitionRepository); }
@Test(expected = BadRequestException.class)
public void testUpdateDefinition_idIsNull() throws BadRequestException, UnprocessableEntityException {
definitionController.updateDefinition(null, createDefinition(), bindingResult);
} }
@Test @Test
public void testUpdateDefinition_definitionDtoIsNull() { public void testUpdateDefinition_definitionDoesntExist() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity<Definition> 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<Definition> responseEntity = definitionController.updateDefinition(null, createDefinition(), bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(definitionRepository);
}
@Test
public void testUpdateDefinition_definitionDoesntExist() {
when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty()); when(definitionRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity<Definition> responseEntity = definitionController.updateDefinition(1, createDefinition(), bindingResult); final ResponseEntity<Definition> responseEntity = definitionController.updateDefinition(1, createDefinition(), bindingResult);
assertNotNull(responseEntity); assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody()); assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
verify(definitionRepository, times(0)).save(any(Definition.class)); verify(definitionRepository, times(0)).save(any(Definition.class));
} }
@Test @Test
public void testDeleteDefinitionById() { public void testDeleteDefinitionById() throws BadRequestException {
doNothing().when(definitionRepository).deleteById(anyInt()); doNothing().when(definitionRepository).deleteById(anyInt());
final ResponseEntity responseEntity = definitionController.deleteDefinitionById(1); final ResponseEntity responseEntity = definitionController.deleteDefinitionById(1);
@@ -200,14 +172,9 @@ public class DefinitionControllerTest {
verify(definitionRepository).deleteById(anyInt()); verify(definitionRepository).deleteById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testDeleteDefinitionById_nullId() { public void testDeleteDefinitionById_nullId() throws BadRequestException {
final ResponseEntity responseEntity = definitionController.deleteDefinitionById(null); definitionController.deleteDefinitionById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(definitionRepository);
} }
private Definition createDefinition() { private Definition createDefinition() {
@@ -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());
}
}
@@ -1,6 +1,8 @@
package edu.msudenver.tsp.persistence.controller; package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Proof; 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.persistence.repository.ProofRepository;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -45,7 +47,7 @@ public class ProofControllerTest {
} }
@Test @Test
public void testGetAllProofsByBranch() { public void testGetAllProofsByBranch() throws BadRequestException {
final Proof proofDto = createProof(); final Proof proofDto = createProof();
final List<Proof> listOfProofs = new ArrayList<>(); final List<Proof> listOfProofs = new ArrayList<>();
listOfProofs.add(proofDto); listOfProofs.add(proofDto);
@@ -63,18 +65,13 @@ public class ProofControllerTest {
responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof)); responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof));
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAllProfsByBranch_nullBranch() { public void testGetAllProfsByBranch_nullBranch() throws BadRequestException {
final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByBranch(null); proofController.getAllProofsByBranch(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
@Test @Test
public void testGetAllProofsByBranch_noProofsFound() { public void testGetAllProofsByBranch_noProofsFound() throws BadRequestException {
when(proofRepository.findByBranch(anyString())).thenReturn(Collections.emptyList()); when(proofRepository.findByBranch(anyString())).thenReturn(Collections.emptyList());
final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByBranch("test-nonexistent-branch"); final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByBranch("test-nonexistent-branch");
@@ -85,7 +82,7 @@ public class ProofControllerTest {
} }
@Test @Test
public void testGetAllProofsByTheoremName() { public void testGetAllProofsByTheoremName() throws BadRequestException {
final Proof proofDto = createProof(); final Proof proofDto = createProof();
final List<Proof> listOfProofs = new ArrayList<>(); final List<Proof> listOfProofs = new ArrayList<>();
listOfProofs.add(proofDto); listOfProofs.add(proofDto);
@@ -103,18 +100,13 @@ public class ProofControllerTest {
responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof)); responseEntity.getBody().forEach(proof -> assertEquals(proofDto, proof));
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAllProofsByTheoremName_nullTheoremName() { public void testGetAllProofsByTheoremName_nullTheoremName() throws BadRequestException {
final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByTheoremName(null); proofController.getAllProofsByTheoremName(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
@Test @Test
public void testGetAllProofsByTheoremName_noProofsFound() { public void testGetAllProofsByTheoremName_noProofsFound() throws BadRequestException {
when(proofRepository.findByTheoremName(anyString())).thenReturn(Collections.emptyList()); when(proofRepository.findByTheoremName(anyString())).thenReturn(Collections.emptyList());
final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByTheoremName("test-nonexistent-proof"); final ResponseEntity<List<Proof>> responseEntity = proofController.getAllProofsByTheoremName("test-nonexistent-proof");
@@ -125,7 +117,7 @@ public class ProofControllerTest {
} }
@Test @Test
public void testGetProofById() { public void testGetProofById() throws BadRequestException {
final Proof proof = createProof(); final Proof proof = createProof();
when(proofRepository.findById(anyInt())).thenReturn(Optional.ofNullable(proof)); when(proofRepository.findById(anyInt())).thenReturn(Optional.ofNullable(proof));
@@ -139,18 +131,13 @@ public class ProofControllerTest {
verify(proofRepository).findById(anyInt()); verify(proofRepository).findById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testGetProofById_nullId() { public void testGetProofById_nullId() throws BadRequestException {
final ResponseEntity responseEntity = proofController.getProofById(null); proofController.getProofById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
@Test @Test
public void testGetProofById_noProofFound() { public void testGetProofById_noProofFound() throws BadRequestException {
when(proofRepository.findById(anyInt())).thenReturn(Optional.empty()); when(proofRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity responseEntity = proofController.getProofById(1); final ResponseEntity responseEntity = proofController.getProofById(1);
@@ -162,7 +149,7 @@ public class ProofControllerTest {
} }
@Test @Test
public void testInsertProof() { public void testInsertProof() throws BadRequestException, UnprocessableEntityException {
final Proof proof = createProof(); final Proof proof = createProof();
when(proofRepository.save(any(Proof.class))).thenReturn(proof); when(proofRepository.save(any(Proof.class))).thenReturn(proof);
@@ -176,31 +163,21 @@ public class ProofControllerTest {
verify(proofRepository).save(any(Proof.class)); verify(proofRepository).save(any(Proof.class));
} }
@Test @Test(expected = BadRequestException.class)
public void testInsertProof_proofDtoIsNull() { public void testInsertProof_proofDtoIsNull() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity responseEntity = proofController.insertProof(null, bindingResult); proofController.insertProof(null, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testInsertProof_bindingResultHasErrors() { public void testInsertProof_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException {
final Proof proof = createProof(); final Proof proof = createProof();
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity responseEntity = proofController.insertProof(proof, bindingResult); proofController.insertProof(proof, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
@Test @Test
public void testUpdateProof() { public void testUpdateProof() throws BadRequestException, UnprocessableEntityException {
final Proof existingProof = createProof(); final Proof existingProof = createProof();
existingProof.setId(1); existingProof.setId(1);
existingProof.setVersion(1); existingProof.setVersion(1);
@@ -221,52 +198,37 @@ public class ProofControllerTest {
verify(proofRepository).save(any(Proof.class)); verify(proofRepository).save(any(Proof.class));
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testUpdateProof_bindingResultHasErrors() { public void testUpdateProof_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException {
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity<Proof> responseEntity = proofController.updateProof(1, createProof(), bindingResult); proofController.updateProof(1, createProof(), bindingResult);
}
assertNotNull(responseEntity); @Test(expected = BadRequestException.class)
assertFalse(responseEntity.hasBody()); public void testUpdateProof_proofDtoIsNull() throws BadRequestException, UnprocessableEntityException {
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); proofController.updateProof(1, null, bindingResult);
verifyZeroInteractions(proofRepository); }
@Test(expected = BadRequestException.class)
public void testUpdateProof_idIsNull() throws BadRequestException, UnprocessableEntityException {
proofController.updateProof(null, createProof(), bindingResult);
} }
@Test @Test
public void testUpdateProof_proofDtoIsNull() { public void testUpdateProof_theoremDoesNotExist() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity<Proof> 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<Proof> responseEntity = proofController.updateProof(null, createProof(), bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
}
@Test
public void testUpdateProof_theoremDoesNotExist() {
when(proofRepository.findById(anyInt())).thenReturn(Optional.empty()); when(proofRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity<Proof> responseEntity = proofController.updateProof(1, createProof(), bindingResult); final ResponseEntity<Proof> responseEntity = proofController.updateProof(1, createProof(), bindingResult);
assertNotNull(responseEntity); assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody()); assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
verify(proofRepository, times(0)).save(any(Proof.class)); verify(proofRepository, times(0)).save(any(Proof.class));
} }
@Test @Test
public void testDeleteProofById() { public void testDeleteProofById() throws BadRequestException {
doNothing().when(proofRepository).deleteById(anyInt()); doNothing().when(proofRepository).deleteById(anyInt());
final ResponseEntity responseEntity = proofController.deleteProofById(1); final ResponseEntity responseEntity = proofController.deleteProofById(1);
@@ -277,14 +239,9 @@ public class ProofControllerTest {
verify(proofRepository).deleteById(anyInt()); verify(proofRepository).deleteById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testDeleteProofById_idIsNull() { public void testDeleteProofById_idIsNull() throws BadRequestException {
final ResponseEntity responseEntity = proofController.deleteProofById(null); proofController.deleteProofById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(proofRepository);
} }
private Proof createProof() { private Proof createProof() {
@@ -2,6 +2,8 @@ package edu.msudenver.tsp.persistence.controller;
import edu.msudenver.tsp.persistence.dto.Theorem; import edu.msudenver.tsp.persistence.dto.Theorem;
import edu.msudenver.tsp.persistence.dto.TheoremType; 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 edu.msudenver.tsp.persistence.repository.TheoremRepository;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -50,7 +52,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testGetTheoremById() { public void testGetTheoremById() throws BadRequestException {
final Theorem theorem = createTheorem(); final Theorem theorem = createTheorem();
when(theoremRepository.findById(anyInt())).thenReturn(Optional.ofNullable(theorem)); when(theoremRepository.findById(anyInt())).thenReturn(Optional.ofNullable(theorem));
@@ -64,18 +66,13 @@ public class TheoremControllerTest {
verify(theoremRepository).findById(anyInt()); verify(theoremRepository).findById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testGetTheoremById_nullId() { public void testGetTheoremById_nullId() throws BadRequestException {
final ResponseEntity responseEntity = theoremController.getTheoremById(null); theoremController.getTheoremById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test
public void testGetTheoremById_noTheoremFound() { public void testGetTheoremById_noTheoremFound() throws BadRequestException {
when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty()); when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity responseEntity = theoremController.getTheoremById(1); final ResponseEntity responseEntity = theoremController.getTheoremById(1);
@@ -87,7 +84,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testGetAllTheoremsByBranch() { public void testGetAllTheoremsByBranch() throws BadRequestException {
final Theorem theoremDto = createTheorem(); final Theorem theoremDto = createTheorem();
final List<Theorem> listOfTheorems = new ArrayList<>(); final List<Theorem> listOfTheorems = new ArrayList<>();
listOfTheorems.add(theoremDto); listOfTheorems.add(theoremDto);
@@ -105,18 +102,13 @@ public class TheoremControllerTest {
responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem));
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAllTheoremsByBranch_nullBranch() { public void testGetAllTheoremsByBranch_nullBranch() throws BadRequestException {
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByBranch(null); theoremController.getAllTheoremsByBranch(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test
public void testGetAllTheoremsByBranch_noTheoremsFound() { public void testGetAllTheoremsByBranch_noTheoremsFound() throws BadRequestException {
when(theoremRepository.findByBranch(anyString())).thenReturn(Collections.emptyList()); when(theoremRepository.findByBranch(anyString())).thenReturn(Collections.emptyList());
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByBranch("test_nonexistent_branch"); final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByBranch("test_nonexistent_branch");
@@ -127,7 +119,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testGetAllTheoremsByProvenStatus() { public void testGetAllTheoremsByProvenStatus() throws BadRequestException {
final Theorem theoremDto = createTheorem(); final Theorem theoremDto = createTheorem();
final List<Theorem> listOfTheorems = new ArrayList<>(); final List<Theorem> listOfTheorems = new ArrayList<>();
listOfTheorems.add(theoremDto); listOfTheorems.add(theoremDto);
@@ -145,18 +137,13 @@ public class TheoremControllerTest {
responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem));
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAllTheoremsByProvenStatus_nullProvenStatus() { public void testGetAllTheoremsByProvenStatus_nullProvenStatus() throws BadRequestException {
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByProvenStatus(null); theoremController.getAllTheoremsByProvenStatus(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test
public void testGetAllTheoremsByProvenStatus_invalidProvenStatus() { public void testGetAllTheoremsByProvenStatus_invalidProvenStatus() throws BadRequestException {
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByProvenStatus("test"); final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByProvenStatus("test");
assertNotNull(responseEntity); assertNotNull(responseEntity);
@@ -165,7 +152,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testGetAllTheoremsByProvenStatus_noTheoremsFound() { public void testGetAllTheoremsByProvenStatus_noTheoremsFound() throws BadRequestException {
when(theoremRepository.findByProvenStatus(anyBoolean())).thenReturn(Collections.emptyList()); when(theoremRepository.findByProvenStatus(anyBoolean())).thenReturn(Collections.emptyList());
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByProvenStatus("false"); final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByProvenStatus("false");
@@ -176,7 +163,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testGetAllTheoremsByName() { public void testGetAllTheoremsByName() throws BadRequestException {
final Theorem theoremDto = createTheorem(); final Theorem theoremDto = createTheorem();
final List<Theorem> listOfTheorems = new ArrayList<>(); final List<Theorem> listOfTheorems = new ArrayList<>();
listOfTheorems.add(theoremDto); listOfTheorems.add(theoremDto);
@@ -194,18 +181,13 @@ public class TheoremControllerTest {
responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem)); responseEntity.getBody().forEach(theorem -> assertEquals(theoremDto, theorem));
} }
@Test @Test(expected = BadRequestException.class)
public void testGetAllTheoremsByName_nullName() { public void testGetAllTheoremsByName_nullName() throws BadRequestException {
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByName(null); theoremController.getAllTheoremsByName(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test
public void testGetAllTheoremsByName_noNameFound() { public void testGetAllTheoremsByName_noNameFound() throws BadRequestException {
when(theoremRepository.findByName(anyString())).thenReturn(Collections.emptyList()); when(theoremRepository.findByName(anyString())).thenReturn(Collections.emptyList());
final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByName("No-name"); final ResponseEntity<List<Theorem>> responseEntity = theoremController.getAllTheoremsByName("No-name");
@@ -216,7 +198,7 @@ public class TheoremControllerTest {
} }
@Test @Test
public void testInsertTheorem() { public void testInsertTheorem() throws BadRequestException, UnprocessableEntityException {
final Theorem theorem = createTheorem(); final Theorem theorem = createTheorem();
when(theoremRepository.save(any(Theorem.class))).thenReturn(theorem); when(theoremRepository.save(any(Theorem.class))).thenReturn(theorem);
@@ -230,31 +212,21 @@ public class TheoremControllerTest {
verify(theoremRepository).save(any(Theorem.class)); verify(theoremRepository).save(any(Theorem.class));
} }
@Test @Test(expected = BadRequestException.class)
public void testInsertTheorem_theoremDtoIsNull() { public void testInsertTheorem_theoremDtoIsNull() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity responseEntity = theoremController.insertTheorem(null, bindingResult); theoremController.insertTheorem(null, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testInsertTheorem_bindingResultHasErrors() { public void testInsertTheorem_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException {
final Theorem theorem = createTheorem(); final Theorem theorem = createTheorem();
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity responseEntity = theoremController.insertTheorem(theorem, bindingResult); theoremController.insertTheorem(theorem, bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
@Test @Test
public void testUpdateTheorem() { public void testUpdateTheorem() throws BadRequestException, UnprocessableEntityException {
final Theorem existingTheorem = createTheorem(); final Theorem existingTheorem = createTheorem();
existingTheorem.setId(1); existingTheorem.setId(1);
existingTheorem.setVersion(1); existingTheorem.setVersion(1);
@@ -275,52 +247,37 @@ public class TheoremControllerTest {
verify(theoremRepository).save(any(Theorem.class)); verify(theoremRepository).save(any(Theorem.class));
} }
@Test @Test(expected = UnprocessableEntityException.class)
public void testUpdateTheorem_bindingResultHasErrors() { public void testUpdateTheorem_bindingResultHasErrors() throws BadRequestException, UnprocessableEntityException {
when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasErrors()).thenReturn(true);
final ResponseEntity<Theorem> responseEntity = theoremController.updateTheorem(1, createTheorem(), bindingResult); theoremController.updateTheorem(1, createTheorem(), bindingResult);
}
assertNotNull(responseEntity); @Test(expected = BadRequestException.class)
assertFalse(responseEntity.hasBody()); public void testUpdateTheorem_theoremDtoIsNull() throws BadRequestException, UnprocessableEntityException {
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); theoremController.updateTheorem(1, null, bindingResult);
verifyZeroInteractions(theoremRepository); }
@Test(expected = BadRequestException.class)
public void testUpdateTheorem_idIsNull() throws BadRequestException, UnprocessableEntityException {
theoremController.updateTheorem(null, createTheorem(), bindingResult);
} }
@Test @Test
public void testUpdateTheorem_theoremDtoIsNull() { public void testUpdateTheorem_theoremDoesNotExist() throws BadRequestException, UnprocessableEntityException {
final ResponseEntity<Theorem> 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<Theorem> responseEntity = theoremController.updateTheorem(null, createTheorem(), bindingResult);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
}
@Test
public void testUpdateTheorem_theoremDoesNotExist() {
when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty()); when(theoremRepository.findById(anyInt())).thenReturn(Optional.empty());
final ResponseEntity<Theorem> responseEntity = theoremController.updateTheorem(1, createTheorem(), bindingResult); final ResponseEntity<Theorem> responseEntity = theoremController.updateTheorem(1, createTheorem(), bindingResult);
assertNotNull(responseEntity); assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody()); assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
verify(theoremRepository, times(0)).save(any(Theorem.class)); verify(theoremRepository, times(0)).save(any(Theorem.class));
} }
@Test @Test
public void testDeleteTheoremById() { public void testDeleteTheoremById() throws BadRequestException {
doNothing().when(theoremRepository).deleteById(anyInt()); doNothing().when(theoremRepository).deleteById(anyInt());
final ResponseEntity responseEntity = theoremController.deleteTheoremById(1); final ResponseEntity responseEntity = theoremController.deleteTheoremById(1);
@@ -331,14 +288,9 @@ public class TheoremControllerTest {
verify(theoremRepository).deleteById(anyInt()); verify(theoremRepository).deleteById(anyInt());
} }
@Test @Test(expected = BadRequestException.class)
public void testDeleteTheoremById_idIsNull() { public void testDeleteTheoremById_idIsNull() throws BadRequestException {
final ResponseEntity responseEntity = theoremController.deleteTheoremById(null); theoremController.deleteTheoremById(null);
assertNotNull(responseEntity);
assertFalse(responseEntity.hasBody());
assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
verifyZeroInteractions(theoremRepository);
} }
private Theorem createTheorem() { private Theorem createTheorem() {
+4 -1
View File
@@ -18,12 +18,15 @@ repositories {
} }
dependencies { dependencies {
compile project(':persistence')
compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.11' 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: 'org.apache.httpcomponents', name: 'fluent-hc', version: '4.5.7'
compile group: 'com.google.code.gson', name: 'gson', version: '2.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') compile fileTree(dir: 'lib', include: '**/*.jar')
testCompile "org.springframework:spring-test:5.0.9.RELEASE" testCompile "org.springframework:spring-test:5.0.9.RELEASE"
testCompile group: 'junit', name: 'junit', version: '4.12' testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.springframework', name: 'spring-test', version: '5.1.5.RELEASE'
} }
@@ -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<Definition> 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<Definition> 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<Definition> 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<Definition> deletedDefinitionFoundById = definitionService.findById(createdDefinition.get().getId());
assertFalse(deletedDefinitionFoundById.isPresent());
}
private Definition createDefinition() {
final List<String> definitionList = new ArrayList<>();
definitionList.add("Test definition 1");
final List<String> notationList = new ArrayList<>();
notationList.add("\\testLaTeX");
final Definition definition = new Definition();
definition.setName("Test Name");
definition.setDefinition(definitionList);
definition.setNotation(notationList);
return definition;
}
}
@@ -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);
}
}
@@ -0,0 +1,74 @@
package edu.msudenver.tsp.services;
import edu.msudenver.tsp.services.dto.Account;
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.util.Date;
import java.util.Optional;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ServicesTestConfig.class)
@TestPropertySource("classpath:test.properties")
public class UserServiceIntegrationTest {
@Autowired
@Qualifier("userService")
private UserService userService;
@Test
public void testCRUD() {
final Account testAccount = createAccount();
final Optional<Account> testCreatedAccount = userService.createAccount(testAccount);
assertTrue(testCreatedAccount.isPresent());
final Account returnedAccount = testCreatedAccount.get();
assertEquals("test_user", returnedAccount.getUsername());
assertEquals("test_password", returnedAccount.getPassword());
assertFalse(returnedAccount.isAdministrator());
final Optional<Account> 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.isAdministrator());
final Optional<Account> 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.isAdministrator());
returnedAccount.setUsername("test_updatedUser");
returnedAccount.setPassword("test_updatedPassword");
final Optional<Account> updatedAccount = userService.updateAccount(returnedAccount);
assertTrue(updatedAccount .isPresent());
final Account returnedUpdatedAccount = updatedAccount.get();
assertEquals("test_updatedUser", returnedUpdatedAccount.getUsername());
assertEquals("test_updatedPassword", returnedUpdatedAccount.getPassword());
assertFalse(returnedUpdatedAccount.isAdministrator());
final boolean result = userService.deleteAccount(returnedUpdatedAccount);
assertTrue(result);
}
private Account createAccount() {
final Account testAccount = new Account();
testAccount.setUsername("test_user");
testAccount.setPassword("test_password");
testAccount.setAdministrator(false);
testAccount.setLastLogin(new Date());
return testAccount;
}
}
@@ -0,0 +1,3 @@
persistence.api.connection.timeout.milliseconds=5000
persistence.api.socket.timeout.milliseconds=10000
persistence.api.base.url=http://localhost:8090/
@@ -0,0 +1,186 @@
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.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
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<List<Definition>> getAllDefinitions() {
final Instant start = Instant.now();
try {
final TypeToken<List<Definition>> typeToken = new TypeToken<List<Definition>>(){};
final Optional<List<Definition>> 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<Definition> 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<Definition> typeToken = new TypeToken<Definition>(){};
final Optional<Definition> persistenceApiResponse = restService.get(persistenceApiBaseUrl + "definitions/" + 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<Definition> 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<Definition> typeToken = new TypeToken<Definition>() {};
final Optional<Definition> persistenceApiResponse = restService.post(persistenceApiBaseUrl + "definitions/",
new GsonBuilder().create().toJson(definition),
typeToken,
connectionTimeoutMilliseconds,
socketTimeoutMilliseconds);
if (persistenceApiResponse.isPresent()) {
LOG.info("Creation successful. Returning {}", persistenceApiResponse.get());
} else {
LOG.info("Unable to create new definition {}", definition);
}
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());
}
}
public Optional<Definition> updateDefinition(final Definition definition) {
if (definition == null) {
LOG.error("Given null definition, returning {}");
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();
try {
final TypeToken<Definition> typeToken = new TypeToken<Definition>(){};
final Optional<Definition> persistenceApiResponse = restService.patch(persistenceApiBaseUrl + "definitions/" + definition.getId(),
new GsonBuilder().create().toJson(definition),
typeToken,
connectionTimeoutMilliseconds,
socketTimeoutMilliseconds);
if (persistenceApiResponse.isPresent()) {
LOG.info("Update successful. Returning {}", persistenceApiResponse.get());
} else {
LOG.info("Unable to update definition {}", definition);
}
return persistenceApiResponse;
} 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());
}
}
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 + "definitions/" + 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());
}
}
}
@@ -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 {
}
@@ -6,10 +6,12 @@ import edu.msudenver.tsp.services.dto.Account;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.List;
import java.util.Optional; import java.util.Optional;
@Slf4j @Slf4j
@@ -25,7 +27,96 @@ public class UserService {
this.restService = restService; this.restService = restService;
} }
public Optional<Account> createNewAccount(final Account account) { public Optional<List<Account>> getListOfAccounts() {
final Instant start = Instant.now();
try {
final TypeToken<List<Account>> typeToken = new TypeToken<List<Account>>() {};
final Optional<List<Account>> persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/",
typeToken,
connectionTimeoutMilliseconds,
socketTimeoutMilliseconds,
null);
if (persistenceApiResponse.isPresent()) {
LOG.info("Returning {}", persistenceApiResponse.get());
} else {
LOG.warn("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("Get the list of accounts request took {}ms", Duration.between(start, Instant.now()).toMillis());
}
}
public Optional<Account> findAccountById(final int id) {
if (id == 0) {
LOG.error("No user ID specified! Returning {}");
return Optional.empty();
}
final Instant start = Instant.now();
try {
final TypeToken<Account> typeToken = new TypeToken<Account>() {};
final Optional<Account> persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/id?id=" + id,
typeToken,
connectionTimeoutMilliseconds,
socketTimeoutMilliseconds,
null);
if (persistenceApiResponse.isPresent()) {
LOG.info("Returning {}", persistenceApiResponse.get());
} else {
LOG.warn("Unable to find account with id {}", id);
}
return persistenceApiResponse;
} catch (final Exception e) {
LOG.error("Error finding account by id", e);
return Optional.empty();
} finally {
LOG.info("Find account by ID request took {}ms", Duration.between(start, Instant.now()).toMillis());
}
}
public Optional<Account> findAccountByUsername(final String username) {
if (username == null) {
LOG.error("No username specified! Returning {}");
return Optional.empty();
}
final Instant start = Instant.now();
try {
final TypeToken<Account> typeToken = new TypeToken<Account>() {};
final Optional<Account> persistenceApiResponse = restService.get(persistenceApiBaseUrl + "accounts/username?username=" + username,
typeToken,
connectionTimeoutMilliseconds,
socketTimeoutMilliseconds,
null);
if (persistenceApiResponse.isPresent()) {
LOG.info("Returning {}", persistenceApiResponse.get());
} else {
LOG.warn("Unable to GET account with username {}", username);
}
return persistenceApiResponse;
} catch (final Exception e) {
LOG.error("Error finding account by username", e);
return Optional.empty();
} finally {
LOG.info("Find account by username request took {}ms", Duration.between(start, Instant.now()).toMillis());
}
}
public Optional<Account> createAccount(final Account account) {
if (account == null) { if (account == null) {
LOG.error("Given null account, returning {}"); LOG.error("Given null account, returning {}");
return Optional.empty(); return Optional.empty();
@@ -34,8 +125,8 @@ public class UserService {
try { try {
final TypeToken<Account> typeToken = new TypeToken<Account>() {}; final TypeToken<Account> typeToken = new TypeToken<Account>() {};
final Optional<Account> persistenceApiResponse = restService.post(persistenceApiBaseUrl + "/accounts/", final Optional<Account> persistenceApiResponse = restService.post(persistenceApiBaseUrl + "accounts/",
new GsonBuilder().create().toJson(account), new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(account),
typeToken, typeToken,
connectionTimeoutMilliseconds, connectionTimeoutMilliseconds,
socketTimeoutMilliseconds); socketTimeoutMilliseconds);
@@ -43,15 +134,88 @@ public class UserService {
if (persistenceApiResponse.isPresent()) { if (persistenceApiResponse.isPresent()) {
LOG.info("Returning {}", persistenceApiResponse.get()); LOG.info("Returning {}", persistenceApiResponse.get());
} else { } else {
LOG.info("Unable to create new account {}", account.toString()); LOG.warn("Unable to create new account {}", account.toString());
} }
return persistenceApiResponse; return persistenceApiResponse;
} catch (final Exception e) { } catch (final Exception e) {
LOG.error("Error creating new account {}", e); LOG.error("Error creating new account", e);
return Optional.empty(); return Optional.empty();
} finally { } 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());
} }
} }
public Optional<Account> updateAccount(final Account account) {
if (account == null) {
LOG.error("Specified account is null; returning {}");
return Optional.empty();
}
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 TypeToken<Account> typeToken = new TypeToken<Account>(){};
final Optional<Account> 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.warn("Unable to update user with id {}", account.getId());
}
return persistenceApiResponse;
} catch (final Exception e) {
LOG.error("Error updating user", e);
return Optional.empty();
} finally {
LOG.info("Update user request took {}ms", Duration.between(start, Instant.now()).toMillis());
}
}
public boolean deleteAccount(final Account account) {
if (account == null){
LOG.error("Specified account is null; returning {}");
return false;
}
if (account.getId() == 0) {
LOG.error("No user ID specified! Returning {}");
return false;
}
final int 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("Returning {}", persistenceApiResponse);
}
else {
LOG.error("Unable to delete user {}", account);
}
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());
}
}
} }
@@ -6,7 +6,6 @@ import lombok.EqualsAndHashCode;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.io.Serializable; import java.io.Serializable;
@@ -15,11 +14,10 @@ import java.util.Date;
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class Account extends BaseDto implements Serializable { 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; @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; @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; @Temporal(TemporalType.DATE) @SerializedName("last_login") private Date lastLogin;
private static final long serialVersionUID = 7095627971593953734L; private static final long serialVersionUID = 7095627971593953734L;
} }
@@ -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<String> definition;
private List<String> notation;
private static final long serialVersionUID = 3412178112996807691L;
public interface Insert {}
}
@@ -24,6 +24,6 @@ public class RequestFactory {
} }
public Request patch(final String uri, final String requestJson) { public Request patch(final String uri, final String requestJson) {
return StringUtils.isNotBlank(requestJson) ? Request.Put(uri).bodyString(requestJson, ContentType.APPLICATION_JSON) : Request.Patch(uri); return StringUtils.isNotBlank(requestJson) ? Request.Patch(uri).bodyString(requestJson, ContentType.APPLICATION_JSON) : Request.Patch(uri);
} }
} }
@@ -0,0 +1,290 @@
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.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.*;
@RunWith(MockitoJUnitRunner.class)
public class DefinitionServiceTest {
@Mock private RestService restService;
@InjectMocks private DefinitionService definitionService;
@Test
public void testGetAllDefinitions() {
final List<Definition> definitionList = new ArrayList<>();
final Definition testDefinition = createDefinition();
definitionList.add(testDefinition);
definitionList.add(testDefinition);
when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString()))
.thenReturn(Optional.of(definitionList));
final Optional<List<Definition>> listOfDefinitions = definitionService.getAllDefinitions();
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_RequestReturnsEmptyOptional() {
when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString()))
.thenReturn(Optional.empty());
final Optional<List<Definition>> listOfDefinitions = definitionService.getAllDefinitions();
assertFalse(listOfDefinitions.isPresent());
verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString());
}
@Test
public void testGetAllDefinitions_ExceptionThrownWhenSendingRequest() {
when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString()))
.thenThrow(new UnsupportedOperationException("Test exception"));
final Optional<List<Definition>> 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<Definition> 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_RequestReturnsEmptyOptional() {
when(restService.get(anyString(), any(), anyInt(), anyInt(), anyString()))
.thenReturn(Optional.empty());
final Optional<Definition> 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<Definition> exceptionThrowingDefinition = definitionService.findById(1);
assertFalse(exceptionThrowingDefinition.isPresent());
verify(restService).get(anyString(), any(), anyInt(), anyInt(), anyString());
}
@Test
public void testFindById_IdIsZero() {
final Optional<Definition> impossibleDefinition = definitionService.findById(0);
assertFalse(impossibleDefinition.isPresent());
verifyZeroInteractions(restService);
}
@Test
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<Definition> createdDefinition = definitionService.createDefinition(testDefinition);
assertNotNull(createdDefinition);
assertTrue(createdDefinition.isPresent());
assertEquals(testDefinition, createdDefinition.get());
verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt());
}
@Test
public void testCreateDefinition_NullDefinition() {
final Optional<Definition> nullDefinition = definitionService.createDefinition(null);
assertFalse(nullDefinition.isPresent());
verifyZeroInteractions(restService);
}
@Test
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<Definition> createdDefinition = definitionService.createDefinition(testDefinition);
assertNotNull(createdDefinition);
assertFalse(createdDefinition.isPresent());
verify(restService).post(anyString(), eq(testDefinitionJson), any(), anyInt(), anyInt());
}
@Test
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<Definition> createdDefinition = definitionService.createDefinition(testDefinition);
assertNotNull(createdDefinition);
assertFalse(createdDefinition.isPresent());
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<Definition> 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<Definition> testUpdate = definitionService.updateDefinition(null);
assertFalse(testUpdate.isPresent());
verifyZeroInteractions(restService);
}
@Test
public void testUpdateDefinition_IdIsZero() {
final Definition impossibleDefinition = createDefinition();
impossibleDefinition.setId(0);
final Optional<Definition> 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<Definition> 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<Definition> exceptionThrowingDefinition = definitionService.updateDefinition(createDefinition());
assertFalse(exceptionThrowingDefinition.isPresent());
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<String> definitionList = new ArrayList<>();
definitionList.add("Test definition 1");
final List<String> notationList = new ArrayList<>();
notationList.add("\\testLaTeX");
final Definition definition = new Definition();
definition.setName("Test Name");
definition.setDefinition(definitionList);
definition.setNotation(notationList);
definition.setId(1);
return definition;
}
}
@@ -0,0 +1,313 @@
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.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
@Mock private RestService restService;
@InjectMocks private UserService userService;
@Test
public void testGetListOfAccounts() {
final List<Account> accountList = new ArrayList<>();
accountList.add(createAccount());
accountList.add(createAccount());
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(), anyString())).thenReturn(Optional.of(accountList));
final Optional<List<Account>> response = userService.getListOfAccounts();
assertTrue(response.isPresent());
assertEquals(accountList, response.get());
verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString());
}
@Test
public void testGetListOfAccounts_PersistenceApiResponseIsEmpty() {
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty());
final Optional<List<Account>> response = userService.getListOfAccounts();
assertFalse(response.isPresent());
verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString());
}
@Test
public void testGetListOfAccounts_RestServiceThrowsException() {
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenThrow(Exception.class);
final Optional<List<Account>> response = userService.getListOfAccounts();
assertFalse(response.isPresent());
verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString());
}
@Test
public void testFindAccountById() {
final Account account = createAccount();
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.of(account));
final Optional<Account> response = userService.findAccountById(1);
assertTrue(response.isPresent());
assertEquals(account, response.get());
verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString());
}
@Test
public void testFindAccountById_IdEqualsZero() {
final Optional<Account> response = userService.findAccountById(0);
assertFalse(response.isPresent());
assertEquals(Optional.empty(), response);
verifyZeroInteractions(restService);
}
@Test
public void testFindAccountById_PersistenceApiResponseIsEmpty() {
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty());
final Optional<Account> response = userService.findAccountById(1);
assertFalse(response.isPresent());
verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString());
}
@Test
public void testFindAccountById_RestServiceThrowsException() {
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenThrow(Exception.class);
final Optional<Account> response = userService.findAccountById(1);
assertFalse(response.isPresent());
verify(restService).get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString());
}
@Test
public void testFindAccountByUsername() {
final Account account = createAccount();
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.of(account));
final Optional<Account> response = userService.findAccountByUsername(account.getUsername());
assertTrue(response.isPresent());
assertEquals(account, response.get());
verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString());
}
@Test
public void testFindAccountByUsername_NullUsername() {
final Optional<Account> response = userService.findAccountByUsername(null);
assertFalse(response.isPresent());
assertEquals(Optional.empty(), response);
verifyZeroInteractions(restService);
}
@Test
public void testFindAccountByUsername_PersistenceApiResponseIsEmpty() {
final Account account = createAccount();
when(restService.get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString())).thenReturn(Optional.empty());
final Optional<Account> response = userService.findAccountByUsername(account.getUsername());
assertFalse(response.isPresent());
verify(restService).get(anyString(),any(TypeToken.class), anyInt(), anyInt(),anyString());
}
@Test
public void testFindAccountByUsername_RestServiceThrowsException() {
when(restService.get(anyString(), any(TypeToken.class), anyInt(), anyInt(), anyString())).thenThrow(Exception.class);
final Optional<Account> 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));
final Optional<Account> response = userService.createAccount(account);
assertTrue(response.isPresent());
assertEquals(account, response.get());
verify(restService).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt());
}
@Test
public void testCreateAccount_NullAccount() {
final Optional<Account> 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_AccountCouldNotBeCreated() {
when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.empty());
final Optional<Account> response = userService.createAccount(createAccount());
assertFalse(response.isPresent());
verify(restService).post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt());
}
@Test
public void testCreateAccount_RestServiceThrowsException() {
when(restService.post(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class);
final Optional<Account> 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));
final Optional<Account> response = userService.updateAccount(account);
assertTrue(response.isPresent());
assertEquals(account, response.get());
verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt());
}
@Test
public void testUpdateAccount_NullAccount() {
final Optional<Account> response = userService.updateAccount(null);
assertFalse(response.isPresent());
verifyZeroInteractions(restService);
}
@Test
public void testUpdateAccount_IdEqualsZero() {
final Account account = createAccount();
account.setId(0);
final Optional<Account> response = userService.updateAccount(account);
assertFalse(response.isPresent());
verifyZeroInteractions(restService);
}
@Test
public void testUpdateAccount_PersistenceApiResponseIsEmpty() {
final Account account = createAccount();
account.setId(1);
when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenReturn(Optional.empty());
final Optional<Account> response = userService.updateAccount(account);
assertFalse(response.isPresent());
verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt());
}
@Test
public void testUpdateAccount_RestServiceThrowsException() {
final Account account = createAccount();
account.setId(1);
when(restService.patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt())).thenThrow(Exception.class);
final Optional<Account> response = userService.updateAccount(account);
assertFalse(response.isPresent());
verify(restService).patch(anyString(), anyString(), any(TypeToken.class), anyInt(), anyInt());
}
@Test
public void testDeleteAccount() {
final Account account = createAccount();
account.setId(1);
when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenReturn(true);
final boolean isDeleteSuccessful = userService.deleteAccount(account);
assertTrue(isDeleteSuccessful);
verify(restService).delete(anyString(), anyInt(), anyInt(), any());
}
@Test
public void testDeleteAccount_NullAccount() {
final boolean isDeleteSuccessful = userService.deleteAccount(null);
assertFalse(isDeleteSuccessful);
verifyZeroInteractions(restService);
}
@Test
public void testDeleteAccount_IdEqualsZero() {
final Account account = createAccount();
account.setId(0);
final boolean isDeleteSuccessful = userService.deleteAccount(account);
assertFalse(isDeleteSuccessful);
verifyZeroInteractions(restService);
}
@Test
public void testDeleteAccount_PersistenceApiResponseIsEmpty() {
final Account account = createAccount();
account.setId(1);
when(restService.delete(anyString(), anyInt(), anyInt(), any())).thenReturn(false);
final boolean isDeleteSuccessful = userService.deleteAccount(account);
assertFalse(isDeleteSuccessful);
verify(restService).delete(anyString(), anyInt(), anyInt(), any());
}
@Test
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);
assertFalse(persistenceApiResponse);
verify(restService).delete(anyString(), anyInt(), anyInt(), any());
}
private Account createAccount() {
final Account account = new Account();
account.setUsername("Test username");
account.setPassword("test password");
account.setAdministrator(true);
account.setLastLogin(new Date());
return account;
}
}
@@ -18,7 +18,6 @@ import static org.mockito.Mockito.when;
public class ParserServiceTest { public class ParserServiceTest {
@Mock private ParserService mockParserService; @Mock private ParserService mockParserService;
@InjectMocks private ParserService parserService; @InjectMocks private ParserService parserService;
@Test @Test
+27
View File
@@ -0,0 +1,27 @@
<%--
Created by IntelliJ IDEA.
User: atusa
Date: 2/1/19
Time: 8:03 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pandamonium™ Theorem Prover</title>
</head>
<body>
<div>
<div>
<h1>Theorem Prover</h1>
<h2>Hello! Welcome to Pandamonium™ Theorem Prover!!</h2>
Click on this <strong><a href="/theorem/">link</a></strong> to visit theorem entering page.
</div>
</div>
</body>
</html>
-16
View File
@@ -1,16 +0,0 @@
<%--
Created by IntelliJ IDEA.
User: atusa
Date: 2/1/19
Time: 8:03 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>