46 Commits

Author SHA1 Message Date
959bd79d1a see if i get token correctly to config
All checks were successful
Run nightly tests / build (push) Successful in 34s
Run nightly tests / nightly-tests-play (push) Successful in 15s
Run short tests / run-tests (push) Successful in 1m17s
2025-05-24 13:50:28 +02:00
1290bdb0fa token not printed yet
All checks were successful
Run nightly tests / build (push) Successful in 37s
Run nightly tests / nightly-tests-play (push) Successful in 37s
Run short tests / run-tests (push) Successful in 1m19s
2025-05-24 13:06:35 +02:00
23df98f586 try if token is readable
All checks were successful
Run nightly tests / build (push) Successful in 1m25s
Run nightly tests / nightly-tests-play (push) Successful in 17s
Run short tests / run-tests (push) Successful in 1m57s
2025-05-24 13:04:02 +02:00
6d4ad23abb Use tee
Some checks failed
Run nightly tests / build (push) Successful in 1m13s
Run short tests / run-tests (push) Successful in 1m41s
Run nightly tests / nightly-tests-play (push) Failing after 34s
2025-05-23 12:30:03 +02:00
8205232db3 I dont understand why hosts not take effect
Some checks failed
Run nightly tests / build (push) Successful in 1m16s
Run short tests / run-tests (push) Successful in 1m40s
Run nightly tests / nightly-tests-play (push) Failing after 33s
2025-05-23 12:27:47 +02:00
c1d56f8ee0 echo needs -e to pass linefeed
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m15s
Run nightly tests / nightly-tests-play (push) Failing after 45s
2025-05-23 12:24:54 +02:00
cf5a47ed4a try if host format is correct or not
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m16s
Run nightly tests / nightly-tests-play (push) Failing after 46s
2025-05-23 12:21:35 +02:00
63cec9b9d8 host not found either, install it and try
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m17s
Run nightly tests / nightly-tests-play (push) Failing after 33s
2025-05-23 12:14:58 +02:00
909b45b51e ping not permitted, use host instead
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m41s
Run nightly tests / nightly-tests-play (push) Failing after 26s
2025-05-23 12:12:20 +02:00
2d529b1f1c doesnt have ping yet, needs to install
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m40s
Run nightly tests / nightly-tests-play (push) Failing after 31s
2025-05-23 12:08:21 +02:00
f3dfae6e12 let's check the ip returned by new hosts
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m38s
Run nightly tests / nightly-tests-play (push) Failing after 41s
2025-05-23 12:05:43 +02:00
6900be6904 while loop hangs the flow, will use background
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m37s
Run nightly tests / nightly-tests-play (push) Failing after 41s
2025-05-23 12:02:39 +02:00
ab0be6ea45 workflow run hangs, modify version
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Has been cancelled
2025-05-23 11:59:21 +02:00
daaf79e721 Looks like need to use netcat-openbsd
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m17s
Run nightly tests / nightly-tests-play (push) Has been cancelled
2025-05-23 11:55:25 +02:00
482f23912c nc not there, install first
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m15s
Run nightly tests / nightly-tests-play (push) Failing after 38s
2025-05-23 11:52:02 +02:00
a8ac1e359d See if modifying host is working
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Failing after 15s
2025-05-23 11:49:21 +02:00
8438944f8a Needs to +x permission of executable
All checks were successful
Run nightly tests / build (push) Successful in 1m14s
Run short tests / run-tests (push) Successful in 1m36s
Run nightly tests / nightly-tests-play (push) Successful in 17s
Run nightly tests / nightly-tests (push) Successful in 37s
2025-05-23 11:43:01 +02:00
175e3e36a7 Upload with use a nother version of github workspace
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m16s
Run nightly tests / nightly-tests-play (push) Failing after 32s
Run nightly tests / nightly-tests (push) Successful in 34s
2025-05-23 11:40:23 +02:00
05381bde3a Test with help message
Some checks failed
Run nightly tests / build (push) Successful in 1m10s
Run short tests / run-tests (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Failing after 16s
Run nightly tests / nightly-tests (push) Failing after 36s
2025-05-23 11:38:31 +02:00
ab53a7dc71 Check workspace location
All checks were successful
Run short tests / run-tests (push) Successful in 1m19s
Run nightly tests / build (push) Successful in 1m19s
Run nightly tests / nightly-tests-play (push) Successful in 18s
Run nightly tests / nightly-tests (push) Successful in 34s
2025-05-23 11:35:49 +02:00
d9264885ab Change location
Some checks failed
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / build (push) Successful in 1m37s
Run nightly tests / nightly-tests-play (push) Failing after 37s
Run nightly tests / nightly-tests (push) Successful in 25s
2025-05-23 11:33:04 +02:00
cb3f1ee9fd Test download artifacts and print message
Some checks failed
Run nightly tests / build (push) Successful in 1m41s
Run short tests / run-tests (push) Successful in 1m33s
Run nightly tests / nightly-tests-play (push) Failing after 36s
Run nightly tests / nightly-tests (push) Successful in 40s
2025-05-23 11:29:44 +02:00
6c4be53f4b Add second step
All checks were successful
Run short tests / run-tests (push) Successful in 1m11s
Run nightly tests / build (push) Successful in 1m45s
Run nightly tests / nightly-tests (push) Successful in 42s
2025-05-21 20:30:55 +02:00
85e4863f12 try another one
All checks were successful
Run short tests / run-tests (push) Successful in 1m16s
Run nightly tests / build (push) Successful in 1m39s
2025-05-21 20:28:03 +02:00
a0c5a92bb9 looks like path is not correct
All checks were successful
Run short tests / run-tests (push) Successful in 1m22s
Run nightly tests / build (push) Successful in 1m41s
2025-05-21 20:12:53 +02:00
439f7e64bd paths should be path
All checks were successful
Run short tests / run-tests (push) Successful in 1m23s
Run nightly tests / build (push) Successful in 1m34s
2025-05-21 20:09:15 +02:00
61a544ca29 Lets see if we can upload artifacts
Some checks failed
Run short tests / run-tests (push) Successful in 1m21s
Run nightly tests / build (push) Failing after 1m48s
2025-05-21 20:07:09 +02:00
5348d2a8f4 Add ls lr to see where is the artifactory
All checks were successful
Run short tests / run-tests (push) Successful in 1m23s
Run nightly tests / build (push) Successful in 1m27s
2025-05-21 20:04:17 +02:00
14e589f2ee add working directory should work
All checks were successful
Run short tests / run-tests (push) Successful in 1m21s
Run nightly tests / build (push) Successful in 1m30s
2025-05-21 20:01:40 +02:00
e1a9f24d2b pwd
Some checks failed
Run nightly tests / build (push) Successful in 35s
Run short tests / run-tests (push) Has been cancelled
2025-05-21 20:01:05 +02:00
69c6d2fd3f try build
Some checks failed
Run nightly tests / build (push) Failing after 35s
Run short tests / run-tests (push) Successful in 1m23s
2025-05-21 19:59:11 +02:00
f288b32092 will try
Some checks failed
Run nightly tests / nightly-tests (push) Failing after 38s
Run short tests / run-tests (push) Successful in 1m22s
2025-05-21 19:57:33 +02:00
06606ca06c try build
Some checks failed
Run short tests / run-tests (push) Has been cancelled
2025-05-21 19:56:54 +02:00
8df89d3478 schedule looks good now, run at 20 utc, so 21 cest.
All checks were successful
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / nightly-tests (push) Successful in 1m50s
2025-05-21 14:51:24 +02:00
f97841b079 print working see with checkout
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / nightly-tests (push) Successful in 1m40s
2025-05-21 14:41:44 +02:00
17d2f4d1f5 test cron
All checks were successful
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / test-cron-job (push) Successful in 30s
2025-05-21 14:38:05 +02:00
1aa6c7dac4 test cron at 1430
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / run-tests (push) Successful in 1m41s
2025-05-21 14:24:22 +02:00
da5bf43197 add push to main
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / run-tests (push) Successful in 1m40s
2025-05-21 10:52:29 +02:00
0d803f4b23 add nightly cron at 0am
All checks were successful
Run short tests / run-tests (push) Successful in 1m38s
2025-05-20 15:22:30 +02:00
fc4e0217b2 check if lable works
All checks were successful
Run short tests / run-tests (push) Successful in 1m13s
Run nightly tests / run-tests (push) Successful in 1m36s
2025-05-20 15:20:07 +02:00
d4db20be16 add nightly test template
Some checks failed
Run nightly tests / run-tests (push) Failing after 13s
Run short tests / run-tests (push) Has been cancelled
2025-05-20 15:19:16 +02:00
1041016210 Revert "change runner to linux"
Some checks failed
Run short tests / run-tests (push) Has been cancelled
This reverts commit 99ed529600.
2025-05-20 15:18:18 +02:00
99ed529600 change runner to linux
Some checks failed
Run short tests / run-tests (push) Failing after 12s
2025-05-20 15:16:58 +02:00
f02bb1e6fb Merge pull request 'feature/refactoring' (#1) from feature/refactoring into master
All checks were successful
Run short tests / run-tests (push) Successful in 1m58s
Reviewed-on: https://code.jamesvillage.dev/tliu93/home-automation-backend/pulls/1
2025-05-19 22:28:40 +02:00
ccb70e3165 Use struct, idomatic go way to write homeassistant component and make it 100 test covered
All checks were successful
Run short tests / run-tests (push) Successful in 1m2s
Run short tests / run-tests (pull_request) Successful in 1m2s
2025-05-19 22:20:05 +02:00
0a76c5feca wip 2025-05-19 20:25:53 +02:00
7 changed files with 281 additions and 62 deletions

70
.github/workflows/nightly.yml vendored Normal file
View File

@@ -0,0 +1,70 @@
name: Run nightly tests
on:
workflow_dispatch:
schedule:
- cron: '0 20 * * *' # Every day at 20:00 UTC
push:
jobs:
build:
runs-on: [ubuntu-latest, cloud]
steps:
- uses: actions/checkout@v4
# - name: Set up Go
# uses: actions/setup-go@v4
# with:
# go-version: '1.23'
# - name: build
# working-directory: ./src
# run: |
# go build
# - name: Upload artifacts
# uses: actions/upload-artifact@v3
# with:
# path: ${{ github.workspace }}/src/home-automation-backend
# name: home-automation-backend_build_${{ github.run_number }}
# retention-days: 1
nightly-tests-play:
runs-on: [ubuntu-latest, cloud]
needs: build
steps:
- name: Put token into config file
run: |
cat <<EOF > ${GITHUB_WORKSPACE}/config.json
{
"token": "${{ secrets.TEST_TOKEN }}"
}
EOF
- name: print config file
run: cat ${GITHUB_WORKSPACE}/config.json
# - name: Download artifacts
# uses: actions/download-artifact@v3
# with:
# name: home-automation-backend_build_${{ github.run_number }}
# - name: Print helping message
# run: |
# chmod +x ${GITHUB_WORKSPACE}/home-automation-backend
# ${GITHUB_WORKSPACE}/home-automation-backend help
# nightly-tests:
# runs-on: [ubuntu-latest, cloud]
# needs: build
# steps:
# - uses: actions/checkout@v4
# - name: Download artifacts
# uses: actions/download-artifact@v3
# with:
# name: home-automation-backend_build_${{ github.run_number }}
# - name: Check files
# run: ls -lR
# - name: Set up Go
# uses: actions/setup-go@v4
# with:
# go-version: '1.23'
# - name: build
# run: go build
# - name: Run nightly tests
# working-directory: ./tests
# run: go test -v --short ./...

View File

@@ -27,7 +27,8 @@ import (
var ( var (
port string port string
scheduler gocron.Scheduler scheduler gocron.Scheduler
ticktick *ticktickutil.TicktickUtilImpl ticktick ticktickutil.TicktickUtil
ha *homeassistant.HomeAssistant
) )
// serveCmd represents the serve command // serveCmd represents the serve command
@@ -55,7 +56,7 @@ func initComponent() {
// init location recorder // init location recorder
locationRecorder.Init() locationRecorder.Init()
// init homeassistant // init homeassistant
homeassistant.Init(ticktick) ha = homeassistant.NewHomeAssistant(ticktick)
} }
func serve(cmd *cobra.Command, args []string) { 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/latest", pooRecorder.HandleNotifyLatestPoo).Methods("GET")
router.HandleFunc("/poo/record", pooRecorder.HandleRecordPoo).Methods("POST") 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") router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST")

View File

@@ -18,60 +18,68 @@ type haMessage struct {
Content string `json:"content"` Content string `json:"content"`
} }
type HomeAssistant struct {
ticktickUtil ticktickutil.TicktickUtil
}
type actionTask struct { type actionTask struct {
Action string `json:"action"` Action string `json:"action"`
DueHour int `json:"due_hour"` DueHour int `json:"due_hour"`
} }
var ( func NewHomeAssistant(ticktick ticktickutil.TicktickUtil) *HomeAssistant {
ticktickUtil ticktickutil.TicktickUtil return &HomeAssistant{
) ticktickUtil: ticktick,
}
func Init(ticktick ticktickutil.TicktickUtil) {
ticktickUtil = ticktick
} }
func HandleHaMessage(w http.ResponseWriter, r *http.Request) { func (ha *HomeAssistant) HandleHaMessage(w http.ResponseWriter, r *http.Request) {
var message haMessage var message haMessage
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields() decoder.DisallowUnknownFields()
err := decoder.Decode(&message) err := decoder.Decode(&message)
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("HandleHaMessage: Error decoding request body", err)) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error decoding request body", err))
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, "", http.StatusInternalServerError)
return return
} }
switch message.Target { switch message.Target {
case "poo_recorder": case "poo_recorder":
res := handlePooRecorderMsg(message) res := ha.handlePooRecorderMsg(message)
if !res { 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": case "location_recorder":
res := handleLocationRecorderMsg(message) res := ha.handleLocationRecorderMsg(message)
if !res { 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": 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: default:
slog.Warn(fmt.Sprintln("HandleHaMessage Unknown target", message.Target)) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Unknown target", message.Target))
http.Error(w, "Unknown target", http.StatusBadRequest) http.Error(w, "", http.StatusInternalServerError)
} }
} }
func handlePooRecorderMsg(message haMessage) bool { func (ha *HomeAssistant) handlePooRecorderMsg(message haMessage) bool {
switch message.Action { switch message.Action {
case "get_latest": case "get_latest":
return handleGetLatestPoo() return ha.handleGetLatestPoo()
default: default:
slog.Warn(fmt.Sprintln("handlePooRecorderMsg: Unknown action", message.Action)) slog.Warn(fmt.Sprintln("homeassistant.handlePooRecorderMsg: Unknown action", message.Action))
return false return false
} }
} }
func handleLocationRecorderMsg(message haMessage) bool { func (ha *HomeAssistant) handleLocationRecorderMsg(message haMessage) bool {
if message.Action == "record" { if message.Action == "record" {
port := viper.GetString("port") port := viper.GetString("port")
client := &http.Client{ 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, "'", "\""))) _, err := client.Post("http://localhost:"+port+"/location/record", "application/json", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\"")))
if err != nil { 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 return false
} }
} else { } else {
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Unknown action", message.Action)) slog.Warn(fmt.Sprintln("homeassistant.handleLocationRecorderMsg: Unknown action", message.Action))
return false return false
} }
return true return true
} }
func handleTicktickMsg(message haMessage) { func (ha *HomeAssistant) handleTicktickMsg(message haMessage) bool {
switch message.Action { switch message.Action {
case "create_action_task": 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{ client := &http.Client{
Timeout: time.Second * 1, Timeout: time.Second * 1,
} }
port := viper.GetString("port") port := viper.GetString("port")
_, err := client.Get("http://localhost:" + port + "/poo/latest") _, err := client.Get("http://localhost:" + port + "/poo/latest")
if err != nil { 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 false
} }
return true return true
} }
func createActionTask(message haMessage) { func (ha *HomeAssistant) createActionTask(message haMessage) bool {
if !viper.InConfig("homeassistant.actionTaskProjectId") { if !viper.IsSet("homeassistant.actionTaskProjectId") {
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file") slog.Warn("homeassistant.createActionTask: actionTaskProjectId not found in config file")
return return false
} }
projectId := viper.GetString("homeassistant.actionTaskProjectId") projectId := viper.GetString("homeassistant.actionTaskProjectId")
detail := strings.ReplaceAll(message.Content, "'", "\"") detail := strings.ReplaceAll(message.Content, "'", "\"")
var task actionTask var task actionTask
err := json.Unmarshal([]byte(detail), &task) err := json.Unmarshal([]byte(detail), &task)
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("Homeassistant.createActionTask Error unmarshalling", err)) slog.Warn(fmt.Sprintln("homeassistant.createActionTask: Error unmarshalling", err))
return return false
} }
dueHour := task.DueHour dueHour := task.DueHour
due := time.Now().Add(time.Hour * time.Duration(dueHour)) due := time.Now().Add(time.Hour * time.Duration(dueHour))
@@ -132,8 +143,10 @@ func createActionTask(message haMessage) {
Title: task.Action, Title: task.Action,
DueDate: dueTicktick, DueDate: dueTicktick,
} }
err = ticktickUtil.CreateTask(ticktickTask) err = ha.ticktickUtil.CreateTask(ticktickTask)
if err != nil { 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
} }

View File

@@ -2,26 +2,56 @@ package homeassistant
import ( import (
"bytes" "bytes"
"errors"
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"testing" "testing"
"time"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
) )
var ( var (
loggerText = new(bytes.Buffer) 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() loggertearDown := loggerSetupTeardown()
mockTicktick := &MockTicktickUtil{}
ha := NewHomeAssistant(mockTicktick)
return func() { return func() {
loggertearDown() loggertearDown()
} viper.Reset()
}, ha
} }
func loggerSetupTeardown() func() { func loggerSetupTeardown() func() {
@@ -36,20 +66,20 @@ func loggerSetupTeardown() func() {
} }
func TestHandleHaMessageJsonDecodeError(t *testing.T) { func TestHandleHaMessageJsonDecodeError(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }` invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "HandleHaMessage: Error decoding request body") assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Error decoding request body")
} }
func TestHandlePooRecorderMsgGetLatest(t *testing.T) { func TestHandlePooRecorderMsgGetLatest(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) 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] port := strings.Split(server.URL, ":")[2]
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String()) assert.Empty(t, loggerText.String())
} }
func TestHandlePooRecorderMsgUnknownAction(t *testing.T) { func TestHandlePooRecorderMsgUnknownAction(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) 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) { func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
@@ -91,13 +121,13 @@ func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
port := "invalid port" port := "invalid port"
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) 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) { func TestHandleLocationRecorderMsg(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` 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] port := strings.Split(server.URL, ":")[2]
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String()) assert.Empty(t, loggerText.String())
} }
func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) { func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}` requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) 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) { func TestHandleLocationRecorderMsgRequestErr(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` 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" port := "invalid port"
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) 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")
} }

View File

@@ -8,7 +8,7 @@ require (
github.com/jomei/notionapi v1.13.2 github.com/jomei/notionapi v1.13.2
github.com/spf13/cobra v1.8.1 github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0 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 golang.org/x/term v0.24.0
modernc.org/sqlite v1.33.1 modernc.org/sqlite v1.33.1
) )
@@ -36,6 +36,7 @@ require (
github.com/spf13/afero v1.11.0 // indirect github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // 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 github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect go.uber.org/multierr v1.9.0 // indirect

View File

@@ -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.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.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.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/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.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.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.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.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.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 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=

View File

@@ -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{} ticktickUtilImpl := &TicktickUtilImpl{}
if !viper.InConfig("ticktick.clientId") { if !viper.InConfig("ticktick.clientId") {
slog.Error("TickTick clientId not found in config file, exiting..") slog.Error("TickTick clientId not found in config file, exiting..")