Skip to content

Commit

Permalink
test(utils_test.go): add test cases for FetchEntriesByWeekDate func…
Browse files Browse the repository at this point in the history
…tion
deadpyxel committed Nov 10, 2023
1 parent de2e55e commit f02769d
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions internal/utils_test.go
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit f02769d

Please sign in to comment.