Back to Repositories

Testing Graph Adjacency List Operations Implementation in hello-algo

This test suite validates the implementation of an adjacency list graph data structure in Go, covering core graph operations including vertex and edge manipulation. The tests demonstrate comprehensive verification of graph initialization, modification, and structural integrity.

Test Coverage Overview

The test suite provides thorough coverage of fundamental graph operations:
  • Graph initialization with vertices and edges
  • Edge addition and removal operations
  • Vertex addition and removal functionality
  • Graph state verification after each operation
Edge cases are addressed through vertex relationship management and graph structure modifications.

Implementation Analysis

The testing approach utilizes Go’s native testing framework with a focus on behavioral validation. The implementation employs a structured testing pattern that progresses through graph mutations, verifying each state transition. The test leverages custom vertex creation and management utilities from the hello-algo package.

Technical Details

Testing tools and configuration:
  • Go testing package (testing.T)
  • Custom vertex management utilities (ValsToVets)
  • Graph adjacency list implementation
  • Formatted output verification using fmt package

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Systematic state verification after operations
  • Clear test case organization and progression
  • Proper setup and initialization of test data
  • Comprehensive coverage of graph operations

krahets/hello-algo

zh-hant/codes/go/chapter_graph/graph_adjacency_list_test.go

            
// File: graph_adjacency_list_test.go
// Created Time: 2023-01-31
// Author: Reanon ([email protected])

package chapter_graph

import (
	"fmt"
	"testing"

	. "github.com/krahets/hello-algo/pkg"
)

func TestGraphAdjList(t *testing.T) {
	/* 初始化無向圖 */
	v := ValsToVets([]int{1, 3, 2, 5, 4})
	edges := [][]Vertex{{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]}, {v[2], v[3]}, {v[2], v[4]}, {v[3], v[4]}}
	graph := newGraphAdjList(edges)
	fmt.Println("初始化後,圖為:")
	graph.print()

	/* 新增邊 */
	// 頂點 1, 2 即 v[0], v[2]
	graph.addEdge(v[0], v[2])
	fmt.Println("\n新增邊 1-2 後,圖為")
	graph.print()

	/* 刪除邊 */
	// 頂點 1, 3 即 v[0], v[1]
	graph.removeEdge(v[0], v[1])
	fmt.Println("\n刪除邊 1-3 後,圖為")
	graph.print()

	/* 新增頂點 */
	v5 := NewVertex(6)
	graph.addVertex(v5)
	fmt.Println("\n新增頂點 6 後,圖為")
	graph.print()

	/* 刪除頂點 */
	// 頂點 3 即 v[1]
	graph.removeVertex(v[1])
	fmt.Println("\n刪除頂點 3 後,圖為")
	graph.print()
}