tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/engine/assembly_test.go (about) 1 package engine 2 3 import ( 4 "fmt" 5 "reflect" 6 "testing" 7 ) 8 9 type TypeA struct { 10 Value string 11 } 12 13 type TypeB struct { 14 Value string 15 } 16 17 func (t TypeB) String() string { 18 return t.Value 19 } 20 21 func fatal(t *testing.T, err error) { 22 t.Helper() 23 if err != nil { 24 t.Fatal(err) 25 } 26 } 27 28 func TestValueTo(t *testing.T) { 29 orig := &TypeA{Value: "A"} 30 a, err := New(orig, TypeB{Value: "B"}) 31 fatal(t, err) 32 33 u := a.Units() 34 if len(u) != 2 { 35 t.Fatal("unexpected value") 36 } 37 38 var v TypeB 39 fatal(t, a.ValueTo(&v)) 40 if v.Value != "B" { 41 t.Fatal("unexpected value") 42 } 43 44 var vv *TypeA 45 fatal(t, a.ValueTo(&vv)) 46 if vv.Value != "A" { 47 t.Fatal("unexpected value") 48 } 49 50 } 51 52 func TestAssignableTo(t *testing.T) { 53 a, _ := New() 54 fatal(t, a.Add( 55 TypeA{}, 56 TypeA{}, 57 )) 58 59 typ := reflect.TypeOf(&TypeA{}) 60 u := a.AssignableTo(typ) 61 if len(u) != 2 { 62 t.Fatalf("unexpected count: %d", len(u)) 63 } 64 } 65 66 type assembleTest struct { 67 A *TypeA 68 B []*TypeB 69 I fmt.Stringer 70 hidden *TypeA 71 } 72 73 func TestAssemble(t *testing.T) { 74 a, _ := New() 75 fatal(t, a.Add( 76 TypeA{}, 77 TypeB{Value: "B1"}, 78 TypeB{Value: "B2"}, 79 )) 80 81 v := assembleTest{} 82 a.Assemble(&v) 83 84 if v.A == nil { 85 t.Fatal("unexpected nil") 86 } 87 if v.hidden != nil { 88 t.Fatal("expected nil") 89 } 90 if len(v.B) != 2 { 91 t.Fatal("unexpected len") 92 } 93 if v.I == nil { 94 t.Fatal("unexpected nil") 95 } 96 if v.I.String() != "B1" { 97 t.Fatal("unexpected value") 98 } 99 } 100 101 type selfTypeA struct { 102 TypeB *selfTypeB 103 } 104 105 type selfTypeB struct { 106 TypeA *selfTypeA 107 } 108 109 func TestSelfAssemble(t *testing.T) { 110 a := &selfTypeA{} 111 b := &selfTypeB{} 112 r, err := New(a, b) 113 fatal(t, err) 114 115 if a.TypeB != nil { 116 t.Fatal("expected nil") 117 } 118 if b.TypeA != nil { 119 t.Fatal("expected nil") 120 } 121 122 r.SelfAssemble() 123 124 if a.TypeB != b { 125 t.Fatal("expected set to b") 126 } 127 if b.TypeA != a { 128 t.Fatal("expected set to a") 129 } 130 } 131 132 type methodAssembleType struct { 133 a *TypeA 134 b *TypeB 135 } 136 137 func (o *methodAssembleType) Assemble(b *TypeB, a *TypeA) { 138 o.a = a 139 o.b = b 140 } 141 142 func TestMethodAssemble(t *testing.T) { 143 o := &methodAssembleType{} 144 a := &TypeA{} 145 b := &TypeB{} 146 r, err := New(o, a, b) 147 fatal(t, err) 148 149 if o.a != nil { 150 t.Fatal("expected nil") 151 } 152 if o.b != nil { 153 t.Fatal("expected nil") 154 } 155 156 r.SelfAssemble() 157 158 if o.b != b { 159 t.Fatal("expected set to b") 160 } 161 if o.a != a { 162 t.Fatal("expected set to a") 163 } 164 }