Add tests for loops and multiple edges

This commit is contained in:
2025-11-03 14:03:21 +01:00
parent 3565b6b548
commit c5a0f2a3f6
+80
View File
@@ -154,6 +154,17 @@ mod tests {
} }
} }
#[test]
fn are_adjacent_vertex_self() {
let mut graph = Graph::new();
let v = graph.add_vertex();
assert_eq!(
graph.are_adjacent(v, v),
false,
"should not be adjacent to itself"
);
}
#[test] #[test]
fn are_adjacent_single_edge() { fn are_adjacent_single_edge() {
let mut graph = Graph::new(); let mut graph = Graph::new();
@@ -269,6 +280,75 @@ mod tests {
} }
} }
#[test]
fn loop_edge() {
let mut graph = Graph::new();
let v = graph.add_vertex();
graph.add_edge(v, v);
assert_eq!(graph.vertex_count(), 1, "unexpected vertex count");
assert_eq!(graph.edge_count(), 1, "unexpected edge count");
assert_eq!(graph.degree(v), 2, "unexpected degree");
assert_eq!(
graph.are_adjacent(v, v),
true,
"vertex with loop edge should be adjacent to itself"
);
let mut neighbors = graph.neighbors(v);
assert_eq!(
neighbors.next(),
Some(v),
"vertex should be neighbor of itself"
);
assert_eq!(
neighbors.next(),
Some(v),
"vertex should be neighbor of itself twice"
);
assert_eq!(neighbors.next(), None, "two many neighbors from iterator");
}
#[test]
fn multiple_edges() {
let mult = 3;
let mut graph = Graph::new();
let vertices = [graph.add_vertex(), graph.add_vertex()];
for _ in 0..mult {
graph.add_edge(vertices[0], vertices[1]);
}
assert_eq!(
graph.vertex_count(),
vertices.len(),
"unexpected vertex count"
);
assert_eq!(graph.edge_count(), mult, "unexpected edge count");
for v in vertices {
assert_eq!(graph.degree(v), mult, "unexpected degree of {v:?}");
}
assert_eq!(
graph.are_adjacent(vertices[0], vertices[1]),
true,
"should be adjacent"
);
for i in 0..2 {
let mut neighbors = graph.neighbors(vertices[i]);
for j in 0..mult {
assert_eq!(
neighbors.next(),
Some(vertices[1 - i]),
"neighbor {j} of vertex {:?} should be {:?}",
vertices[i],
vertices[1 - i]
);
}
assert_eq!(
neighbors.next(),
None,
"two many neighbors of {:?} from iterator",
vertices[i]
);
}
}
fn make_test_graph() -> (Graph, [Vertex; 10]) { fn make_test_graph() -> (Graph, [Vertex; 10]) {
let mut graph = Graph::new(); let mut graph = Graph::new();
let vertices: [Vertex; 10] = core::array::from_fn(|_| graph.add_vertex()); let vertices: [Vertex; 10] = core::array::from_fn(|_| graph.add_vertex());