diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ea1563af..990f7aac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,8 +2,6 @@ name: test on: push -env: - TZ: "PRC" jobs: test: diff --git a/database_unit_test.go b/database_unit_test.go index f09f81cd..b12c4bb0 100755 --- a/database_unit_test.go +++ b/database_unit_test.go @@ -915,6 +915,8 @@ func TestCarbon_Issue240(t *testing.T) { // https://github.com/dromara/carbon/issues/243 func TestCarbon_Issue243(t *testing.T) { + prepareTest(t) + SetDefault(Default{ Layout: DateTimeLayout, Timezone: PRC, diff --git a/default_bench_test.go b/default_bench_test.go index d3f4b089..5a0de996 100755 --- a/default_bench_test.go +++ b/default_bench_test.go @@ -3,6 +3,8 @@ package carbon import "testing" func BenchmarkCarbon_SetDefault(b *testing.B) { + prepareTest(b) + d := Default{ Layout: DateTimeLayout, Timezone: Local, diff --git a/default_unit_test.go b/default_unit_test.go index 97b00c20..84963e48 100644 --- a/default_unit_test.go +++ b/default_unit_test.go @@ -7,6 +7,8 @@ import ( ) func TestCarbon_SetDefault(t *testing.T) { + prepareTest(t) + SetDefault(Default{ Layout: DateTimeLayout, Timezone: PRC, diff --git a/test.go b/test.go index c4481d02..c1947519 100644 --- a/test.go +++ b/test.go @@ -1,5 +1,10 @@ package carbon +import ( + "os" + "testing" +) + // SetTestNow sets a test Carbon instance (real or mock) to be returned when a "now" instance is created. // 设置当前测试时间 func (c *Carbon) SetTestNow(carbon Carbon) { @@ -17,3 +22,31 @@ func (c *Carbon) UnSetTestNow() { func (c Carbon) IsSetTestNow() bool { return c.testNow > 0 } + +// TestMain sets up the testing environment for all tests +// https://pkg.go.dev/testing#hdr-Main +func TestMain(m *testing.M) { + // The whole tests were written for PRC timezone (China). + // The codebase of test is too large to be changed. + // Without this hack the tests will fail if you use a different timezone than PRC + // This will affect the way Go compute the timezone when using time.Local + _ = os.Setenv("TZ", "PRC") + + m.Run() +} + +func prepareTest(tb testing.TB) { + tb.Helper() + + // Store the current default + savedDefault := Default{ + Layout: defaultLayout, + Timezone: defaultTimezone, + Locale: defaultLocale, + WeekStartsAt: defaultWeekStartsAt, + } + tb.Cleanup(func() { + // restore the default when test is done + SetDefault(savedDefault) + }) +}