github.com/Accefy/pop@v0.0.0-20230428174248-e9f677eab5b9/associations/belongs_to_association_test.go (about)

     1  package associations_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/gobuffalo/pop/v6/associations"
     8  	"github.com/gofrs/uuid"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  type fooBelongsTo struct {
    13  	ID uuid.UUID `db:"id"`
    14  }
    15  
    16  func (f fooBelongsTo) TableName() string {
    17  	return "foosy"
    18  }
    19  
    20  type barBelongsTo struct {
    21  	FooID uuid.UUID    `db:"foo_id"`
    22  	Foo   fooBelongsTo `belongs_to:"foo"`
    23  }
    24  
    25  type barBelongsToNullable struct {
    26  	FooID uuid.NullUUID `db:"foo_id"`
    27  	Foo   *fooBelongsTo `belongs_to:"foo"`
    28  }
    29  
    30  func Test_Belongs_To_Association(t *testing.T) {
    31  	a := require.New(t)
    32  
    33  	id, _ := uuid.NewV1()
    34  	bar := barBelongsTo{FooID: id}
    35  
    36  	as, err := associations.ForStruct(&bar, "Foo")
    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("id = ?", where)
    43  	a.Equal(id, args[0].(uuid.UUID))
    44  
    45  	bar2 := barBelongsTo{FooID: uuid.Nil}
    46  	as, err = associations.ForStruct(&bar2, "Foo")
    47  
    48  	a.NoError(err)
    49  	a.Equal(len(as), 1)
    50  	a.Equal(reflect.Struct, as[0].Kind())
    51  
    52  	before := as.AssociationsBeforeCreatable()
    53  
    54  	for index := range before {
    55  		a.Equal(nil, before[index].BeforeInterface())
    56  	}
    57  }
    58  
    59  func Test_Belongs_To_Nullable_Association(t *testing.T) {
    60  	a := require.New(t)
    61  	id, _ := uuid.NewV1()
    62  
    63  	bar := barBelongsToNullable{Foo: &fooBelongsTo{id}}
    64  	as, err := associations.ForStruct(&bar, "Foo")
    65  	a.NoError(err)
    66  
    67  	before := as.AssociationsBeforeCreatable()
    68  	for index := range before {
    69  		a.Equal(nil, before[index].BeforeSetup())
    70  	}
    71  }