1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
|
package handlers
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"task-dashboard/internal/api"
"task-dashboard/internal/config"
"task-dashboard/internal/models"
"task-dashboard/internal/store"
)
// setupTestDB creates a temporary test database
func setupTestDB(t *testing.T) (*store.Store, func()) {
t.Helper()
// Create temp database file
tmpFile, err := os.CreateTemp("", "test_*.db")
if err != nil {
t.Fatalf("Failed to create temp db: %v", err)
}
tmpFile.Close()
// Save current directory and change to project root
// This ensures migrations can be found
originalDir, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
// Change to project root (2 levels up from internal/handlers)
if err := os.Chdir("../../"); err != nil {
t.Fatalf("Failed to change to project root: %v", err)
}
// Initialize store (this runs migrations)
db, err := store.New(tmpFile.Name(), "migrations")
if err != nil {
os.Chdir(originalDir)
os.Remove(tmpFile.Name())
t.Fatalf("Failed to initialize store: %v", err)
}
// Return to original directory
os.Chdir(originalDir)
// Return cleanup function
cleanup := func() {
db.Close()
os.Remove(tmpFile.Name())
}
return db, cleanup
}
// mockTodoistClient creates a mock Todoist client for testing
type mockTodoistClient struct {
tasks []models.Task
err error
}
func (m *mockTodoistClient) GetTasks(ctx context.Context) ([]models.Task, error) {
if m.err != nil {
return nil, m.err
}
return m.tasks, nil
}
func (m *mockTodoistClient) GetProjects(ctx context.Context) ([]models.Project, error) {
return []models.Project{}, nil
}
func (m *mockTodoistClient) CreateTask(ctx context.Context, content, projectID string, dueDate *time.Time, priority int) (*models.Task, error) {
return nil, nil
}
func (m *mockTodoistClient) UpdateTask(ctx context.Context, taskID string, updates map[string]interface{}) error {
return m.err
}
func (m *mockTodoistClient) CompleteTask(ctx context.Context, taskID string) error {
return nil
}
func (m *mockTodoistClient) Sync(ctx context.Context, syncToken string) (*api.TodoistSyncResponse, error) {
if m.err != nil {
return nil, m.err
}
// Return a mock sync response with tasks converted to sync items
items := make([]api.SyncItemResponse, 0, len(m.tasks))
for _, task := range m.tasks {
items = append(items, api.SyncItemResponse{
ID: task.ID,
Content: task.Content,
Description: task.Description,
ProjectID: task.ProjectID,
Priority: task.Priority,
Labels: task.Labels,
IsCompleted: task.Completed,
IsDeleted: false,
})
}
return &api.TodoistSyncResponse{
SyncToken: "test-sync-token",
FullSync: true,
Items: items,
Projects: []api.SyncProjectResponse{},
}, nil
}
// mockTrelloClient creates a mock Trello client for testing
type mockTrelloClient struct {
boards []models.Board
err error
}
func (m *mockTrelloClient) GetBoardsWithCards(ctx context.Context) ([]models.Board, error) {
if m.err != nil {
return nil, m.err
}
return m.boards, nil
}
func (m *mockTrelloClient) GetBoards(ctx context.Context) ([]models.Board, error) {
if m.err != nil {
return nil, m.err
}
return m.boards, nil
}
func (m *mockTrelloClient) GetCards(ctx context.Context, boardID string) ([]models.Card, error) {
return []models.Card{}, nil
}
func (m *mockTrelloClient) GetLists(ctx context.Context, boardID string) ([]models.List, error) {
return []models.List{}, nil
}
func (m *mockTrelloClient) CreateCard(ctx context.Context, listID, name, description string, dueDate *time.Time) (*models.Card, error) {
return nil, nil
}
func (m *mockTrelloClient) UpdateCard(ctx context.Context, cardID string, updates map[string]interface{}) error {
return nil
}
// TestHandleGetTasks tests the HandleGetTasks handler
func TestHandleGetTasks(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Create test tasks
testTasks := []models.Task{
{
ID: "1",
Content: "Test task 1",
Description: "Description 1",
ProjectID: "proj1",
ProjectName: "Project 1",
Priority: 1,
Completed: false,
Labels: []string{"label1"},
URL: "https://todoist.com/task/1",
CreatedAt: time.Now(),
},
{
ID: "2",
Content: "Test task 2",
Description: "Description 2",
ProjectID: "proj2",
ProjectName: "Project 2",
Priority: 2,
Completed: true,
Labels: []string{"label2"},
URL: "https://todoist.com/task/2",
CreatedAt: time.Now(),
},
}
// Save tasks to database
if err := db.SaveTasks(testTasks); err != nil {
t.Fatalf("Failed to save test tasks: %v", err)
}
// Create handler with mock client
cfg := &config.Config{
CacheTTLMinutes: 5,
}
mockTodoist := &mockTodoistClient{}
h := &Handler{
store: db,
todoistClient: mockTodoist,
config: cfg,
}
// Create test request
req := httptest.NewRequest("GET", "/api/tasks", nil)
w := httptest.NewRecorder()
// Execute handler
h.HandleGetTasks(w, req)
// Check response
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Parse response
var tasks []models.Task
if err := json.NewDecoder(w.Body).Decode(&tasks); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Verify tasks
if len(tasks) != 2 {
t.Errorf("Expected 2 tasks, got %d", len(tasks))
}
}
// TestHandleGetBoards tests the HandleGetBoards handler
func TestHandleGetBoards(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Create test boards
testBoards := []models.Board{
{
ID: "board1",
Name: "Test Board 1",
Cards: []models.Card{
{
ID: "card1",
Name: "Card 1",
ListID: "list1",
ListName: "To Do",
URL: "https://trello.com/c/card1",
},
},
},
{
ID: "board2",
Name: "Test Board 2",
Cards: []models.Card{
{
ID: "card2",
Name: "Card 2",
ListID: "list2",
ListName: "Done",
URL: "https://trello.com/c/card2",
},
},
},
}
// Save boards to database
if err := db.SaveBoards(testBoards); err != nil {
t.Fatalf("Failed to save test boards: %v", err)
}
// Create handler
cfg := &config.Config{
CacheTTLMinutes: 5,
}
h := &Handler{
store: db,
trelloClient: &mockTrelloClient{boards: testBoards},
config: cfg,
}
// Create test request
req := httptest.NewRequest("GET", "/api/boards", nil)
w := httptest.NewRecorder()
// Execute handler
h.HandleGetBoards(w, req)
// Check response
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Parse response
var boards []models.Board
if err := json.NewDecoder(w.Body).Decode(&boards); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Verify boards
if len(boards) != 2 {
t.Errorf("Expected 2 boards, got %d", len(boards))
}
// Just verify we got boards back - cards may or may not be populated
// depending on how the store handles the board->card relationship
}
// TestHandleRefresh tests the HandleRefresh handler
func TestHandleRefresh(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Create mock clients
mockTodoist := &mockTodoistClient{
tasks: []models.Task{
{
ID: "1",
Content: "Test task",
},
},
}
mockTrello := &mockTrelloClient{
boards: []models.Board{
{
ID: "board1",
Name: "Test Board",
},
},
}
// Create handler
cfg := &config.Config{
CacheTTLMinutes: 5,
}
h := &Handler{
store: db,
todoistClient: mockTodoist,
trelloClient: mockTrello,
config: cfg,
}
// Create test request
req := httptest.NewRequest("POST", "/api/refresh", nil)
w := httptest.NewRecorder()
// Execute handler
h.HandleRefresh(w, req)
// Check response
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Parse response - check that it returns aggregated data
var response models.DashboardData
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
// If it's not DashboardData, try a success response
t.Log("Response is not DashboardData format, checking alternative format")
}
// Just verify we got a 200 OK - the actual response format can vary
// The important thing is the handler doesn't error
}
// TestHandleGetMeals tests the HandleGetMeals handler
func TestHandleGetMeals(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Test with nil client should return empty array
cfg := &config.Config{
CacheTTLMinutes: 5,
}
h := &Handler{
store: db,
planToEatClient: nil,
config: cfg,
}
req := httptest.NewRequest("GET", "/api/meals", nil)
w := httptest.NewRecorder()
h.HandleGetMeals(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var meals []models.Meal
if err := json.NewDecoder(w.Body).Decode(&meals); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Handler returns empty array when client is nil
if len(meals) != 0 {
t.Errorf("Expected 0 meals when client is nil, got %d", len(meals))
}
}
// mockTodoistClientWithComplete tracks CompleteTask calls
type mockTodoistClientWithComplete struct {
mockTodoistClient
completedTaskIDs []string
completeErr error
}
func (m *mockTodoistClientWithComplete) CompleteTask(ctx context.Context, taskID string) error {
if m.completeErr != nil {
return m.completeErr
}
m.completedTaskIDs = append(m.completedTaskIDs, taskID)
return nil
}
// mockTrelloClientWithUpdate tracks UpdateCard calls
type mockTrelloClientWithUpdate struct {
mockTrelloClient
updatedCards []string
updateErr error
}
func (m *mockTrelloClientWithUpdate) UpdateCard(ctx context.Context, cardID string, updates map[string]interface{}) error {
if m.updateErr != nil {
return m.updateErr
}
m.updatedCards = append(m.updatedCards, cardID)
return nil
}
// TestHandleCompleteAtom_Todoist tests completing a Todoist task
func TestHandleCompleteAtom_Todoist(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Save a task to the cache
tasks := []models.Task{
{
ID: "task123",
Content: "Test task",
Completed: false,
Labels: []string{},
CreatedAt: time.Now(),
},
}
if err := db.SaveTasks(tasks); err != nil {
t.Fatalf("Failed to save test task: %v", err)
}
// Verify task exists in cache
cachedTasks, _ := db.GetTasks()
if len(cachedTasks) != 1 {
t.Fatalf("Expected 1 task in cache, got %d", len(cachedTasks))
}
// Create handler with mock client
mockTodoist := &mockTodoistClientWithComplete{}
h := &Handler{
store: db,
todoistClient: mockTodoist,
config: &config.Config{},
}
// Create request
req := httptest.NewRequest("POST", "/complete-atom", nil)
req.Form = map[string][]string{
"id": {"task123"},
"source": {"todoist"},
}
w := httptest.NewRecorder()
// Execute handler
h.HandleCompleteAtom(w, req)
// Check response
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Verify CompleteTask was called on the API
if len(mockTodoist.completedTaskIDs) != 1 || mockTodoist.completedTaskIDs[0] != "task123" {
t.Errorf("Expected CompleteTask to be called with 'task123', got %v", mockTodoist.completedTaskIDs)
}
// Verify task was deleted from cache
cachedTasks, _ = db.GetTasks()
if len(cachedTasks) != 0 {
t.Errorf("Expected task to be deleted from cache, but found %d tasks", len(cachedTasks))
}
}
// TestHandleCompleteAtom_Trello tests completing a Trello card
func TestHandleCompleteAtom_Trello(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Save a board with a card to the cache
boards := []models.Board{
{
ID: "board1",
Name: "Test Board",
Cards: []models.Card{
{
ID: "card456",
Name: "Test Card",
ListID: "list1",
ListName: "To Do",
},
},
},
}
if err := db.SaveBoards(boards); err != nil {
t.Fatalf("Failed to save test board: %v", err)
}
// Verify card exists in cache
cachedBoards, _ := db.GetBoards()
if len(cachedBoards) != 1 || len(cachedBoards[0].Cards) != 1 {
t.Fatalf("Expected 1 board with 1 card in cache")
}
// Create handler with mock client
mockTrello := &mockTrelloClientWithUpdate{}
h := &Handler{
store: db,
trelloClient: mockTrello,
config: &config.Config{},
}
// Create request
req := httptest.NewRequest("POST", "/complete-atom", nil)
req.Form = map[string][]string{
"id": {"card456"},
"source": {"trello"},
}
w := httptest.NewRecorder()
// Execute handler
h.HandleCompleteAtom(w, req)
// Check response
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Verify UpdateCard was called on the API
if len(mockTrello.updatedCards) != 1 || mockTrello.updatedCards[0] != "card456" {
t.Errorf("Expected UpdateCard to be called with 'card456', got %v", mockTrello.updatedCards)
}
// Verify card was deleted from cache
cachedBoards, _ = db.GetBoards()
if len(cachedBoards[0].Cards) != 0 {
t.Errorf("Expected card to be deleted from cache, but found %d cards", len(cachedBoards[0].Cards))
}
}
// TestHandleCompleteAtom_MissingParams tests error handling for missing parameters
func TestHandleCompleteAtom_MissingParams(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
h := &Handler{
store: db,
config: &config.Config{},
}
tests := []struct {
name string
id string
source string
}{
{"missing id", "", "todoist"},
{"missing source", "task123", ""},
{"both missing", "", ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "/complete-atom", nil)
req.Form = map[string][]string{
"id": {tc.id},
"source": {tc.source},
}
w := httptest.NewRecorder()
h.HandleCompleteAtom(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400 for %s, got %d", tc.name, w.Code)
}
})
}
}
// TestHandleCompleteAtom_UnknownSource tests error handling for unknown source
func TestHandleCompleteAtom_UnknownSource(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
h := &Handler{
store: db,
config: &config.Config{},
}
req := httptest.NewRequest("POST", "/complete-atom", nil)
req.Form = map[string][]string{
"id": {"task123"},
"source": {"unknown"},
}
w := httptest.NewRecorder()
h.HandleCompleteAtom(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400 for unknown source, got %d", w.Code)
}
}
// TestHandleCompleteAtom_APIError tests that API errors are handled correctly
func TestHandleCompleteAtom_APIError(t *testing.T) {
db, cleanup := setupTestDB(t)
defer cleanup()
// Save a task to the cache
tasks := []models.Task{
{
ID: "task123",
Content: "Test task",
Completed: false,
Labels: []string{},
CreatedAt: time.Now(),
},
}
if err := db.SaveTasks(tasks); err != nil {
t.Fatalf("Failed to save test task: %v", err)
}
// Create handler with mock client that returns an error
mockTodoist := &mockTodoistClientWithComplete{
completeErr: context.DeadlineExceeded,
}
h := &Handler{
store: db,
todoistClient: mockTodoist,
config: &config.Config{},
}
req := httptest.NewRequest("POST", "/complete-atom", nil)
req.Form = map[string][]string{
"id": {"task123"},
"source": {"todoist"},
}
w := httptest.NewRecorder()
h.HandleCompleteAtom(w, req)
// Should return 500 on API error
if w.Code != http.StatusInternalServerError {
t.Errorf("Expected status 500 on API error, got %d", w.Code)
}
// Verify task was NOT deleted from cache (rollback behavior)
cachedTasks, _ := db.GetTasks()
if len(cachedTasks) != 1 {
t.Errorf("Task should NOT be deleted from cache on API error, found %d tasks", len(cachedTasks))
}
}
|