Last active
March 15, 2022 14:01
-
-
Save endorama/315c4e9a9279d4701d58c1fd39d82a61 to your computer and use it in GitHub Desktop.
Golang time testing pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package str | |
func UnixTimestamp() int64 { | |
return time.Now().Unix() | |
} | |
type FragmentCreator struct { | |
slug string | |
// timeNowUnix is only used in testing to override getting the current timestamp | |
timestamp func() int64 | |
} | |
func (f FragmentCreator) filename() string { | |
filename := fmt.Sprintf("%d-%s.yaml", f.timestamp(), f.slug) | |
return filename | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package str | |
func TestFilename(t *testing.T) { | |
fc := FragmentCreator{ | |
slug: "foobar", | |
timestamp: func() int64 { return 1647345675 }, | |
} | |
expected := "1647345675-foobar.yaml" | |
got := fc.filename() | |
assert.Equal(t, expected, got) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package vr | |
type FragmentCreator struct { | |
slug string | |
} | |
var timeNowUnix = time.Now().Unix | |
func filename(fc FragmentCreator) string { | |
t := timeNowUnix() | |
filename := fmt.Sprintf("%d-%s.yaml", t, fc.slug) | |
return filename | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package vr | |
func TestFilename(t *testing.T) { | |
fc := FragmentCreator{ | |
slug: "foobar" | |
} | |
timeNowUnix = func() int64 { | |
return 1647345675 | |
} | |
expected := "1647345675-foobar.yaml" | |
got := filename(fc) | |
assert.Equal(t, expected, got) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment