github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/util/extract/extract_test.go (about) 1 package extract_test 2 3 import ( 4 "code.cloudfoundry.org/cli/util/extract" 5 . "github.com/onsi/ginkgo" 6 . "github.com/onsi/gomega" 7 ) 8 9 var _ = Describe("List", func() { 10 It("extracts elements from a slice of structs", func() { 11 input := []struct{ Name, Type string }{ 12 {Name: "flopsy", Type: "rabbit"}, 13 {Name: "mopsy", Type: "rabbit"}, 14 {Name: "cottontail", Type: "rabbit"}, 15 {Name: "peter", Type: "rabbit"}, 16 {Name: "mopsy", Type: "rabbit"}, 17 {Name: "jemima", Type: "duck"}, 18 } 19 20 Expect(extract.List("Name", input)).To(Equal([]string{ 21 "flopsy", 22 "mopsy", 23 "cottontail", 24 "peter", 25 "mopsy", 26 "jemima", 27 })) 28 29 Expect(extract.List("Type", input)).To(Equal([]string{ 30 "rabbit", 31 "rabbit", 32 "rabbit", 33 "rabbit", 34 "rabbit", 35 "duck", 36 })) 37 }) 38 39 It("can recurse", func() { 40 type a struct{ Name string } 41 type b struct { 42 Name string 43 Children []a 44 } 45 type c struct { 46 Container b 47 } 48 type d struct { 49 Name string 50 Descendents []c 51 } 52 input := []d{ 53 { 54 Name: "alpha", 55 Descendents: []c{ 56 { 57 Container: b{ 58 Name: "foo", 59 Children: []a{ 60 {Name: "flopsy"}, 61 {Name: "mopsy"}, 62 }, 63 }, 64 }, 65 { 66 Container: b{ 67 Name: "bar", 68 Children: []a{}, 69 }, 70 }, 71 }, 72 }, 73 { 74 Name: "beta", 75 }, 76 { 77 Name: "gamma", 78 Descendents: []c{}, 79 }, 80 { 81 Name: "delta", 82 Descendents: []c{ 83 { 84 Container: b{ 85 Name: "baz", 86 Children: []a{ 87 {Name: "cottontail"}, 88 {Name: "peter"}, 89 }, 90 }, 91 }, 92 }, 93 }, 94 } 95 96 Expect(extract.List("Descendents.Container.Children.Name", input)).To(Equal([]string{ 97 "flopsy", 98 "mopsy", 99 "cottontail", 100 "peter", 101 })) 102 }) 103 104 When("the expression does not match", func() { 105 It("omits it from the result", func() { 106 input := []interface{}{ 107 struct{ Name, Value string }{Name: "foo", Value: "bar"}, 108 struct{ Foo, Bar string }{Foo: "name", Bar: "value"}, 109 } 110 111 Expect(extract.List("Name", input)).To(ConsistOf("foo")) 112 Expect(extract.List("Foo", input)).To(ConsistOf("name")) 113 }) 114 }) 115 116 When("the input is not a slice", func() { 117 It("extracts a single value", func() { 118 input := struct{ Foo, Bar string }{ 119 Foo: "foo", 120 Bar: "bar", 121 } 122 123 Expect(extract.List("Foo", input)).To(ConsistOf("foo")) 124 }) 125 }) 126 })