Skip to content

Commit 56279f5

Browse files
authored
chore(fetchers): simplify tests (#2156)
* chore(fetchers): simplify TestBuildProjectAndFetchJsonnetFrom * chore(fetchers): simplify TestFetchJsonnet * chore(fetchers): deprecate normalizeAndCompareJSON helper * chore(fetchers): simplify URL tests
1 parent d418619 commit 56279f5

File tree

3 files changed

+98
-151
lines changed

3 files changed

+98
-151
lines changed

controllers/content/fetchers/jsonnet_fetcher.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import (
2323
"github.com/grafana/grafana-operator/v5/api/v1beta1"
2424
)
2525

26+
var errJsonnetNoContent = errors.New("no jsonnet Content Found, nil or empty string")
27+
2628
// EmbedFSImporter "imports" data from an in-memory embedFS.
2729
type EmbedFSImporter struct {
2830
Embed embed.FS
@@ -105,7 +107,7 @@ func FetchJsonnet(cr v1beta1.GrafanaContentResource, envs map[string]string, lib
105107
spec := cr.GrafanaContentSpec()
106108

107109
if spec.Jsonnet == "" {
108-
return nil, fmt.Errorf("no jsonnet Content Found, nil or empty string")
110+
return nil, errJsonnetNoContent
109111
}
110112

111113
vm := jsonnet.MakeVM()

controllers/content/fetchers/jsonnet_fetcher_test.go

Lines changed: 66 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
package fetchers
22

33
import (
4-
"embed"
5-
"encoding/json"
6-
"errors"
7-
"fmt"
84
"os"
9-
"reflect"
105
"strings"
116
"testing"
127

138
"github.com/grafana/grafana-operator/v5/controllers/config"
9+
"github.com/stretchr/testify/assert"
1410
"github.com/stretchr/testify/require"
11+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1512

1613
"github.com/grafana/grafana-operator/v5/api/v1beta1"
1714
"github.com/grafana/grafana-operator/v5/embeds"
18-
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1915
)
2016

2117
func setup(t *testing.T) {
@@ -28,162 +24,101 @@ func teardown(t *testing.T) {
2824
require.NoError(t, os.RemoveAll(config.GrafanaDashboardsRuntimeBuild))
2925
}
3026

31-
func normalizeAndCompareJSON(json1, json2 []byte) bool {
32-
var data1, data2 map[string]any
33-
34-
if err := json.Unmarshal(json1, &data1); err != nil {
35-
return false
36-
}
37-
38-
if err := json.Unmarshal(json2, &data2); err != nil {
39-
return false
40-
}
41-
42-
normalized1, err := json.Marshal(data1)
43-
if err != nil {
44-
return false
45-
}
46-
47-
normalized2, err := json.Marshal(data2)
48-
if err != nil {
49-
return false
50-
}
51-
52-
return reflect.DeepEqual(normalized1, normalized2)
53-
}
54-
5527
func TestFetchJsonnet(t *testing.T) {
5628
tests := []struct {
57-
name string
58-
dashboard *v1beta1.GrafanaDashboard
59-
libsonnet embed.FS
60-
expected []byte
61-
envs map[string]string
62-
expectedError error
29+
name string
30+
jsonnet string
31+
envs map[string]string
32+
want []byte
6333
}{
6434
{
65-
name: "Successful Jsonnet Evaluation",
66-
dashboard: &v1beta1.GrafanaDashboard{
67-
ObjectMeta: metav1.ObjectMeta{
68-
Name: "grafanadashboard-jsonnet",
69-
Namespace: "grafana",
70-
},
71-
Spec: v1beta1.GrafanaDashboardSpec{
72-
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
73-
Jsonnet: string(embeds.TestDashboardEmbed),
74-
},
75-
},
76-
Status: v1beta1.GrafanaDashboardStatus{},
77-
},
78-
libsonnet: embeds.GrafonnetEmbed,
79-
expected: embeds.TestDashboardEmbedExpectedJSON,
80-
envs: map[string]string{},
81-
expectedError: nil,
35+
name: "Successful Jsonnet Evaluation",
36+
jsonnet: string(embeds.TestDashboardEmbed),
37+
envs: map[string]string{},
38+
want: embeds.TestDashboardEmbedExpectedJSON,
8239
},
8340
{
84-
name: "Empty Jsonnet Content",
85-
dashboard: &v1beta1.GrafanaDashboard{
86-
ObjectMeta: metav1.ObjectMeta{Name: "dashboard-1"},
87-
Spec: v1beta1.GrafanaDashboardSpec{
88-
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
89-
Jsonnet: "",
90-
},
91-
},
92-
Status: v1beta1.GrafanaDashboardStatus{},
41+
name: "Successful Jsonnet Evaluation with non-empty envs",
42+
jsonnet: string(embeds.TestDashboardEmbedWithEnv),
43+
want: embeds.TestDashboardEmbedWithEnvExpectedJSON,
44+
envs: map[string]string{
45+
"TEST_ENV": "123",
9346
},
94-
libsonnet: embeds.GrafonnetEmbed,
95-
expected: nil,
96-
envs: map[string]string{},
97-
expectedError: errors.New("no jsonnet Content Found, nil or empty string"),
9847
},
99-
{
100-
name: "Successful Jsonnet Evaluation with non-empty envs",
101-
dashboard: &v1beta1.GrafanaDashboard{
48+
}
49+
50+
for _, tt := range tests {
51+
t.Run(tt.name, func(t *testing.T) {
52+
cr := &v1beta1.GrafanaDashboard{
10253
ObjectMeta: metav1.ObjectMeta{
10354
Name: "grafanadashboard-jsonnet",
10455
Namespace: "grafana",
10556
},
10657
Spec: v1beta1.GrafanaDashboardSpec{
10758
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
108-
Jsonnet: string(embeds.TestDashboardEmbedWithEnv),
59+
Jsonnet: tt.jsonnet,
10960
},
11061
},
111-
Status: v1beta1.GrafanaDashboardStatus{},
112-
},
113-
libsonnet: embeds.GrafonnetEmbed,
114-
expected: embeds.TestDashboardEmbedWithEnvExpectedJSON,
115-
envs: map[string]string{
116-
"TEST_ENV": "123",
117-
},
118-
expectedError: nil,
119-
},
120-
}
121-
122-
for _, test := range tests {
123-
t.Run(test.name, func(t *testing.T) {
124-
result, err := FetchJsonnet(test.dashboard, test.envs, test.libsonnet)
125-
if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", test.expectedError) {
126-
t.Errorf("expected error %v, but got %v", test.expectedError, err)
12762
}
12863

129-
if test.expected != nil && !normalizeAndCompareJSON(test.expected, result) {
130-
t.Errorf("expected string %s, but got %s", string(test.expected), string(result))
131-
}
64+
got, err := FetchJsonnet(cr, tt.envs, embeds.GrafonnetEmbed)
65+
require.NoError(t, err)
66+
67+
assert.JSONEq(t, string(tt.want), string(got))
13268
})
13369
}
70+
71+
t.Run("Empty Jsonnet Content", func(t *testing.T) {
72+
cr := &v1beta1.GrafanaDashboard{
73+
ObjectMeta: metav1.ObjectMeta{
74+
Name: "grafanadashboard-jsonnet",
75+
Namespace: "grafana",
76+
},
77+
Spec: v1beta1.GrafanaDashboardSpec{
78+
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
79+
Jsonnet: "",
80+
},
81+
},
82+
}
83+
84+
got, err := FetchJsonnet(cr, map[string]string{}, embeds.GrafonnetEmbed)
85+
assert.Nil(t, got)
86+
require.ErrorIs(t, err, errJsonnetNoContent)
87+
})
13488
}
13589

13690
func TestBuildProjectAndFetchJsonnetFrom(t *testing.T) {
13791
setup(t)
13892
defer teardown(t)
13993

140-
tests := []struct {
141-
name string
142-
dashboard *v1beta1.GrafanaDashboard
143-
libsonnet embed.FS
144-
expected []byte
145-
envs map[string]string
146-
expectedError error
147-
}{
148-
{
149-
name: "Successful Jsonnet Evaluation with jsonnet build",
150-
dashboard: &v1beta1.GrafanaDashboard{
151-
ObjectMeta: metav1.ObjectMeta{
152-
Name: "grafanadashboard-jsonnet",
153-
Namespace: "grafana",
154-
},
155-
Spec: v1beta1.GrafanaDashboardSpec{
156-
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
157-
JsonnetProjectBuild: &v1beta1.JsonnetProjectBuild{
158-
JPath: []string{"/testing/jsonnetProjectWithRuntimeRaw"},
159-
FileName: "testing/jsonnetProjectWithRuntimeRaw/dashboard_with_envs.jsonnet",
160-
GzipJsonnetProject: embeds.TestJsonnetProjectBuildFolderGzip,
161-
},
94+
t.Run("Successful Jsonnet Evaluation with jsonnet build", func(t *testing.T) {
95+
cr := &v1beta1.GrafanaDashboard{
96+
ObjectMeta: metav1.ObjectMeta{
97+
Name: "grafanadashboard-jsonnet",
98+
Namespace: "grafana",
99+
},
100+
Spec: v1beta1.GrafanaDashboardSpec{
101+
GrafanaContentSpec: v1beta1.GrafanaContentSpec{
102+
JsonnetProjectBuild: &v1beta1.JsonnetProjectBuild{
103+
JPath: []string{"/testing/jsonnetProjectWithRuntimeRaw"},
104+
FileName: "testing/jsonnetProjectWithRuntimeRaw/dashboard_with_envs.jsonnet",
105+
GzipJsonnetProject: embeds.TestJsonnetProjectBuildFolderGzip,
162106
},
163107
},
164-
Status: v1beta1.GrafanaDashboardStatus{},
165-
},
166-
libsonnet: embeds.GrafonnetEmbed,
167-
expected: []byte("{\n \"env\" : \"123\" \n}"),
168-
envs: map[string]string{
169-
"TEST_ENV": "123",
170108
},
171-
expectedError: nil,
172-
},
173-
}
109+
}
174110

175-
for _, test := range tests {
176-
t.Run(test.name, func(t *testing.T) {
177-
result, err := BuildProjectAndFetchJsonnetFrom(test.dashboard, test.envs)
178-
if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", test.expectedError) {
179-
t.Errorf("expected error %v, but got %v", test.expectedError, err)
180-
}
111+
envs := map[string]string{
112+
"TEST_ENV": "123",
113+
}
181114

182-
if test.expected != nil && !normalizeAndCompareJSON(test.expected, result) {
183-
t.Errorf("expected string %s, but got %s", string(test.expected), string(result))
184-
}
185-
})
186-
}
115+
want := []byte("{\n \"env\" : \"123\" \n}")
116+
117+
got, err := BuildProjectAndFetchJsonnetFrom(cr, envs)
118+
require.NoError(t, err)
119+
120+
assert.JSONEq(t, string(want), string(got))
121+
})
187122
}
188123

189124
func TestGetJsonProjectBuildRoundName(t *testing.T) {

controllers/content/fetchers/url_fetcher_test.go

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,24 @@ import (
55
"net/http"
66

77
"github.com/onsi/gomega/ghttp"
8+
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/require"
810
v1 "k8s.io/api/core/v1"
911
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1012

1113
"github.com/grafana/grafana-operator/v5/api/v1beta1"
1214
"github.com/grafana/grafana-operator/v5/controllers/content/cache"
1315

1416
. "github.com/onsi/ginkgo/v2"
15-
. "github.com/onsi/gomega"
1617
)
1718

1819
var _ = Describe("Fetching dashboards from URL", func() {
19-
dashboardJSON := []byte(`{"dummyField": "dummyData"}`)
20-
compressedJSON, err := cache.Gzip(dashboardJSON)
21-
Expect(err).NotTo(HaveOccurred())
20+
t := GinkgoT()
21+
22+
want := []byte(`{"dummyField": "dummyData"}`)
23+
wantCompressed, err := cache.Gzip(want)
24+
25+
require.NoError(t, err)
2226

2327
var server *ghttp.Server
2428

@@ -29,7 +33,7 @@ var _ = Describe("Fetching dashboards from URL", func() {
2933
When("using no authentication", func() {
3034
BeforeEach(func() {
3135
server.AppendHandlers(ghttp.CombineHandlers(
32-
ghttp.RespondWith(http.StatusOK, dashboardJSON),
36+
ghttp.RespondWith(http.StatusOK, want),
3337
))
3438
})
3539

@@ -43,21 +47,24 @@ var _ = Describe("Fetching dashboards from URL", func() {
4347
Status: v1beta1.GrafanaDashboardStatus{},
4448
}
4549

46-
fetchedDashboard, err := FetchFromURL(context.Background(), dashboard, k8sClient, nil)
47-
Expect(err).NotTo(HaveOccurred())
48-
Expect(fetchedDashboard).To(Equal(fetchedDashboard))
49-
Expect(dashboard.Status.ContentTimestamp.Time.IsZero()).To(BeFalse())
50-
Expect(dashboard.Status.ContentCache).To(Equal(compressedJSON))
51-
Expect(dashboard.Status.ContentURL).To(Equal(server.URL()))
50+
got, err := FetchFromURL(context.Background(), dashboard, k8sClient, nil)
51+
require.NoError(t, err)
52+
53+
assert.Equal(t, want, got)
54+
assert.Equal(t, wantCompressed, dashboard.Status.ContentCache)
55+
assert.Equal(t, server.URL(), dashboard.Status.ContentURL)
56+
assert.NotZero(t, dashboard.Status.ContentTimestamp.Time)
5257
})
5358
})
59+
5460
When("using authentication", func() {
5561
basicAuthUsername := "admin"
5662
basicAuthPassword := "admin"
63+
5764
BeforeEach(func() {
5865
server.AppendHandlers(ghttp.CombineHandlers(
5966
ghttp.VerifyBasicAuth(basicAuthUsername, basicAuthPassword),
60-
ghttp.RespondWith(http.StatusOK, dashboardJSON),
67+
ghttp.RespondWith(http.StatusOK, want),
6168
))
6269
})
6370

@@ -103,14 +110,17 @@ var _ = Describe("Fetching dashboards from URL", func() {
103110
"PASSWORD": "admin",
104111
},
105112
}
113+
106114
err = k8sClient.Create(context.Background(), credentialsSecret)
107-
Expect(err).NotTo(HaveOccurred())
108-
fetchedDashboard, err := FetchFromURL(context.Background(), dashboard, k8sClient, nil)
109-
Expect(err).NotTo(HaveOccurred())
110-
Expect(fetchedDashboard).To(Equal(fetchedDashboard))
111-
Expect(dashboard.Status.ContentTimestamp.Time.IsZero()).To(BeFalse())
112-
Expect(dashboard.Status.ContentCache).To(Equal(compressedJSON))
113-
Expect(dashboard.Status.ContentURL).To(Equal(server.URL()))
115+
require.NoError(t, err)
116+
117+
got, err := FetchFromURL(context.Background(), dashboard, k8sClient, nil)
118+
require.NoError(t, err)
119+
120+
assert.Equal(t, want, got)
121+
assert.Equal(t, wantCompressed, dashboard.Status.ContentCache)
122+
assert.Equal(t, server.URL(), dashboard.Status.ContentURL)
123+
assert.NotZero(t, dashboard.Status.ContentTimestamp.Time)
114124
})
115125
})
116126
})

0 commit comments

Comments
 (0)