github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/time/time_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package time_test 6 7 import ( 8 "bytes" 9 "encoding/gob" 10 "encoding/json" 11 "fmt" 12 "math/big" 13 "math/rand" 14 "runtime" 15 "testing" 16 "testing/quick" 17 . "time" 18 ) 19 20 // We should be in PST/PDT, but if the time zone files are missing we 21 // won't be. The purpose of this test is to at least explain why some of 22 // the subsequent tests fail. 23 func TestZoneData(t *testing.T) { 24 lt := Now() 25 // PST is 8 hours west, PDT is 7 hours west. We could use the name but it's not unique. 26 if name, off := lt.Zone(); off != -8*60*60 && off != -7*60*60 { 27 t.Errorf("Unable to find US Pacific time zone data for testing; time zone is %q offset %d", name, off) 28 t.Error("Likely problem: the time zone files have not been installed.") 29 } 30 } 31 32 // parsedTime is the struct representing a parsed time value. 33 type parsedTime struct { 34 Year int 35 Month Month 36 Day int 37 Hour, Minute, Second int // 15:04:05 is 15, 4, 5. 38 Nanosecond int // Fractional second. 39 Weekday Weekday 40 ZoneOffset int // seconds east of UTC, e.g. -7*60*60 for -0700 41 Zone string // e.g., "MST" 42 } 43 44 type TimeTest struct { 45 seconds int64 46 golden parsedTime 47 } 48 49 var utctests = []TimeTest{ 50 {0, parsedTime{1970, January, 1, 0, 0, 0, 0, Thursday, 0, "UTC"}}, 51 {1221681866, parsedTime{2008, September, 17, 20, 4, 26, 0, Wednesday, 0, "UTC"}}, 52 {-1221681866, parsedTime{1931, April, 16, 3, 55, 34, 0, Thursday, 0, "UTC"}}, 53 {-11644473600, parsedTime{1601, January, 1, 0, 0, 0, 0, Monday, 0, "UTC"}}, 54 {599529660, parsedTime{1988, December, 31, 0, 1, 0, 0, Saturday, 0, "UTC"}}, 55 {978220860, parsedTime{2000, December, 31, 0, 1, 0, 0, Sunday, 0, "UTC"}}, 56 } 57 58 var nanoutctests = []TimeTest{ 59 {0, parsedTime{1970, January, 1, 0, 0, 0, 1e8, Thursday, 0, "UTC"}}, 60 {1221681866, parsedTime{2008, September, 17, 20, 4, 26, 2e8, Wednesday, 0, "UTC"}}, 61 } 62 63 var localtests = []TimeTest{ 64 {0, parsedTime{1969, December, 31, 16, 0, 0, 0, Wednesday, -8 * 60 * 60, "PST"}}, 65 {1221681866, parsedTime{2008, September, 17, 13, 4, 26, 0, Wednesday, -7 * 60 * 60, "PDT"}}, 66 } 67 68 var nanolocaltests = []TimeTest{ 69 {0, parsedTime{1969, December, 31, 16, 0, 0, 1e8, Wednesday, -8 * 60 * 60, "PST"}}, 70 {1221681866, parsedTime{2008, September, 17, 13, 4, 26, 3e8, Wednesday, -7 * 60 * 60, "PDT"}}, 71 } 72 73 func same(t Time, u *parsedTime) bool { 74 // Check aggregates. 75 year, month, day := t.Date() 76 hour, min, sec := t.Clock() 77 name, offset := t.Zone() 78 if year != u.Year || month != u.Month || day != u.Day || 79 hour != u.Hour || min != u.Minute || sec != u.Second || 80 name != u.Zone || offset != u.ZoneOffset { 81 return false 82 } 83 // Check individual entries. 84 return t.Year() == u.Year && 85 t.Month() == u.Month && 86 t.Day() == u.Day && 87 t.Hour() == u.Hour && 88 t.Minute() == u.Minute && 89 t.Second() == u.Second && 90 t.Nanosecond() == u.Nanosecond && 91 t.Weekday() == u.Weekday 92 } 93 94 func TestSecondsToUTC(t *testing.T) { 95 for _, test := range utctests { 96 sec := test.seconds 97 golden := &test.golden 98 tm := Unix(sec, 0).UTC() 99 newsec := tm.Unix() 100 if newsec != sec { 101 t.Errorf("SecondsToUTC(%d).Seconds() = %d", sec, newsec) 102 } 103 if !same(tm, golden) { 104 t.Errorf("SecondsToUTC(%d): // %#v", sec, tm) 105 t.Errorf(" want=%+v", *golden) 106 t.Errorf(" have=%v", tm.Format(RFC3339+" MST")) 107 } 108 } 109 } 110 111 func TestNanosecondsToUTC(t *testing.T) { 112 for _, test := range nanoutctests { 113 golden := &test.golden 114 nsec := test.seconds*1e9 + int64(golden.Nanosecond) 115 tm := Unix(0, nsec).UTC() 116 newnsec := tm.Unix()*1e9 + int64(tm.Nanosecond()) 117 if newnsec != nsec { 118 t.Errorf("NanosecondsToUTC(%d).Nanoseconds() = %d", nsec, newnsec) 119 } 120 if !same(tm, golden) { 121 t.Errorf("NanosecondsToUTC(%d):", nsec) 122 t.Errorf(" want=%+v", *golden) 123 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 124 } 125 } 126 } 127 128 func TestSecondsToLocalTime(t *testing.T) { 129 for _, test := range localtests { 130 sec := test.seconds 131 golden := &test.golden 132 tm := Unix(sec, 0) 133 newsec := tm.Unix() 134 if newsec != sec { 135 t.Errorf("SecondsToLocalTime(%d).Seconds() = %d", sec, newsec) 136 } 137 if !same(tm, golden) { 138 t.Errorf("SecondsToLocalTime(%d):", sec) 139 t.Errorf(" want=%+v", *golden) 140 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 141 } 142 } 143 } 144 145 func TestNanosecondsToLocalTime(t *testing.T) { 146 for _, test := range nanolocaltests { 147 golden := &test.golden 148 nsec := test.seconds*1e9 + int64(golden.Nanosecond) 149 tm := Unix(0, nsec) 150 newnsec := tm.Unix()*1e9 + int64(tm.Nanosecond()) 151 if newnsec != nsec { 152 t.Errorf("NanosecondsToLocalTime(%d).Seconds() = %d", nsec, newnsec) 153 } 154 if !same(tm, golden) { 155 t.Errorf("NanosecondsToLocalTime(%d):", nsec) 156 t.Errorf(" want=%+v", *golden) 157 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 158 } 159 } 160 } 161 162 func TestSecondsToUTCAndBack(t *testing.T) { 163 f := func(sec int64) bool { return Unix(sec, 0).UTC().Unix() == sec } 164 f32 := func(sec int32) bool { return f(int64(sec)) } 165 cfg := &quick.Config{MaxCount: 10000} 166 167 // Try a reasonable date first, then the huge ones. 168 if err := quick.Check(f32, cfg); err != nil { 169 t.Fatal(err) 170 } 171 if err := quick.Check(f, cfg); err != nil { 172 t.Fatal(err) 173 } 174 } 175 176 func TestNanosecondsToUTCAndBack(t *testing.T) { 177 f := func(nsec int64) bool { 178 t := Unix(0, nsec).UTC() 179 ns := t.Unix()*1e9 + int64(t.Nanosecond()) 180 return ns == nsec 181 } 182 f32 := func(nsec int32) bool { return f(int64(nsec)) } 183 cfg := &quick.Config{MaxCount: 10000} 184 185 // Try a small date first, then the large ones. (The span is only a few hundred years 186 // for nanoseconds in an int64.) 187 if err := quick.Check(f32, cfg); err != nil { 188 t.Fatal(err) 189 } 190 if err := quick.Check(f, cfg); err != nil { 191 t.Fatal(err) 192 } 193 } 194 195 // The time routines provide no way to get absolute time 196 // (seconds since zero), but we need it to compute the right 197 // answer for bizarre roundings like "to the nearest 3 ns". 198 // Compute as t - year1 = (t - 1970) + (1970 - 2001) + (2001 - 1). 199 // t - 1970 is returned by Unix and Nanosecond. 200 // 1970 - 2001 is -(31*365+8)*86400 = -978307200 seconds. 201 // 2001 - 1 is 2000*365.2425*86400 = 63113904000 seconds. 202 const unixToZero = -978307200 + 63113904000 203 204 // abs returns the absolute time stored in t, as seconds and nanoseconds. 205 func abs(t Time) (sec, nsec int64) { 206 unix := t.Unix() 207 nano := t.Nanosecond() 208 return unix + unixToZero, int64(nano) 209 } 210 211 // absString returns abs as a decimal string. 212 func absString(t Time) string { 213 sec, nsec := abs(t) 214 if sec < 0 { 215 sec = -sec 216 nsec = -nsec 217 if nsec < 0 { 218 nsec += 1e9 219 sec-- 220 } 221 return fmt.Sprintf("-%d%09d", sec, nsec) 222 } 223 return fmt.Sprintf("%d%09d", sec, nsec) 224 } 225 226 var truncateRoundTests = []struct { 227 t Time 228 d Duration 229 }{ 230 {Date(-1, January, 1, 12, 15, 30, 5e8, UTC), 3}, 231 {Date(-1, January, 1, 12, 15, 31, 5e8, UTC), 3}, 232 {Date(2012, January, 1, 12, 15, 30, 5e8, UTC), Second}, 233 {Date(2012, January, 1, 12, 15, 31, 5e8, UTC), Second}, 234 } 235 236 func TestTruncateRound(t *testing.T) { 237 var ( 238 bsec = new(big.Int) 239 bnsec = new(big.Int) 240 bd = new(big.Int) 241 bt = new(big.Int) 242 br = new(big.Int) 243 bq = new(big.Int) 244 b1e9 = new(big.Int) 245 ) 246 247 b1e9.SetInt64(1e9) 248 249 testOne := func(ti, tns, di int64) bool { 250 t0 := Unix(ti, int64(tns)).UTC() 251 d := Duration(di) 252 if d < 0 { 253 d = -d 254 } 255 if d <= 0 { 256 d = 1 257 } 258 259 // Compute bt = absolute nanoseconds. 260 sec, nsec := abs(t0) 261 bsec.SetInt64(sec) 262 bnsec.SetInt64(nsec) 263 bt.Mul(bsec, b1e9) 264 bt.Add(bt, bnsec) 265 266 // Compute quotient and remainder mod d. 267 bd.SetInt64(int64(d)) 268 bq.DivMod(bt, bd, br) 269 270 // To truncate, subtract remainder. 271 // br is < d, so it fits in an int64. 272 r := br.Int64() 273 t1 := t0.Add(-Duration(r)) 274 275 // Check that time.Truncate works. 276 if trunc := t0.Truncate(d); trunc != t1 { 277 t.Errorf("Time.Truncate(%s, %s) = %s, want %s\n"+ 278 "%v trunc %v =\n%v want\n%v", 279 t0.Format(RFC3339Nano), d, trunc, t1.Format(RFC3339Nano), 280 absString(t0), int64(d), absString(trunc), absString(t1)) 281 return false 282 } 283 284 // To round, add d back if remainder r > d/2 or r == exactly d/2. 285 // The commented out code would round half to even instead of up, 286 // but that makes it time-zone dependent, which is a bit strange. 287 if r > int64(d)/2 || r+r == int64(d) /*&& bq.Bit(0) == 1*/ { 288 t1 = t1.Add(Duration(d)) 289 } 290 291 // Check that time.Round works. 292 if rnd := t0.Round(d); rnd != t1 { 293 t.Errorf("Time.Round(%s, %s) = %s, want %s\n"+ 294 "%v round %v =\n%v want\n%v", 295 t0.Format(RFC3339Nano), d, rnd, t1.Format(RFC3339Nano), 296 absString(t0), int64(d), absString(rnd), absString(t1)) 297 return false 298 } 299 return true 300 } 301 302 // manual test cases 303 for _, tt := range truncateRoundTests { 304 testOne(tt.t.Unix(), int64(tt.t.Nanosecond()), int64(tt.d)) 305 } 306 307 // exhaustive near 0 308 for i := 0; i < 100; i++ { 309 for j := 1; j < 100; j++ { 310 testOne(unixToZero, int64(i), int64(j)) 311 testOne(unixToZero, -int64(i), int64(j)) 312 if t.Failed() { 313 return 314 } 315 } 316 } 317 318 if t.Failed() { 319 return 320 } 321 322 // randomly generated test cases 323 cfg := &quick.Config{MaxCount: 100000} 324 if testing.Short() { 325 cfg.MaxCount = 1000 326 } 327 328 // divisors of Second 329 f1 := func(ti int64, tns int32, logdi int32) bool { 330 d := Duration(1) 331 a, b := uint(logdi%9), (logdi>>16)%9 332 d <<= a 333 for i := 0; i < int(b); i++ { 334 d *= 5 335 } 336 return testOne(ti, int64(tns), int64(d)) 337 } 338 quick.Check(f1, cfg) 339 340 // multiples of Second 341 f2 := func(ti int64, tns int32, di int32) bool { 342 d := Duration(di) * Second 343 if d < 0 { 344 d = -d 345 } 346 return testOne(ti, int64(tns), int64(d)) 347 } 348 quick.Check(f2, cfg) 349 350 // halfway cases 351 f3 := func(tns, di int64) bool { 352 di &= 0xfffffffe 353 if di == 0 { 354 di = 2 355 } 356 tns -= tns % di 357 if tns < 0 { 358 tns += di / 2 359 } else { 360 tns -= di / 2 361 } 362 return testOne(0, tns, di) 363 } 364 quick.Check(f3, cfg) 365 366 // full generality 367 f4 := func(ti int64, tns int32, di int64) bool { 368 return testOne(ti, int64(tns), di) 369 } 370 quick.Check(f4, cfg) 371 } 372 373 type ISOWeekTest struct { 374 year int // year 375 month, day int // month and day 376 yex int // expected year 377 wex int // expected week 378 } 379 380 var isoWeekTests = []ISOWeekTest{ 381 {1981, 1, 1, 1981, 1}, {1982, 1, 1, 1981, 53}, {1983, 1, 1, 1982, 52}, 382 {1984, 1, 1, 1983, 52}, {1985, 1, 1, 1985, 1}, {1986, 1, 1, 1986, 1}, 383 {1987, 1, 1, 1987, 1}, {1988, 1, 1, 1987, 53}, {1989, 1, 1, 1988, 52}, 384 {1990, 1, 1, 1990, 1}, {1991, 1, 1, 1991, 1}, {1992, 1, 1, 1992, 1}, 385 {1993, 1, 1, 1992, 53}, {1994, 1, 1, 1993, 52}, {1995, 1, 2, 1995, 1}, 386 {1996, 1, 1, 1996, 1}, {1996, 1, 7, 1996, 1}, {1996, 1, 8, 1996, 2}, 387 {1997, 1, 1, 1997, 1}, {1998, 1, 1, 1998, 1}, {1999, 1, 1, 1998, 53}, 388 {2000, 1, 1, 1999, 52}, {2001, 1, 1, 2001, 1}, {2002, 1, 1, 2002, 1}, 389 {2003, 1, 1, 2003, 1}, {2004, 1, 1, 2004, 1}, {2005, 1, 1, 2004, 53}, 390 {2006, 1, 1, 2005, 52}, {2007, 1, 1, 2007, 1}, {2008, 1, 1, 2008, 1}, 391 {2009, 1, 1, 2009, 1}, {2010, 1, 1, 2009, 53}, {2010, 1, 1, 2009, 53}, 392 {2011, 1, 1, 2010, 52}, {2011, 1, 2, 2010, 52}, {2011, 1, 3, 2011, 1}, 393 {2011, 1, 4, 2011, 1}, {2011, 1, 5, 2011, 1}, {2011, 1, 6, 2011, 1}, 394 {2011, 1, 7, 2011, 1}, {2011, 1, 8, 2011, 1}, {2011, 1, 9, 2011, 1}, 395 {2011, 1, 10, 2011, 2}, {2011, 1, 11, 2011, 2}, {2011, 6, 12, 2011, 23}, 396 {2011, 6, 13, 2011, 24}, {2011, 12, 25, 2011, 51}, {2011, 12, 26, 2011, 52}, 397 {2011, 12, 27, 2011, 52}, {2011, 12, 28, 2011, 52}, {2011, 12, 29, 2011, 52}, 398 {2011, 12, 30, 2011, 52}, {2011, 12, 31, 2011, 52}, {1995, 1, 1, 1994, 52}, 399 {2012, 1, 1, 2011, 52}, {2012, 1, 2, 2012, 1}, {2012, 1, 8, 2012, 1}, 400 {2012, 1, 9, 2012, 2}, {2012, 12, 23, 2012, 51}, {2012, 12, 24, 2012, 52}, 401 {2012, 12, 30, 2012, 52}, {2012, 12, 31, 2013, 1}, {2013, 1, 1, 2013, 1}, 402 {2013, 1, 6, 2013, 1}, {2013, 1, 7, 2013, 2}, {2013, 12, 22, 2013, 51}, 403 {2013, 12, 23, 2013, 52}, {2013, 12, 29, 2013, 52}, {2013, 12, 30, 2014, 1}, 404 {2014, 1, 1, 2014, 1}, {2014, 1, 5, 2014, 1}, {2014, 1, 6, 2014, 2}, 405 {2015, 1, 1, 2015, 1}, {2016, 1, 1, 2015, 53}, {2017, 1, 1, 2016, 52}, 406 {2018, 1, 1, 2018, 1}, {2019, 1, 1, 2019, 1}, {2020, 1, 1, 2020, 1}, 407 {2021, 1, 1, 2020, 53}, {2022, 1, 1, 2021, 52}, {2023, 1, 1, 2022, 52}, 408 {2024, 1, 1, 2024, 1}, {2025, 1, 1, 2025, 1}, {2026, 1, 1, 2026, 1}, 409 {2027, 1, 1, 2026, 53}, {2028, 1, 1, 2027, 52}, {2029, 1, 1, 2029, 1}, 410 {2030, 1, 1, 2030, 1}, {2031, 1, 1, 2031, 1}, {2032, 1, 1, 2032, 1}, 411 {2033, 1, 1, 2032, 53}, {2034, 1, 1, 2033, 52}, {2035, 1, 1, 2035, 1}, 412 {2036, 1, 1, 2036, 1}, {2037, 1, 1, 2037, 1}, {2038, 1, 1, 2037, 53}, 413 {2039, 1, 1, 2038, 52}, {2040, 1, 1, 2039, 52}, 414 } 415 416 func TestISOWeek(t *testing.T) { 417 // Selected dates and corner cases 418 for _, wt := range isoWeekTests { 419 dt := Date(wt.year, Month(wt.month), wt.day, 0, 0, 0, 0, UTC) 420 y, w := dt.ISOWeek() 421 if w != wt.wex || y != wt.yex { 422 t.Errorf("got %d/%d; expected %d/%d for %d-%02d-%02d", 423 y, w, wt.yex, wt.wex, wt.year, wt.month, wt.day) 424 } 425 } 426 427 // The only real invariant: Jan 04 is in week 1 428 for year := 1950; year < 2100; year++ { 429 if y, w := Date(year, January, 4, 0, 0, 0, 0, UTC).ISOWeek(); y != year || w != 1 { 430 t.Errorf("got %d/%d; expected %d/1 for Jan 04", y, w, year) 431 } 432 } 433 } 434 435 type YearDayTest struct { 436 year, month, day int 437 yday int 438 } 439 440 // Test YearDay in several different scenarios 441 // and corner cases 442 var yearDayTests = []YearDayTest{ 443 // Non-leap-year tests 444 {2007, 1, 1, 1}, 445 {2007, 1, 15, 15}, 446 {2007, 2, 1, 32}, 447 {2007, 2, 15, 46}, 448 {2007, 3, 1, 60}, 449 {2007, 3, 15, 74}, 450 {2007, 4, 1, 91}, 451 {2007, 12, 31, 365}, 452 453 // Leap-year tests 454 {2008, 1, 1, 1}, 455 {2008, 1, 15, 15}, 456 {2008, 2, 1, 32}, 457 {2008, 2, 15, 46}, 458 {2008, 3, 1, 61}, 459 {2008, 3, 15, 75}, 460 {2008, 4, 1, 92}, 461 {2008, 12, 31, 366}, 462 463 // Looks like leap-year (but isn't) tests 464 {1900, 1, 1, 1}, 465 {1900, 1, 15, 15}, 466 {1900, 2, 1, 32}, 467 {1900, 2, 15, 46}, 468 {1900, 3, 1, 60}, 469 {1900, 3, 15, 74}, 470 {1900, 4, 1, 91}, 471 {1900, 12, 31, 365}, 472 473 // Year one tests (non-leap) 474 {1, 1, 1, 1}, 475 {1, 1, 15, 15}, 476 {1, 2, 1, 32}, 477 {1, 2, 15, 46}, 478 {1, 3, 1, 60}, 479 {1, 3, 15, 74}, 480 {1, 4, 1, 91}, 481 {1, 12, 31, 365}, 482 483 // Year minus one tests (non-leap) 484 {-1, 1, 1, 1}, 485 {-1, 1, 15, 15}, 486 {-1, 2, 1, 32}, 487 {-1, 2, 15, 46}, 488 {-1, 3, 1, 60}, 489 {-1, 3, 15, 74}, 490 {-1, 4, 1, 91}, 491 {-1, 12, 31, 365}, 492 493 // 400 BC tests (leap-year) 494 {-400, 1, 1, 1}, 495 {-400, 1, 15, 15}, 496 {-400, 2, 1, 32}, 497 {-400, 2, 15, 46}, 498 {-400, 3, 1, 61}, 499 {-400, 3, 15, 75}, 500 {-400, 4, 1, 92}, 501 {-400, 12, 31, 366}, 502 503 // Special Cases 504 505 // Gregorian calendar change (no effect) 506 {1582, 10, 4, 277}, 507 {1582, 10, 15, 288}, 508 } 509 510 // Check to see if YearDay is location sensitive 511 var yearDayLocations = []*Location{ 512 FixedZone("UTC-8", -8*60*60), 513 FixedZone("UTC-4", -4*60*60), 514 UTC, 515 FixedZone("UTC+4", 4*60*60), 516 FixedZone("UTC+8", 8*60*60), 517 } 518 519 func TestYearDay(t *testing.T) { 520 for _, loc := range yearDayLocations { 521 for _, ydt := range yearDayTests { 522 dt := Date(ydt.year, Month(ydt.month), ydt.day, 0, 0, 0, 0, loc) 523 yday := dt.YearDay() 524 if yday != ydt.yday { 525 t.Errorf("got %d, expected %d for %d-%02d-%02d in %v", 526 yday, ydt.yday, ydt.year, ydt.month, ydt.day, loc) 527 } 528 } 529 } 530 } 531 532 var durationTests = []struct { 533 str string 534 d Duration 535 }{ 536 {"0", 0}, 537 {"1ns", 1 * Nanosecond}, 538 {"1.1µs", 1100 * Nanosecond}, 539 {"2.2ms", 2200 * Microsecond}, 540 {"3.3s", 3300 * Millisecond}, 541 {"4m5s", 4*Minute + 5*Second}, 542 {"4m5.001s", 4*Minute + 5001*Millisecond}, 543 {"5h6m7.001s", 5*Hour + 6*Minute + 7001*Millisecond}, 544 {"8m0.000000001s", 8*Minute + 1*Nanosecond}, 545 {"2562047h47m16.854775807s", 1<<63 - 1}, 546 {"-2562047h47m16.854775808s", -1 << 63}, 547 } 548 549 func TestDurationString(t *testing.T) { 550 for _, tt := range durationTests { 551 if str := tt.d.String(); str != tt.str { 552 t.Errorf("Duration(%d).String() = %s, want %s", int64(tt.d), str, tt.str) 553 } 554 if tt.d > 0 { 555 if str := (-tt.d).String(); str != "-"+tt.str { 556 t.Errorf("Duration(%d).String() = %s, want %s", int64(-tt.d), str, "-"+tt.str) 557 } 558 } 559 } 560 } 561 562 var dateTests = []struct { 563 year, month, day, hour, min, sec, nsec int 564 z *Location 565 unix int64 566 }{ 567 {2011, 11, 6, 1, 0, 0, 0, Local, 1320566400}, // 1:00:00 PDT 568 {2011, 11, 6, 1, 59, 59, 0, Local, 1320569999}, // 1:59:59 PDT 569 {2011, 11, 6, 2, 0, 0, 0, Local, 1320573600}, // 2:00:00 PST 570 571 {2011, 3, 13, 1, 0, 0, 0, Local, 1300006800}, // 1:00:00 PST 572 {2011, 3, 13, 1, 59, 59, 0, Local, 1300010399}, // 1:59:59 PST 573 {2011, 3, 13, 3, 0, 0, 0, Local, 1300010400}, // 3:00:00 PDT 574 {2011, 3, 13, 2, 30, 0, 0, Local, 1300008600}, // 2:30:00 PDT ≡ 1:30 PST 575 576 // Many names for Fri Nov 18 7:56:35 PST 2011 577 {2011, 11, 18, 7, 56, 35, 0, Local, 1321631795}, // Nov 18 7:56:35 578 {2011, 11, 19, -17, 56, 35, 0, Local, 1321631795}, // Nov 19 -17:56:35 579 {2011, 11, 17, 31, 56, 35, 0, Local, 1321631795}, // Nov 17 31:56:35 580 {2011, 11, 18, 6, 116, 35, 0, Local, 1321631795}, // Nov 18 6:116:35 581 {2011, 10, 49, 7, 56, 35, 0, Local, 1321631795}, // Oct 49 7:56:35 582 {2011, 11, 18, 7, 55, 95, 0, Local, 1321631795}, // Nov 18 7:55:95 583 {2011, 11, 18, 7, 56, 34, 1e9, Local, 1321631795}, // Nov 18 7:56:34 + 10⁹ns 584 {2011, 12, -12, 7, 56, 35, 0, Local, 1321631795}, // Dec -21 7:56:35 585 {2012, 1, -43, 7, 56, 35, 0, Local, 1321631795}, // Jan -52 7:56:35 2012 586 {2012, int(January - 2), 18, 7, 56, 35, 0, Local, 1321631795}, // (Jan-2) 18 7:56:35 2012 587 {2010, int(December + 11), 18, 7, 56, 35, 0, Local, 1321631795}, // (Dec+11) 18 7:56:35 2010 588 } 589 590 func TestDate(t *testing.T) { 591 for _, tt := range dateTests { 592 time := Date(tt.year, Month(tt.month), tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z) 593 want := Unix(tt.unix, 0) 594 if !time.Equal(want) { 595 t.Errorf("Date(%d, %d, %d, %d, %d, %d, %d, %s) = %v, want %v", 596 tt.year, tt.month, tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z, 597 time, want) 598 } 599 } 600 } 601 602 // Several ways of getting from 603 // Fri Nov 18 7:56:35 PST 2011 604 // to 605 // Thu Mar 19 7:56:35 PST 2016 606 var addDateTests = []struct { 607 years, months, days int 608 }{ 609 {4, 4, 1}, 610 {3, 16, 1}, 611 {3, 15, 30}, 612 {5, -6, -18 - 30 - 12}, 613 } 614 615 func TestAddDate(t *testing.T) { 616 t0 := Date(2011, 11, 18, 7, 56, 35, 0, UTC) 617 t1 := Date(2016, 3, 19, 7, 56, 35, 0, UTC) 618 for _, at := range addDateTests { 619 time := t0.AddDate(at.years, at.months, at.days) 620 if !time.Equal(t1) { 621 t.Errorf("AddDate(%d, %d, %d) = %v, want %v", 622 at.years, at.months, at.days, 623 time, t1) 624 } 625 } 626 } 627 628 var daysInTests = []struct { 629 year, month, di int 630 }{ 631 {2011, 1, 31}, // January, first month, 31 days 632 {2011, 2, 28}, // February, non-leap year, 28 days 633 {2012, 2, 29}, // February, leap year, 29 days 634 {2011, 6, 30}, // June, 30 days 635 {2011, 12, 31}, // December, last month, 31 days 636 } 637 638 func TestDaysIn(t *testing.T) { 639 // The daysIn function is not exported. 640 // Test the daysIn function via the `var DaysIn = daysIn` 641 // statement in the internal_test.go file. 642 for _, tt := range daysInTests { 643 di := DaysIn(Month(tt.month), tt.year) 644 if di != tt.di { 645 t.Errorf("got %d; expected %d for %d-%02d", 646 di, tt.di, tt.year, tt.month) 647 } 648 } 649 } 650 651 func TestAddToExactSecond(t *testing.T) { 652 // Add an amount to the current time to round it up to the next exact second. 653 // This test checks that the nsec field still lies within the range [0, 999999999]. 654 t1 := Now() 655 t2 := t1.Add(Second - Duration(t1.Nanosecond())) 656 sec := (t1.Second() + 1) % 60 657 if t2.Second() != sec || t2.Nanosecond() != 0 { 658 t.Errorf("sec = %d, nsec = %d, want sec = %d, nsec = 0", t2.Second(), t2.Nanosecond(), sec) 659 } 660 } 661 662 func equalTimeAndZone(a, b Time) bool { 663 aname, aoffset := a.Zone() 664 bname, boffset := b.Zone() 665 return a.Equal(b) && aoffset == boffset && aname == bname 666 } 667 668 var gobTests = []Time{ 669 Date(0, 1, 2, 3, 4, 5, 6, UTC), 670 Date(7, 8, 9, 10, 11, 12, 13, FixedZone("", 0)), 671 Unix(81985467080890095, 0x76543210), // Time.sec: 0x0123456789ABCDEF 672 {}, // nil location 673 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", 32767*60)), 674 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", -32768*60)), 675 } 676 677 func TestTimeGob(t *testing.T) { 678 var b bytes.Buffer 679 enc := gob.NewEncoder(&b) 680 dec := gob.NewDecoder(&b) 681 for _, tt := range gobTests { 682 var gobtt Time 683 if err := enc.Encode(&tt); err != nil { 684 t.Errorf("%v gob Encode error = %q, want nil", tt, err) 685 } else if err := dec.Decode(&gobtt); err != nil { 686 t.Errorf("%v gob Decode error = %q, want nil", tt, err) 687 } else if !equalTimeAndZone(gobtt, tt) { 688 t.Errorf("Decoded time = %v, want %v", gobtt, tt) 689 } 690 b.Reset() 691 } 692 } 693 694 var invalidEncodingTests = []struct { 695 bytes []byte 696 want string 697 }{ 698 {[]byte{}, "Time.UnmarshalBinary: no data"}, 699 {[]byte{0, 2, 3}, "Time.UnmarshalBinary: unsupported version"}, 700 {[]byte{1, 2, 3}, "Time.UnmarshalBinary: invalid length"}, 701 } 702 703 func TestInvalidTimeGob(t *testing.T) { 704 for _, tt := range invalidEncodingTests { 705 var ignored Time 706 err := ignored.GobDecode(tt.bytes) 707 if err == nil || err.Error() != tt.want { 708 t.Errorf("time.GobDecode(%#v) error = %v, want %v", tt.bytes, err, tt.want) 709 } 710 err = ignored.UnmarshalBinary(tt.bytes) 711 if err == nil || err.Error() != tt.want { 712 t.Errorf("time.UnmarshalBinary(%#v) error = %v, want %v", tt.bytes, err, tt.want) 713 } 714 } 715 } 716 717 var notEncodableTimes = []struct { 718 time Time 719 want string 720 }{ 721 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 1)), "Time.MarshalBinary: zone offset has fractional minute"}, 722 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -1*60)), "Time.MarshalBinary: unexpected zone offset"}, 723 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -32769*60)), "Time.MarshalBinary: unexpected zone offset"}, 724 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 32768*60)), "Time.MarshalBinary: unexpected zone offset"}, 725 } 726 727 func TestNotGobEncodableTime(t *testing.T) { 728 for _, tt := range notEncodableTimes { 729 _, err := tt.time.GobEncode() 730 if err == nil || err.Error() != tt.want { 731 t.Errorf("%v GobEncode error = %v, want %v", tt.time, err, tt.want) 732 } 733 _, err = tt.time.MarshalBinary() 734 if err == nil || err.Error() != tt.want { 735 t.Errorf("%v MarshalBinary error = %v, want %v", tt.time, err, tt.want) 736 } 737 } 738 } 739 740 var jsonTests = []struct { 741 time Time 742 json string 743 }{ 744 {Date(9999, 4, 12, 23, 20, 50, 520*1e6, UTC), `"9999-04-12T23:20:50.52Z"`}, 745 {Date(1996, 12, 19, 16, 39, 57, 0, Local), `"1996-12-19T16:39:57-08:00"`}, 746 {Date(0, 1, 1, 0, 0, 0, 1, FixedZone("", 1*60)), `"0000-01-01T00:00:00.000000001+00:01"`}, 747 } 748 749 func TestTimeJSON(t *testing.T) { 750 for _, tt := range jsonTests { 751 var jsonTime Time 752 753 if jsonBytes, err := json.Marshal(tt.time); err != nil { 754 t.Errorf("%v json.Marshal error = %v, want nil", tt.time, err) 755 } else if string(jsonBytes) != tt.json { 756 t.Errorf("%v JSON = %#q, want %#q", tt.time, string(jsonBytes), tt.json) 757 } else if err = json.Unmarshal(jsonBytes, &jsonTime); err != nil { 758 t.Errorf("%v json.Unmarshal error = %v, want nil", tt.time, err) 759 } else if !equalTimeAndZone(jsonTime, tt.time) { 760 t.Errorf("Unmarshaled time = %v, want %v", jsonTime, tt.time) 761 } 762 } 763 } 764 765 func TestInvalidTimeJSON(t *testing.T) { 766 var tt Time 767 err := json.Unmarshal([]byte(`{"now is the time":"buddy"}`), &tt) 768 _, isParseErr := err.(*ParseError) 769 if !isParseErr { 770 t.Errorf("expected *time.ParseError unmarshaling JSON, got %v", err) 771 } 772 } 773 774 var notJSONEncodableTimes = []struct { 775 time Time 776 want string 777 }{ 778 {Date(10000, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 779 {Date(-1, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 780 } 781 782 func TestNotJSONEncodableTime(t *testing.T) { 783 for _, tt := range notJSONEncodableTimes { 784 _, err := tt.time.MarshalJSON() 785 if err == nil || err.Error() != tt.want { 786 t.Errorf("%v MarshalJSON error = %v, want %v", tt.time, err, tt.want) 787 } 788 } 789 } 790 791 var parseDurationTests = []struct { 792 in string 793 ok bool 794 want Duration 795 }{ 796 // simple 797 {"0", true, 0}, 798 {"5s", true, 5 * Second}, 799 {"30s", true, 30 * Second}, 800 {"1478s", true, 1478 * Second}, 801 // sign 802 {"-5s", true, -5 * Second}, 803 {"+5s", true, 5 * Second}, 804 {"-0", true, 0}, 805 {"+0", true, 0}, 806 // decimal 807 {"5.0s", true, 5 * Second}, 808 {"5.6s", true, 5*Second + 600*Millisecond}, 809 {"5.s", true, 5 * Second}, 810 {".5s", true, 500 * Millisecond}, 811 {"1.0s", true, 1 * Second}, 812 {"1.00s", true, 1 * Second}, 813 {"1.004s", true, 1*Second + 4*Millisecond}, 814 {"1.0040s", true, 1*Second + 4*Millisecond}, 815 {"100.00100s", true, 100*Second + 1*Millisecond}, 816 // different units 817 {"10ns", true, 10 * Nanosecond}, 818 {"11us", true, 11 * Microsecond}, 819 {"12µs", true, 12 * Microsecond}, // U+00B5 820 {"12μs", true, 12 * Microsecond}, // U+03BC 821 {"13ms", true, 13 * Millisecond}, 822 {"14s", true, 14 * Second}, 823 {"15m", true, 15 * Minute}, 824 {"16h", true, 16 * Hour}, 825 // composite durations 826 {"3h30m", true, 3*Hour + 30*Minute}, 827 {"10.5s4m", true, 4*Minute + 10*Second + 500*Millisecond}, 828 {"-2m3.4s", true, -(2*Minute + 3*Second + 400*Millisecond)}, 829 {"1h2m3s4ms5us6ns", true, 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond}, 830 {"39h9m14.425s", true, 39*Hour + 9*Minute + 14*Second + 425*Millisecond}, 831 // large value 832 {"52763797000ns", true, 52763797000 * Nanosecond}, 833 // more than 9 digits after decimal point, see https://golang.org/issue/6617 834 {"0.3333333333333333333h", true, 20 * Minute}, 835 // 9007199254740993 = 1<<53+1 cannot be stored precisely in a float64 836 {"9007199254740993ns", true, (1<<53 + 1) * Nanosecond}, 837 // largest duration that can be represented by int64 in nanoseconds 838 {"9223372036854775807ns", true, (1<<63 - 1) * Nanosecond}, 839 {"9223372036854775.807us", true, (1<<63 - 1) * Nanosecond}, 840 {"9223372036s854ms775us807ns", true, (1<<63 - 1) * Nanosecond}, 841 // large negative value 842 {"-9223372036854775807ns", true, -1<<63 + 1*Nanosecond}, 843 844 // errors 845 {"", false, 0}, 846 {"3", false, 0}, 847 {"-", false, 0}, 848 {"s", false, 0}, 849 {".", false, 0}, 850 {"-.", false, 0}, 851 {".s", false, 0}, 852 {"+.s", false, 0}, 853 {"3000000h", false, 0}, // overflow 854 {"9223372036854775808ns", false, 0}, // overflow 855 {"9223372036854775.808us", false, 0}, // overflow 856 {"9223372036854ms775us808ns", false, 0}, // overflow 857 // largest negative value of type int64 in nanoseconds should fail 858 // see https://go-review.googlesource.com/#/c/2461/ 859 {"-9223372036854775808ns", false, 0}, 860 } 861 862 func TestParseDuration(t *testing.T) { 863 for _, tc := range parseDurationTests { 864 d, err := ParseDuration(tc.in) 865 if tc.ok && (err != nil || d != tc.want) { 866 t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want) 867 } else if !tc.ok && err == nil { 868 t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in) 869 } 870 } 871 } 872 873 func TestParseDurationRoundTrip(t *testing.T) { 874 for i := 0; i < 100; i++ { 875 // Resolutions finer than milliseconds will result in 876 // imprecise round-trips. 877 d0 := Duration(rand.Int31()) * Millisecond 878 s := d0.String() 879 d1, err := ParseDuration(s) 880 if err != nil || d0 != d1 { 881 t.Errorf("round-trip failed: %d => %q => %d, %v", d0, s, d1, err) 882 } 883 } 884 } 885 886 // golang.org/issue/4622 887 func TestLocationRace(t *testing.T) { 888 ResetLocalOnceForTest() // reset the Once to trigger the race 889 890 c := make(chan string, 1) 891 go func() { 892 c <- Now().String() 893 }() 894 Now().String() 895 <-c 896 Sleep(100 * Millisecond) 897 898 // Back to Los Angeles for subsequent tests: 899 ForceUSPacificForTesting() 900 } 901 902 var ( 903 t Time 904 u int64 905 ) 906 907 var mallocTest = []struct { 908 count int 909 desc string 910 fn func() 911 }{ 912 {0, `time.Now()`, func() { t = Now() }}, 913 {0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }}, 914 } 915 916 func TestCountMallocs(t *testing.T) { 917 if testing.Short() { 918 t.Skip("skipping malloc count in short mode") 919 } 920 if runtime.GOMAXPROCS(0) > 1 { 921 t.Skip("skipping; GOMAXPROCS>1") 922 } 923 for _, mt := range mallocTest { 924 allocs := int(testing.AllocsPerRun(100, mt.fn)) 925 if allocs > mt.count { 926 t.Errorf("%s: %d allocs, want %d", mt.desc, allocs, mt.count) 927 } 928 } 929 } 930 931 func TestLoadFixed(t *testing.T) { 932 // Issue 4064: handle locations without any zone transitions. 933 loc, err := LoadLocation("Etc/GMT+1") 934 if err != nil { 935 t.Fatal(err) 936 } 937 938 // The tzdata name Etc/GMT+1 uses "east is negative", 939 // but Go and most other systems use "east is positive". 940 // So GMT+1 corresponds to -3600 in the Go zone, not +3600. 941 name, offset := Now().In(loc).Zone() 942 if name != "GMT+1" || offset != -1*60*60 { 943 t.Errorf("Now().In(loc).Zone() = %q, %d, want %q, %d", name, offset, "GMT+1", -1*60*60) 944 } 945 } 946 947 const ( 948 minDuration Duration = -1 << 63 949 maxDuration Duration = 1<<63 - 1 950 ) 951 952 var subTests = []struct { 953 t Time 954 u Time 955 d Duration 956 }{ 957 {Time{}, Time{}, Duration(0)}, 958 {Date(2009, 11, 23, 0, 0, 0, 1, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), Duration(1)}, 959 {Date(2009, 11, 23, 0, 0, 0, 0, UTC), Date(2009, 11, 24, 0, 0, 0, 0, UTC), -24 * Hour}, 960 {Date(2009, 11, 24, 0, 0, 0, 0, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour}, 961 {Date(-2009, 11, 24, 0, 0, 0, 0, UTC), Date(-2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour}, 962 {Time{}, Date(2109, 11, 23, 0, 0, 0, 0, UTC), Duration(minDuration)}, 963 {Date(2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(maxDuration)}, 964 {Time{}, Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Duration(maxDuration)}, 965 {Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(minDuration)}, 966 {Date(2290, 1, 1, 0, 0, 0, 0, UTC), Date(2000, 1, 1, 0, 0, 0, 0, UTC), 290*365*24*Hour + 71*24*Hour}, 967 {Date(2300, 1, 1, 0, 0, 0, 0, UTC), Date(2000, 1, 1, 0, 0, 0, 0, UTC), Duration(maxDuration)}, 968 {Date(2000, 1, 1, 0, 0, 0, 0, UTC), Date(2290, 1, 1, 0, 0, 0, 0, UTC), -290*365*24*Hour - 71*24*Hour}, 969 {Date(2000, 1, 1, 0, 0, 0, 0, UTC), Date(2300, 1, 1, 0, 0, 0, 0, UTC), Duration(minDuration)}, 970 } 971 972 func TestSub(t *testing.T) { 973 for i, st := range subTests { 974 got := st.t.Sub(st.u) 975 if got != st.d { 976 t.Errorf("#%d: Sub(%v, %v): got %v; want %v", i, st.t, st.u, got, st.d) 977 } 978 } 979 } 980 981 var nsDurationTests = []struct { 982 d Duration 983 want int64 984 }{ 985 {Duration(-1000), -1000}, 986 {Duration(-1), -1}, 987 {Duration(1), 1}, 988 {Duration(1000), 1000}, 989 } 990 991 func TestDurationNanoseconds(t *testing.T) { 992 for _, tt := range nsDurationTests { 993 if got := tt.d.Nanoseconds(); got != tt.want { 994 t.Errorf("d.Nanoseconds() = %d; want: %d", got, tt.want) 995 } 996 } 997 } 998 999 var minDurationTests = []struct { 1000 d Duration 1001 want float64 1002 }{ 1003 {Duration(-60000000000), -1}, 1004 {Duration(-1), -1 / 60e9}, 1005 {Duration(1), 1 / 60e9}, 1006 {Duration(60000000000), 1}, 1007 } 1008 1009 func TestDurationMinutes(t *testing.T) { 1010 for _, tt := range minDurationTests { 1011 if got := tt.d.Minutes(); got != tt.want { 1012 t.Errorf("d.Minutes() = %g; want: %g", got, tt.want) 1013 } 1014 } 1015 } 1016 1017 var hourDurationTests = []struct { 1018 d Duration 1019 want float64 1020 }{ 1021 {Duration(-3600000000000), -1}, 1022 {Duration(-1), -1 / 3600e9}, 1023 {Duration(1), 1 / 3600e9}, 1024 {Duration(3600000000000), 1}, 1025 } 1026 1027 func TestDurationHours(t *testing.T) { 1028 for _, tt := range hourDurationTests { 1029 if got := tt.d.Hours(); got != tt.want { 1030 t.Errorf("d.Hours() = %g; want: %g", got, tt.want) 1031 } 1032 } 1033 } 1034 1035 func BenchmarkNow(b *testing.B) { 1036 for i := 0; i < b.N; i++ { 1037 t = Now() 1038 } 1039 } 1040 1041 func BenchmarkNowUnixNano(b *testing.B) { 1042 for i := 0; i < b.N; i++ { 1043 u = Now().UnixNano() 1044 } 1045 } 1046 1047 func BenchmarkFormat(b *testing.B) { 1048 t := Unix(1265346057, 0) 1049 for i := 0; i < b.N; i++ { 1050 t.Format("Mon Jan 2 15:04:05 2006") 1051 } 1052 } 1053 1054 func BenchmarkFormatNow(b *testing.B) { 1055 // Like BenchmarkFormat, but easier, because the time zone 1056 // lookup cache is optimized for the present. 1057 t := Now() 1058 for i := 0; i < b.N; i++ { 1059 t.Format("Mon Jan 2 15:04:05 2006") 1060 } 1061 } 1062 1063 func BenchmarkMarshalJSON(b *testing.B) { 1064 t := Now() 1065 for i := 0; i < b.N; i++ { 1066 t.MarshalJSON() 1067 } 1068 } 1069 1070 func BenchmarkMarshalText(b *testing.B) { 1071 t := Now() 1072 for i := 0; i < b.N; i++ { 1073 t.MarshalText() 1074 } 1075 } 1076 1077 func BenchmarkParse(b *testing.B) { 1078 for i := 0; i < b.N; i++ { 1079 Parse(ANSIC, "Mon Jan 2 15:04:05 2006") 1080 } 1081 } 1082 1083 func BenchmarkParseDuration(b *testing.B) { 1084 for i := 0; i < b.N; i++ { 1085 ParseDuration("9007199254.740993ms") 1086 ParseDuration("9007199254740993ns") 1087 } 1088 } 1089 1090 func BenchmarkHour(b *testing.B) { 1091 t := Now() 1092 for i := 0; i < b.N; i++ { 1093 _ = t.Hour() 1094 } 1095 } 1096 1097 func BenchmarkSecond(b *testing.B) { 1098 t := Now() 1099 for i := 0; i < b.N; i++ { 1100 _ = t.Second() 1101 } 1102 } 1103 1104 func BenchmarkYear(b *testing.B) { 1105 t := Now() 1106 for i := 0; i < b.N; i++ { 1107 _ = t.Year() 1108 } 1109 } 1110 1111 func BenchmarkDay(b *testing.B) { 1112 t := Now() 1113 for i := 0; i < b.N; i++ { 1114 _ = t.Day() 1115 } 1116 }