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

Function TestBelongsToAssociation

tests/associations_belongs_to_test.go:10–144  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

8)
9
10func TestBelongsToAssociation(t *testing.T) {
11 user := *GetUser("belongs-to", Config{Company: true, Manager: true})
12
13 if err := DB.Create(&user).Error; err != nil {
14 t.Fatalf("errors happened when create: %v", err)
15 }
16
17 CheckUser(t, user, user)
18
19 // Find
20 var user2 User
21 DB.Find(&user2, "id = ?", user.ID)
22 pointerOfUser := &user2
23 if err := DB.Model(&pointerOfUser).Association("Company").Find(&user2.Company); err != nil {
24 t.Errorf("failed to query users, got error %#v", err)
25 }
26 user2.Manager = &User{}
27 DB.Model(&user2).Association("Manager").Find(user2.Manager)
28 CheckUser(t, user2, user)
29
30 // Count
31 AssertAssociationCount(t, user, "Company", 1, "")
32 AssertAssociationCount(t, user, "Manager", 1, "")
33
34 // Append
35 company := Company{Name: "company-belongs-to-append"}
36 manager := GetUser("manager-belongs-to-append", Config{})
37
38 if err := DB.Model(&user2).Association("Company").Append(&company); err != nil {
39 t.Fatalf("Error happened when append Company, got %v", err)
40 }
41
42 if company.ID == 0 {
43 t.Fatalf("Company's ID should be created")
44 }
45
46 if err := DB.Model(&user2).Association("Manager").Append(manager); err != nil {
47 t.Fatalf("Error happened when append Manager, got %v", err)
48 }
49
50 if manager.ID == 0 {
51 t.Fatalf("Manager's ID should be created")
52 }
53
54 user.Company = company
55 user.Manager = manager
56 user.CompanyID = &company.ID
57 user.ManagerID = &manager.ID
58 CheckUser(t, user2, user)
59
60 AssertAssociationCount(t, user2, "Company", 1, "AfterAppend")
61 AssertAssociationCount(t, user2, "Manager", 1, "AfterAppend")
62
63 // Replace
64 company2 := Company{Name: "company-belongs-to-replace"}
65 manager2 := GetUser("manager-belongs-to-replace", Config{})
66
67 if err := DB.Model(&user2).Association("Company").Replace(&company2); err != nil {

Callers

nothing calls this directly

Calls 12

GetUserFunction · 0.85
CheckUserFunction · 0.85
AssertAssociationCountFunction · 0.85
tidbSkipFunction · 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