Skip to content

Commit

Permalink
✨ Add testing helper to create devices
Browse files Browse the repository at this point in the history
Adds a CreateDevicesFromJSON that's nearly identical to cmd/demo
to help with testing bridges
  • Loading branch information
daenney committed May 26, 2019
1 parent f2c1c55 commit f12f655
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions testutils/client.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package testutils // import "lib.hemtjan.st/testutils"

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"testing"

"github.com/goiiot/libmqtt"
"lib.hemtjan.st/client"
"lib.hemtjan.st/device"
)

var errNoDevices = errors.New("unable to create any devices")

type dummyMqtt struct {
initCh chan error
}
Expand Down Expand Up @@ -66,3 +74,40 @@ func MQTTAddress(t *testing.T) string {

return mqttHostPort
}

type config struct {
Devices []struct {
*device.Info
Init *map[string]string `json:"init"`
} `json:"devices"`
}

// CreateDevicesFromJSON creates fake devices on the broker based
// on the devices defined in a JSON file
func CreateDevicesFromJSON(path string, m device.Transport) error {
c := &config{}
f, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if err = json.Unmarshal(f, c); err != nil {
return err
}
if len(c.Devices) == 0 {
return errNoDevices
}
// Loop through config and create the devices
for _, info := range c.Devices {
d, err := client.NewDevice(info.Info, m)
if err != nil {
log.Printf("Error creating device: %v", err)
continue
}
if info.Init != nil {
for ft, v := range *info.Init {
d.Feature(ft).Update(v)
}
}
}
return nil
}

0 comments on commit f12f655

Please sign in to comment.