Skip to content

Commit 7117a5e

Browse files
committed
tests: Playing with Carbon Default is dangerous.
These variable are global. It has consequences. People launching tests another timezone where facing random issues. It was random because the tests are launched in different order on each run. This was hidden by the CI forcing the timezone to PRC, and impossible to see by someone working in PRC timezone.
1 parent b6f786d commit 7117a5e

File tree

4 files changed

+26
-0
lines changed

4 files changed

+26
-0
lines changed

database_unit_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,8 @@ func TestCarbon_Issue240(t *testing.T) {
913913

914914
// https://github.com/dromara/carbon/issues/243
915915
func TestCarbon_Issue243(t *testing.T) {
916+
prepareTest(t)
917+
916918
SetDefault(Default{
917919
Layout: DateTimeLayout,
918920
Timezone: PRC,

default_bench_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package carbon
33
import "testing"
44

55
func BenchmarkCarbon_SetDefault(b *testing.B) {
6+
prepareTest(b)
7+
68
d := Default{
79
Layout: DateTimeLayout,
810
Timezone: Local,

default_unit_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
)
88

99
func TestCarbon_SetDefault(t *testing.T) {
10+
prepareTest(t)
11+
1012
SetDefault(Default{
1113
Layout: DateTimeLayout,
1214
Timezone: PRC,

test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package carbon
22

3+
import (
4+
"testing"
5+
)
6+
37
// SetTestNow sets a test Carbon instance (real or mock) to be returned when a "now" instance is created.
48
// 设置当前测试时间
59
func (c *Carbon) SetTestNow(carbon Carbon) {
@@ -17,3 +21,19 @@ func (c *Carbon) UnSetTestNow() {
1721
func (c Carbon) IsSetTestNow() bool {
1822
return c.testNow > 0
1923
}
24+
25+
func prepareTest(tb testing.TB) {
26+
tb.Helper()
27+
28+
// Store the current default
29+
savedDefault := Default{
30+
Layout: defaultLayout,
31+
Timezone: defaultTimezone,
32+
Locale: defaultLocale,
33+
WeekStartsAt: defaultWeekStartsAt,
34+
}
35+
tb.Cleanup(func() {
36+
// restore the default when test is done
37+
SetDefault(savedDefault)
38+
})
39+
}

0 commit comments

Comments
 (0)