MCPcopy
hub / github.com/go-gorm/gorm / TestPolymorphicHasOneAssociation

Function TestPolymorphicHasOneAssociation

tests/associations_has_one_test.go:141–216  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

139}
140
141func TestPolymorphicHasOneAssociation(t *testing.T) {
142 pet := Pet{Name: "hasone", Toy: Toy{Name: "toy-has-one"}}
143
144 if err := DB.Create(&pet).Error; err != nil {
145 t.Fatalf("errors happened when create: %v", err)
146 }
147
148 CheckPet(t, pet, pet)
149
150 // Find
151 var pet2 Pet
152 DB.Find(&pet2, "id = ?", pet.ID)
153 DB.Model(&pet2).Association("Toy").Find(&pet2.Toy)
154 CheckPet(t, pet2, pet)
155
156 // Count
157 AssertAssociationCount(t, pet, "Toy", 1, "")
158
159 // Append
160 toy := Toy{Name: "toy-has-one-append"}
161
162 if err := DB.Model(&pet2).Association("Toy").Append(&toy); err != nil {
163 t.Fatalf("Error happened when append toy, got %v", err)
164 }
165
166 if toy.ID == 0 {
167 t.Fatalf("Toy's ID should be created")
168 }
169
170 pet.Toy = toy
171 CheckPet(t, pet2, pet)
172
173 AssertAssociationCount(t, pet, "Toy", 1, "AfterAppend")
174
175 // Replace
176 toy2 := Toy{Name: "toy-has-one-replace"}
177
178 if err := DB.Model(&pet2).Association("Toy").Replace(&toy2); err != nil {
179 t.Fatalf("Error happened when append Toy, got %v", err)
180 }
181
182 if toy2.ID == 0 {
183 t.Fatalf("toy2's ID should be created")
184 }
185
186 pet.Toy = toy2
187 CheckPet(t, pet2, pet)
188
189 AssertAssociationCount(t, pet2, "Toy", 1, "AfterReplace")
190
191 // Delete
192 if err := DB.Model(&pet2).Association("Toy").Delete(&Toy{}); err != nil {
193 t.Fatalf("Error happened when delete toy, got %v", err)
194 }
195 AssertAssociationCount(t, pet2, "Toy", 1, "after delete non-existing data")
196
197 if err := DB.Model(&pet2).Association("Toy").Delete(&toy2); err != nil {
198 t.Fatalf("Error happened when delete Toy, got %v", err)

Callers

nothing calls this directly

Calls 10

CheckPetFunction · 0.85
AssertAssociationCountFunction · 0.85
ModelMethod · 0.80
AppendMethod · 0.80
ClearMethod · 0.80
CreateMethod · 0.65
FindMethod · 0.65
ReplaceMethod · 0.65
DeleteMethod · 0.65
AssociationMethod · 0.45

Tested by

no test coverage detected