Skip to content

Commit

Permalink
fix tests for non China based people (#269)
Browse files Browse the repository at this point in the history
- **tests: Playing with Carbon Default is dangerous.**
- **ci: tests were written by someone in PRC timezone**

Fixes #268
  • Loading branch information
gouguoyin authored Dec 31, 2024
2 parents 31060b9 + 83a65e5 commit 26cb9ec
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 2 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ name: test

on:
push
env:
TZ: "PRC"
jobs:

test:
Expand Down
2 changes: 2 additions & 0 deletions database_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions default_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package carbon
import "testing"

func BenchmarkCarbon_SetDefault(b *testing.B) {
prepareTest(b)

d := Default{
Layout: DateTimeLayout,
Timezone: Local,
Expand Down
2 changes: 2 additions & 0 deletions default_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
)

func TestCarbon_SetDefault(t *testing.T) {
prepareTest(t)

SetDefault(Default{
Layout: DateTimeLayout,
Timezone: PRC,
Expand Down
33 changes: 33 additions & 0 deletions test.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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)
})
}

0 comments on commit 26cb9ec

Please sign in to comment.