package time_test import ( "testing" "time" utime "apigo.cc/go/time" ) func TestTimeZoneRobustness(t *testing.T) { // 定义一个特定时间: 2026-05-01 10:00:00 (UTC) // 在上海时区 (UTC+8) 应该是 18:00:00 const input = "2026-05-01 10:00:00" shanghai, _ := time.LoadLocation("Asia/Shanghai") utcTZ := utime.New(time.UTC) shTZ := utime.New(shanghai) // 验证 1: 跨时区解析一致性 t1 := utcTZ.Parse(input) if t1.Hour() != 10 || t1.Location() != time.UTC { t.Errorf("UTC Parse failed: expected 10:00 UTC, got %02d:00 %s", t1.Hour(), t1.Location()) } t2 := shTZ.Parse(input) // 解析为上海时区,意味着输入被视为上海时间的 10:00 if t2.Hour() != 10 || t2.Location() != shanghai { t.Errorf("Shanghai Parse failed: expected 10:00 Shanghai, got %02d:00 %s", t2.Hour(), t2.Location()) } // 验证 2: 转换能力 (Shift/Convert 逻辑) // 期望:将 UTC 的 10:00 搬移到上海时区,应该是 18:00 // 我们的逻辑: shTZ.Parse(t1) 实际上就是将 t1 搬移到了上海时区 t3 := shTZ.Parse(t1) if t3.Hour() != 18 || t3.Location() != shanghai { t.Errorf("Time Shift failed: expected 18:00 Shanghai, got %02d:00 %s", t3.Hour(), t3.Location()) } // 验证 3: 异常鲁棒性 (无效输入) // 设计哲学: 失败回退到 Now() invalid := "not-a-time" t4 := shTZ.Parse(invalid) if t4.Location() != shanghai { t.Errorf("Invalid input failed to use context timezone: expected %s, got %s", shanghai, t4.Location()) } }