diff --git a/src/cmd/serve.go b/src/cmd/serve.go index 1fdf266..6cb09b5 100644 --- a/src/cmd/serve.go +++ b/src/cmd/serve.go @@ -27,7 +27,8 @@ import ( var ( port string scheduler gocron.Scheduler - ticktick *ticktickutil.TicktickUtilImpl + ticktick ticktickutil.TicktickUtil + ha *homeassistant.HomeAssistant ) // serveCmd represents the serve command @@ -55,7 +56,7 @@ func initComponent() { // init location recorder locationRecorder.Init() // init homeassistant - homeassistant.Init(ticktick) + ha = homeassistant.NewHomeAssistant(ticktick) } func serve(cmd *cobra.Command, args []string) { @@ -108,7 +109,7 @@ func serve(cmd *cobra.Command, args []string) { router.HandleFunc("/poo/latest", pooRecorder.HandleNotifyLatestPoo).Methods("GET") router.HandleFunc("/poo/record", pooRecorder.HandleRecordPoo).Methods("POST") - router.HandleFunc("/homeassistant/publish", homeassistant.HandleHaMessage).Methods("POST") + router.HandleFunc("/homeassistant/publish", ha.HandleHaMessage).Methods("POST") router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST") diff --git a/src/components/homeassistant/homeassistant.go b/src/components/homeassistant/homeassistant.go index b041478..5630b2f 100644 --- a/src/components/homeassistant/homeassistant.go +++ b/src/components/homeassistant/homeassistant.go @@ -18,60 +18,68 @@ type haMessage struct { Content string `json:"content"` } +type HomeAssistant struct { + ticktickUtil ticktickutil.TicktickUtil +} + type actionTask struct { Action string `json:"action"` DueHour int `json:"due_hour"` } -var ( - ticktickUtil ticktickutil.TicktickUtil -) - -func Init(ticktick ticktickutil.TicktickUtil) { - ticktickUtil = ticktick +func NewHomeAssistant(ticktick ticktickutil.TicktickUtil) *HomeAssistant { + return &HomeAssistant{ + ticktickUtil: ticktick, + } } -func HandleHaMessage(w http.ResponseWriter, r *http.Request) { +func (ha *HomeAssistant) HandleHaMessage(w http.ResponseWriter, r *http.Request) { var message haMessage decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() err := decoder.Decode(&message) if err != nil { - slog.Warn(fmt.Sprintln("HandleHaMessage: Error decoding request body", err)) - http.Error(w, err.Error(), http.StatusBadRequest) + slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error decoding request body", err)) + http.Error(w, "", http.StatusInternalServerError) return } switch message.Target { case "poo_recorder": - res := handlePooRecorderMsg(message) + res := ha.handlePooRecorderMsg(message) if !res { - http.Error(w, "Error handling poo recorder message", http.StatusInternalServerError) + slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling poo recorder message")) + http.Error(w, "", http.StatusInternalServerError) } case "location_recorder": - res := handleLocationRecorderMsg(message) + res := ha.handleLocationRecorderMsg(message) if !res { - http.Error(w, "Error handling location recorder message", http.StatusInternalServerError) + slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling location recorder message")) + http.Error(w, "", http.StatusInternalServerError) } case "ticktick": - handleTicktickMsg(message) + res := ha.handleTicktickMsg(message) + if !res { + slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling ticktick message")) + http.Error(w, "", http.StatusInternalServerError) + } default: - slog.Warn(fmt.Sprintln("HandleHaMessage Unknown target", message.Target)) - http.Error(w, "Unknown target", http.StatusBadRequest) + slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Unknown target", message.Target)) + http.Error(w, "", http.StatusInternalServerError) } } -func handlePooRecorderMsg(message haMessage) bool { +func (ha *HomeAssistant) handlePooRecorderMsg(message haMessage) bool { switch message.Action { case "get_latest": - return handleGetLatestPoo() + return ha.handleGetLatestPoo() default: - slog.Warn(fmt.Sprintln("handlePooRecorderMsg: Unknown action", message.Action)) + slog.Warn(fmt.Sprintln("homeassistant.handlePooRecorderMsg: Unknown action", message.Action)) return false } } -func handleLocationRecorderMsg(message haMessage) bool { +func (ha *HomeAssistant) handleLocationRecorderMsg(message haMessage) bool { if message.Action == "record" { port := viper.GetString("port") client := &http.Client{ @@ -79,49 +87,52 @@ func handleLocationRecorderMsg(message haMessage) bool { } _, err := client.Post("http://localhost:"+port+"/location/record", "application/json", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\""))) if err != nil { - slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Error sending request to location recorder", err)) + slog.Warn(fmt.Sprintln("homeassistant.handleLocationRecorderMsg: Error sending request to location recorder", err)) return false } } else { - slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Unknown action", message.Action)) + slog.Warn(fmt.Sprintln("homeassistant.handleLocationRecorderMsg: Unknown action", message.Action)) return false } return true } -func handleTicktickMsg(message haMessage) { +func (ha *HomeAssistant) handleTicktickMsg(message haMessage) bool { switch message.Action { case "create_action_task": - createActionTask(message) + return ha.createActionTask(message) + default: + slog.Warn(fmt.Sprintln("homeassistant.handleTicktickMsg: Unknown action", message.Action)) + return false } } -func handleGetLatestPoo() bool { +func (ha *HomeAssistant) handleGetLatestPoo() bool { client := &http.Client{ Timeout: time.Second * 1, } port := viper.GetString("port") _, err := client.Get("http://localhost:" + port + "/poo/latest") if err != nil { - slog.Warn(fmt.Sprintln("handleGetLatestPoo: Error sending request to poo recorder", err)) + slog.Warn(fmt.Sprintln("homeassistant.handleGetLatestPoo: Error sending request to poo recorder", err)) return false } return true } -func createActionTask(message haMessage) { - if !viper.InConfig("homeassistant.actionTaskProjectId") { - slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file") - return +func (ha *HomeAssistant) createActionTask(message haMessage) bool { + if !viper.IsSet("homeassistant.actionTaskProjectId") { + slog.Warn("homeassistant.createActionTask: actionTaskProjectId not found in config file") + return false } projectId := viper.GetString("homeassistant.actionTaskProjectId") detail := strings.ReplaceAll(message.Content, "'", "\"") var task actionTask err := json.Unmarshal([]byte(detail), &task) if err != nil { - slog.Warn(fmt.Sprintln("Homeassistant.createActionTask Error unmarshalling", err)) - return + slog.Warn(fmt.Sprintln("homeassistant.createActionTask: Error unmarshalling", err)) + return false } dueHour := task.DueHour due := time.Now().Add(time.Hour * time.Duration(dueHour)) @@ -132,8 +143,10 @@ func createActionTask(message haMessage) { Title: task.Action, DueDate: dueTicktick, } - err = ticktickUtil.CreateTask(ticktickTask) + err = ha.ticktickUtil.CreateTask(ticktickTask) if err != nil { - slog.Warn(fmt.Sprintf("Homeassistant.createActionTask Error creating task %s", err)) + slog.Warn(fmt.Sprintf("homeassistant.createActionTask: Error creating task %s", err)) + return false } + return true } diff --git a/src/components/homeassistant/homeassistant_test.go b/src/components/homeassistant/homeassistant_test.go index f9c5513..7b28b22 100644 --- a/src/components/homeassistant/homeassistant_test.go +++ b/src/components/homeassistant/homeassistant_test.go @@ -2,26 +2,56 @@ package homeassistant import ( "bytes" + "errors" "log/slog" "net/http" "net/http/httptest" "strings" "testing" + "time" "github.com/spf13/viper" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/t-liu93/home-automation-backend/util/ticktickutil" ) var ( loggerText = new(bytes.Buffer) ) -func SetupTearDown(t *testing.T) func() { +type MockTicktickUtil struct { + mock.Mock +} + +func (m *MockTicktickUtil) HandleAuthCode(w http.ResponseWriter, r *http.Request) { + m.Called(w, r) +} + +func (m *MockTicktickUtil) GetTasks(projectId string) []ticktickutil.Task { + args := m.Called(projectId) + return args.Get(0).([]ticktickutil.Task) +} + +func (m *MockTicktickUtil) HasDuplicateTask(projectId string, taskTitile string) bool { + args := m.Called(projectId, taskTitile) + return args.Bool(0) +} + +func (m *MockTicktickUtil) CreateTask(task ticktickutil.Task) error { + args := m.Called(task) + return args.Error(0) +} + +func SetupTearDown(t *testing.T) (func(), *HomeAssistant) { loggertearDown := loggerSetupTeardown() + mockTicktick := &MockTicktickUtil{} + ha := NewHomeAssistant(mockTicktick) return func() { loggertearDown() - } + viper.Reset() + }, ha } func loggerSetupTeardown() func() { @@ -36,20 +66,20 @@ func loggerSetupTeardown() func() { } func TestHandleHaMessageJsonDecodeError(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }` req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody)) w := httptest.NewRecorder() - HandleHaMessage(w, req) - assert.Equal(t, http.StatusBadRequest, w.Code) - assert.Contains(t, loggerText.String(), "HandleHaMessage: Error decoding request body") + ha.HandleHaMessage(w, req) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Error decoding request body") } func TestHandlePooRecorderMsgGetLatest(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) @@ -62,26 +92,26 @@ func TestHandlePooRecorderMsgGetLatest(t *testing.T) { port := strings.Split(server.URL, ":")[2] viper.Set("port", port) - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Empty(t, loggerText.String()) } func TestHandlePooRecorderMsgUnknownAction(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}` req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) w := httptest.NewRecorder() - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusInternalServerError, w.Code) - assert.Contains(t, loggerText.String(), "handlePooRecorderMsg: Unknown action") + assert.Contains(t, loggerText.String(), "homeassistant.handlePooRecorderMsg: Unknown action") } func TestHandlePooRecorderMsgGetLatestError(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` @@ -91,13 +121,13 @@ func TestHandlePooRecorderMsgGetLatestError(t *testing.T) { port := "invalid port" viper.Set("port", port) - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusInternalServerError, w.Code) - assert.Contains(t, loggerText.String(), "handleGetLatestPoo: Error sending request to poo recorder") + assert.Contains(t, loggerText.String(), "homeassistant.handleGetLatestPoo: Error sending request to poo recorder") } func TestHandleLocationRecorderMsg(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` @@ -113,26 +143,26 @@ func TestHandleLocationRecorderMsg(t *testing.T) { port := strings.Split(server.URL, ":")[2] viper.Set("port", port) - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Empty(t, loggerText.String()) } func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}` req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) w := httptest.NewRecorder() - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusInternalServerError, w.Code) - assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Unknown action") + assert.Contains(t, loggerText.String(), "homeassistant.handleLocationRecorderMsg: Unknown action") } func TestHandleLocationRecorderMsgRequestErr(t *testing.T) { - teardown := SetupTearDown(t) + teardown, ha := SetupTearDown(t) defer teardown() requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` @@ -142,7 +172,109 @@ func TestHandleLocationRecorderMsgRequestErr(t *testing.T) { port := "invalid port" viper.Set("port", port) - HandleHaMessage(w, req) + ha.HandleHaMessage(w, req) assert.Equal(t, http.StatusInternalServerError, w.Code) - assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Error sending request to location recorder") + assert.Contains(t, loggerText.String(), "homeassistant.handleLocationRecorderMsg: Error sending request to location recorder") +} + +func TestHandleTicktickMsgCreateActionTask(t *testing.T) { + teardown, _ := SetupTearDown(t) + defer teardown() + const expectedProjectId = "test_project_id" + const dueHour = 12 + due := time.Now().Add(time.Hour * time.Duration(dueHour)) + dueNextMidnight := time.Date(due.Year(), due.Month(), due.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, 1) + dueTicktick := dueNextMidnight.UTC().Format(ticktickutil.DateTimeLayout) + + requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) + w := httptest.NewRecorder() + + mockTicktick := &MockTicktickUtil{} + mockTicktick.On("CreateTask", mock.Anything).Return(nil) + ha := NewHomeAssistant(mockTicktick) + viper.Set("homeassistant.actionTaskProjectId", expectedProjectId) + ha.HandleHaMessage(w, req) + expectedTask := ticktickutil.Task{ + Title: "test_action", + DueDate: dueTicktick, + ProjectId: expectedProjectId, + } + mockTicktick.AssertCalled(t, "CreateTask", expectedTask) + mockTicktick.AssertNumberOfCalls(t, "CreateTask", 1) + assert.Equal(t, http.StatusOK, w.Code) + assert.Empty(t, loggerText.String()) +} + +func TestHandleTicktickMsgUnknownAction(t *testing.T) { + teardown, ha := SetupTearDown(t) + defer teardown() + + requestBody := `{"target": "ticktick", "action": "unknown_action", "content": ""}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) + w := httptest.NewRecorder() + + ha.HandleHaMessage(w, req) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.handleTicktickMsg: Unknown action") +} + +func TestHandleTicktickMsgProjectIdUnset(t *testing.T) { + teardown, ha := SetupTearDown(t) + defer teardown() + + requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) + w := httptest.NewRecorder() + + ha.HandleHaMessage(w, req) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.createActionTask: actionTaskProjectId not found in config file") +} + +func TestHandleTicktickMsgJsonError(t *testing.T) { + teardown, ha := SetupTearDown(t) + defer teardown() + + invalidRequestBody := ` { "target": "ticktick", "action": "create_action_task", "content": "{'title': 'tes, 'action': 'test_action', 'due_hour': 12}"}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody)) + w := httptest.NewRecorder() + viper.Set("homeassistant.actionTaskProjectId", "some project id") + ha.HandleHaMessage(w, req) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.createActionTask: Error unmarshalling") +} + +func TestHandleTicktickMsgTicktickUtilErr(t *testing.T) { + teardown, _ := SetupTearDown(t) + defer teardown() + + requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) + w := httptest.NewRecorder() + mockedTicktickUtil := &MockTicktickUtil{} + viper.Set("homeassistant.actionTaskProjectId", "some project id") + + mockedTicktickUtil.On("CreateTask", mock.Anything).Return(errors.New("some error")) + + ha := NewHomeAssistant(mockedTicktickUtil) + + ha.HandleHaMessage(w, req) + + mockedTicktickUtil.AssertCalled(t, "CreateTask", mock.Anything) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.createActionTask: Error creating task") +} + +func TestHandleHaMessageUnknownTarget(t *testing.T) { + teardown, ha := SetupTearDown(t) + defer teardown() + + requestBody := `{"target": "unknown_target", "action": "record", "content": ""}` + req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) + w := httptest.NewRecorder() + + ha.HandleHaMessage(w, req) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Unknown target") } diff --git a/src/go.mod b/src/go.mod index a85caf1..33aa41a 100644 --- a/src/go.mod +++ b/src/go.mod @@ -8,7 +8,7 @@ require ( github.com/jomei/notionapi v1.13.2 github.com/spf13/cobra v1.8.1 github.com/spf13/viper v1.19.0 - github.com/stretchr/testify v1.9.0 + github.com/stretchr/testify v1.10.0 golang.org/x/term v0.24.0 modernc.org/sqlite v1.33.1 ) @@ -36,6 +36,7 @@ require ( github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.6.0 // indirect github.com/spf13/pflag v1.0.5 // indirect + github.com/stretchr/objx v0.5.2 // indirect github.com/subosito/gotenv v1.6.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.9.0 // indirect diff --git a/src/go.sum b/src/go.sum index 31842a7..27cceef 100644 --- a/src/go.sum +++ b/src/go.sum @@ -72,13 +72,15 @@ github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= diff --git a/src/util/ticktickutil/ticktickutil.go b/src/util/ticktickutil/ticktickutil.go index c1e57e8..23b1627 100644 --- a/src/util/ticktickutil/ticktickutil.go +++ b/src/util/ticktickutil/ticktickutil.go @@ -78,7 +78,7 @@ type ( } ) -func Init() *TicktickUtilImpl { // TODO: Will modify Init to a proper behavior +func Init() TicktickUtil { // TODO: Will modify Init to a proper behavior ticktickUtilImpl := &TicktickUtilImpl{} if !viper.InConfig("ticktick.clientId") { slog.Error("TickTick clientId not found in config file, exiting..")