github.com/rjgonzale/pop/v5@v5.1.3-dev/associations/has_one_association_test.go (about) 1 package associations_test 2 3 import ( 4 "reflect" 5 "testing" 6 7 "github.com/gobuffalo/nulls" 8 "github.com/gobuffalo/pop/v5/associations" 9 "github.com/gofrs/uuid" 10 "github.com/stretchr/testify/require" 11 ) 12 13 type FooHasOne struct { 14 ID uuid.UUID `db:"id"` 15 BarHasOne barHasOne `has_one:"barHasOne"` 16 } 17 18 type barHasOne struct { 19 Title string `db:"title"` 20 FooHasOneID nulls.UUID `db:"foo_has_one_id"` 21 BazHasOneID nulls.UUID `db:"baz_id"` 22 } 23 24 type bazHasOne struct { 25 ID uuid.UUID `db:"id"` 26 BarHasOne *barHasOne `has_one:"barHasOne" fk_id:"baz_id"` 27 } 28 29 func Test_Has_One_Association(t *testing.T) { 30 a := require.New(t) 31 32 id, _ := uuid.NewV1() 33 foo := FooHasOne{ID: id} 34 35 as, err := associations.ForStruct(&foo) 36 37 a.NoError(err) 38 a.Equal(len(as), 1) 39 a.Equal(reflect.Struct, as[0].Kind()) 40 41 where, args := as[0].Constraint() 42 a.Equal("foo_has_one_id = ?", where) 43 a.Equal(id, args[0].(uuid.UUID)) 44 45 foo2 := FooHasOne{} 46 47 as, err = associations.ForStruct(&foo2) 48 a.NoError(err) 49 after := as.AssociationsAfterCreatable() 50 for index := range after { 51 a.Equal(nil, after[index].AfterInterface()) 52 } 53 54 baz := bazHasOne{ID: id} 55 56 as, err = associations.ForStruct(&baz) 57 58 a.NoError(err) 59 a.Equal(len(as), 1) 60 a.Equal(reflect.Struct, as[0].Kind()) 61 62 where, args = as[0].Constraint() 63 a.Equal("baz_id = ?", where) 64 a.Equal(id, args[0].(uuid.UUID)) 65 } 66 67 func Test_Has_One_SetValue(t *testing.T) { 68 a := require.New(t) 69 id, _ := uuid.NewV1() 70 foo := FooHasOne{ID: id, BarHasOne: barHasOne{Title: "bar"}} 71 72 as, _ := associations.ForStruct(&foo) 73 a.Equal(len(as), 1) 74 75 ca, ok := as[0].(associations.AssociationAfterCreatable) 76 a.True(ok) 77 78 a.NoError(ca.AfterSetup()) 79 a.Equal(foo.ID, foo.BarHasOne.FooHasOneID.Interface().(uuid.UUID)) 80 }