Skip to content

Commit

Permalink
experimental: query: sort keys in json-marshal (#1220)
Browse files Browse the repository at this point in the history
  • Loading branch information
gabor authored Feb 10, 2025
1 parent 9b26693 commit 39e30e5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion experimental/apis/data/v0alpha1/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package v0alpha1
import (
"encoding/json"
"fmt"
"maps"
"slices"
"strconv"
"unsafe"

Expand Down Expand Up @@ -309,7 +311,11 @@ func writeQuery(g *DataQuery, stream *j.Stream) {

// The additional properties
if g.additional != nil {
for k, v := range g.additional {
// we must sort the map-keys to always produce the same JSON
keys := slices.Sorted(maps.Keys(g.additional))

for _, k := range keys {
v := g.additional[k]
stream.WriteMore()
stream.WriteObjectField(k)
stream.WriteVal(v)
Expand Down
25 changes: 25 additions & 0 deletions experimental/apis/data/v0alpha1/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,31 @@ import (
"github.com/stretchr/testify/require"
)

func TestSerializeAdditionalQueryFieldsOrdered(t *testing.T) {
q := DataQuery{
CommonQueryProperties: CommonQueryProperties{
RefID: "A",
MaxDataPoints: 10,
IntervalMS: 500,
},
additional: map[string]any{
"utcOffsetSec": 3600,
"exemplar": false,
"instant": false,
"range": true,
"editorMode": "code",
"legendFormat": "__auto",
},
}
jsonBytes, err := json.Marshal(q)
require.NoError(t, err)
// NOTE: we cannot use require.JSONEq() here,
// because we want to make sure the object-keys
// are ordered
expectedBytes := []byte(`{"refId":"A","maxDataPoints":10,"intervalMs":500,"editorMode":"code","exemplar":false,"instant":false,"legendFormat":"__auto","range":true,"utcOffsetSec":3600}`)
require.Equal(t, expectedBytes, jsonBytes)
}

func TestParseQueriesIntoQueryDataRequest(t *testing.T) {
request := []byte(`{
"queries": [
Expand Down

0 comments on commit 39e30e5

Please sign in to comment.