Skip to content

Commit

Permalink
Merge pull request nytm#31 from matthiasng/dashboard-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tonglil authored Jun 2, 2020
2 parents c9c958b + c3a11b4 commit 7d74f3b
Show file tree
Hide file tree
Showing 9 changed files with 204 additions and 48 deletions.
2 changes: 1 addition & 1 deletion .drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ steps:
image: golang
commands:
- go mod download
- go test
- go test -cover -race -vet all -mod readonly ./...
4 changes: 4 additions & 0 deletions admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import (
func (c *Client) CreateUser(user User) (int64, error) {
id := int64(0)
data, err := json.Marshal(user)
if err != nil {
return id, err
}

req, err := c.newRequest("POST", "/api/admin/users", nil, bytes.NewBuffer(data))
if err != nil {
return id, err
Expand Down
2 changes: 1 addition & 1 deletion dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type Dashboard struct {
Meta DashboardMeta `json:"meta"`
Model map[string]interface{} `json:"dashboard"`
Folder int64 `json:"folderId"`
Overwrite bool `json:overwrite`
Overwrite bool `json:"overwrite"`
}

// Deprecated: use NewDashboard instead
Expand Down
149 changes: 133 additions & 16 deletions dashboard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,140 @@ import (
)

const (
getDashboardsJSON = `
[
{
"id": 1,
"uid": "RGAPB1cZz",
"title": "Grafana Stats",
"uri": "db/grafana-stats",
"url": "/dashboards/d/RGAPB1cZz/grafana-stat",
"slug": "",
"type": "dash-db",
"tags": [],
"isStarred": false
}
]
`
createdAndUpdateDashboardResponse = `{
"slug": "test",
"id": 1,
"uid": "nErXDvCkzz",
"status": "success",
"version": 1
}`

getDashboardResponse = `{
"dashboard": {
"id": 1,
"uid": "cIBgcSjkk",
"title": "Production Overview",
"version": 0
},
"meta": {
"isStarred": false,
"url": "/d/cIBgcSjkk/production-overview",
"slug": "production-overview"
}
}`

getDashboardsJSON = `[
{
"id": 1,
"uid": "RGAPB1cZz",
"title": "Grafana Stats",
"uri": "db/grafana-stats",
"url": "/dashboards/d/RGAPB1cZz/grafana-stat",
"slug": "",
"type": "dash-db",
"tags": [],
"isStarred": false
}
]`
)

func TestDashboardCreateAndUpdate(t *testing.T) {
server, client := gapiTestTools(200, createdAndUpdateDashboardResponse)
defer server.Close()

dashboard := Dashboard{
Model: map[string]interface{}{
"title": "test",
},
Folder: 0,
Overwrite: false,
}

resp, err := client.NewDashboard(dashboard)
if err != nil {
t.Fatal(err)
}

t.Log(pretty.PrettyFormat(resp))

if resp.Uid != "nErXDvCkzz" {
t.Errorf("Invalid uid - %s, Expected %s", resp.Uid, "nErXDvCkzz")
}

for _, code := range []int{400, 401, 403, 412} {
server.code = code
_, err = client.NewDashboard(dashboard)
if err == nil {
t.Errorf("%d not detected", code)
}
}
}

func TestDashboardGet(t *testing.T) {
server, client := gapiTestTools(200, getDashboardResponse)
defer server.Close()

resp, err := client.Dashboard("test")
if err != nil {
t.Error(err)
}
uid, ok := resp.Model["uid"]
if !ok || uid != "cIBgcSjkk" {
t.Errorf("Invalid uid - %s, Expected %s", uid, "cIBgcSjkk")
}

resp, err = client.DashboardByUID("cIBgcSjkk")
if err != nil {
t.Error(err)
}
uid, ok = resp.Model["uid"]
if !ok || uid != "cIBgcSjkk" {
t.Errorf("Invalid uid - %s, Expected %s", uid, "cIBgcSjkk")
}

for _, code := range []int{401, 403, 404} {
server.code = code
_, err = client.Dashboard("test")
if err == nil {
t.Errorf("%d not detected", code)
}

_, err = client.DashboardByUID("cIBgcSjkk")
if err == nil {
t.Errorf("%d not detected", code)
}
}
}

func TestDashboardDelete(t *testing.T) {
server, client := gapiTestTools(200, "")
defer server.Close()

err := client.DeleteDashboard("test")
if err != nil {
t.Error(err)
}

err = client.DeleteDashboardByUID("cIBgcSjkk")
if err != nil {
t.Error(err)
}

for _, code := range []int{401, 403, 404, 412} {
server.code = code

err = client.DeleteDashboard("test")
if err == nil {
t.Errorf("%d not detected", code)
}

err = client.DeleteDashboardByUID("cIBgcSjkk")
if err == nil {
t.Errorf("%d not detected", code)
}
}
}

func TestDashboards(t *testing.T) {
server, client := gapiTestTools(200, getDashboardsJSON)
defer server.Close()
Expand All @@ -42,4 +159,4 @@ func TestDashboards(t *testing.T) {
if dashboards[0].Id != 1 || dashboards[0].Title != "Grafana Stats" {
t.Error("Not correctly parsing returned dashboards.")
}
}
}
29 changes: 0 additions & 29 deletions datasource_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package gapi

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/gobs/pretty"
Expand All @@ -14,31 +10,6 @@ const (
createdDataSourceJSON = `{"id":1,"message":"Datasource added", "name": "test_datasource"}`
)

func gapiTestTools(code int, body string) (*httptest.Server, *Client) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, body)
}))

tr := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}

httpClient := &http.Client{Transport: tr}

url := url.URL{
Scheme: "http",
Host: "my-grafana.com",
}

client := &Client{"my-key", url, httpClient}

return server, client
}

func TestNewDataSource(t *testing.T) {
server, client := gapiTestTools(200, createdDataSourceJSON)
defer server.Close()
Expand Down
6 changes: 6 additions & 0 deletions folder.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ func (c *Client) NewFolder(title string) (Folder, error) {
"title": title,
}
data, err := json.Marshal(dataMap)
if err != nil {
return folder, err
}
req, err := c.newRequest("POST", "/api/folders", nil, bytes.NewBuffer(data))
if err != nil {
return folder, err
Expand Down Expand Up @@ -91,6 +94,9 @@ func (c *Client) UpdateFolder(id string, name string) error {
"name": name,
}
data, err := json.Marshal(dataMap)
if err != nil {
return err
}
req, err := c.newRequest("PUT", fmt.Sprintf("/api/folders/%s", id), nil, bytes.NewBuffer(data))
if err != nil {
return err
Expand Down
45 changes: 45 additions & 0 deletions mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package gapi

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
)

type mockServer struct {
code int
server *httptest.Server
}

func (m *mockServer) Close() {
m.server.Close()
}

func gapiTestTools(code int, body string) (*mockServer, *Client) {
mock := &mockServer{
code: code,
}

mock.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(mock.code)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, body)
}))

tr := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(mock.server.URL)
},
}

httpClient := &http.Client{Transport: tr}

url := url.URL{
Scheme: "http",
Host: "my-grafana.com",
}

client := &Client{"my-key", url, httpClient}
return mock, client
}
6 changes: 6 additions & 0 deletions org_users.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ func (c *Client) AddOrgUser(orgId int64, user, role string) error {
"role": role,
}
data, err := json.Marshal(dataMap)
if err != nil {
return err
}
req, err := c.newRequest("POST", fmt.Sprintf("/api/orgs/%d/users", orgId), nil, bytes.NewBuffer(data))
if err != nil {
return err
Expand All @@ -65,6 +68,9 @@ func (c *Client) UpdateOrgUser(orgId, userId int64, role string) error {
"role": role,
}
data, err := json.Marshal(dataMap)
if err != nil {
return err
}
req, err := c.newRequest("PATCH", fmt.Sprintf("/api/orgs/%d/users/%d", orgId, userId), nil, bytes.NewBuffer(data))
if err != nil {
return err
Expand Down
9 changes: 8 additions & 1 deletion orgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,15 @@ func (c *Client) Org(id int64) (Org, error) {
}

func (c *Client) NewOrg(name string) (int64, error) {
id := int64(0)

dataMap := map[string]string{
"name": name,
}
data, err := json.Marshal(dataMap)
id := int64(0)
if err != nil {
return id, err
}
req, err := c.newRequest("POST", "/api/orgs", nil, bytes.NewBuffer(data))
if err != nil {
return id, err
Expand Down Expand Up @@ -114,6 +118,9 @@ func (c *Client) UpdateOrg(id int64, name string) error {
"name": name,
}
data, err := json.Marshal(dataMap)
if err != nil {
return err
}
req, err := c.newRequest("PUT", fmt.Sprintf("/api/orgs/%d", id), nil, bytes.NewBuffer(data))
if err != nil {
return err
Expand Down

0 comments on commit 7d74f3b

Please sign in to comment.