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

     1  package outlet
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/martinohmann/rfoutlet/internal/schedule"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestStateFile_ReadBack(t *testing.T) {
    15  	sf := NewStateFile("testdata/valid_state.json")
    16  
    17  	outlets := []*Outlet{{ID: "foo"}, {ID: "bar"}, {ID: "baz"}}
    18  
    19  	expected := []*Outlet{
    20  		{ID: "foo", State: StateOn, Schedule: schedule.NewWithIntervals([]schedule.Interval{
    21  			{
    22  				Enabled:  true,
    23  				Weekdays: []time.Weekday{time.Monday},
    24  				From:     schedule.NewDayTime(0, 59),
    25  				To:       schedule.NewDayTime(2, 1),
    26  			},
    27  		})},
    28  		{ID: "bar", State: StateOn, Schedule: schedule.New()},
    29  		{ID: "baz"},
    30  	}
    31  
    32  	require.NoError(t, sf.ReadBack(outlets))
    33  	assert.Equal(t, expected, outlets)
    34  }
    35  
    36  func TestStateFile_ReadBack_Invalid(t *testing.T) {
    37  	sf := NewStateFile("testdata/invalid_state.json")
    38  	outlets := []*Outlet{}
    39  	require.Error(t, sf.ReadBack(outlets))
    40  }
    41  
    42  func TestStateFile_WriteOut(t *testing.T) {
    43  	f, err := ioutil.TempFile("", "rfoutlet-state-*")
    44  	if err != nil {
    45  		t.Fatal(err)
    46  	}
    47  	defer os.Remove(f.Name())
    48  
    49  	sf := NewStateFile(f.Name())
    50  
    51  	outlets := []*Outlet{
    52  		{ID: "foo", State: StateOn, Schedule: schedule.NewWithIntervals([]schedule.Interval{
    53  			{
    54  				Enabled:  true,
    55  				Weekdays: []time.Weekday{time.Monday},
    56  				From:     schedule.NewDayTime(0, 59),
    57  				To:       schedule.NewDayTime(2, 1),
    58  			},
    59  		})},
    60  		{ID: "bar", State: StateOn, Schedule: schedule.New()},
    61  		{ID: "baz"},
    62  	}
    63  
    64  	require.NoError(t, sf.WriteOut(outlets))
    65  
    66  	buf, err := ioutil.ReadFile(f.Name())
    67  	if err != nil {
    68  		t.Fatal(err)
    69  	}
    70  
    71  	expected := `{"bar":{"state":1,"schedule":[]},"baz":{},"foo":{"state":1,"schedule":[{"id":"","enabled":true,"weekdays":[1],"from":{"hour":0,"minute":59},"to":{"hour":2,"minute":1}}]}}`
    72  
    73  	assert.Equal(t, expected, string(buf))
    74  }