Files
cKit/Graph/c_Topological.t.c
T

86 lines
2.2 KiB
C
Raw Normal View History

2026-09-07 18:48:16 +08:00
#include "c_Test.h"
#include "c_Digraph.h"
#include "c_Topological.h"
#include "c_VertexIdList.h"
TEST_CASE(test_topological_sort_dag) {
c_Digraph_t g;
c_Digraph_Init(&g, 3, NULL);
/* Construct a valid DAG:
* 0 -> 1
* 1 -> 2
* 0 -> 2
*/
c_Digraph_AddEdge(&g, 0, 1);
c_Digraph_AddEdge(&g, 1, 2);
c_Digraph_AddEdge(&g, 0, 2);
c_Topological_t topo;
c_err_t err = c_Topological_Init(&topo, &g, 0);
ASSERT_INT_EQ(C_SUCCESS, err);
/* It must successfully identify the graph as a DAG */
ASSERT_TRUE(c_Topological_HasOrder(&topo));
c_VertexIdList_t result_order;
c_VertexIdList_Init(&result_order, 0, 0);
err = c_Topological_GetOrder(&topo, &result_order);
ASSERT_INT_EQ(C_SUCCESS, err);
ASSERT_INT_EQ(3, c_VertexIdList_GetSize(&result_order));
/* Verify the sequence yields a valid dependency layout (0, 1, 2) */
c_uint_t v0 = 0, v1 = 0, v2 = 0;
c_VertexIdList_Get(&result_order, 0, &v0);
c_VertexIdList_Get(&result_order, 1, &v1);
c_VertexIdList_Get(&result_order, 2, &v2);
ASSERT_LL_EQ(0, v0);
ASSERT_LL_EQ(1, v1);
ASSERT_LL_EQ(2, v2);
c_VertexIdList_Destroy(&result_order);
c_Topological_Destroy(&topo);
c_Digraph_Destroy(&g);
}
TEST_CASE(test_topological_sort_cyclic_fail) {
c_Digraph_t g;
c_Digraph_Init(&g, 2, NULL);
/* Construct a cyclic graph (0 -> 1 -> 0) */
c_Digraph_AddEdge(&g, 0, 1);
c_Digraph_AddEdge(&g, 1, 0);
c_Topological_t topo;
c_err_t err = c_Topological_Init(&topo, &g, &g.allocator);
ASSERT_INT_EQ(C_SUCCESS, err);
/* It should gracefully determine that no valid topological order exists */
ASSERT_FALSE(c_Topological_HasOrder(&topo));
c_VertexIdList_t result_order;
c_VertexIdList_Init(&result_order, 0, 0);
err = c_Topological_GetOrder(&topo, &result_order);
ASSERT_INT_EQ(C_ERR_FAIL, err); /* Query must fail */
c_VertexIdList_Destroy(&result_order);
c_Topological_Destroy(&topo);
c_Digraph_Destroy(&g);
}
int main(int argc, char** argv){
TEST_START(c_NonrecursiveDFS Component Tests);
// Execution list configurations
RUN_TEST(test_topological_sort_dag);
RUN_TEST(test_topological_sort_cyclic_fail);
TEST_REPORT();
RETURN_TEST_STATUS;
}