92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package testenv
|
|
|
|
import (
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
"src.dualinventive.com/go/dinet"
|
|
"src.dualinventive.com/go/dinet/ditime"
|
|
"src.dualinventive.com/go/dinet/rpc"
|
|
"src.dualinventive.com/go/lib/cp3000"
|
|
"src.dualinventive.com/go/lib/dilog"
|
|
)
|
|
|
|
// TestData contains setup and teardown functions to make unit tests more readable
|
|
type TestData struct {
|
|
wg sync.WaitGroup
|
|
t *testing.T
|
|
Logger dilog.Logger
|
|
Repo *RAMRepository
|
|
dinetConnection *dinet.TestTransport
|
|
serviceDevUID string
|
|
ServiceDev *dinet.ParentDeviceMock
|
|
deviceDevUID string
|
|
Cp3000Connection *CP3000IO
|
|
Cp3000Router cp3000.Router
|
|
}
|
|
|
|
// CreateTestData setup a test suite and return it
|
|
func CreateTestData(t *testing.T) *TestData {
|
|
td := &TestData{t: t}
|
|
td.Logger = dilog.NewTestLogger(t)
|
|
td.Repo = NewRAMRepository()
|
|
|
|
parent, conn := dinet.NewParentDeviceMock(t)
|
|
td.dinetConnection = conn
|
|
td.serviceDevUID = parent.UID()
|
|
td.ServiceDev = parent
|
|
td.deviceDevUID = "01000000000000000000000000000002"
|
|
|
|
td.Cp3000Connection = NewCP3000IO(td.Logger)
|
|
td.Cp3000Router = cp3000.NewIORouter(td.Cp3000Connection)
|
|
|
|
td.wg.Add(2)
|
|
go func() {
|
|
p := parent.Router().ListenAndServe()
|
|
require.Equal(t, dinet.ErrDisconnected, p)
|
|
td.wg.Done()
|
|
}()
|
|
go func() {
|
|
td.Cp3000Router.Run()
|
|
td.wg.Done()
|
|
}()
|
|
return td
|
|
}
|
|
|
|
// Finish teardowns the test suite
|
|
func (td *TestData) Finish() {
|
|
require.Nil(td.t, td.Cp3000Router.Close())
|
|
require.Nil(td.t, td.dinetConnection.Close())
|
|
td.wg.Wait()
|
|
}
|
|
|
|
// WaitForMessage waits until a new message is received and returns the message
|
|
func (td *TestData) WaitForMessage() *rpc.Msg {
|
|
return <-td.dinetConnection.Read
|
|
}
|
|
|
|
// ReqRep requestsa value from a CP3000 device
|
|
func (td *TestData) ReqRep(classMethod rpc.ClassMethod, param ...interface{}) *rpc.Msg {
|
|
// Send class method
|
|
msg := &rpc.Msg{
|
|
Dinetrpc: rpc.CurrentDinetrpc,
|
|
ID: 3,
|
|
Time: ditime.Now(),
|
|
DeviceUID: td.deviceDevUID,
|
|
Type: rpc.MsgTypeRequest,
|
|
ClassMethod: classMethod,
|
|
}
|
|
if len(param) > 0 {
|
|
msg.Params = rpc.NewParams(param[0])
|
|
}
|
|
td.dinetConnection.Write <- msg
|
|
// keep waiting for the reply
|
|
for {
|
|
rep := <-td.dinetConnection.Read
|
|
if rep.ID == msg.ID && rep.ClassMethod == msg.ClassMethod {
|
|
return rep
|
|
}
|
|
}
|
|
}
|