github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+incompatible/common/graph/tree_test.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package graph 8 9 import ( 10 "fmt" 11 "testing" 12 13 "github.com/stretchr/testify/assert" 14 ) 15 16 func TestFindAndExists(t *testing.T) { 17 v := NewTreeVertex("1", nil) 18 u := v.AddDescendant(NewTreeVertex("2", nil)).AddDescendant(NewTreeVertex("4", nil)) 19 v.AddDescendant(NewTreeVertex("3", nil)).AddDescendant(NewTreeVertex("5", nil)) 20 assert.Equal(t, u, v.Find("4")) 21 assert.True(t, v.Exists("4")) 22 assert.Nil(t, v.Find("10")) 23 assert.False(t, v.Exists("10")) 24 assert.Nil(t, u.Find("1")) 25 assert.False(t, u.Exists("1")) 26 assert.Equal(t, v, v.Find("1")) 27 assert.True(t, v.Exists("1")) 28 } 29 30 func TestIsLeaf(t *testing.T) { 31 v := NewTreeVertex("1", nil) 32 assert.True(t, v.AddDescendant(NewTreeVertex("2", nil)).IsLeaf()) 33 assert.False(t, v.IsLeaf()) 34 } 35 36 func TestBFS(t *testing.T) { 37 v := NewTreeVertex("1", nil) 38 v.AddDescendant(NewTreeVertex("2", nil)).AddDescendant(NewTreeVertex("4", nil)) 39 v.AddDescendant(NewTreeVertex("3", nil)).AddDescendant(NewTreeVertex("5", nil)) 40 tree := v.ToTree() 41 assert.Equal(t, v, tree.Root) 42 i := tree.BFS() 43 j := 1 44 for { 45 v := i.Next() 46 if v == nil { 47 assert.True(t, j == 6) 48 break 49 } 50 assert.Equal(t, fmt.Sprintf("%d", j), v.Id) 51 j++ 52 } 53 } 54 55 func TestClone(t *testing.T) { 56 v := NewTreeVertex("1", 1) 57 v.AddDescendant(NewTreeVertex("2", 2)).AddDescendant(NewTreeVertex("4", 3)) 58 v.AddDescendant(NewTreeVertex("3", 4)).AddDescendant(NewTreeVertex("5", 5)) 59 60 copy := v.Clone() 61 // They are different references 62 assert.False(t, copy == v) 63 // They are equal 64 assert.Equal(t, v, copy) 65 66 v.AddDescendant(NewTreeVertex("6", 6)) 67 assert.NotEqual(t, v, copy) 68 } 69 70 func TestReplace(t *testing.T) { 71 v := &TreeVertex{ 72 Id: "r", 73 Descendants: []*TreeVertex{ 74 {Id: "D", Descendants: []*TreeVertex{}}, 75 {Id: "E", Descendants: []*TreeVertex{}}, 76 {Id: "F", Descendants: []*TreeVertex{}}, 77 }, 78 } 79 80 v.replace("D", &TreeVertex{ 81 Id: "d", 82 Descendants: []*TreeVertex{ 83 {Id: "a", Descendants: []*TreeVertex{}}, 84 {Id: "b", Descendants: []*TreeVertex{}}, 85 {Id: "c", Descendants: []*TreeVertex{}}, 86 }, 87 }) 88 89 assert.Equal(t, "r", v.Id) 90 assert.Equal(t, &TreeVertex{Id: "F", Descendants: []*TreeVertex{}}, v.Descendants[2]) 91 assert.Equal(t, &TreeVertex{Id: "E", Descendants: []*TreeVertex{}}, v.Descendants[1]) 92 assert.Equal(t, "D", v.Descendants[0].Id) 93 assert.Equal(t, []*TreeVertex{ 94 {Id: "a", Descendants: []*TreeVertex{}}, 95 {Id: "b", Descendants: []*TreeVertex{}}, 96 {Id: "c", Descendants: []*TreeVertex{}}, 97 }, v.Descendants[0].Descendants) 98 }