Skip to content

Commit

Permalink
add more test for JSONType
Browse files Browse the repository at this point in the history
fix select field

fix test
  • Loading branch information
alingse committed Apr 10, 2023
1 parent 8d25568 commit 97cb352
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions json_type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ func TestJSONType(t *testing.T) {
AssertEqual(t, result.Attributes.Data().Admin, users[1].Attributes.Data().Admin)
AssertEqual(t, len(result.Attributes.Data().Orgs), len(users[1].Attributes.Data().Orgs))

// List
var users2 []UserWithJSON
if err := DB.Model(&UserWithJSON{}).Limit(10).Order("id asc").Find(&users2).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, users2[0].Attributes.Data().Age, 18)

// Select Field
var singleUser UserWithJSON
if err := DB.Model(&UserWithJSON{}).Select("attributes").Limit(1).Order("id asc").Find(&singleUser).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, singleUser.Attributes.Data().Age, 18)

// Pluck
var attr datatypes.JSONType[Attribute]
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("attributes", &attr).Error; err != nil {
Expand All @@ -80,6 +94,15 @@ func TestJSONType(t *testing.T) {
var attribute = attr.Data()
AssertEqual(t, attribute.Age, 18)

// Smart Select Fields
var row struct {
Attributes datatypes.JSONType[Attribute]
}
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, row.Attributes.Data().Age, 18)

// FirstOrCreate
jsonMap := UserWithJSON{
Attributes: newJSONType[Attribute]([]byte(`{"age":19,"name":"json-1","orgs":{"orga":"orga"},"tags":["tag1","tag2"]}`)),
Expand Down Expand Up @@ -154,6 +177,24 @@ func TestJSONSlice(t *testing.T) {
AssertEqual(t, result.Name, users[0].Name)
AssertEqual(t, result.Tags[0], users[0].Tags[0])

// Pluck
var pluckTags datatypes.JSONSlice[Tag]
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("tags", &pluckTags).Error; err != nil {
t.Fatalf("failed to pluck for field, got error %v", err)
}
AssertEqual(t, len(pluckTags), 2)
AssertEqual(t, pluckTags[0].Name, "tag1")

// Smart Select Fields
var row struct {
Tags datatypes.JSONSlice[Tag]
}
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, len(row.Tags), 2)
AssertEqual(t, row.Tags[0].Name, "tag1")

// FirstOrCreate
jsonMap := UserWithJSON{
Tags: datatypes.NewJSONSlice(tags),
Expand Down

0 comments on commit 97cb352

Please sign in to comment.