(t *testing.T)
| 144 | } |
| 145 | |
| 146 | func TestBelongsToAssociationForSlice(t *testing.T) { |
| 147 | users := []User{ |
| 148 | *GetUser("slice-belongs-to-1", Config{Company: true, Manager: true}), |
| 149 | *GetUser("slice-belongs-to-2", Config{Company: true, Manager: false}), |
| 150 | *GetUser("slice-belongs-to-3", Config{Company: true, Manager: true}), |
| 151 | } |
| 152 | |
| 153 | DB.Create(&users) |
| 154 | |
| 155 | AssertAssociationCount(t, users, "Company", 3, "") |
| 156 | AssertAssociationCount(t, users, "Manager", 2, "") |
| 157 | |
| 158 | // Find |
| 159 | var companies []Company |
| 160 | if DB.Model(&users).Association("Company").Find(&companies); len(companies) != 3 { |
| 161 | t.Errorf("companies count should be %v, but got %v", 3, len(companies)) |
| 162 | } |
| 163 | |
| 164 | var managers []User |
| 165 | if DB.Model(&users).Association("Manager").Find(&managers); len(managers) != 2 { |
| 166 | t.Errorf("managers count should be %v, but got %v", 2, len(managers)) |
| 167 | } |
| 168 | |
| 169 | // Append |
| 170 | DB.Model(&users).Association("Company").Append( |
| 171 | &Company{Name: "company-slice-append-1"}, |
| 172 | &Company{Name: "company-slice-append-2"}, |
| 173 | &Company{Name: "company-slice-append-3"}, |
| 174 | ) |
| 175 | |
| 176 | AssertAssociationCount(t, users, "Company", 3, "After Append") |
| 177 | |
| 178 | DB.Model(&users).Association("Manager").Append( |
| 179 | GetUser("manager-slice-belongs-to-1", Config{}), |
| 180 | GetUser("manager-slice-belongs-to-2", Config{}), |
| 181 | GetUser("manager-slice-belongs-to-3", Config{}), |
| 182 | ) |
| 183 | AssertAssociationCount(t, users, "Manager", 3, "After Append") |
| 184 | |
| 185 | if err := DB.Model(&users).Association("Manager").Append( |
| 186 | GetUser("manager-slice-belongs-to-test-1", Config{}), |
| 187 | ).Error; err == nil { |
| 188 | t.Errorf("unmatched length when update user's manager") |
| 189 | } |
| 190 | |
| 191 | // Replace -> same as append |
| 192 | |
| 193 | // Delete |
| 194 | if err := DB.Model(&users).Association("Company").Delete(&users[0].Company); err != nil { |
| 195 | t.Errorf("no error should happened when deleting company, but got %v", err) |
| 196 | } |
| 197 | |
| 198 | if users[0].CompanyID != nil || users[0].Company.ID != 0 { |
| 199 | t.Errorf("users[0]'s company should be deleted'") |
| 200 | } |
| 201 | |
| 202 | AssertAssociationCount(t, users, "Company", 2, "After Delete") |
| 203 |
nothing calls this directly
no test coverage detected