Skip to content

Commit

Permalink
Correct parseTime; Improve test
Browse files Browse the repository at this point in the history
  • Loading branch information
robinbraemer committed Feb 1, 2023
1 parent 4cc7bed commit 7dff20a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
2 changes: 1 addition & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var timeNow = time.Now
func parseTime(unixMillis string) time.Time {
now := timeNow()
ms, err := strconv.ParseInt(unixMillis, 10, 64)
if err != nil {
if err == nil {
unix := time.UnixMilli(ms)
// some vote sites don't sent a timestamp,
// fallback to now if older than 1 hour
Expand Down
47 changes: 27 additions & 20 deletions util_test.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,45 @@
package votifier

import (
"strconv"
"testing"
"time"
)

func TestParseTime(t *testing.T) {
now := time.Now()
timeNow = func() time.Time { return now }

t.Run("valid", func(t *testing.T) {
unixMillis := "1609459200000"
expected := now
result := parseTime(unixMillis)
if !result.Equal(expected) {
t.Errorf("Expected %v, got %v", expected, result)

t.Run("Valid Unix Millis", func(t *testing.T) {
unixMillis := strconv.FormatInt(now.UnixMilli(), 10)
parsedTime := parseTime(unixMillis)
expectedTime := now.UnixMilli()
actualTime := parsedTime.UnixMilli()

if expectedTime != actualTime {
t.Errorf("Expected %v, but got %v", expectedTime, actualTime)
}
})

t.Run("invalid", func(t *testing.T) {
unixMillis := "" // invalid
expected := now
result := parseTime(unixMillis)
if !result.Equal(expected) {
t.Errorf("Expected %v, got %v", expected, result)
t.Run("Invalid Unix Millis", func(t *testing.T) {
unixMillis := "invalid"
parsedTime := parseTime(unixMillis)
expectedTime := now.UnixMilli()
actualTime := parsedTime.UnixMilli()

if expectedTime != actualTime {
t.Errorf("Expected %v, but got %v", expectedTime, actualTime)
}
})

t.Run("older than 1 hour", func(t *testing.T) {
unixMillis := "0"
expected := now
result := parseTime(unixMillis)
if !result.Equal(expected) {
t.Errorf("Expected %v, got %v", expected, result)
t.Run("Older than 1 hour", func(t *testing.T) {
oneHourAgo := now.Add(-2 * time.Hour)
unixMillis := strconv.FormatInt(oneHourAgo.UnixMilli(), 10)
parsedTime := parseTime(unixMillis)
expectedTime := now.UnixMilli()
actualTime := parsedTime.UnixMilli()

if expectedTime != actualTime {
t.Errorf("Expected %v, but got %v", expectedTime, actualTime)
}
})
}

0 comments on commit 7dff20a

Please sign in to comment.