Fix JSON result of empty array (#5154)

This commit is contained in:
Antoine GIRARD 2018-10-24 15:17:21 +02:00 committed by Lunny Xiao
parent 317ddb7283
commit 70ad46133f
2 changed files with 39 additions and 19 deletions

View File

@ -16,7 +16,8 @@ type UserHeatmapData struct {
} }
// GetUserHeatmapDataByUser returns an array of UserHeatmapData // GetUserHeatmapDataByUser returns an array of UserHeatmapData
func GetUserHeatmapDataByUser(user *User) (hdata []*UserHeatmapData, err error) { func GetUserHeatmapDataByUser(user *User) ([]*UserHeatmapData, error) {
hdata := make([]*UserHeatmapData, 0)
var groupBy string var groupBy string
switch { switch {
case setting.UseSQLite3: case setting.UseSQLite3:
@ -29,12 +30,12 @@ func GetUserHeatmapDataByUser(user *User) (hdata []*UserHeatmapData, err error)
groupBy = "dateadd(DAY,0, datediff(day,0, dateadd(s, created_unix, '19700101')))" groupBy = "dateadd(DAY,0, datediff(day,0, dateadd(s, created_unix, '19700101')))"
} }
err = x.Select(groupBy+" as timestamp, count(user_id) as contributions"). err := x.Select(groupBy+" as timestamp, count(user_id) as contributions").
Table("action"). Table("action").
Where("user_id = ?", user.ID). Where("user_id = ?", user.ID).
And("created_unix > ?", (util.TimeStampNow() - 31536000)). And("created_unix > ?", (util.TimeStampNow() - 31536000)).
GroupBy("timestamp"). GroupBy("timestamp").
OrderBy("timestamp"). OrderBy("timestamp").
Find(&hdata) Find(&hdata)
return return hdata, err
} }

View File

@ -5,16 +5,28 @@
package models package models
import ( import (
"github.com/stretchr/testify/assert" "encoding/json"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestGetUserHeatmapDataByUser(t *testing.T) { func TestGetUserHeatmapDataByUser(t *testing.T) {
testCases := []struct {
userID int64
CountResult int
JSONResult string
}{
{2, 1, `[{"timestamp":1540080000,"contributions":1}]`},
{3, 0, `[]`},
}
// Prepare // Prepare
assert.NoError(t, PrepareTestDatabase()) assert.NoError(t, PrepareTestDatabase())
for _, tc := range testCases {
// Insert some action // Insert some action
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user := AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User)
// get the action for comparison // get the action for comparison
actions, err := GetFeeds(GetFeedsOptions{ actions, err := GetFeeds(GetFeedsOptions{
@ -30,4 +42,11 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
heatmap, err := GetUserHeatmapDataByUser(user) heatmap, err := GetUserHeatmapDataByUser(user)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, len(actions), len(heatmap)) assert.Equal(t, len(actions), len(heatmap))
assert.Equal(t, tc.CountResult, len(heatmap))
//Test JSON rendering
jsonData, err := json.Marshal(heatmap)
assert.NoError(t, err)
assert.Equal(t, tc.JSONResult, string(jsonData))
}
} }