From f02769d3ce49c6aa278642bdd09bd12276f6a6d7 Mon Sep 17 00:00:00 2001 From: Robson Cruz Date: Fri, 10 Nov 2023 18:31:00 -0300 Subject: [PATCH] test(utils_test.go): add test cases for `FetchEntriesByWeekDate` function --- internal/utils_test.go | 47 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/internal/utils_test.go b/internal/utils_test.go index 5d1ae9d..3275ff4 100644 --- a/internal/utils_test.go +++ b/internal/utils_test.go @@ -3,6 +3,7 @@ package journal import ( "strconv" "testing" + "time" ) func TestFindEntryByID(t *testing.T) { @@ -57,6 +58,52 @@ func TestFindEntryByID(t *testing.T) { } } +func TestFetchEntriesByWeek(t *testing.T) { + currentDate := time.Now() + currYear, currWeek := currentDate.ISOWeek() + + entries := []JournalEntry{ + {ID: "1", StartTime: time.Now().AddDate(0, 0, -7), Notes: []string{"Note 1", "Note 2"}}, // Entry from one week ago + {ID: "2", StartTime: time.Now(), Notes: []string{"Note 3", "Note 4"}}, // Entry for today + {ID: "3", StartTime: time.Now().AddDate(0, 0, 7), Notes: []string{"Note 5", "Note 6"}}, // Entry for next week + } + + testCases := []struct { + name string + entries []JournalEntry + expectedErr string + expectedResult []JournalEntry + }{ + {name: "When passing an empty slice function returns an error", entries: []JournalEntry{}, expectedErr: "No entries were passed", expectedResult: nil}, + {name: "When passing a slice with no date in current week returns an error", entries: entries[:1], expectedErr: "No entries found for the current week", expectedResult: nil}, + {name: "When passing a slice with entries in current week returns filtered slice with no errors", entries: entries, expectedErr: "", expectedResult: []JournalEntry{entries[1]}}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result, err := FetchEntriesByWeekDate(tc.entries, currentDate) + // If we expcted a nil result, but a non nil error + if tc.expectedResult == nil && err == nil { + t.Errorf("Expected an error, but got none") + } + // If the err is not nil, but the message does not match + if err != nil && err.Error() != tc.expectedErr { + t.Errorf("Expected error: %s, but got %s", tc.expectedErr, err.Error()) + } + // If the result is not nil, context should match expectation + if result != nil { + resultYear, resultWeek := result[0].StartTime.ISOWeek() + if len(result) != len(tc.expectedResult) { + t.Errorf("Expected result to be %v, got %v", tc.expectedResult, result) + } + if resultYear != currYear || resultWeek != currWeek { + t.Errorf("The resulting entries are not from the current week") + } + } + }) + } +} + func BenchmarkFetchEntryByID(b *testing.B) { // Setup entries for benchmark entries := make([]JournalEntry, 1e6)