github.com/hashicorp/packer@v1.14.3/internal/dag/graph_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package dag 5 6 import ( 7 "fmt" 8 "strings" 9 "testing" 10 ) 11 12 func TestGraph_empty(t *testing.T) { 13 var g Graph 14 g.Add(1) 15 g.Add(2) 16 g.Add(3) 17 18 actual := strings.TrimSpace(g.String()) 19 expected := strings.TrimSpace(testGraphEmptyStr) 20 if actual != expected { 21 t.Fatalf("bad: %s", actual) 22 } 23 } 24 25 func TestGraph_basic(t *testing.T) { 26 var g Graph 27 g.Add(1) 28 g.Add(2) 29 g.Add(3) 30 g.Connect(BasicEdge(1, 3)) 31 32 actual := strings.TrimSpace(g.String()) 33 expected := strings.TrimSpace(testGraphBasicStr) 34 if actual != expected { 35 t.Fatalf("bad: %s", actual) 36 } 37 } 38 39 // This tests that connecting edges works based on custom Hashcode 40 // implementations for uniqueness. 41 func TestGraph_hashcode(t *testing.T) { 42 var g Graph 43 g.Add(&hashVertex{code: 1}) 44 g.Add(&hashVertex{code: 2}) 45 g.Add(&hashVertex{code: 3}) 46 g.Connect(BasicEdge( 47 &hashVertex{code: 1}, 48 &hashVertex{code: 3})) 49 50 actual := strings.TrimSpace(g.String()) 51 expected := strings.TrimSpace(testGraphBasicStr) 52 if actual != expected { 53 t.Fatalf("bad: %s", actual) 54 } 55 } 56 57 func TestGraphHasVertex(t *testing.T) { 58 var g Graph 59 g.Add(1) 60 61 if !g.HasVertex(1) { 62 t.Fatal("should have 1") 63 } 64 if g.HasVertex(2) { 65 t.Fatal("should not have 2") 66 } 67 } 68 69 func TestGraphHasEdge(t *testing.T) { 70 var g Graph 71 g.Add(1) 72 g.Add(2) 73 g.Connect(BasicEdge(1, 2)) 74 75 if !g.HasEdge(BasicEdge(1, 2)) { 76 t.Fatal("should have 1,2") 77 } 78 if g.HasVertex(BasicEdge(2, 3)) { 79 t.Fatal("should not have 2,3") 80 } 81 } 82 83 func TestGraphEdgesFrom(t *testing.T) { 84 var g Graph 85 g.Add(1) 86 g.Add(2) 87 g.Add(3) 88 g.Connect(BasicEdge(1, 3)) 89 g.Connect(BasicEdge(2, 3)) 90 91 edges := g.EdgesFrom(1) 92 93 expected := make(Set) 94 expected.Add(BasicEdge(1, 3)) 95 96 s := make(Set) 97 for _, e := range edges { 98 s.Add(e) 99 } 100 101 if s.Intersection(expected).Len() != expected.Len() { 102 t.Fatalf("bad: %#v", edges) 103 } 104 } 105 106 func TestGraphEdgesTo(t *testing.T) { 107 var g Graph 108 g.Add(1) 109 g.Add(2) 110 g.Add(3) 111 g.Connect(BasicEdge(1, 3)) 112 g.Connect(BasicEdge(1, 2)) 113 114 edges := g.EdgesTo(3) 115 116 expected := make(Set) 117 expected.Add(BasicEdge(1, 3)) 118 119 s := make(Set) 120 for _, e := range edges { 121 s.Add(e) 122 } 123 124 if s.Intersection(expected).Len() != expected.Len() { 125 t.Fatalf("bad: %#v", edges) 126 } 127 } 128 129 type hashVertex struct { 130 code interface{} 131 } 132 133 func (v *hashVertex) Hashcode() interface{} { 134 return v.code 135 } 136 137 func (v *hashVertex) Name() string { 138 return fmt.Sprintf("%#v", v.code) 139 } 140 141 const testGraphBasicStr = ` 142 1 143 3 144 2 145 3 146 ` 147 148 const testGraphEmptyStr = ` 149 1 150 2 151 3 152 `