github.com/bendemaree/terraform@v0.5.4-0.20150613200311-f50d97d6eee6/digraph/tarjan_test.go (about)

     1  package digraph
     2  
     3  import (
     4  	"reflect"
     5  	"sort"
     6  	"testing"
     7  )
     8  
     9  func TestStronglyConnectedComponents(t *testing.T) {
    10  	nodes := ParseBasic(`a -> b
    11  a -> c
    12  b -> c
    13  c -> b
    14  c -> d
    15  d -> e`)
    16  	var nlist []Node
    17  	for _, n := range nodes {
    18  		nlist = append(nlist, n)
    19  	}
    20  
    21  	sccs := StronglyConnectedComponents(nlist, false)
    22  	if len(sccs) != 4 {
    23  		t.Fatalf("bad: %v", sccs)
    24  	}
    25  
    26  	sccs = StronglyConnectedComponents(nlist, true)
    27  	if len(sccs) != 1 {
    28  		t.Fatalf("bad: %v", sccs)
    29  	}
    30  
    31  	cycle := sccs[0]
    32  	if len(cycle) != 2 {
    33  		t.Fatalf("bad: %v", sccs)
    34  	}
    35  
    36  	cycleNodes := make([]string, len(cycle))
    37  	for i, c := range cycle {
    38  		cycleNodes[i] = c.(*BasicNode).Name
    39  	}
    40  	sort.Strings(cycleNodes)
    41  
    42  	expected := []string{"b", "c"}
    43  	if !reflect.DeepEqual(cycleNodes, expected) {
    44  		t.Fatalf("bad: %#v", cycleNodes)
    45  	}
    46  }
    47  
    48  func TestStronglyConnectedComponents2(t *testing.T) {
    49  	nodes := ParseBasic(`a -> b
    50  a -> c
    51  b -> d
    52  b -> e
    53  c -> f
    54  c -> g
    55  g -> a
    56  `)
    57  	var nlist []Node
    58  	for _, n := range nodes {
    59  		nlist = append(nlist, n)
    60  	}
    61  
    62  	sccs := StronglyConnectedComponents(nlist, true)
    63  	if len(sccs) != 1 {
    64  		t.Fatalf("bad: %v", sccs)
    65  	}
    66  
    67  	cycle := sccs[0]
    68  	if len(cycle) != 3 {
    69  		t.Fatalf("bad: %v", sccs)
    70  	}
    71  
    72  	cycleNodes := make([]string, len(cycle))
    73  	for i, c := range cycle {
    74  		cycleNodes[i] = c.(*BasicNode).Name
    75  	}
    76  	sort.Strings(cycleNodes)
    77  
    78  	expected := []string{"a", "c", "g"}
    79  	if !reflect.DeepEqual(cycleNodes, expected) {
    80  		t.Fatalf("bad: %#v", cycleNodes)
    81  	}
    82  }