Added project

This commit is contained in:
2023-06-11 00:14:30 +03:00
parent a9048a9b39
commit 32c1d5fb0b
103 changed files with 9633 additions and 2 deletions

View File

@@ -0,0 +1,48 @@
package ru.resprojects.linkchecker;
import com.google.gson.Gson;
import ru.resprojects.linkchecker.dto.GraphDto;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Helper class for unit testing.
*/
public class TestUtils {
public static final GraphDto.NodeGraph nodeGraph = new GraphDto.NodeGraph(5000, "v1", 0);
public static final GraphDto.EdgeGraph edgeGraph = new GraphDto.EdgeGraph(5005, "v1", "v2");
public static final Set<GraphDto.NodeGraph> nodesGraph = Stream.of(
nodeGraph,
new GraphDto.NodeGraph(5001, "v2", 0),
new GraphDto.NodeGraph(5002, "v3", 0),
new GraphDto.NodeGraph(5003, "v4", 0),
new GraphDto.NodeGraph(5004, "v5", 0)
).collect(Collectors.toSet());
public static final Set<GraphDto.EdgeGraph> edgesGraph = Stream.of(
edgeGraph,
new GraphDto.EdgeGraph(5006, "v1", "v3"),
new GraphDto.EdgeGraph(5007, "v1", "v5"),
new GraphDto.EdgeGraph(5008, "v3", "v4")
).collect(Collectors.toSet());
public static final GraphDto graph = new GraphDto(nodesGraph, edgesGraph);
private TestUtils() {
}
public static String mapToJson(Object obj) {
return new Gson().toJson(obj);
}
public static <T> T mapFromJson(String json, Type type) {
return new Gson().fromJson(json, type);
}
public static <T> T mapFromJson(String json, Class<T> clazz) {
return new Gson().fromJson(json, clazz);
}
}

View File

@@ -0,0 +1,86 @@
package ru.resprojects.linkchecker.model;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.util.ValidationUtil;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = "moc_test")
public class ValidationModelTests {
private static final Logger LOG = LoggerFactory.getLogger(ValidationModelTests.class);
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeClass
public static void createValidator() {
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@AfterClass
public static void close() {
validatorFactory.close();
}
@Test
public void tryCreateNodeWithBlankName() {
Node node = new Node("");
Set<ConstraintViolation<Node>> violations = validator.validate(node);
Assert.assertEquals(2, violations.size());
ConstraintViolation<Node> violation = violations.stream()
.filter(v -> ValidationUtil.VALIDATOR_NODE_NOT_BLANK_NAME_MESSAGE.equals(v.getMessage()))
.findFirst()
.orElse(null);
Assert.assertNotNull(violation);
violation = violations.stream()
.filter(v -> ValidationUtil.VALIDATOR_NODE_NAME_RANGE_MESSAGE.equals(v.getMessage()))
.findFirst()
.orElse(null);
Assert.assertNotNull(violation);
printViolationMessage(violations);
}
@Test
public void tryCreateNodeWithTooLongNodeName() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 51; i++) {
sb.append('a');
}
Node node = new Node(sb.toString());
Set<ConstraintViolation<Node>> violations = validator.validate(node);
Assert.assertEquals(1, violations.size());
ConstraintViolation<Node> violation = violations.stream()
.filter(v -> ValidationUtil.VALIDATOR_NODE_NAME_RANGE_MESSAGE.equals(v.getMessage()))
.findFirst()
.orElse(null);
Assert.assertNotNull(violation);
printViolationMessage(violations);
}
private static void printViolationMessage(Set<ConstraintViolation<Node>> violations) {
violations.forEach(v -> {
LOG.info("VIOLATION INFO");
LOG.info("--> MESSAGE: " + v.getMessage());
LOG.info("--> PROPERTY PATH: " + v.getPropertyPath().toString());
LOG.info("--> INVALID VALUE: " + v.getInvalidValue());
});
}
}

View File

@@ -0,0 +1,144 @@
package ru.resprojects.linkchecker.repositories;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.model.Edge;
import ru.resprojects.linkchecker.model.Node;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
public class EdgeRepositoryH2DBTests {
private static final Logger LOG = LoggerFactory.getLogger(EdgeRepositoryH2DBTests.class);
@Autowired
EdgeRepository edgeRepository;
@Autowired
NodeRepository nodeRepository;
@Test
public void persistNewEdge() {
Node nodeOne = nodeRepository.save(new Node("v6"));
Node nodeTwo = nodeRepository.getByName("v5");
Edge edge = edgeRepository.save(new Edge(nodeOne, nodeTwo));
Assert.assertNotNull(edge);
LOG.info("New Edge: " + edge);
List<Edge> edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
Assert.assertEquals(5, edges.size());
LOG.info("EDGES count = " + edges.size());
}
@Test
public void persistEdgeList() {
List<Node> nodes = nodeRepository.findAll();
Node nodeOne = nodeRepository.save(new Node("v6"));
List<Edge> edges = new ArrayList<>();
nodes.forEach(node -> edges.add(new Edge(nodeOne, node)));
edgeRepository.saveAll(edges);
List<Edge> newEdgeList = edgeRepository.findAll();
Assert.assertNotNull(newEdgeList);
Assert.assertEquals(9, newEdgeList.size());
LOG.info("Size: " + newEdgeList.size());
newEdgeList.forEach(edge -> LOG.info(edge.toString()));
}
@Test
public void getAllEdges() {
List<Edge> edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
Assert.assertEquals(4, edges.size());
LOG.info("LIST count = " + edges.size());
edges.forEach(edge -> LOG.info(edge.toString()));
}
@Test
public void getEdgeById() {
Edge edge = edgeRepository.findById(5005).orElse(null);
Assert.assertNotNull(edge);
Assert.assertEquals("v1", edge.getNodeOne().getName());
LOG.info("EDGE INFO WITH ID = 5005: " + edge);
}
@Test
public void getEdgeByNodeOneAndNodeTwo() {
Node nodeOne = nodeRepository.getByName("v1");
Node nodeTwo = nodeRepository.getByName("v2");
Edge edge = edgeRepository.findEdgeByNodeOneAndNodeTwo(nodeOne, nodeTwo).orElse(null);
Assert.assertNotNull(edge);
Assert.assertEquals(new Integer(5005), edge.getId());
LOG.info("EDGE FOR NODES v1 and v2: " + edge);
}
@Test
public void getEdgeByNodeOneOrNodeTwo() {
Node nodeOne = nodeRepository.getByName("v1");
Node nodeTwo = nodeRepository.getByName("v2");
List<Edge> edges = edgeRepository.findEdgesByNodeOneOrNodeTwo(nodeOne, null);
Assert.assertNotNull(edges);
Assert.assertNotEquals(0, edges.size());
edges.forEach(edge -> LOG.info(edge.toString()));
LOG.info("-------------");
edges = edgeRepository.findEdgesByNodeOneOrNodeTwo(null, nodeTwo);
Assert.assertNotNull(edges);
Assert.assertNotEquals(0, edges.size());
edges.forEach(edge -> LOG.info(edge.toString()));
LOG.info("-------------");
edges = edgeRepository.findEdgesByNodeOneOrNodeTwo(nodeOne, nodeTwo);
Assert.assertNotNull(edges);
Assert.assertNotEquals(0, edges.size());
edges.forEach(edge -> LOG.info(edge.toString()));
LOG.info("-------------");
edges = edgeRepository.findEdgesByNodeOneOrNodeTwo(nodeTwo, nodeTwo);
Assert.assertNotNull(edges);
Assert.assertNotEquals(0, edges.size());
edges.forEach(edge -> LOG.info(edge.toString()));
}
@Test
public void deleteEdgesInBatch() {
Node node = nodeRepository.getByName("v1");
List<Edge> edges = edgeRepository.findEdgesByNodeOneOrNodeTwo(node, node);
Assert.assertNotNull(edges);
edgeRepository.deleteInBatch(edges);
edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
edges.forEach(edge -> LOG.info(edge.toString()));
}
@Test
public void deleteById() {
edgeRepository.deleteById(5005);
List<Edge> edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
Assert.assertEquals(3, edges.size());
LOG.info("EDGES count = " + edges.size());
}
@Test
public void deleteAllEdges() {
edgeRepository.deleteAllInBatch();
List<Edge> edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
Assert.assertEquals(0, edges.size());
}
}

View File

@@ -0,0 +1,139 @@
package ru.resprojects.linkchecker.repositories;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.model.Edge;
import ru.resprojects.linkchecker.model.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
public class NodeRepositoryH2DBTests {
private static final Logger LOG = LoggerFactory.getLogger(NodeRepositoryH2DBTests.class);
@Autowired
NodeRepository nodeRepository;
@Autowired
EdgeRepository edgeRepository;
@Test
public void persistNewNode() {
Node node = new Node("v11");
Node savedNode = nodeRepository.save(node);
Assert.assertNotNull(savedNode.getId());
LOG.info(nodeRepository.getByName("v11").toString());
int count = nodeRepository.findAll().size();
Assert.assertEquals(6, count);
LOG.info("LIST count = " + count);
}
@Test
public void persistNodeList() {
List<Node> nodes = new ArrayList<>();
IntStream.range(1, 60).forEach(i -> nodes.add(new Node("w" + i)));
nodeRepository.saveAll(nodes);
List<Node> savedNodes = nodeRepository.findAll();
Assert.assertNotNull(savedNodes);
Assert.assertEquals(64, savedNodes.size());
LOG.info("LIST count = " + savedNodes.size());
savedNodes.forEach(node -> LOG.info(node.toString()));
}
@Test
public void getAllNodes() {
List<Node> nodes = nodeRepository.findAll();
Assert.assertNotNull(nodes);
Assert.assertEquals(5, nodes.size());
LOG.info("LIST count = " + nodes.size());
nodes.forEach(node -> LOG.info(node.toString()));
}
@Test
public void getNodeById() {
Node node = nodeRepository.findById(5000).orElse(null);
Assert.assertNotNull(node);
Assert.assertEquals("v1", node.getName());
LOG.info("NODE INFO WITH ID = 5000: " + node);
}
@Test
public void nodeNotFoundById() {
Node node = nodeRepository.findById(5010).orElse(null);
Assert.assertNull(node);
}
@Test
public void getNodeByName() {
Node node = nodeRepository.getByName("v1");
Assert.assertNotNull(node);
Assert.assertEquals("v1", node.getName());
LOG.info("NODE INFO WITH ID = 5000: " + node);
}
@Test
public void nodeNotFoundIfNameIsNull() {
Node node = nodeRepository.getByName(null);
Assert.assertNull(node);
}
@Test
public void nodeNotFoundByName() {
Node node = nodeRepository.getByName("v11");
Assert.assertNull(node);
}
@Test
public void deleteById() {
nodeRepository.deleteById(5000);
List<Node> nodes = nodeRepository.findAll();
Assert.assertNotNull(nodes);
Assert.assertEquals(4, nodes.size());
LOG.info("LIST count = " + nodes.size());
nodes.forEach(node -> LOG.info(node.toString()));
}
@Test
public void deleteByName() {
nodeRepository.deleteByName("v1");
List<Node> nodes = nodeRepository.findAll();
Assert.assertNotNull(nodes);
Assert.assertEquals(4, nodes.size());
LOG.info("LIST count = " + nodes.size());
nodes.forEach(node -> LOG.info(node.toString()));
}
@Test
public void cascadeDeleteAllNodesAndEdges() {
nodeRepository.deleteAllInBatch();
List<Node> nodes = nodeRepository.findAll();
Assert.assertNotNull(nodes);
Assert.assertEquals(0, nodes.size());
List<Edge> edges = edgeRepository.findAll();
Assert.assertNotNull(edges);
Assert.assertEquals(0, edges.size());
}
@Test
public void existNodeByName() {
Assert.assertTrue(nodeRepository.existsByName("v1"));
}
}

View File

@@ -0,0 +1,259 @@
package ru.resprojects.linkchecker.services;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.util.exeptions.ApplicationException;
import ru.resprojects.linkchecker.util.exeptions.NotFoundException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
public class GraphEdgeServiceH2DBTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphEdgeServiceH2DBTests.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
private GraphEdgeService edgeService;
@Autowired
private AppProperties properties;
@Test
public void createEdge() {
EdgeGraph edgeGraph = new EdgeGraph("v1", "v4");
EdgeGraph actual = edgeService.create(edgeGraph);
Assert.assertNotNull(actual);
Assert.assertEquals(new Integer(5009), actual.getId());
Set<EdgeGraph> egList = edgeService.getAll();
Assert.assertEquals(5, egList.size());
egList.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void createEdgeNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
edgeService.create((EdgeGraph) null);
}
@Test
public void createEdgeNodeNotFoundException() {
EdgeGraph edgeGraph = new EdgeGraph("v10", "v4");
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v10"));
edgeService.create(edgeGraph);
}
@Test
public void createEdgeAlreadyPresentException() {
EdgeGraph edgeGraph = new EdgeGraph("v1", "v2");
thrown.expect(ApplicationException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_ALREADY_PRESENT_ERROR"), "v1", "v2", "v2", "v1"));
edgeService.create(edgeGraph);
}
@Test
public void createEdgeAlreadyPresentVariantTwoException() {
EdgeGraph edgeGraph = new EdgeGraph("v2", "v1");
thrown.expect(ApplicationException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_ALREADY_PRESENT_ERROR"), "v2", "v1", "v1", "v2"));
edgeService.create(edgeGraph);
}
@Test
public void createEdges() {
Set<EdgeGraph> edgeGraphs = Stream.of(
new EdgeGraph("v2", "v3"),
new EdgeGraph("v2", "v5"),
new EdgeGraph("v3", "v5")
).collect(Collectors.toSet());
Set<EdgeGraph> actual = edgeService.create(edgeGraphs);
Assert.assertFalse(actual.isEmpty());
Assert.assertNotNull(actual.iterator().next().getId());
actual.forEach(eg -> LOG.info("---- RETURNED EDGE: " + eg));
Set<EdgeGraph> egList = edgeService.getAll();
Assert.assertEquals(7, egList.size());
egList.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void createEdgesEmptyCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_EMPTY"));
edgeService.create(new HashSet<>());
}
@Test
public void createEdgesNodeNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v21"));
Set<EdgeGraph> edgeGraphs = Stream.of(
new EdgeGraph("v21", "v3"),
new EdgeGraph("v2", "v5"),
new EdgeGraph("v3", "v5")
).collect(Collectors.toSet());
edgeService.create(edgeGraphs);
}
@Test
public void createEdgesCollectionContainNullException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_NULL"));
Set<EdgeGraph> edgeGraphs = Stream.of(
null,
new EdgeGraph("v2", "v5"),
new EdgeGraph("v3", "v5")
).collect(Collectors.toSet());
edgeService.create(edgeGraphs);
}
@Test
public void createEdgesEdgeAlreadyPresentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_ALREADY_PRESENT_ERROR"), "v1", "v2", "v2", "v1"));
Set<EdgeGraph> edgeGraphs = Stream.of(
new EdgeGraph("v1", "v2"),
new EdgeGraph("v2", "v5")
).collect(Collectors.toSet());
edgeService.create(edgeGraphs);
}
@Test
public void deleteEdgeById() {
edgeService.delete(5005);
Set<EdgeGraph> egList = edgeService.getAll();
Assert.assertEquals(3, egList.size());
egList.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void deleteEdgeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "EDGE", 5022));
edgeService.delete(5022);
}
@Test
public void deleteEdgeByNodeOneAndNodeTwoNames() {
edgeService.delete("v1", "v2");
Set<EdgeGraph> actual = edgeService.getAll();
actual.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void deleteEdgeByNodeOneAndNodeTwoNamesNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_ERROR"), "v15", "v2"));
edgeService.delete("v15", "v2");
}
@Test
public void deleteEdgeByNodeName() {
edgeService.delete("v1");
Set<EdgeGraph> actual = edgeService.getAll();
actual.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void deleteEdgeByNodeNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_BY_NAME_ERROR"), "v15"));
edgeService.delete("v15");
}
@Test
public void deleteAllEdges() {
edgeService.deleteAll();
Set<EdgeGraph> actual = edgeService.getAll();
Assert.assertTrue(actual.isEmpty());
}
@Test
public void getAllEdges() {
Set<EdgeGraph> actual = edgeService.getAll();
Assert.assertEquals(4, actual.size());
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5007))
.findFirst()
.get().getNodeOne()).isEqualTo("v1");
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5007))
.findFirst()
.get().getNodeTwo()).isEqualTo("v5");
actual.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void getEdgeById() {
EdgeGraph actual = edgeService.getById(5005);
Assert.assertNotNull(actual);
Assert.assertEquals(TestUtils.edgeGraph, actual);
LOG.info(actual.toString());
}
@Test
public void getEdgeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "EDGE", 7000));
edgeService.getById(7000);
}
@Test
public void getEdgesByNodeName() {
Set<EdgeGraph> actual = edgeService.get("v1");
Set<EdgeGraph> expected = TestUtils.edgesGraph.stream()
.filter(eg -> eg.getId() != 5008)
.collect(Collectors.toSet());
Assert.assertFalse(actual.isEmpty());
Assert.assertEquals(expected.size(), actual.size());
assertThat(actual).containsAnyOf(expected.iterator().next());
actual.forEach(eg -> LOG.info("---- EDGE: " + eg));
}
@Test
public void getEdgesByNodeNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_BY_NAME_ERROR"), "v100"));
edgeService.get("v100");
}
@Test
public void getEdgeByNodeNameOneAndNodeNameTwo() {
EdgeGraph actual = edgeService.get("v1", "v2");
Assert.assertNotNull(actual);
Assert.assertEquals(TestUtils.edgeGraph, actual);
Integer actualId = actual.getId();
LOG.info(actual.toString());
actual = edgeService.get("v2", "v1");
Assert.assertEquals(actualId, actual.getId()); //must equal because graph is undirected
}
}

View File

@@ -0,0 +1,314 @@
package ru.resprojects.linkchecker.services;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.model.Edge;
import ru.resprojects.linkchecker.model.Node;
import ru.resprojects.linkchecker.repositories.EdgeRepository;
import ru.resprojects.linkchecker.repositories.NodeRepository;
import ru.resprojects.linkchecker.util.GraphUtil;
import ru.resprojects.linkchecker.util.exeptions.ApplicationException;
import ru.resprojects.linkchecker.util.exeptions.NotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyIterable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = "moc_test")
public class GraphEdgeServiceMockTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@MockBean
private EdgeRepository edgeRepository;
@MockBean
private NodeRepository nodeRepository;
@Autowired
private AppProperties properties;
private GraphEdgeService edgeService;
private List<Node> nodes;
@Before
public void init() {
edgeService = new GraphEdgeServiceImpl(edgeRepository, nodeRepository, properties);
nodes = Stream.of(
new Node(5000, "v1", 0),
new Node(5001, "v2", 0),
new Node(5002, "v3", 0),
new Node(5003, "v4", 0),
new Node(5004, "v5", 0)
).collect(Collectors.toList());
}
@Test
public void createEdge() {
Node nodeOne = nodes.get(0);
Node nodeTwo = nodes.get(1);
Edge edge = new Edge(5005, nodeOne, nodeTwo);
EdgeGraph edgeGraph = new EdgeGraph("v1", "v2");
given(nodeRepository.getByName("v1")).willReturn(nodeOne);
given(nodeRepository.getByName("v2")).willReturn(nodeTwo);
when(edgeRepository.save(any(Edge.class))).thenReturn(edge);
EdgeGraph actual = edgeService.create(edgeGraph);
Assert.assertNotNull(actual);
Assert.assertEquals(new Integer(5005), actual.getId());
}
@Test
public void createEdgeNodeNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v1"));
EdgeGraph edgeGraph = new EdgeGraph("v1", "v2");
given(nodeRepository.getByName("v1")).willReturn(null);
edgeService.create(edgeGraph);
}
@Test
public void createEdgeNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
edgeService.create((EdgeGraph) null);
}
@Test
public void createEdges() {
List<Edge> edges = new ArrayList<>();
edges.add(new Edge(5005,nodes.get(0), nodes.get(1)));
edges.add(new Edge(5006,nodes.get(0), nodes.get(2)));
edges.add(new Edge(5007,nodes.get(0), nodes.get(4)));
edges.add(new Edge(5008,nodes.get(2), nodes.get(3)));
Set<EdgeGraph> edgeGraphs = edges.stream()
.map(e -> new EdgeGraph(e.getNodeOne().getName(), e.getNodeTwo().getName()))
.collect(Collectors.toSet());
given(nodeRepository.getByName("v1")).willReturn(nodes.get(0));
given(nodeRepository.getByName("v2")).willReturn(nodes.get(1));
given(nodeRepository.getByName("v3")).willReturn(nodes.get(2));
given(nodeRepository.getByName("v4")).willReturn(nodes.get(3));
given(nodeRepository.getByName("v5")).willReturn(nodes.get(4));
when(edgeRepository.saveAll(anyIterable())).thenReturn(edges);
Set<EdgeGraph> actual = edgeService.create(edgeGraphs);
Assert.assertNotNull(actual);
Assert.assertEquals(4, actual.size());
}
@Test
public void createEdgesNodeNotFoundException() {
List<Edge> edges = Stream.of(
new Edge(5005,nodes.get(0), nodes.get(1)),
new Edge(5006,nodes.get(0), nodes.get(2)),
new Edge(5007,nodes.get(0), nodes.get(4)),
new Edge(5008,nodes.get(2), nodes.get(3))
).collect(Collectors.toList());
Set<EdgeGraph> edgeGraphs = edges.stream()
.map(e -> new EdgeGraph(e.getNodeOne().getName(), e.getNodeTwo().getName()))
.collect(Collectors.toSet());
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v1"));
given(nodeRepository.getByName("v1")).willReturn(null);
edgeService.create(edgeGraphs);
}
@Test
public void createEdgesNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
edgeService.create((Set<EdgeGraph>) null);
}
@Test
public void createEdgesEmptyCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_EMPTY"));
edgeService.create(new HashSet<>());
}
@Test
public void createEdgesCollectionContainNullException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_NULL"));
Set<EdgeGraph> edgeGraphs = new HashSet<>();
edgeGraphs.add(new EdgeGraph("v1", "v2"));
edgeGraphs.add(null);
edgeService.create(edgeGraphs);
}
@Test
public void deleteEdgeById() {
List<Edge> edges = Stream.of(
new Edge(5008, nodes.get(2), nodes.get(3))
).collect(Collectors.toList());
given(edgeRepository.existsById(new Integer(5005))).willReturn(true);
given(edgeRepository.findAll()).willReturn(edges);
edgeService.delete(5005);
Set<EdgeGraph> actual = edgeService.getAll();
Assert.assertEquals(1, actual.size());
}
@Test
public void deleteEdgeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "EDGE", 5050));
when(edgeRepository.existsById(5050)).thenReturn(false);
edgeService.delete(5050);
}
@Test
public void deleteEdgesByNodeName() {
List<Edge> edges = Stream.of(
new Edge(5005,nodes.get(0), nodes.get(1)),
new Edge(5006,nodes.get(0), nodes.get(2)),
new Edge(5007,nodes.get(0), nodes.get(4))
).collect(Collectors.toList());
List<Edge> edgesAfterDelete = Stream.of(
new Edge(5008, nodes.get(2), nodes.get(3))
).collect(Collectors.toList());
given(nodeRepository.getByName("v1")).willReturn(nodes.get(0));
given(edgeRepository.findEdgesByNodeOneOrNodeTwo(any(Node.class), any(Node.class))).willReturn(edges);
given(edgeRepository.findAll()).willReturn(edgesAfterDelete);
edgeService.delete("v1");
Set<EdgeGraph> actual = edgeService.getAll();
Assert.assertEquals(1, actual.size());
}
@Test
public void deleteEdgesByNodeNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_BY_NAME_ERROR"), "v1"));
List<Edge> emptyList = new ArrayList<>();
given(edgeRepository.findEdgesByNodeOneOrNodeTwo(any(Node.class), any(Node.class))).
willReturn(emptyList);
edgeService.delete("v1");
}
@Test
public void deleteEdgeByNodeNameOneAndNodeNameTwo() {
Edge edge = new Edge(5005,nodes.get(0), nodes.get(1));
given(nodeRepository.getByName("v1")).willReturn(nodes.get(0));
given(nodeRepository.getByName("v2")).willReturn(nodes.get(1));
given(edgeRepository.findEdgeByNodeOneAndNodeTwo(any(Node.class), any(Node.class))).
willReturn(Optional.of(edge));
edgeService.delete("v1", "v2");
}
@Test
public void deleteEdgeByNodeNameOneAndNodeNameTwoNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_ERROR"), "v1", "v2"));
edgeService.delete("v1", "v2");
}
@Test
public void getAllEdges() {
List<Edge> edges = Stream.of(
new Edge(5005, nodes.get(0), nodes.get(1)),
new Edge(5006, nodes.get(0), nodes.get(2)),
new Edge(5007, nodes.get(0), nodes.get(4)),
new Edge(5008, nodes.get(2), nodes.get(3))
).collect(Collectors.toList());
given(edgeRepository.findAll()).willReturn(edges);
Set<EdgeGraph> actual = edgeService.getAll();
EdgeGraph edgeGraph = GraphUtil.edgeToEdgeGraph(edges.get(2));
Assert.assertEquals(4, actual.size());
assertThat(actual).contains(edgeGraph);
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5007))
.findFirst()
.get().getNodeOne()).isEqualTo("v1");
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5007))
.findFirst()
.get().getNodeTwo()).isEqualTo("v5");
}
@Test
public void getEdgeById() {
Node nodeOne = nodes.get(0);
Node nodeTwo = nodes.get(1);
Edge edge = new Edge(5005, nodeOne, nodeTwo);
given(edgeRepository.findById(5005)).willReturn(Optional.of(edge));
EdgeGraph actual = edgeService.getById(5005);
Assert.assertEquals("v1", actual.getNodeOne());
Assert.assertEquals("v2", actual.getNodeTwo());
}
@Test
public void getEdgeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "EDGE", 7000));
edgeService.getById(7000);
}
@Test
public void getEdgesByNodeName() {
List<Edge> edges = Stream.of(
new Edge(5005, nodes.get(0), nodes.get(1)),
new Edge(5006, nodes.get(0), nodes.get(2)),
new Edge(5007, nodes.get(0), nodes.get(4))
).collect(Collectors.toList());
given(nodeRepository.getByName("v1")).willReturn(nodes.get(0));
given(edgeRepository.findEdgesByNodeOneOrNodeTwo(nodes.get(0),nodes.get(0)))
.willReturn(edges);
Set<EdgeGraph> actual = edgeService.get("v1");
EdgeGraph edgeGraph = GraphUtil.edgeToEdgeGraph(edges.get(0));
assertThat(actual).contains(edgeGraph);
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5005))
.findFirst()
.get().getNodeOne()).isEqualTo("v1");
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5005))
.findFirst()
.get().getNodeTwo()).isEqualTo("v2");
}
@Test
public void getEdgeByNodeOneAndNodeTwoNames() {
Node nodeOne = nodes.get(0);
Node nodeTwo = nodes.get(1);
Edge edge = new Edge(5005, nodeOne, nodeTwo);
given(nodeRepository.getByName("v1")).willReturn(nodeOne);
given(nodeRepository.getByName("v2")).willReturn(nodeTwo);
given(edgeRepository.findEdgeByNodeOneAndNodeTwo(nodeOne, nodeTwo)).willReturn(Optional.of(edge));
EdgeGraph actual = edgeService.get("v1", "v2");
Assert.assertNotNull(actual);
Assert.assertEquals("v1", actual.getNodeOne());
Assert.assertEquals("v2", actual.getNodeTwo());
}
@Test
public void exceptionWhileEdgeByNodeOneAndNodeTwoNames() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_ERROR"), "v1", "v2"));
edgeService.get("v1", "v2");
}
}

View File

@@ -0,0 +1,199 @@
package ru.resprojects.linkchecker.services;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.util.exeptions.ApplicationException;
import ru.resprojects.linkchecker.util.exeptions.NotFoundException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
public class GraphNodeServiceH2DBTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphNodeServiceH2DBTests.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
GraphNodeService nodeService;
@Autowired
AppProperties properties;
@Test
public void getNodeByName() {
NodeGraph nodeGraph = nodeService.get("v1");
Assert.assertNotNull(nodeGraph);
Assert.assertEquals("v1", nodeGraph.getName());
LOG.info("NODE DTO: " + nodeGraph);
}
@Test
public void getNodeById() {
NodeGraph nodeGraph = nodeService.getById(5000);
Assert.assertNotNull(nodeGraph);
Assert.assertEquals("v1", nodeGraph.getName());
LOG.info("NODE DTO: " + nodeGraph);
}
@Test
public void getNodeByNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v11"));
nodeService.get("v11");
}
@Test
public void getNodeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "NODE", 5050));
nodeService.getById(5050);
}
@Test
public void getAllNodes() {
Set<NodeGraph> actual = nodeService.getAll();
Assert.assertEquals(5, actual.size());
assertThat(actual.stream()
.filter(eg -> eg.getId().equals(5000))
.findFirst()
.get().getName()).isEqualTo("v1");
actual.forEach(ng -> LOG.info("---- NODE: " + ng));
}
@Test
public void deleteNodeByNodeGraph() {
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 0);
nodeService.delete(nodeGraph);
Set<NodeGraph> actual = nodeService.getAll();
Assert.assertEquals(4, actual.size());
}
@Test
public void deleteNodeByNodeGraphNotFoundException() {
NodeGraph nodeGraph = new NodeGraph(5020, "v1", 0);
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), nodeGraph.toString()));
nodeService.delete(nodeGraph);
}
@Test
public void deleteNodeByNodeGraphAnotherNotFoundException() {
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 1);
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), nodeGraph.toString()));
nodeService.delete(nodeGraph);
}
@Test
public void deleteNodeByName() {
nodeService.delete("v1");
Set<NodeGraph> actual = nodeService.getAll();
Assert.assertEquals(4, actual.size());
}
@Test
public void deleteNodeByNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v10"));
nodeService.delete("v10");
}
@Test
public void deleteNodeById() {
nodeService.delete(5000);
Set<NodeGraph> actual = nodeService.getAll();
Assert.assertEquals(4, actual.size());
}
@Test
public void deleteNodeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "NODE", 5100));
nodeService.delete(5100);
}
@Test
public void deleteAllNodes() {
nodeService.deleteAll();
Set<NodeGraph> nodeGraphs = nodeService.getAll();
Assert.assertNotNull(nodeGraphs);
Assert.assertEquals(0, nodeGraphs.size());
}
@Test
public void createNode() {
NodeGraph nodeGraph = new NodeGraph("v6");
nodeService.create(nodeGraph);
NodeGraph actual = nodeService.get("v6");
Assert.assertNotNull(actual);
Set<NodeGraph> nodeGraphs = nodeService.getAll();
nodeGraphs.forEach(ng -> LOG.info("---- NODE: " + ng));
}
@Test
public void createNodes() {
Set<NodeGraph> nodeGraphs = new HashSet<>();
IntStream.range(1, 6).forEach(i -> {
nodeGraphs.add(new NodeGraph("w" + i));
});
nodeService.create(nodeGraphs);
Set<NodeGraph> actual = nodeService.getAll();
Assert.assertNotNull(actual);
Assert.assertEquals(10, actual.size());
Assert.assertEquals("w1", actual.stream()
.filter(ng -> "w1".equals(ng.getName()))
.findFirst().get().getName());
actual.forEach(ng -> LOG.info("---- NODE: " + ng));
}
@Test
public void createNodeNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
nodeService.create((NodeGraph) null);
}
@Test
public void nodeUpdate() {
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 1);
nodeService.update(nodeGraph);
NodeGraph actual = nodeService.get("v1");
Assert.assertNotNull(actual);
Assert.assertEquals(1, actual.getCounter(), 0);
Set<NodeGraph> nodeGraphs = nodeService.getAll();
nodeGraphs.forEach(ng -> LOG.info("---- NODE: " + ng));
}
@Test
public void nodeUpdateNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
nodeService.update(null);
}
}

View File

@@ -0,0 +1,303 @@
package ru.resprojects.linkchecker.services;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.model.Node;
import ru.resprojects.linkchecker.repositories.NodeRepository;
import ru.resprojects.linkchecker.util.GraphUtil;
import ru.resprojects.linkchecker.util.exeptions.ApplicationException;
import ru.resprojects.linkchecker.util.exeptions.NotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyIterable;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.when;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = "moc_test")
public class GraphNodeServiceMockTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private GraphNodeService graphNodeService;
@MockBean
private NodeRepository nodeRepository;
@Autowired
private AppProperties properties;
private List<Node> nodes = Stream.of(
new Node(5001, "v2", 0),
new Node(5002, "v3", 0),
new Node(5003, "v4", 0),
new Node(5004, "v5", 0)
).collect(Collectors.toList());
@Before
public void init() {
graphNodeService = new GraphNodeServiceImpl(nodeRepository, properties);
}
@Test
public void getNodeByName() {
given(nodeRepository.getByName("v1")).willReturn(
new Node(5000, "v1", 0)
);
NodeGraph actual = graphNodeService.get("v1");
assertThat(actual.getName()).isEqualTo("v1");
assertThat(actual.getCounter()).isEqualTo(0);
}
@Test
public void getNodeByNameNotFoundException() throws NotFoundException {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v1"));
graphNodeService.get("v1");
}
@Test
public void getNodeById() {
given(nodeRepository.findById(5000)).willReturn(
Optional.of(new Node(5000, "v1", 0))
);
NodeGraph actual = graphNodeService.getById(5000);
assertThat(actual.getName()).isEqualTo("v1");
assertThat(actual.getCounter()).isEqualTo(0);
}
@Test
public void getNodeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "NODE", 5000));
graphNodeService.getById(5000);
}
@Test
public void getAllNodes() {
List<Node> nodes = Stream.of(
new Node(5000, "v1", 0),
new Node(5001, "v2", 0),
new Node(5002, "v3", 0),
new Node(5003, "v4", 0),
new Node(5004, "v5", 0)
).collect(Collectors.toList());
given(nodeRepository.findAll()).willReturn(nodes);
Set<NodeGraph> actual = graphNodeService.getAll();
NodeGraph nodeGraph = GraphUtil.nodeToNodeGraph(nodes.get(4));
Assert.assertEquals(5, actual.size());
assertThat(actual).contains(nodeGraph);
}
@Test
public void deleteNodeByNodeGraph() {
given(nodeRepository.findById(5000)).willReturn(
Optional.of(new Node(5000, "v1", 0))
);
given(nodeRepository.findAll()).willReturn(nodes);
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 0);
graphNodeService.delete(nodeGraph);
Set<NodeGraph> actual = graphNodeService.getAll();
Assert.assertEquals(4, actual.size());
}
@Test
public void deleteNodeByNodeGraphNotFoundException() {
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 0);
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), nodeGraph.toString()));
graphNodeService.delete(nodeGraph);
}
@Test
public void deleteNodeByNodeGraphWithNullIdNotFoundException() {
NodeGraph nodeGraph = new NodeGraph(null, "v1", 0);
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), nodeGraph.toString()));
graphNodeService.delete(nodeGraph);
}
@Test
public void deleteNodeByNodeGraphNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphNodeService.delete((NodeGraph) null);
}
@Test
public void deleteNodeByName() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v1"));
when(nodeRepository.existsByName("v1")).thenReturn(true).thenReturn(false);
given(nodeRepository.findAll()).willReturn(nodes);
graphNodeService.delete("v1");
Set<NodeGraph> actual = graphNodeService.getAll();
Assert.assertEquals(4, actual.size());
graphNodeService.delete("v1");
}
@Test
public void deleteNodeByNameNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "null"));
graphNodeService.delete((String) null);
}
@Test
public void deleteNodeById() {
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "NODE", 5000));
when(nodeRepository.existsById(5000)).thenReturn(true).thenReturn(false);
given(nodeRepository.findAll()).willReturn(nodes);
graphNodeService.delete(5000);
Set<NodeGraph> actual = graphNodeService.getAll();
Assert.assertEquals(4, actual.size());
graphNodeService.delete(5000);
}
@Test
public void deleteNodeByIdNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage( String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), "NODE", null));
graphNodeService.delete((Integer) null);
}
@Test
public void createNode() {
NodeGraph nodeGraph = new NodeGraph("v1");
Node node = new Node("v1");
node.setId(5000);
when(nodeRepository.save(any(Node.class))).thenReturn(node);
NodeGraph actual = graphNodeService.create(nodeGraph);
Assert.assertNotNull(actual);
Assert.assertNotNull(actual.getId());
Assert.assertEquals(5000, actual.getId().intValue());
Assert.assertEquals("v1", actual.getName());
}
@Test
public void createNodeIsPresentException() {
thrown.expect(ApplicationException.class);
NodeGraph nodeGraph = new NodeGraph("v1");
thrown.expectMessage(String.format(
properties.getNodeMsg().get("NODE_MSG_ALREADY_PRESENT_ERROR"),
nodeGraph.getName()
));
Node node = new Node("v1");
node.setId(5000);
when(nodeRepository.getByName(any(String.class))).thenReturn(node);
graphNodeService.create(nodeGraph);
}
@Test
public void createNodeNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphNodeService.create((NodeGraph) null);
}
@Test
public void createNodes() {
Set<NodeGraph> nodeGraphs = new HashSet<>();
List<Node> nodes = new ArrayList<>();
IntStream.range(1, 6).forEach(i -> {
nodeGraphs.add(new NodeGraph("w" + i));
nodes.add(new Node(5000 + i, "w" + i, 0));
});
when(nodeRepository.saveAll(anyIterable())).thenReturn(nodes);
Set<NodeGraph> actual = graphNodeService.create(nodeGraphs);
Assert.assertNotNull(actual);
Assert.assertEquals(5, actual.size());
}
@Test
public void createNodesIsPresentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(String.format(
properties.getNodeMsg().get("NODE_MSG_ALREADY_PRESENT_ERROR"),
"w1"
));
Set<NodeGraph> nodeGraphs = new HashSet<>();
nodeGraphs.add(new NodeGraph("w1"));
Node node = new Node(5000, "w1", 0);
when(nodeRepository.getByName(any(String.class))).thenReturn(node);
graphNodeService.create(nodeGraphs);
}
@Test
public void createNodesNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphNodeService.create((Set<NodeGraph>) null);
}
@Test
public void createNodesEmptyCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_EMPTY"));
graphNodeService.create(new HashSet<>());
}
@Test
public void createNodesCollectionContainNullException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_NULL"));
Set<NodeGraph> nodeGraphs = new HashSet<>();
nodeGraphs.add(new NodeGraph("v1"));
nodeGraphs.add(null);
graphNodeService.create(nodeGraphs);
}
@Test
public void updateNode() {
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 2);
Node node = new Node(5000, "v1", 2);
when(nodeRepository.save(any(Node.class))).thenReturn(node);
when(nodeRepository.findById(5000)).thenReturn(Optional.of(node));
graphNodeService.update(nodeGraph);
NodeGraph actual = graphNodeService.getById(5000);
Assert.assertNotNull(actual);
Assert.assertEquals(nodeGraph, GraphUtil.nodeToNodeGraph(node));
}
@Test
public void updateNodeNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphNodeService.update(null);
}
@Test
public void updateNodeWhileUpdateException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_UPDATE_ERROR"), 5000));
NodeGraph nodeGraph = new NodeGraph(5000, "v1", 0);
when(nodeRepository.save(any(Node.class))).thenReturn(null);
graphNodeService.update(nodeGraph);
}
}

View File

@@ -0,0 +1,194 @@
package ru.resprojects.linkchecker.services;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.dto.GraphDto;
import ru.resprojects.linkchecker.util.exeptions.ApplicationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
public class GraphServiceH2DBTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphServiceH2DBTests.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
private GraphService graphService;
@Autowired
private AppProperties properties;
private Set<EdgeGraph> edgeGraphSet = Stream.of(
new EdgeGraph("v1", "v2"),
new EdgeGraph("v1", "v3"),
new EdgeGraph("v1", "v4"),
new EdgeGraph("v2", "v3"),
new EdgeGraph("v2", "v4"),
new EdgeGraph("v3", "v4")
).collect(Collectors.toSet());
@Test
public void createGraph() {
GraphDto graphDto = new GraphDto();
graphDto.setNodes(Stream.of(
new NodeGraph("v1"),
new NodeGraph("v2"),
new NodeGraph("v3"),
new NodeGraph("v4")
).collect(Collectors.toSet()));
graphDto.setEdges(edgeGraphSet);
GraphDto actual = graphService.create(graphDto);
Assert.assertNotNull(actual);
LOG.info(actual.toString());
}
@Test
public void createGraphWithExtraEdges() {
GraphDto graphDto = new GraphDto();
graphDto.setNodes(Stream.of(
new NodeGraph("v1"),
new NodeGraph("v2"),
new NodeGraph("v3")
).collect(Collectors.toSet()));
graphDto.setEdges(edgeGraphSet);
GraphDto actual = graphService.create(graphDto);
Assert.assertNotNull(actual);
LOG.info(actual.toString());
}
@Test
public void createGraphNullArgumentException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphService.create(null);
}
@Test
public void createGraphEmptyCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage("NODES: " + properties.getAppMsg().get("MSG_COLLECTION_EMPTY"));
GraphDto graphDto = new GraphDto();
graphDto.setNodes(new HashSet<>());
graphDto.setEdges(edgeGraphSet);
graphService.create(graphDto);
}
@Test
public void getGraphWithRemovedEdges() {
graphService.getEdges().create(Stream.of(
new EdgeGraph("v2", "v3"),
new EdgeGraph("v3", "v5"),
new EdgeGraph("v2", "v4"),
new EdgeGraph("v5", "v4")
).collect(Collectors.toSet()));
Set<EdgeGraph> edgeGraphs = graphService.getEdges().getAll();
LOG.info(edgeGraphs.toString());
GraphDto actual = graphService.get();
Assert.assertNotNull(actual);
Assert.assertNotEquals(edgeGraphs.size(), actual.getEdges().size());
LOG.info(actual.toString());
}
@Test
public void getGraphWithoutRemovingEdges() {
GraphDto actual = graphService.get();
Assert.assertNotNull(actual);
Assert.assertEquals(4, actual.getEdges().size());
LOG.info(actual.toString());
}
@Test
public void deleteGraph() {
graphService.clear();
GraphDto actual = graphService.get();
Assert.assertNotNull(actual);
Assert.assertEquals(0, actual.getEdges().size());
Assert.assertEquals(0, actual.getNodes().size());
}
@Test
public void getGraphAfterAddedNewNode() {
graphService.getNodes().create(new NodeGraph("v6"));
GraphDto actual = graphService.get();
Assert.assertNotNull(actual);
Assert.assertEquals(6, actual.getNodes().size());
Assert.assertEquals(4, actual.getEdges().size());
}
@Test
public void checkNodesRoute() {
Set<String> nodeNames = Stream.of("v1", "v2", "v3", "v5").collect(Collectors.toSet());
int faultCount = 0;
Map<String, Integer> nodeErrorStat = new HashMap<>();
for (int i = 0; i < 100; i++) {
try {
LOG.info(graphService.checkRoute(nodeNames));
} catch (ApplicationException e) {
String node = e.getMessage().split(" ")[1];
LOG.info(node);
if (!nodeErrorStat.containsKey(node)) {
nodeErrorStat.put(node, 1);
} else {
Integer val = nodeErrorStat.get(node);
nodeErrorStat.put(node, ++val);
}
faultCount++;
}
}
LOG.info(graphService.get().toString());
LOG.info("FAULT COUNT for CHECK ROUTE = " + faultCount);
nodeErrorStat.forEach((key, value) -> LOG.info("NODE " + key + " error count = " + value));
}
@Test
public void checkRouteNullCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_ARGUMENT_NULL"));
graphService.checkRoute(null);
}
@Test
public void checkRouteEmptyCollectionException() {
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_EMPTY"));
graphService.checkRoute(new HashSet<>());
}
@Test
public void checkRouteCollectionHaveOneElementException() {
Set<String> nodeNames = Stream.of("v10").collect(Collectors.toSet());
thrown.expect(ApplicationException.class);
thrown.expectMessage(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_ONE_ELEMENT"));
graphService.checkRoute(nodeNames);
}
}

View File

@@ -0,0 +1,110 @@
package ru.resprojects.linkchecker.services;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.util.GraphUtil;
import ru.resprojects.linkchecker.util.exeptions.NotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.when;
import static org.powermock.api.mockito.PowerMockito.spy;
//How to use PowerMock https://www.baeldung.com/intro-to-powermock
//How to use PowerMock and SpringRunner https://stackoverflow.com/a/57780838
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = "moc_test")
@PrepareForTest(GraphUtil.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*",
"javax.xml.transform.*", "org.xml.*", "javax.management.*",
"javax.net.ssl.*", "com.sun.org.apache.xalan.internal.xsltc.trax.*"})
public class GraphServiceMockTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private GraphService graphService;
@MockBean
private GraphEdgeService edgeService;
@MockBean
private GraphNodeService nodeService;
@Autowired
private AppProperties properties;
@Before
public void init() {
graphService = new GraphServiceImpl(edgeService, nodeService, properties);
}
@Test
public void checkRouteNodeFaultException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_IS_FAULT"), "v1"));
spy(GraphUtil.class);
Map<String, Boolean> nodesFault = new HashMap<>();
nodesFault.put("v1", true);
nodesFault.put("v2", false);
nodesFault.put("v3", false);
given(nodeService.getAll()).willReturn(TestUtils.nodesGraph);
given(edgeService.getAll()).willReturn(TestUtils.edgesGraph);
when(GraphUtil.getRandomNodeFault(anyCollection())).thenReturn(nodesFault);
graphService.checkRoute(Stream.of("v1", "v2", "v3").collect(Collectors.toSet()));
}
@Test
public void checkRouteNodeNotReachableException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_NOT_REACHABLE"), "v1", "v4"));
spy(GraphUtil.class);
Map<String, Boolean> nodesFault = new HashMap<>();
nodesFault.put("v1", false);
nodesFault.put("v2", false);
nodesFault.put("v3", false);
nodesFault.put("v4", false);
given(nodeService.getAll()).willReturn(TestUtils.nodesGraph);
given(edgeService.getAll()).willReturn(TestUtils.edgesGraph);
when(GraphUtil.getRandomNodeFault(anyCollection())).thenReturn(nodesFault);
graphService.checkRoute(Stream.of("v1", "v2", "v4").collect(Collectors.toSet()));
}
@Test
public void checkRouteNodeNotFoundException() {
thrown.expect(NotFoundException.class);
thrown.expectMessage(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v7"));
spy(GraphUtil.class);
Map<String, Boolean> nodesFault = new HashMap<>();
nodesFault.put("v1", false);
nodesFault.put("v2", false);
nodesFault.put("v3", false);
given(nodeService.getAll()).willReturn(TestUtils.nodesGraph);
given(edgeService.getAll()).willReturn(TestUtils.edgesGraph);
when(GraphUtil.getRandomNodeFault(anyCollection())).thenReturn(nodesFault);
graphService.checkRoute(Stream.of("v1", "v2", "v3", "v7").collect(Collectors.toSet()));
}
}

View File

@@ -0,0 +1,332 @@
package ru.resprojects.linkchecker.util;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.dto.GraphDto;
import ru.resprojects.linkchecker.model.Edge;
import ru.resprojects.linkchecker.model.Node;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
import static ru.resprojects.linkchecker.util.GraphUtil.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = "moc_test")
public class GraphUtilTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphUtilTests.class);
private GraphDto graphDto;
@Before
public void init() {
Set<NodeGraph> nodeGraphSet = Stream.of(
new NodeGraph(5000, "v1", 0),
new NodeGraph(5001, "v2", 0),
new NodeGraph(5002, "v3", 0),
new NodeGraph(5003, "v4", 0),
new NodeGraph(5004, "v5", 0)
).collect(Collectors.toSet());
Set<EdgeGraph> edgeGraphSet = Stream.of(
new EdgeGraph(5005, "v1", "v2"),
new EdgeGraph(5006, "v1", "v3"),
new EdgeGraph(5007, "v1", "v5"),
new EdgeGraph(5008, "v3", "v4")
).collect(Collectors.toSet());
graphDto = new GraphDto(nodeGraphSet, edgeGraphSet);
}
@Test
public void generateRandomNodeFaultTest() {
Set<NodeGraph> nodeGraphSet = new HashSet<>();
IntStream.range(0, 23).forEach(v -> nodeGraphSet.add(new NodeGraph(5000 + v, "v" + v, 0)));
Map<String, Boolean> result = getRandomNodeFault(nodeGraphSet);
Assert.assertNotNull(result);
result.forEach((key, value) -> LOG.debug("Node: " + key + " is fault = " + value));
long countOfFault = result.entrySet().stream().filter(Map.Entry::getValue).count();
LOG.debug("Count of fault elements = " + countOfFault);
}
@Test
public void returnEmptyMapFromGenerateRandomNodeFault() {
Map<String, Boolean> result = getRandomNodeFault(null);
Assert.assertTrue(result.isEmpty());
result = getRandomNodeFault(new HashSet<>());
Assert.assertTrue(result.isEmpty());
}
@Test
public void getEdgesFromGraphDtoTest() {
Set<Edge> actual = getEdgesFromGraphDto(graphDto);
Assert.assertNotNull(actual);
assertThat(actual).isNotEmpty();
Assert.assertEquals(graphDto.getEdges().size(), actual.size());
Assert.assertTrue(actual.stream()
.anyMatch(edge -> edge.getId().equals(
graphDto.getEdges().iterator().next().getId())
)
);
actual.forEach(edge -> LOG.debug(edge.toString()));
}
@Test
public void getEdgesFromGraphDtoSkipEdgeGraph() {
EdgeGraph eg = new EdgeGraph(5009, "v3", "v7");
graphDto.getEdges().add(eg);
Set<Edge> actual = getEdgesFromGraphDto(graphDto);
Assert.assertNotNull(actual);
Assert.assertTrue(actual.stream().noneMatch(
edge -> edge.getId().equals(eg.getId()))
);
LOG.debug("EdgeGraph collection:");
graphDto.getEdges().forEach(edgeGraph -> LOG.debug(edgeGraph.toString()));
LOG.debug("Edge collection:");
actual.forEach(edge -> LOG.debug(edge.toString()));
}
@Test
public void edgeToEdgeGraphTest() {
Edge edge = new Edge(3, new Node(1, "v1", 0),
new Node(2, "v2", 0));
EdgeGraph actual = edgeToEdgeGraph(edge);
Assert.assertNotNull(actual);
Assert.assertEquals(edge.getId(), actual.getId());
}
@Test
public void edgeToEdgeGraphReturnNull() {
Assert.assertNull(edgeToEdgeGraph(null));
}
@Test
public void edgesToEdgeGraphsTest() {
Set<Edge> edges = Stream.of(
new Edge(3, new Node(1, "v1", 0),
new Node(2, "v2", 0)),
new Edge(6, new Node(4, "v1", 0),
new Node(5, "v3", 0))
).collect(Collectors.toSet());
Set<EdgeGraph> actual = edgesToEdgeGraphs(edges);
Assert.assertNotNull(actual);
assertThat(actual).isNotEmpty();
Assert.assertEquals(edges.size(), actual.size());
for (EdgeGraph edgeGraph : actual) {
Assert.assertTrue(edges.stream()
.anyMatch(e -> e.getId().equals(edgeGraph.getId())));
}
}
@Test
public void edgesToEdgeGraphsReturnEmptyCollection() {
assertThat(edgesToEdgeGraphs(null)).isEmpty();
}
@Test
public void nodeGraphToNodeTest() {
NodeGraph nodeGraph = graphDto.getNodes().iterator().next();
Node node = nodeGraphToNode(nodeGraph);
Assert.assertNotNull(node);
Assert.assertEquals(nodeGraph.getId(), node.getId());
}
@Test
public void nodeGraphToNodeReturnNull() {
Assert.assertNull(nodeGraphToNode(null));
}
@Test
public void nodeToNodeGraphTest() {
Node node = new Node(1, "v1", 0);
NodeGraph actual = nodeToNodeGraph(node);
Assert.assertNotNull(actual);
Assert.assertEquals(node.getId(), node.getId());
}
@Test
public void nodeToNodeGraphReturnNull() {
Assert.assertNull(nodeToNodeGraph(null));
}
@Test
public void nodeGraphsToNodesTest() {
Set<Node> actual = nodeGraphsToNodes(graphDto.getNodes());
Assert.assertNotNull(actual);
assertThat(actual).isNotEmpty();
Assert.assertEquals(graphDto.getNodes().size(), actual.size());
for (Node node : actual) {
Assert.assertTrue(graphDto.getNodes().stream()
.anyMatch(n -> n.getId().equals(node.getId())));
}
}
@Test
public void nodeGraphsToNodesReturnEmptyCollection() {
assertThat(nodeGraphsToNodes(null)).isEmpty();
}
@Test
public void nodesToNodeGraphsTest() {
Set<Node> nodes = Stream.of(
new Node(1, "v1", 0),
new Node(2, "v2", 0)
).collect(Collectors.toSet());
Set<NodeGraph> actual = nodesToNodeGraphs(nodes);
Assert.assertNotNull(actual);
assertThat(actual).isNotEmpty();
for (NodeGraph nodeGraph : actual) {
Assert.assertTrue(nodes.stream()
.anyMatch(n -> n.getId().equals(nodeGraph.getId())));
}
}
@Test
public void nodesToNodeGraphsReturnEmptyCollection() {
assertThat(nodesToNodeGraphs(null)).isEmpty();
}
@Test
public void exportToGraphVizTest() {
String actual = exportToGraphViz(graphDto);
assertThat(actual).isNotEmpty();
assertThat(actual).contains("strict graph");
}
@Test
public void exportToGraphVizReturnNull() {
assertThat(exportToGraphViz(null)).isEmpty();
}
@Test
public void graphBuilderTest() {
Graph<Node, DefaultEdge> actual = graphBuilder(graphDto.getNodes(),
graphDto.getEdges());
Assert.assertNotNull(actual);
Assert.assertEquals(actual.vertexSet().size(), graphDto.getNodes().size());
Assert.assertEquals(actual.edgeSet().size(), graphDto.getEdges().size());
LOG.debug(actual.toString());
}
@Test
public void graphBuilderSkipNullElementFromNodesAndEdges() {
graphDto.getNodes().add(null);
graphDto.getEdges().add(null);
Graph<Node, DefaultEdge> actual = graphBuilder(graphDto.getNodes(),
graphDto.getEdges());
Assert.assertNotNull(actual);
Assert.assertNotEquals(actual.vertexSet().size(), graphDto.getNodes().size());
Assert.assertNotEquals(actual.edgeSet().size(), graphDto.getEdges().size());
LOG.debug(actual.toString());
}
@Test
public void graphBuilderSkipEdgeWithNonExistsNodes() {
graphDto.getEdges().add(new EdgeGraph(5009, "v10", "v12"));
Graph<Node, DefaultEdge> actual = graphBuilder(graphDto.getNodes(),
graphDto.getEdges());
Assert.assertNotNull(actual);
Assert.assertNotEquals(actual.edgeSet().size(), graphDto.getEdges().size());
LOG.debug(actual.toString());
}
@Test
public void graphBuilderReturnEmptyGraph() {
Graph<Node, DefaultEdge> actual = graphBuilder(null,
graphDto.getEdges());
assertThat(actual.vertexSet()).isEmpty();
assertThat(actual.edgeSet()).isEmpty();
LOG.debug(actual.toString());
actual = graphBuilder(graphDto.getNodes(), null);
assertThat(actual.vertexSet()).isEmpty();
assertThat(actual.edgeSet()).isEmpty();
LOG.debug(actual.toString());
actual = graphBuilder(null, null);
assertThat(actual.vertexSet()).isEmpty();
assertThat(actual.edgeSet()).isEmpty();
LOG.debug(actual.toString());
}
@Test
public void graphToGraphDtoTest() {
GraphDto actual = graphToGraphDto(graphBuilder(graphDto.getNodes(),
graphDto.getEdges()));
assertThat(actual.getNodes()).isNotEmpty();
assertThat(actual.getEdges()).isNotEmpty();
Assert.assertEquals(graphDto.getNodes().size(), actual.getNodes().size());
Assert.assertEquals(graphDto.getEdges().size(), actual.getEdges().size());
for (NodeGraph nodeGraph : actual.getNodes()) {
Assert.assertTrue(graphDto.getNodes().stream()
.anyMatch(ng -> ng.equals(nodeGraph)));
}
// Because method graphToGraphDto is return edges without IDs ,
// IDs is not checked.
for (EdgeGraph edgeGraph : actual.getEdges()) {
Assert.assertTrue(graphDto.getEdges().stream()
.anyMatch(eg -> eg.getNodeOne().equals(edgeGraph.getNodeOne())
&& eg.getNodeTwo().equals(edgeGraph.getNodeTwo()))
);
}
LOG.debug(actual.toString());
}
@Test
public void graphToGraphDtoReturnEmptyGraphDto() {
GraphDto actual = graphToGraphDto(null);
assertThat(actual.getNodes()).isEmpty();
assertThat(actual.getEdges()).isEmpty();
}
@Test
public void removeCyclesFromGraphTest() {
GraphDto cyclesGraph = new GraphDto();
cyclesGraph.getNodes().addAll(graphDto.getNodes());
cyclesGraph.getEdges().addAll(graphDto.getEdges());
cyclesGraph.getEdges().add(new EdgeGraph(5009, "v2", "v4"));
cyclesGraph.getEdges().add(new EdgeGraph(5010, "v2", "v3"));
cyclesGraph.getEdges().add(new EdgeGraph(5011, "v3", "v5"));
cyclesGraph.getEdges().add(new EdgeGraph(5012, "v3", "v4"));
cyclesGraph.getEdges().add(new EdgeGraph(5013, "v5", "v4"));
GraphDto actual = graphToGraphDto(removeCyclesFromGraph(graphBuilder(
cyclesGraph.getNodes(), cyclesGraph.getEdges())));
Assert.assertEquals(graphDto.getNodes().size(), actual.getNodes().size());
Assert.assertEquals(graphDto.getEdges().size(), actual.getEdges().size());
}
@Test
public void removeCyclesFromGraphCyclesNotFound() {
GraphDto actual = graphToGraphDto(removeCyclesFromGraph(graphBuilder(
graphDto.getNodes(), graphDto.getEdges())));
for (NodeGraph nodeGraph : actual.getNodes()) {
Assert.assertTrue(graphDto.getNodes().stream()
.anyMatch(ng -> ng.equals(nodeGraph)));
}
// Because method graphToGraphDto is return edges without IDs ,
// IDs is not checked.
for (EdgeGraph edgeGraph : actual.getEdges()) {
Assert.assertTrue(graphDto.getEdges().stream()
.anyMatch(eg -> eg.getNodeOne().equals(edgeGraph.getNodeOne())
&& eg.getNodeTwo().equals(edgeGraph.getNodeTwo()))
);
}
}
}

View File

@@ -0,0 +1,310 @@
package ru.resprojects.linkchecker.web.rest;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.util.exeptions.ErrorInfo;
import ru.resprojects.linkchecker.util.exeptions.ErrorPlaceType;
import ru.resprojects.linkchecker.util.exeptions.ErrorType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
public class GraphEdgeRestControllerTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphRestControllerTests.class);
@Autowired
private MockMvc mvc;
@Autowired
private AppProperties properties;
@Test
public void addNewEdge() throws Exception {
EdgeGraph newEdge = new EdgeGraph("v1", "v4");
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newEdge))).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
EdgeGraph returnedEdge = TestUtils.mapFromJson(result.getResponse().getContentAsString(), EdgeGraph.class);
Assert.assertNotNull(returnedEdge);
Assert.assertEquals(newEdge.getNodeOne(), returnedEdge.getNodeOne());
Assert.assertEquals(newEdge.getNodeTwo(), returnedEdge.getNodeTwo());
Assert.assertNotNull(returnedEdge.getId());
}
@Test
public void addNewEdgeValidationException() throws Exception {
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(new EdgeGraph()))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.VALIDATION_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.APP, error.getPlace());
LOG.info(Arrays.asList(error.getMessages()).toString());
}
@Test
public void addNewEdgeAlreadyPresentException() throws Exception {
EdgeGraph newEdge = new EdgeGraph("v1", "v2");
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newEdge))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getEdgeMsg().get("EDGE_MSG_ALREADY_PRESENT_ERROR"),
newEdge.getNodeOne(), newEdge.getNodeTwo(),
newEdge.getNodeTwo(), newEdge.getNodeOne())));
LOG.info(errMsgs.toString());
}
@Test
public void addNewEdges() throws Exception {
Set<EdgeGraph> newEdges = Stream.of(
new EdgeGraph("v1", "v4"),
new EdgeGraph("v2", "v4")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newEdges))).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
Type listType = new TypeToken<HashSet<EdgeGraph>>() {}.getType();
Set<EdgeGraph> returnedEdges = TestUtils.mapFromJson(result.getResponse().getContentAsString(), listType);
Assert.assertEquals(newEdges.size(), returnedEdges.size());
Assert.assertTrue(returnedEdges.stream().anyMatch(ng -> ng.getNodeOne().equals("v1") && ng.getNodeTwo().equals("v4")));
}
@Test
public void addNewEdgesEmptyCollectionException() throws Exception {
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(Collections.emptySet()))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_EMPTY")));
LOG.info(errMsgs.toString());
}
@Test
public void addNewEdgesCollectionContainNullObjectException() throws Exception {
Set<EdgeGraph> newEdges = Stream.of(
null,
new EdgeGraph("v1", "v4"),
new EdgeGraph("v2", "v4")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newEdges))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_NULL")));
LOG.info(errMsgs.toString());
}
@Test
public void addNewEdgesCollectionContainAlreadyPresentNodeException() throws Exception {
EdgeGraph newEdge = new EdgeGraph("v1", "v2");
Set<EdgeGraph> newEdges = Stream.of(
newEdge,
new EdgeGraph("v1", "v4"),
new EdgeGraph("v2", "v4")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newEdges))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getEdgeMsg().get("EDGE_MSG_ALREADY_PRESENT_ERROR"),
newEdge.getNodeOne(), newEdge.getNodeTwo(),
newEdge.getNodeTwo(), newEdge.getNodeOne())));
LOG.info(errMsgs.toString());
}
@Test
public void getEdges() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.edgesGraph)));
}
@Test
public void getEdgeById() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byId/5005").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.edgeGraph)));
}
@Test
public void getEdgesByNodeName() throws Exception {
Set<EdgeGraph> expected = TestUtils.edgesGraph.stream()
.filter(eg -> eg.getId() != 5008)
.collect(Collectors.toSet());
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(expected)));
}
@Test
public void getEdgeByNodeNames() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v1&nodeTwo=v2").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.edgeGraph)));
}
@Test
public void getEdgeByIdNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), ErrorPlaceType.EDGE, 5050)));
}
@Test
public void getEdgesByNameNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName/v100")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_BY_NAME_ERROR"), "v100")));
}
@Test
public void deleteAllEdges() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(Collections.EMPTY_SET)));
}
@Test
public void deleteEdgeById() throws Exception {
Set<EdgeGraph> expected = TestUtils.edgesGraph.stream()
.filter(eg -> eg.getId() != 5005)
.collect(Collectors.toSet());
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byId/5005").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(expected)));
}
@Test
public void deleteEdgeByIdNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), ErrorPlaceType.EDGE, 5050)));
}
@Test
public void deleteEdgesByNodeName() throws Exception {
Set<EdgeGraph> expected = TestUtils.edgesGraph.stream()
.filter(eg -> eg.getId() != 5008)
.collect(Collectors.toSet());
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName/v4").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(expected)));
}
@Test
public void deleteEdgesByNodeNameNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName/v50")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_BY_NAME_ERROR"), "v50")));
}
@Test
public void deleteEdgeByNodeNames() throws Exception {
Set<EdgeGraph> expected = TestUtils.edgesGraph.stream()
.filter(eg -> eg.getId() != 5005)
.collect(Collectors.toSet());
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v1&nodeTwo=v2").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(expected)));
}
@Test
public void deleteEdgeByNodeNamesNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v50&nodeTwo=v2")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.EDGE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getEdgeMsg().get("EDGE_MSG_GET_ERROR"), "v50", "v2")));
}
}

View File

@@ -0,0 +1,333 @@
package ru.resprojects.linkchecker.web.rest;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.util.exeptions.ErrorInfo;
import ru.resprojects.linkchecker.util.exeptions.ErrorPlaceType;
import ru.resprojects.linkchecker.util.exeptions.ErrorType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
public class GraphNodeRestControllerTests {
private static final Logger LOG = LoggerFactory.getLogger(GraphNodeRestControllerTests.class);
@Autowired
private MockMvc mvc;
@Autowired
private AppProperties properties;
@Test
public void getNodes() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.nodesGraph)));
}
@Test
public void getNodeById() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byId/5000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.nodeGraph)));
}
@Test
public void getNodeByName() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.nodeGraph)));
}
@Test
public void getNodeByNameNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byName/v10")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v10")));
}
@Test
public void getNodeByIdNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getAppMsg().get("MSG_BY_ID_ERROR"), ErrorPlaceType.NODE, 5050)));
}
@Test
public void addNewNodeToGraph() throws Exception {
NodeGraph newNode = new NodeGraph("v6");
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode))).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
NodeGraph returnedNode = TestUtils.mapFromJson(result.getResponse().getContentAsString(), NodeGraph.class);
Assert.assertNotNull(returnedNode);
Assert.assertEquals(newNode.getName(), returnedNode.getName());
Assert.assertNotNull(returnedNode.getId());
}
@Test
public void addNewNodesToGraph() throws Exception {
Set<NodeGraph> newNodes = Stream.of(
new NodeGraph("v6"),
new NodeGraph("v7"),
new NodeGraph("v8")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNodes))).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
Type listType = new TypeToken<HashSet<NodeGraph>>() {}.getType();
Set<NodeGraph> returnedNodes = TestUtils.mapFromJson(result.getResponse().getContentAsString(), listType);
Assert.assertEquals(newNodes.size(), returnedNodes.size());
Assert.assertTrue(returnedNodes.stream().anyMatch(ng -> ng.getName().equals("v6")));
}
@Test
public void addNewNodeValidationException() throws Exception {
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(new NodeGraph()))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.VALIDATION_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.APP, error.getPlace());
LOG.info(Arrays.asList(error.getMessages()).toString());
}
@Test
public void addNewNodeAlreadyPresentException() throws Exception {
NodeGraph newNode = new NodeGraph("v1");
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getNodeMsg().get("NODE_MSG_ALREADY_PRESENT_ERROR"), newNode.getName())));
LOG.info(errMsgs.toString());
}
@Test
public void addNewNodesEmptyCollectionException() throws Exception {
Set<NodeGraph> newNodes = Collections.emptySet();
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNodes))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_EMPTY")));
LOG.info(errMsgs.toString());
}
@Test
public void addNewNodesCollectionContainNullObjectException() throws Exception {
Set<NodeGraph> newNodes = Stream.of(
null,
new NodeGraph("v7"),
new NodeGraph("v8")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNodes))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_NULL")));
LOG.info(errMsgs.toString());
}
@Test
public void addNewNodesCollectionContainAlreadyPresentNodeException() throws Exception {
Set<NodeGraph> newNodes = Stream.of(
new NodeGraph("v1"),
new NodeGraph("v7"),
new NodeGraph("v8")
).collect(Collectors.toSet());
MvcResult result = this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNodes))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getNodeMsg().get("NODE_MSG_ALREADY_PRESENT_ERROR"),"v1")));
LOG.info(errMsgs.toString());
}
@Test
public void deleteAllNodes() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(Collections.EMPTY_SET)));
}
@Test
public void deleteNodeById() throws Exception {
Set<NodeGraph> nodes = TestUtils.nodesGraph.stream().filter(ng -> ng.getId() != 5000).collect(Collectors.toSet());
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byId/5000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(nodes)));
}
@Test
public void deleteNodeByName() throws Exception {
Set<NodeGraph> nodes = TestUtils.nodesGraph.stream().filter(ng -> !ng.getName().equals("v1")).collect(Collectors.toSet());
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(nodes)));
}
@Test
public void deleteNodeByObject() throws Exception {
Set<NodeGraph> nodes = TestUtils.nodesGraph.stream().filter(ng -> !ng.getName().equals("v1")).collect(Collectors.toSet());
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(TestUtils.nodeGraph)))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(nodes)));
}
@Test
public void deleteNodeByIdNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getAppMsg().get("MSG_BY_ID_ERROR"), ErrorPlaceType.NODE, 5050)));
LOG.info(errMsgs.toString());
}
@Test
public void deleteNodeByNameNotFoundException() throws Exception {
MvcResult result = this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byName/v10")
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v10")));
LOG.info(errMsgs.toString());
}
@Test
public void deleteNodeByObjectWithNullIdNotFoundException() throws Exception {
NodeGraph newNode = new NodeGraph(null, "v10", 0);
MvcResult result = this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), newNode.toString())));
LOG.info(errMsgs.toString());
}
@Test
public void deleteNodeByObjectNotFoundException() throws Exception {
NodeGraph newNode = new NodeGraph(5020, "v10", 0);
MvcResult result = this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), newNode.toString())));
LOG.info(errMsgs.toString());
}
@Test
public void deleteNodeByObjectWithIncorrectIdException() throws Exception {
NodeGraph newNode = new NodeGraph(5000, "v10", 0);
MvcResult result = this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.NODE, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(
properties.getNodeMsg().get("NODE_MSG_BY_OBJECT_ERROR"), newNode.toString())));
LOG.info(errMsgs.toString());
}
}

View File

@@ -0,0 +1,47 @@
package ru.resprojects.linkchecker.web.rest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.services.GraphService;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@RunWith(SpringRunner.class)
@WebMvcTest(GraphRestController.class)
public class GraphRestControllerMockTests {
@Autowired
private MockMvc mvc;
@MockBean
private GraphService graphService;
@Test
public void checkRouteInGraph() throws Exception {
List<String> route = Stream.of("v1", "v2", "v3").collect(Collectors.toList());
String returnedResult = String.format("Route for nodes %s is found", route.toString());
given(this.graphService.checkRoute(anySet())).willReturn(returnedResult);
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route))).andReturn();
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
Assert.assertEquals(result.getResponse().getContentAsString(), returnedResult);
}
}

View File

@@ -0,0 +1,173 @@
package ru.resprojects.linkchecker.web.rest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import ru.resprojects.linkchecker.AppProperties;
import ru.resprojects.linkchecker.LinkcheckerApplication;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.dto.GraphDto;
import ru.resprojects.linkchecker.util.exeptions.ErrorInfo;
import ru.resprojects.linkchecker.util.exeptions.ErrorPlaceType;
import ru.resprojects.linkchecker.util.exeptions.ErrorType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.resprojects.linkchecker.dto.GraphDto.NodeGraph;
import static ru.resprojects.linkchecker.dto.GraphDto.EdgeGraph;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LinkcheckerApplication.class)
@ActiveProfiles(profiles = {"test", "debug"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
public class GraphRestControllerTests {
@Autowired
private MockMvc mvc;
@Autowired
private AppProperties properties;
@Test
public void getGraph() throws Exception {
this.mvc.perform(get(GraphRestController.REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(TestUtils.graph)));
}
@Test
public void exportGraphToGraphVizFormat() throws Exception {
MvcResult result = this.mvc.perform(get(GraphRestController.REST_URL + "/export").accept(MediaType.TEXT_HTML_VALUE))
.andReturn();
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
String content = result.getResponse().getContentAsString();
Assert.assertFalse(content.isEmpty());
Assert.assertTrue(content.contains("strict graph G"));
}
@Test
public void createGraph() throws Exception {
Set<NodeGraph> nodesGraph = TestUtils.nodesGraph.stream()
.map(ng -> new GraphDto.NodeGraph(ng.getName()))
.collect(Collectors.toSet());
Set<EdgeGraph> edgesGraph = TestUtils.edgesGraph.stream()
.map(eg -> new EdgeGraph(eg.getNodeOne(), eg.getNodeTwo()))
.collect(Collectors.toSet());
GraphDto graph = new GraphDto(nodesGraph, edgesGraph);
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(graph))).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
GraphDto returnedGraph = TestUtils.mapFromJson(result.getResponse().getContentAsString(), GraphDto.class);
Assert.assertNotNull(returnedGraph);
Assert.assertEquals(nodesGraph.size(), returnedGraph.getNodes().size());
Assert.assertEquals(edgesGraph.size(), returnedGraph.getEdges().size());
Assert.assertNotNull(returnedGraph.getNodes().iterator().next().getId());
Assert.assertNotNull(returnedGraph.getEdges().iterator().next().getId());
}
@Test
public void createGraphEmptyNodeCollectionException() throws Exception {
Set<NodeGraph> nodesGraph = Collections.emptySet();
Set<EdgeGraph> edgesGraph = TestUtils.edgesGraph.stream()
.map(eg -> new EdgeGraph(eg.getNodeOne(), eg.getNodeTwo()))
.collect(Collectors.toSet());
GraphDto graph = new GraphDto(nodesGraph, edgesGraph);
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(graph))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.GRAPH, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains("NODES: " + properties.getAppMsg().get("MSG_COLLECTION_EMPTY")));
}
@Test
public void deleteGraph() throws Exception {
this.mvc.perform(delete(GraphRestController.REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
this.mvc.perform(get(GraphRestController.REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(TestUtils.mapToJson(new GraphDto())));
}
@Test
public void getOptions() throws Exception {
MvcResult result = this.mvc.perform(options(GraphRestController.REST_URL)
.accept(MediaType.APPLICATION_JSON)).andReturn();
Assert.assertTrue(result.getResponse().containsHeader("Allow"));
Assert.assertEquals("GET,POST,DELETE,OPTIONS", result.getResponse().getHeader("Allow"));
}
@Test
public void checkRouteEmptyInputCollectionException() throws Exception {
List<String> route = new ArrayList<>();
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.GRAPH, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_EMPTY")));
}
@Test
public void checkRouteNotEnoughDataException() throws Exception {
List<String> route = Collections.singletonList("v1");
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_ERROR, error.getType());
Assert.assertEquals(ErrorPlaceType.GRAPH, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(properties.getAppMsg().get("MSG_COLLECTION_CONTAIN_ONE_ELEMENT")));
}
@Test
public void checkRouteNotFoundException() throws Exception {
List<String> route = Stream.of("v7", "v2", "v1").collect(Collectors.toList());
MvcResult result = this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route))).andReturn();
Assert.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY.value(), result.getResponse().getStatus());
ErrorInfo error = TestUtils.mapFromJson(result.getResponse().getContentAsString(), ErrorInfo.class);
Assert.assertEquals(ErrorType.DATA_NOT_FOUND, error.getType());
Assert.assertEquals(ErrorPlaceType.GRAPH, error.getPlace());
List<String> errMsgs = Arrays.asList(error.getMessages());
Assert.assertTrue(errMsgs.contains(String.format(properties.getNodeMsg().get("NODE_MSG_BY_NAME_ERROR"), "v7")));
}
}

View File

@@ -0,0 +1,186 @@
package ru.resprojects.linkchecker.web.rest.apidocs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.dto.GraphDto;
import ru.resprojects.linkchecker.web.rest.GraphRestController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"test"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class GraphApiDocumentation {
@Autowired
private MockMvc mvc;
@Test
public void getGraph() throws Exception {
this.mvc.perform(MockMvcRequestBuilders.get(GraphRestController.REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(getGraphResponseDoc("get-graph"));
}
@Test
public void exportGraphToGraphVizFormat() throws Exception {
this.mvc.perform(get(GraphRestController.REST_URL + "/export").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().isOk())
.andDo(document("export-graph"));
}
@Test
public void createGraph() throws Exception {
String jsonGraph = "{\n" +
" \"nodes\":[\n" +
" {\"name\":\"v1\"},\n" +
" {\"name\":\"v2\"},\n" +
" {\"name\":\"v3\"},\n" +
" {\"name\":\"v4\"},\n" +
" {\"name\":\"v5\"}\n" +
" ],\n" +
" \"edges\":[\n" +
" {\"nodeOne\":\"v1\",\"nodeTwo\":\"v2\"},\n" +
" {\"nodeOne\":\"v2\",\"nodeTwo\":\"v3\"},\n" +
" {\"nodeOne\":\"v3\",\"nodeTwo\":\"v4\"},\n" +
" {\"nodeOne\":\"v3\",\"nodeTwo\":\"v5\"},\n" +
" {\"nodeOne\":\"v5\",\"nodeTwo\":\"v4\"},\n" +
" {\"nodeOne\":\"v5\",\"nodeTwo\":\"v2\"}\n" +
" ]\n" +
"}";
this.mvc.perform(post(GraphRestController.REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonGraph))
.andExpect(status().isCreated())
.andDo(document("create-graph",
requestFields(
fieldWithPath("nodes")
.description("Коллекция вершин графа (ноды)"),
fieldWithPath("nodes[].name")
.description("Уникальное имя вершины графа"),
fieldWithPath("edges")
.description("Коллекция рёбер графа"),
fieldWithPath("edges[].nodeOne")
.description("Уникальное имя вершины графа"),
fieldWithPath("edges[].nodeTwo")
.description("Уникальное имя вершины графа")
)))
.andDo(getGraphResponseDoc("create-graph"));
}
@Test
public void createGraphEmptyNodeCollectionException() throws Exception {
Set<GraphDto.NodeGraph> nodesGraph = Collections.emptySet();
Set<GraphDto.EdgeGraph> edgesGraph = TestUtils.edgesGraph.stream()
.map(eg -> new GraphDto.EdgeGraph(eg.getNodeOne(), eg.getNodeTwo()))
.collect(Collectors.toSet());
GraphDto graph = new GraphDto(nodesGraph, edgesGraph);
this.mvc.perform(post(GraphRestController.REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(graph)))
.andDo(ErrorResponseDoc("create-graph-exception"));
}
@Test
public void checkRouteEmptyInputCollectionException() throws Exception {
List<String> route = new ArrayList<>();
this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route)))
.andDo(ErrorResponseDoc( "checkroute-graph-exception-1"));
}
@Test
public void checkRouteNotEnoughDataException() throws Exception {
List<String> route = Collections.singletonList("v1");
this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route)))
.andDo(ErrorResponseDoc( "checkroute-graph-exception-2"));
}
@Test
public void checkRouteNotFoundException() throws Exception {
List<String> route = Stream.of("v7", "v2", "v1").collect(Collectors.toList());
this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route)))
.andDo(ErrorResponseDoc( "checkroute-graph-exception-3"));
}
@Test
public void deleteGraph() throws Exception {
this.mvc.perform(delete(GraphRestController.REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-graph"));
}
private RestDocumentationResultHandler getGraphResponseDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("nodes")
.description("Коллекция вершин графа (ноды)"),
fieldWithPath("nodes[].id")
.description("Идентификатор вершины графа"),
fieldWithPath("nodes[].name")
.description("Уникальное имя вершины графа"),
fieldWithPath("nodes[].counter")
.description("Колличество проходов через узел"),
fieldWithPath("edges")
.description("Коллекция рёбер графа"),
fieldWithPath("edges[].id")
.description("Уникальный идентификатор ребра графа"),
fieldWithPath("edges[].nodeOne")
.description("Уникальное имя вершины графа"),
fieldWithPath("edges[].nodeTwo")
.description("Уникальное имя вершины графа")
));
}
public static RestDocumentationResultHandler ErrorResponseDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("url")
.description("REST-запрос, при котором возникла ошибка"),
fieldWithPath("type")
.description("тип ошибки"),
fieldWithPath("place")
.description("места возникновения ошибок"),
fieldWithPath("messages")
.description("сообщения об ошибках")
));
}
}

View File

@@ -0,0 +1,50 @@
package ru.resprojects.linkchecker.web.rest.apidocs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.services.GraphService;
import ru.resprojects.linkchecker.web.rest.GraphRestController;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.BDDMockito.given;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(GraphRestController.class)
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class GraphCheckRouteApiDocumentation {
@Autowired
private MockMvc mvc;
@MockBean
private GraphService graphService;
@Test
public void checkRouteInGraph() throws Exception {
List<String> route = Stream.of("v1", "v2", "v3").collect(Collectors.toList());
String returnedResult = String.format("Route for nodes %s is found", route.toString());
given(this.graphService.checkRoute(anySet())).willReturn(returnedResult);
this.mvc.perform(post(GraphRestController.REST_URL + "/checkroute")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(route)))
.andExpect(status().isOk())
.andDo(document("checkroute-graph"))
;
}
}

View File

@@ -0,0 +1,237 @@
package ru.resprojects.linkchecker.web.rest.apidocs;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import ru.resprojects.linkchecker.web.rest.GraphEdgeRestController;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"test"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class GraphEdgeApiDocumentation {
@Autowired
private MockMvc mvc;
@Test
public void getEdges() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseEdgesDoc("get-edges"));
}
@Test
public void getEdgeById() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byId/5005").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseEdgeDoc("get-edge-by-id"));
}
@Test
public void getEdgesByNodeName() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseEdgesDoc("get-edges-by-node-name"));
}
@Test
public void getEdgeByNodeNames() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v1&nodeTwo=v2").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseEdgeDoc("get-edge-by-nodes-name"));
}
@Test
public void getEdgeByIdNotFoundException() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("get-edge-exception-1"));
}
@Test
public void getEdgesByNameNotFoundException() throws Exception {
this.mvc.perform(get(GraphEdgeRestController.EDGE_REST_URL + "/byName/v100")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("get-edge-exception-2"));
}
@Test
public void addNewEdge() throws Exception {
String jsonEdge = "{\"nodeOne\": \"v1\", \"nodeTwo\": \"v4\"}";
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonEdge))
.andExpect(status().isCreated())
.andDo(document("create-edge",
requestFields(
fieldWithPath("nodeOne")
.description("Уникальное имя вершины графа"),
fieldWithPath("nodeTwo")
.description("Уникальное имя вершины графа")
)))
.andDo(ResponseEdgeDoc("create-edge"));
}
@Test
public void addNewEdges() throws Exception {
String jsonEdge = "[{\"nodeOne\": \"v1\", \"nodeTwo\": \"v4\"},{\"nodeOne\": \"v2\", \"nodeTwo\": \"v4\"}]";
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonEdge))
.andExpect(status().isCreated())
.andDo(document("create-edges",
requestFields(
fieldWithPath("[]")
.description("Коллекция рёбер графа"),
fieldWithPath("[].nodeOne")
.description("Уникальное имя вершины графа"),
fieldWithPath("[].nodeTwo")
.description("Уникальное имя вершины графа")
)))
.andDo(ResponseEdgesDoc("create-edges"));
}
@Test
public void addNewEdgeValidationException() throws Exception {
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{\"nodeOne\": \"\", \"nodeTwo\": \"\"}"))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-edge-exception-1"));
}
@Test
public void addNewEdgeAlreadyPresentException() throws Exception {
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{\"nodeOne\": \"v1\", \"nodeTwo\": \"v2\"}"))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-edge-exception-2"));
}
@Test
public void addNewEdgesEmptyCollectionException() throws Exception {
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("[]"))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-edge-exception-3"));
}
@Test
public void addNewEdgesCollectionContainNullObjectException() throws Exception {
String jsonEdge = "[null,{\"nodeOne\": \"v2\", \"nodeTwo\": \"v4\"}]";
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonEdge))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-edge-exception-4"));
}
@Test
public void addNewEdgesCollectionContainAlreadyPresentNodeException() throws Exception {
String jsonEdge = "[{\"nodeOne\": \"v1\", \"nodeTwo\": \"v2\"},{\"nodeOne\": \"v1\", \"nodeTwo\": \"v4\"},{\"nodeOne\": \"v2\", \"nodeTwo\": \"v4\"}]";
this.mvc.perform(post(GraphEdgeRestController.EDGE_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonEdge))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-edge-exception-5"));
}
@Test
public void deleteAllEdges() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-all-edges"));
}
@Test
public void deleteEdgeById() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byId/5005").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-edge-by-id"));
}
@Test
public void deleteEdgesByNodeName() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName/v4").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-edges-by-node-name"));
}
@Test
public void deleteEdgeByNodeNames() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v1&nodeTwo=v2").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-edge-by-nodes-name"));
}
@Test
public void deleteEdgeByIdNotFoundException() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-edge-exception-1"));
}
@Test
public void deleteEdgesByNodeNameNotFoundException() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName/v50")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-edge-exception-2"));
}
@Test
public void deleteEdgeByNodeNamesNotFoundException() throws Exception {
this.mvc.perform(delete(GraphEdgeRestController.EDGE_REST_URL + "/byName?nodeOne=v50&nodeTwo=v2")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-edge-exception-3"));
}
private static RestDocumentationResultHandler ResponseEdgeDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("id")
.description("Идентификатор ребра графа"),
fieldWithPath("nodeOne")
.description("Уникальное имя первой вершины графа, которое связывается текущим ребром"),
fieldWithPath("nodeTwo")
.description("Уникальное имя второй вершины графа, которое связывается текущим ребром")
));
}
private static RestDocumentationResultHandler ResponseEdgesDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("[]")
.description("Коллекция рёбер"),
fieldWithPath("[].id")
.description("Идентификатор ребра графа"),
fieldWithPath("[].nodeOne")
.description("Уникальное имя первой вершины графа, которое связывается текущим ребром"),
fieldWithPath("[].nodeTwo")
.description("Уникальное имя второй вершины графа, которое связывается текущим ребром")
));
}
}

View File

@@ -0,0 +1,242 @@
package ru.resprojects.linkchecker.web.rest.apidocs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import ru.resprojects.linkchecker.TestUtils;
import ru.resprojects.linkchecker.dto.GraphDto;
import ru.resprojects.linkchecker.web.rest.GraphNodeRestController;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"test"})
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD,
scripts = {"classpath:schema-h2.sql", "classpath:data-h2.sql"},
config = @SqlConfig(encoding = "UTF-8"))
@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class GraphNodeApiDocumentation {
@Autowired
private MockMvc mvc;
@Test
public void getNodes() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseNodesDoc("get-nodes"));
}
@Test
public void getNodeById() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byId/5000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseNodeDoc("get-node-by-id"));
}
@Test
public void getNodeByName() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(ResponseNodeDoc("get-node-by-name"));
}
@Test
public void getNodeByNameNotFoundException() throws Exception {
this.mvc.perform(get(GraphNodeRestController.NODES_REST_URL + "/byName/v10")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("get-node-by-name-exception"));
}
@Test
public void addNewNodeToGraph() throws Exception {
String jsonNode = "{\"name\": \"v6\"}";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNode))
.andExpect(status().isCreated())
.andDo(document("create-node",
requestFields(
fieldWithPath("name")
.description("Уникальное имя вершины графа")
)))
.andDo(ResponseNodeDoc("create-node"));
}
@Test
public void addNewNodesToGraph() throws Exception {
String jsonNodes = "[{\"name\":\"v6\"}, {\"name\":\"v7\"}, {\"name\":\"v8\"}]";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNodes))
.andDo(document("create-nodes",
requestFields(
fieldWithPath("[]")
.description("Коллекция вершин графа (ноды)"),
fieldWithPath("[].name")
.description("Уникальное имя вершины графа")
)))
.andDo(ResponseNodesDoc("create-nodes"))
;
}
@Test
public void addNewNodeValidationException() throws Exception {
String jsonNode = "{\"name\":\"\"}";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNode))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-node-exception-1"));
}
@Test
public void addNewNodeAlreadyPresentException() throws Exception {
String jsonNode = "{\"name\": \"v1\"}";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNode))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-node-exception-2"));
}
@Test
public void addNewNodesEmptyCollectionException() throws Exception {
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("[]"))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-node-exception-3"));
}
@Test
public void addNewNodesCollectionContainNullObjectException() throws Exception {
String jsonNodes = "[null, {\"name\": \"v7\"}, {\"name\": \"v8\"}]";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNodes))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-node-exception-4"));
}
@Test
public void addNewNodesCollectionContainAlreadyPresentNodeException() throws Exception {
String jsonNodes = "[{\"name\":\"v1\"}, {\"name\":\"v7\"}, {\"name\":\"v8\"}]";
this.mvc.perform(post(GraphNodeRestController.NODES_REST_URL + "/create/byBatch")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(jsonNodes))
.andDo(GraphApiDocumentation.ErrorResponseDoc("create-node-exception-5"));
}
@Test
public void deleteAllNodes() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-all-nodes"));
}
@Test
public void deleteNodeById() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byId/5000").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-node-by-id"));
}
@Test
public void deleteNodeByName() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byName/v1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent())
.andDo(document("delete-node-by-name"));
}
@Test
public void deleteNodeByObject() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj").contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(TestUtils.nodeGraph)))
.andExpect(status().isNoContent())
.andDo(document("delete-node-by-obj"));
}
@Test
public void deleteNodeByIdNotFoundException() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byId/5050")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-node-exception-1"));
}
@Test
public void deleteNodeByNameNotFoundException() throws Exception {
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byName/v10")
.accept(MediaType.APPLICATION_JSON))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-node-exception-2"));
}
@Test
public void deleteNodeByObjectWithNullIdNotFoundException() throws Exception {
GraphDto.NodeGraph newNode = new GraphDto.NodeGraph(null, "v10", 0);
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode)))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-node-exception-3"));
}
@Test
public void deleteNodeByObjectNotFoundException() throws Exception {
GraphDto.NodeGraph newNode = new GraphDto.NodeGraph(5020, "v10", 0);
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode)))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-node-exception-4"));
}
@Test
public void deleteNodeByObjectWithIncorrectIdException() throws Exception {
GraphDto.NodeGraph newNode = new GraphDto.NodeGraph(5000, "v10", 0);
this.mvc.perform(delete(GraphNodeRestController.NODES_REST_URL + "/byObj")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(TestUtils.mapToJson(newNode)))
.andDo(GraphApiDocumentation.ErrorResponseDoc("delete-node-exception-5"));
}
private static RestDocumentationResultHandler ResponseNodeDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("id")
.description("Идентификатор вершины графа"),
fieldWithPath("name")
.description("Уникальное имя вершины графа"),
fieldWithPath("counter")
.description("Колличество проходов через вершину графа")
));
}
private static RestDocumentationResultHandler ResponseNodesDoc(String documentIdentifier) {
return document(documentIdentifier,
responseFields(
fieldWithPath("[]")
.description("Коллекция вершин графа (ноды)"),
fieldWithPath("[].id")
.description("Идентификатор вершины графа"),
fieldWithPath("[].name")
.description("Уникальное имя вершины графа"),
fieldWithPath("[].counter")
.description("Колличество проходов через вершину графа")
));
}
}

View File

@@ -0,0 +1,99 @@
package ru.resprojects.linkchecker.web.rest.json;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.GsonTester;
import org.springframework.test.context.junit4.SpringRunner;
import ru.resprojects.linkchecker.dto.GraphDto;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static ru.resprojects.linkchecker.TestUtils.*;
@RunWith(SpringRunner.class)
@JsonTest
public class JsonGraphDtoTests {
@Autowired
private GsonTester<GraphDto> jsonGraph;
@Autowired
private GsonTester<GraphDto.NodeGraph> jsonNodeGraph;
@Autowired
private GsonTester<GraphDto.EdgeGraph> jsonEdgeGraph;
@Autowired
private GsonTester<Set<GraphDto.NodeGraph>> jsonNodesGraph;
@Autowired
private GsonTester<Set<GraphDto.EdgeGraph>> jsonEdgesGraph;
@Test
public void serializeJsonGraphDto() throws Exception {
assertThat(this.jsonGraph.write(graph)).isEqualTo("graph.json");
assertThat(this.jsonGraph.write(graph)).isEqualToJson("graph.json");
assertThat(this.jsonGraph.write(graph)).hasJsonPathArrayValue("@.nodes");
assertThat(this.jsonGraph.write(graph)).hasJsonPathArrayValue("@.edges");
assertThat(this.jsonGraph.write(graph))
.extractingJsonPathArrayValue("@.nodes")
.hasSameSizeAs(graph.getNodes());
assertThat(this.jsonGraph.write(graph))
.extractingJsonPathArrayValue("@.edges")
.hasSameSizeAs(graph.getEdges());
}
@Test
public void serializeJsonNodes() throws Exception {
assertThat(this.jsonNodesGraph.write(nodesGraph)).isEqualTo("nodes.json");
assertThat(this.jsonNodesGraph.write(nodesGraph)).isEqualToJson("nodes.json");
}
@Test
public void serializeJsonEdges() throws Exception {
assertThat(this.jsonEdgesGraph.write(edgesGraph)).isEqualTo("edges.json");
assertThat(this.jsonEdgesGraph.write(edgesGraph)).isEqualToJson("edges.json");
}
@Test
public void serializeJsonNode() throws Exception {
assertThat(this.jsonNodeGraph.write(nodeGraph)).isEqualTo("node.json");
assertThat(this.jsonNodeGraph.write(nodeGraph)).isEqualToJson("node.json");
assertThat(this.jsonNodeGraph.write(nodeGraph)).extractingJsonPathStringValue("@.name")
.isEqualTo(nodeGraph.getName());
assertThat(this.jsonNodeGraph.write(nodeGraph))
.extractingJsonPathNumberValue("@.id")
.isEqualTo(nodeGraph.getId());
}
@Test
public void serializeJsonEdge() throws Exception {
assertThat(this.jsonEdgeGraph.write(edgeGraph)).isEqualTo("edge.json");
assertThat(this.jsonEdgeGraph.write(edgeGraph)).isEqualToJson("edge.json");
assertThat(this.jsonEdgeGraph.write(edgeGraph)).extractingJsonPathStringValue("@.nodeOne")
.isEqualTo(edgeGraph.getNodeOne());
assertThat(this.jsonEdgeGraph.write(edgeGraph))
.extractingJsonPathStringValue("@.nodeTwo")
.isEqualTo(edgeGraph.getNodeTwo());
assertThat(this.jsonEdgeGraph.write(edgeGraph))
.extractingJsonPathNumberValue("@.id")
.isEqualTo(edgeGraph.getId());
}
@Test
public void deserializeJsonNode() throws Exception {
String content = "{\"id\": 5000, \"name\": \"v1\", \"counter\": 0}";
assertThat(this.jsonNodeGraph.parse(content)).isEqualTo(nodeGraph);
}
@Test
public void deserializeJsonEdge() throws Exception {
String content = "{\"id\": 5005, \"nodeOne\": \"v1\", \"nodeTwo\": \"v2\"}";
assertThat(this.jsonEdgeGraph.parse(content)).isEqualTo(edgeGraph);
}
}

View File

@@ -0,0 +1 @@
{"id": 5005, "nodeOne": "v1", "nodeTwo": "v2"}

View File

@@ -0,0 +1,22 @@
[
{
"id": 5006,
"nodeOne": "v1",
"nodeTwo": "v3"
},
{
"id": 5005,
"nodeOne": "v1",
"nodeTwo": "v2"
},
{
"id": 5007,
"nodeOne": "v1",
"nodeTwo": "v5"
},
{
"id": 5008,
"nodeOne": "v3",
"nodeTwo": "v4"
}
]

View File

@@ -0,0 +1,51 @@
{
"nodes": [
{
"id": 5000,
"name": "v1",
"counter": 0
},
{
"id": 5001,
"name": "v2",
"counter": 0
},
{
"id": 5002,
"name": "v3",
"counter": 0
},
{
"id": 5003,
"name": "v4",
"counter": 0
},
{
"id": 5004,
"name": "v5",
"counter": 0
}
],
"edges": [
{
"id": 5006,
"nodeOne": "v1",
"nodeTwo": "v3"
},
{
"id": 5005,
"nodeOne": "v1",
"nodeTwo": "v2"
},
{
"id": 5007,
"nodeOne": "v1",
"nodeTwo": "v5"
},
{
"id": 5008,
"nodeOne": "v3",
"nodeTwo": "v4"
}
]
}

View File

@@ -0,0 +1 @@
{"id": 5000, "name": "v1", "counter": 0}

View File

@@ -0,0 +1,27 @@
[
{
"id": 5000,
"name": "v1",
"counter": 0
},
{
"id": 5001,
"name": "v2",
"counter": 0
},
{
"id": 5002,
"name": "v3",
"counter": 0
},
{
"id": 5003,
"name": "v4",
"counter": 0
},
{
"id": 5004,
"name": "v5",
"counter": 0
}
]