Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests #123

Merged
merged 21 commits into from
Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ jobs:
uses: magefile/mage-action@v1
with:
version: latest
args: coverage
args: cover

- name: Build backend
if: steps.check-for-backend.outputs.has-backend == 'true'
Expand All @@ -77,6 +77,7 @@ jobs:
uses: codecov/codecov-action@v1
with:
directory: ./coverage/
files: ./coverage/lcov.info,./coverage/backend.txt
env_vars: OS,PYTHON
fail_ci_if_error: true
path_to_write_report: ./coverage/codecov_report.txt
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ jobs:
uses: magefile/mage-action@v1
with:
version: latest
args: coverage
args: cover

- name: Build backend
if: steps.check-for-backend.outputs.has-backend == 'true'
Expand Down
24 changes: 20 additions & 4 deletions Magefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,30 @@
package main

import (
"fmt"
"os"
"path/filepath"

// mage:import
build "github.com/grafana/grafana-plugin-sdk-go/build"
"github.com/magefile/mage/sh"
)

// Hello prints a message (shows that you can define custom Mage targets).
func Hello() {
fmt.Println("hello plugin developer!")
// runs backend tests and makes a txt coverage report in "atomic" mode and html coverage report.
func Cover() error {
// Create a coverage file if it does not already exist
if err := os.MkdirAll(filepath.Join(".", "coverage"), os.ModePerm); err != nil {
return err
}

if err := sh.RunV("go", "test", "./pkg/...", "-v", "-cover", "-covermode=atomic", "-coverprofile=coverage/backend.txt"); err != nil {
return err
}

if err := sh.RunV("go", "tool", "cover", "-html=coverage/backend.txt", "-o", "coverage/backend.html"); err != nil {
return err
}

return nil
}

// Default configures the default target.
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ If Redis is running as Docker container on MacOS, please update host to `host.do
url: redis://host.docker.internal:6379
```

If Redis is running as Docker container on Linux, please update host to `redis`

```
url: redis://redis:6379
```

### Run using `docker-compose` for development

Data Source have to be built following [BUILD](https://github.com/RedisGrafana/grafana-redis-datasource/blob/master/BUILD.md) instructions before starting using `docker-compose-dev.yml` file.
Expand Down
Binary file modified data/dump.rdb
Binary file not shown.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ require (
github.com/hashicorp/yamux v0.0.0-20200609203250-aecfd211c9ce // indirect
github.com/jhump/protoreflect v1.8.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/magefile/mage v1.10.0
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mediocregopher/radix/v3 v3.6.0
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/prometheus/client_golang v1.8.0 // indirect
github.com/prometheus/common v0.15.0 // indirect
github.com/stretchr/testify v1.6.1
golang.org/x/net v0.0.0-20201209123823-ac852fbbde11 // indirect
golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e // indirect
golang.org/x/text v0.3.4 // indirect
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"start": "docker-compose up",
"start:dev": "docker-compose -f docker-compose-dev.yml up",
"test": "grafana-toolkit plugin:test --coverage",
"test:backend": "mage cover",
"watch": "grafana-toolkit plugin:dev --watch"
},
"version": "1.3.0"
Expand Down
1 change: 1 addition & 0 deletions pkg/data-frame.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func (ds *redisDatasource) addFrameFieldsFromArray(values []interface{}, frame *
key = string(k)
default:
log.DefaultLogger.Error("addFrameFieldsFromArray", "Conversion Error", "Unsupported Key type")
continue
}

// Value
Expand Down
86 changes: 86 additions & 0 deletions pkg/data-frame_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package main

import (
"testing"

"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/stretchr/testify/require"
)

func TestCreateFrameValue(t *testing.T) {
t.Parallel()
tests := []struct {
value string
expected interface{}
}{
{"3.14", 3.14},
{"3", float64(3)},
{"somestring", "somestring"},
}
for _, tt := range tests {
tt := tt
t.Run(tt.value, func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
frame := ds.createFrameValue("keyName", tt.value)
field := frame.Fields[0].At(0)
require.Equal(t, tt.expected, field, "Unexpected conversation")
})
}
}

func TestAddFrameFieldsFromArray(t *testing.T) {
t.Parallel()
tests := []struct {
name string
values []interface{}
fieldsCount int
}{
{
"should not parse key of not []byte type, and should not create field",
[]interface{}{
[]interface{}{"sensor_id", []byte("2")},
},
0,
},
{
"should parse value of type bytes[] with underlying int",
[]interface{}{
[]interface{}{[]byte("sensor_id"), []byte("2")},
[]interface{}{[]byte("area_id"), []byte("32")},
},
2,
},
{
"should parse value of type bytes[] with underlying non-int value",
[]interface{}{
[]interface{}{[]byte("sensor_id"), []byte("some_string")},
},
1,
},
{
"should parse value of type int64",
[]interface{}{
[]interface{}{[]byte("sensor_id"), int64(145)},
},
1,
},
{
"should not parse value of not bytes[] or int64",
[]interface{}{
[]interface{}{[]byte("sensor_id"), float32(3.14)},
},
0,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
frame := data.NewFrame("name")
frame = ds.addFrameFieldsFromArray(tt.values, frame)
require.Len(t, frame.Fields, tt.fieldsCount, "Invalid number of fields created in Frame")
})
}
}
184 changes: 184 additions & 0 deletions pkg/query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package main

import (
"context"
"encoding/json"
"errors"
"testing"
"time"

"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/mediocregopher/radix/v3/resp/resp2"
"github.com/stretchr/testify/require"
)

func TestQuery(t *testing.T) {
t.Parallel()
tests := []struct {
qm queryModel
}{
{queryModel{Command: "ts.get"}},
{queryModel{Command: "ts.info"}},
{queryModel{Command: "ts.queryindex"}},
{queryModel{Command: "ts.range"}},
{queryModel{Command: "ts.mrange"}},
{queryModel{Command: "hgetall"}},
{queryModel{Command: "smembers"}},
{queryModel{Command: "hkeys"}},
{queryModel{Command: "hget"}},
{queryModel{Command: "hmget"}},
{queryModel{Command: "info"}},
{queryModel{Command: "clientList"}},
{queryModel{Command: "slowlogGet"}},
{queryModel{Command: "type"}},
{queryModel{Command: "xinfoStream"}},
{queryModel{Command: "clusterInfo"}},
{queryModel{Command: "clusterNodes"}},
{queryModel{Command: "ft.info"}},
{queryModel{Command: "xinfoStream"}},
{queryModel{Query: "DO something"}},
}
for _, tt := range tests {
tt := tt
t.Run(tt.qm.Command, func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
client := testClient{nil, nil}
var marshaled, _ = json.Marshal(tt.qm)
response := ds.query(context.TODO(), backend.DataQuery{
RefID: "",
QueryType: "",
MaxDataPoints: 100,
Interval: 10,
TimeRange: backend.TimeRange{From: time.Now(), To: time.Now()},
JSON: marshaled,
}, client)
require.NoError(t, response.Error, "Should not return error")
})
}
}

func TestQueryWithErrors(t *testing.T) {
t.Parallel()

t.Run("Marshalling failure", func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
client := testClient{nil, nil}
response := ds.query(context.TODO(), backend.DataQuery{
RefID: "",
QueryType: "",
MaxDataPoints: 100,
Interval: 10,
TimeRange: backend.TimeRange{From: time.Now(), To: time.Now()},
JSON: []byte{31, 17, 45},
}, client)

require.EqualError(t, response.Error, "invalid character '\\x1f' looking for beginning of value", "Should return marshalling error")
})

t.Run("Unknown command failure", func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
client := testClient{nil, nil}
var marshaled, _ = json.Marshal(queryModel{Command: "unknown"})
response := ds.query(context.TODO(), backend.DataQuery{
RefID: "",
QueryType: "",
MaxDataPoints: 100,
Interval: 10,
TimeRange: backend.TimeRange{From: time.Now(), To: time.Now()},
JSON: marshaled,
}, client)

require.EqualError(t, response.Error, "Unknown command", "Should return unknown command error")
})

}

func TestErrorHandler(t *testing.T) {
t.Parallel()

t.Run("Common error", func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
resp := ds.errorHandler(backend.DataResponse{}, errors.New("common error"))
require.EqualError(t, resp.Error, "common error", "Should return marshalling error")
})

t.Run("Redis error", func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
resp := ds.errorHandler(backend.DataResponse{}, resp2.Error{E: errors.New("redis error")})
require.EqualError(t, resp.Error, "redis error", "Should return marshalling error")
})

}

func TestQueryKeyCommand(t *testing.T) {
t.Parallel()
tests := []struct {
name string
qm queryModel
rcv interface{}
fieldsCount int
rowsPerField int
valuesToCheckInResponse []valueToCheckInResponse
err error
}{
{
"should handle string value",
queryModel{Command: "get", Key: "test1"},
"someStr",
1,
1,
[]valueToCheckInResponse{
{frameIndex: 0, fieldIndex: 0, rowIndex: 0, value: "someStr"},
},
nil,
},
{
"should handle float64 value",
queryModel{Command: "get", Key: "test1"},
"3.14",
1,
1,
[]valueToCheckInResponse{
{frameIndex: 0, fieldIndex: 0, rowIndex: 0, value: 3.14},
},
nil,
},
{
"should handle error",
queryModel{Command: "get"},
nil,
0,
0,
nil,
errors.New("error occurred"),
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ds := redisDatasource{}
client := testClient{tt.rcv, tt.err}
response := ds.queryKeyCommand(tt.qm, client)
if tt.err != nil {
require.EqualError(t, response.Error, tt.err.Error(), "Should set error to response if failed")
require.Nil(t, response.Frames, "No frames should be created if failed")
} else {
require.Equal(t, tt.qm.Key, response.Frames[0].Name, "Invalid frame name")
require.Len(t, response.Frames[0].Fields, tt.fieldsCount, "Invalid number of fields created ")
require.Equal(t, tt.rowsPerField, response.Frames[0].Fields[0].Len(), "Invalid number of values in field vectors")

if tt.valuesToCheckInResponse != nil {
for _, value := range tt.valuesToCheckInResponse {
require.Equalf(t, value.value, response.Frames[value.frameIndex].Fields[value.fieldIndex].At(value.rowIndex), "Invalid value at Frame[%v]:Field[%v]:Row[%v]", value.frameIndex, value.fieldIndex, value.rowIndex)
}
}
}
})
}
}
Loading