github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/statedrift/detector_test.go (about)

     1  package statedrift
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/martinohmann/rfoutlet/internal/command"
     7  	"github.com/martinohmann/rfoutlet/internal/outlet"
     8  	"github.com/martinohmann/rfoutlet/pkg/gpio"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  type fakeReceiver struct {
    13  	results chan gpio.ReceiveResult
    14  }
    15  
    16  func (f *fakeReceiver) Receive() <-chan gpio.ReceiveResult {
    17  	return f.results
    18  }
    19  
    20  func (f *fakeReceiver) Close() error { return nil }
    21  
    22  func TestDetector(t *testing.T) {
    23  	o1 := &outlet.Outlet{ID: "foo", CodeOn: 123, CodeOff: 456, State: outlet.StateOff}
    24  	o2 := &outlet.Outlet{ID: "bar", CodeOn: 789, CodeOff: 234, State: outlet.StateOn}
    25  
    26  	reg := outlet.NewRegistry()
    27  	reg.RegisterOutlets(o1, o2)
    28  
    29  	recv := &fakeReceiver{make(chan gpio.ReceiveResult)}
    30  
    31  	queue := make(chan command.Command)
    32  	stopCh := make(chan struct{})
    33  	defer close(stopCh)
    34  
    35  	d := NewDetector(reg, recv, queue)
    36  	go func() {
    37  		d.Run(stopCh)
    38  		close(queue)
    39  	}()
    40  
    41  	go func() {
    42  		defer close(recv.results)
    43  		recv.results <- gpio.ReceiveResult{Code: 456}
    44  		recv.results <- gpio.ReceiveResult{Code: 123}
    45  		recv.results <- gpio.ReceiveResult{Code: 42}
    46  		recv.results <- gpio.ReceiveResult{Code: 789}
    47  		recv.results <- gpio.ReceiveResult{Code: 234}
    48  	}()
    49  
    50  	expected := []command.Command{
    51  		command.StateCorrectionCommand{Outlet: o1, DesiredState: outlet.StateOn},
    52  		command.StateCorrectionCommand{Outlet: o2, DesiredState: outlet.StateOff},
    53  	}
    54  
    55  	received := make([]command.Command, 0)
    56  
    57  	for cmd := range queue {
    58  		received = append(received, cmd)
    59  	}
    60  
    61  	assert.Equal(t, expected, received)
    62  }