github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/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 "strconv" 16 "strings" 17 "testing" 18 "testing/quick" 19 . "time" 20 ) 21 22 // We should be in PST/PDT, but if the time zone files are missing we 23 // won't be. The purpose of this test is to at least explain why some of 24 // the subsequent tests fail. 25 func TestZoneData(t *testing.T) { 26 lt := Now() 27 // PST is 8 hours west, PDT is 7 hours west. We could use the name but it's not unique. 28 if name, off := lt.Zone(); off != -8*60*60 && off != -7*60*60 { 29 t.Errorf("Unable to find US Pacific time zone data for testing; time zone is %q offset %d", name, off) 30 t.Error("Likely problem: the time zone files have not been installed.") 31 } 32 } 33 34 // parsedTime is the struct representing a parsed time value. 35 type parsedTime struct { 36 Year int 37 Month Month 38 Day int 39 Hour, Minute, Second int // 15:04:05 is 15, 4, 5. 40 Nanosecond int // Fractional second. 41 Weekday Weekday 42 ZoneOffset int // seconds east of UTC, e.g. -7*60*60 for -0700 43 Zone string // e.g., "MST" 44 } 45 46 type TimeTest struct { 47 seconds int64 48 golden parsedTime 49 } 50 51 var utctests = []TimeTest{ 52 {0, parsedTime{1970, January, 1, 0, 0, 0, 0, Thursday, 0, "UTC"}}, 53 {1221681866, parsedTime{2008, September, 17, 20, 4, 26, 0, Wednesday, 0, "UTC"}}, 54 {-1221681866, parsedTime{1931, April, 16, 3, 55, 34, 0, Thursday, 0, "UTC"}}, 55 {-11644473600, parsedTime{1601, January, 1, 0, 0, 0, 0, Monday, 0, "UTC"}}, 56 {599529660, parsedTime{1988, December, 31, 0, 1, 0, 0, Saturday, 0, "UTC"}}, 57 {978220860, parsedTime{2000, December, 31, 0, 1, 0, 0, Sunday, 0, "UTC"}}, 58 } 59 60 var nanoutctests = []TimeTest{ 61 {0, parsedTime{1970, January, 1, 0, 0, 0, 1e8, Thursday, 0, "UTC"}}, 62 {1221681866, parsedTime{2008, September, 17, 20, 4, 26, 2e8, Wednesday, 0, "UTC"}}, 63 } 64 65 var localtests = []TimeTest{ 66 {0, parsedTime{1969, December, 31, 16, 0, 0, 0, Wednesday, -8 * 60 * 60, "PST"}}, 67 {1221681866, parsedTime{2008, September, 17, 13, 4, 26, 0, Wednesday, -7 * 60 * 60, "PDT"}}, 68 } 69 70 var nanolocaltests = []TimeTest{ 71 {0, parsedTime{1969, December, 31, 16, 0, 0, 1e8, Wednesday, -8 * 60 * 60, "PST"}}, 72 {1221681866, parsedTime{2008, September, 17, 13, 4, 26, 3e8, Wednesday, -7 * 60 * 60, "PDT"}}, 73 } 74 75 func same(t Time, u *parsedTime) bool { 76 // Check aggregates. 77 year, month, day := t.Date() 78 hour, min, sec := t.Clock() 79 name, offset := t.Zone() 80 if year != u.Year || month != u.Month || day != u.Day || 81 hour != u.Hour || min != u.Minute || sec != u.Second || 82 name != u.Zone || offset != u.ZoneOffset { 83 return false 84 } 85 // Check individual entries. 86 return t.Year() == u.Year && 87 t.Month() == u.Month && 88 t.Day() == u.Day && 89 t.Hour() == u.Hour && 90 t.Minute() == u.Minute && 91 t.Second() == u.Second && 92 t.Nanosecond() == u.Nanosecond && 93 t.Weekday() == u.Weekday 94 } 95 96 func TestSecondsToUTC(t *testing.T) { 97 for _, test := range utctests { 98 sec := test.seconds 99 golden := &test.golden 100 tm := Unix(sec, 0).UTC() 101 newsec := tm.Unix() 102 if newsec != sec { 103 t.Errorf("SecondsToUTC(%d).Seconds() = %d", sec, newsec) 104 } 105 if !same(tm, golden) { 106 t.Errorf("SecondsToUTC(%d): // %#v", sec, tm) 107 t.Errorf(" want=%+v", *golden) 108 t.Errorf(" have=%v", tm.Format(RFC3339+" MST")) 109 } 110 } 111 } 112 113 func TestNanosecondsToUTC(t *testing.T) { 114 for _, test := range nanoutctests { 115 golden := &test.golden 116 nsec := test.seconds*1e9 + int64(golden.Nanosecond) 117 tm := Unix(0, nsec).UTC() 118 newnsec := tm.Unix()*1e9 + int64(tm.Nanosecond()) 119 if newnsec != nsec { 120 t.Errorf("NanosecondsToUTC(%d).Nanoseconds() = %d", nsec, newnsec) 121 } 122 if !same(tm, golden) { 123 t.Errorf("NanosecondsToUTC(%d):", nsec) 124 t.Errorf(" want=%+v", *golden) 125 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 126 } 127 } 128 } 129 130 func TestSecondsToLocalTime(t *testing.T) { 131 for _, test := range localtests { 132 sec := test.seconds 133 golden := &test.golden 134 tm := Unix(sec, 0) 135 newsec := tm.Unix() 136 if newsec != sec { 137 t.Errorf("SecondsToLocalTime(%d).Seconds() = %d", sec, newsec) 138 } 139 if !same(tm, golden) { 140 t.Errorf("SecondsToLocalTime(%d):", sec) 141 t.Errorf(" want=%+v", *golden) 142 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 143 } 144 } 145 } 146 147 func TestNanosecondsToLocalTime(t *testing.T) { 148 for _, test := range nanolocaltests { 149 golden := &test.golden 150 nsec := test.seconds*1e9 + int64(golden.Nanosecond) 151 tm := Unix(0, nsec) 152 newnsec := tm.Unix()*1e9 + int64(tm.Nanosecond()) 153 if newnsec != nsec { 154 t.Errorf("NanosecondsToLocalTime(%d).Seconds() = %d", nsec, newnsec) 155 } 156 if !same(tm, golden) { 157 t.Errorf("NanosecondsToLocalTime(%d):", nsec) 158 t.Errorf(" want=%+v", *golden) 159 t.Errorf(" have=%+v", tm.Format(RFC3339+" MST")) 160 } 161 } 162 } 163 164 func TestSecondsToUTCAndBack(t *testing.T) { 165 f := func(sec int64) bool { return Unix(sec, 0).UTC().Unix() == sec } 166 f32 := func(sec int32) bool { return f(int64(sec)) } 167 cfg := &quick.Config{MaxCount: 10000} 168 169 // Try a reasonable date first, then the huge ones. 170 if err := quick.Check(f32, cfg); err != nil { 171 t.Fatal(err) 172 } 173 if err := quick.Check(f, cfg); err != nil { 174 t.Fatal(err) 175 } 176 } 177 178 func TestNanosecondsToUTCAndBack(t *testing.T) { 179 f := func(nsec int64) bool { 180 t := Unix(0, nsec).UTC() 181 ns := t.Unix()*1e9 + int64(t.Nanosecond()) 182 return ns == nsec 183 } 184 f32 := func(nsec int32) bool { return f(int64(nsec)) } 185 cfg := &quick.Config{MaxCount: 10000} 186 187 // Try a small date first, then the large ones. (The span is only a few hundred years 188 // for nanoseconds in an int64.) 189 if err := quick.Check(f32, cfg); err != nil { 190 t.Fatal(err) 191 } 192 if err := quick.Check(f, cfg); err != nil { 193 t.Fatal(err) 194 } 195 } 196 197 // The time routines provide no way to get absolute time 198 // (seconds since zero), but we need it to compute the right 199 // answer for bizarre roundings like "to the nearest 3 ns". 200 // Compute as t - year1 = (t - 1970) + (1970 - 2001) + (2001 - 1). 201 // t - 1970 is returned by Unix and Nanosecond. 202 // 1970 - 2001 is -(31*365+8)*86400 = -978307200 seconds. 203 // 2001 - 1 is 2000*365.2425*86400 = 63113904000 seconds. 204 const unixToZero = -978307200 + 63113904000 205 206 // abs returns the absolute time stored in t, as seconds and nanoseconds. 207 func abs(t Time) (sec, nsec int64) { 208 unix := t.Unix() 209 nano := t.Nanosecond() 210 return unix + unixToZero, int64(nano) 211 } 212 213 // absString returns abs as a decimal string. 214 func absString(t Time) string { 215 sec, nsec := abs(t) 216 if sec < 0 { 217 sec = -sec 218 nsec = -nsec 219 if nsec < 0 { 220 nsec += 1e9 221 sec-- 222 } 223 return fmt.Sprintf("-%d%09d", sec, nsec) 224 } 225 return fmt.Sprintf("%d%09d", sec, nsec) 226 } 227 228 var truncateRoundTests = []struct { 229 t Time 230 d Duration 231 }{ 232 {Date(-1, January, 1, 12, 15, 30, 5e8, UTC), 3}, 233 {Date(-1, January, 1, 12, 15, 31, 5e8, UTC), 3}, 234 {Date(2012, January, 1, 12, 15, 30, 5e8, UTC), Second}, 235 {Date(2012, January, 1, 12, 15, 31, 5e8, UTC), Second}, 236 } 237 238 func TestTruncateRound(t *testing.T) { 239 var ( 240 bsec = new(big.Int) 241 bnsec = new(big.Int) 242 bd = new(big.Int) 243 bt = new(big.Int) 244 br = new(big.Int) 245 bq = new(big.Int) 246 b1e9 = new(big.Int) 247 ) 248 249 b1e9.SetInt64(1e9) 250 251 testOne := func(ti, tns, di int64) bool { 252 t0 := Unix(ti, int64(tns)).UTC() 253 d := Duration(di) 254 if d < 0 { 255 d = -d 256 } 257 if d <= 0 { 258 d = 1 259 } 260 261 // Compute bt = absolute nanoseconds. 262 sec, nsec := abs(t0) 263 bsec.SetInt64(sec) 264 bnsec.SetInt64(nsec) 265 bt.Mul(bsec, b1e9) 266 bt.Add(bt, bnsec) 267 268 // Compute quotient and remainder mod d. 269 bd.SetInt64(int64(d)) 270 bq.DivMod(bt, bd, br) 271 272 // To truncate, subtract remainder. 273 // br is < d, so it fits in an int64. 274 r := br.Int64() 275 t1 := t0.Add(-Duration(r)) 276 277 // Check that time.Truncate works. 278 if trunc := t0.Truncate(d); trunc != t1 { 279 t.Errorf("Time.Truncate(%s, %s) = %s, want %s\n"+ 280 "%v trunc %v =\n%v want\n%v", 281 t0.Format(RFC3339Nano), d, trunc, t1.Format(RFC3339Nano), 282 absString(t0), int64(d), absString(trunc), absString(t1)) 283 return false 284 } 285 286 // To round, add d back if remainder r > d/2 or r == exactly d/2. 287 // The commented out code would round half to even instead of up, 288 // but that makes it time-zone dependent, which is a bit strange. 289 if r > int64(d)/2 || r+r == int64(d) /*&& bq.Bit(0) == 1*/ { 290 t1 = t1.Add(Duration(d)) 291 } 292 293 // Check that time.Round works. 294 if rnd := t0.Round(d); rnd != t1 { 295 t.Errorf("Time.Round(%s, %s) = %s, want %s\n"+ 296 "%v round %v =\n%v want\n%v", 297 t0.Format(RFC3339Nano), d, rnd, t1.Format(RFC3339Nano), 298 absString(t0), int64(d), absString(rnd), absString(t1)) 299 return false 300 } 301 return true 302 } 303 304 // manual test cases 305 for _, tt := range truncateRoundTests { 306 testOne(tt.t.Unix(), int64(tt.t.Nanosecond()), int64(tt.d)) 307 } 308 309 // exhaustive near 0 310 for i := 0; i < 100; i++ { 311 for j := 1; j < 100; j++ { 312 testOne(unixToZero, int64(i), int64(j)) 313 testOne(unixToZero, -int64(i), int64(j)) 314 if t.Failed() { 315 return 316 } 317 } 318 } 319 320 if t.Failed() { 321 return 322 } 323 324 // randomly generated test cases 325 cfg := &quick.Config{MaxCount: 100000} 326 if testing.Short() { 327 cfg.MaxCount = 1000 328 } 329 330 // divisors of Second 331 f1 := func(ti int64, tns int32, logdi int32) bool { 332 d := Duration(1) 333 a, b := uint(logdi%9), (logdi>>16)%9 334 d <<= a 335 for i := 0; i < int(b); i++ { 336 d *= 5 337 } 338 return testOne(ti, int64(tns), int64(d)) 339 } 340 quick.Check(f1, cfg) 341 342 // multiples of Second 343 f2 := func(ti int64, tns int32, di int32) bool { 344 d := Duration(di) * Second 345 if d < 0 { 346 d = -d 347 } 348 return testOne(ti, int64(tns), int64(d)) 349 } 350 quick.Check(f2, cfg) 351 352 // halfway cases 353 f3 := func(tns, di int64) bool { 354 di &= 0xfffffffe 355 if di == 0 { 356 di = 2 357 } 358 tns -= tns % di 359 if tns < 0 { 360 tns += di / 2 361 } else { 362 tns -= di / 2 363 } 364 return testOne(0, tns, di) 365 } 366 quick.Check(f3, cfg) 367 368 // full generality 369 f4 := func(ti int64, tns int32, di int64) bool { 370 return testOne(ti, int64(tns), di) 371 } 372 quick.Check(f4, cfg) 373 } 374 375 type TimeFormatTest struct { 376 time Time 377 formattedValue string 378 } 379 380 var rfc3339Formats = []TimeFormatTest{ 381 {Date(2008, 9, 17, 20, 4, 26, 0, UTC), "2008-09-17T20:04:26Z"}, 382 {Date(1994, 9, 17, 20, 4, 26, 0, FixedZone("EST", -18000)), "1994-09-17T20:04:26-05:00"}, 383 {Date(2000, 12, 26, 1, 15, 6, 0, FixedZone("OTO", 15600)), "2000-12-26T01:15:06+04:20"}, 384 } 385 386 func TestRFC3339Conversion(t *testing.T) { 387 for _, f := range rfc3339Formats { 388 if f.time.Format(RFC3339) != f.formattedValue { 389 t.Error("RFC3339:") 390 t.Errorf(" want=%+v", f.formattedValue) 391 t.Errorf(" have=%+v", f.time.Format(RFC3339)) 392 } 393 } 394 } 395 396 type FormatTest struct { 397 name string 398 format string 399 result string 400 } 401 402 var formatTests = []FormatTest{ 403 {"ANSIC", ANSIC, "Wed Feb 4 21:00:57 2009"}, 404 {"UnixDate", UnixDate, "Wed Feb 4 21:00:57 PST 2009"}, 405 {"RubyDate", RubyDate, "Wed Feb 04 21:00:57 -0800 2009"}, 406 {"RFC822", RFC822, "04 Feb 09 21:00 PST"}, 407 {"RFC850", RFC850, "Wednesday, 04-Feb-09 21:00:57 PST"}, 408 {"RFC1123", RFC1123, "Wed, 04 Feb 2009 21:00:57 PST"}, 409 {"RFC1123Z", RFC1123Z, "Wed, 04 Feb 2009 21:00:57 -0800"}, 410 {"RFC3339", RFC3339, "2009-02-04T21:00:57-08:00"}, 411 {"RFC3339Nano", RFC3339Nano, "2009-02-04T21:00:57.0123456-08:00"}, 412 {"Kitchen", Kitchen, "9:00PM"}, 413 {"am/pm", "3pm", "9pm"}, 414 {"AM/PM", "3PM", "9PM"}, 415 {"two-digit year", "06 01 02", "09 02 04"}, 416 // Three-letter months and days must not be followed by lower-case letter. 417 {"Janet", "Hi Janet, the Month is January", "Hi Janet, the Month is February"}, 418 // Time stamps, Fractional seconds. 419 {"Stamp", Stamp, "Feb 4 21:00:57"}, 420 {"StampMilli", StampMilli, "Feb 4 21:00:57.012"}, 421 {"StampMicro", StampMicro, "Feb 4 21:00:57.012345"}, 422 {"StampNano", StampNano, "Feb 4 21:00:57.012345600"}, 423 } 424 425 func TestFormat(t *testing.T) { 426 // The numeric time represents Thu Feb 4 21:00:57.012345600 PST 2010 427 time := Unix(0, 1233810057012345600) 428 for _, test := range formatTests { 429 result := time.Format(test.format) 430 if result != test.result { 431 t.Errorf("%s expected %q got %q", test.name, test.result, result) 432 } 433 } 434 } 435 436 func TestFormatShortYear(t *testing.T) { 437 years := []int{ 438 -100001, -100000, -99999, 439 -10001, -10000, -9999, 440 -1001, -1000, -999, 441 -101, -100, -99, 442 -11, -10, -9, 443 -1, 0, 1, 444 9, 10, 11, 445 99, 100, 101, 446 999, 1000, 1001, 447 9999, 10000, 10001, 448 99999, 100000, 100001, 449 } 450 451 for _, y := range years { 452 time := Date(y, January, 1, 0, 0, 0, 0, UTC) 453 result := time.Format("2006.01.02") 454 var want string 455 if y < 0 { 456 // The 4 in %04d counts the - sign, so print -y instead 457 // and introduce our own - sign. 458 want = fmt.Sprintf("-%04d.%02d.%02d", -y, 1, 1) 459 } else { 460 want = fmt.Sprintf("%04d.%02d.%02d", y, 1, 1) 461 } 462 if result != want { 463 t.Errorf("(jan 1 %d).Format(\"2006.01.02\") = %q, want %q", y, result, want) 464 } 465 } 466 } 467 468 type ParseTest struct { 469 name string 470 format string 471 value string 472 hasTZ bool // contains a time zone 473 hasWD bool // contains a weekday 474 yearSign int // sign of year, -1 indicates the year is not present in the format 475 fracDigits int // number of digits of fractional second 476 } 477 478 var parseTests = []ParseTest{ 479 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 480 {"UnixDate", UnixDate, "Thu Feb 4 21:00:57 PST 2010", true, true, 1, 0}, 481 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, 482 {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57 PST", true, true, 1, 0}, 483 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57 PST", true, true, 1, 0}, 484 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 22:00:57 PDT", true, true, 1, 0}, 485 {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57 -0800", true, true, 1, 0}, 486 {"RFC3339", RFC3339, "2010-02-04T21:00:57-08:00", true, false, 1, 0}, 487 {"custom: \"2006-01-02 15:04:05-07\"", "2006-01-02 15:04:05-07", "2010-02-04 21:00:57-08", true, false, 1, 0}, 488 // Optional fractional seconds. 489 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57.0 2010", false, true, 1, 1}, 490 {"UnixDate", UnixDate, "Thu Feb 4 21:00:57.01 PST 2010", true, true, 1, 2}, 491 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57.012 -0800 2010", true, true, 1, 3}, 492 {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57.0123 PST", true, true, 1, 4}, 493 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57.01234 PST", true, true, 1, 5}, 494 {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57.01234 -0800", true, true, 1, 5}, 495 {"RFC3339", RFC3339, "2010-02-04T21:00:57.012345678-08:00", true, false, 1, 9}, 496 {"custom: \"2006-01-02 15:04:05\"", "2006-01-02 15:04:05", "2010-02-04 21:00:57.0", false, false, 1, 0}, 497 // Amount of white space should not matter. 498 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 499 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 500 // Case should not matter 501 {"ANSIC", ANSIC, "THU FEB 4 21:00:57 2010", false, true, 1, 0}, 502 {"ANSIC", ANSIC, "thu feb 4 21:00:57 2010", false, true, 1, 0}, 503 // Fractional seconds. 504 {"millisecond", "Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 21:00:57.012 2010", false, true, 1, 3}, 505 {"microsecond", "Mon Jan _2 15:04:05.000000 2006", "Thu Feb 4 21:00:57.012345 2010", false, true, 1, 6}, 506 {"nanosecond", "Mon Jan _2 15:04:05.000000000 2006", "Thu Feb 4 21:00:57.012345678 2010", false, true, 1, 9}, 507 // Leading zeros in other places should not be taken as fractional seconds. 508 {"zero1", "2006.01.02.15.04.05.0", "2010.02.04.21.00.57.0", false, false, 1, 1}, 509 {"zero2", "2006.01.02.15.04.05.00", "2010.02.04.21.00.57.01", false, false, 1, 2}, 510 // Month and day names only match when not followed by a lower-case letter. 511 {"Janet", "Hi Janet, the Month is January: Jan _2 15:04:05 2006", "Hi Janet, the Month is February: Feb 4 21:00:57 2010", false, true, 1, 0}, 512 513 // GMT with offset. 514 {"GMT-8", UnixDate, "Fri Feb 5 05:00:57 GMT-8 2010", true, true, 1, 0}, 515 516 // Accept any number of fractional second digits (including none) for .999... 517 // In Go 1, .999... was completely ignored in the format, meaning the first two 518 // cases would succeed, but the next four would not. Go 1.1 accepts all six. 519 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, 520 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, 521 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, 522 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, 523 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, 524 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, 525 526 // issue 4502. 527 {"", StampNano, "Feb 4 21:00:57.012345678", false, false, -1, 9}, 528 {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012300000", false, false, -1, 4}, 529 {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, 530 {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.0123", false, false, -1, 4}, 531 {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, 532 } 533 534 func TestParse(t *testing.T) { 535 for _, test := range parseTests { 536 time, err := Parse(test.format, test.value) 537 if err != nil { 538 t.Errorf("%s error: %v", test.name, err) 539 } else { 540 checkTime(time, &test, t) 541 } 542 } 543 } 544 545 func TestParseInSydney(t *testing.T) { 546 loc, err := LoadLocation("Australia/Sydney") 547 if err != nil { 548 t.Fatal(err) 549 } 550 551 // Check that Parse (and ParseInLocation) understand 552 // that Feb EST and Aug EST are different time zones in Sydney 553 // even though both are called EST. 554 t1, err := ParseInLocation("Jan 02 2006 MST", "Feb 01 2013 EST", loc) 555 if err != nil { 556 t.Fatal(err) 557 } 558 t2 := Date(2013, February, 1, 00, 00, 00, 0, loc) 559 if t1 != t2 { 560 t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney) = %v, want %v", t1, t2) 561 } 562 _, offset := t1.Zone() 563 if offset != 11*60*60 { 564 t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 11*60*60) 565 } 566 567 t1, err = ParseInLocation("Jan 02 2006 MST", "Aug 01 2013 EST", loc) 568 if err != nil { 569 t.Fatal(err) 570 } 571 t2 = Date(2013, August, 1, 00, 00, 00, 0, loc) 572 if t1 != t2 { 573 t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney) = %v, want %v", t1, t2) 574 } 575 _, offset = t1.Zone() 576 if offset != 10*60*60 { 577 t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 10*60*60) 578 } 579 } 580 581 var rubyTests = []ParseTest{ 582 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, 583 // Ignore the time zone in the test. If it parses, it'll be OK. 584 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0000 2010", false, true, 1, 0}, 585 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +0000 2010", false, true, 1, 0}, 586 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +1130 2010", false, true, 1, 0}, 587 } 588 589 // Problematic time zone format needs special tests. 590 func TestRubyParse(t *testing.T) { 591 for _, test := range rubyTests { 592 time, err := Parse(test.format, test.value) 593 if err != nil { 594 t.Errorf("%s error: %v", test.name, err) 595 } else { 596 checkTime(time, &test, t) 597 } 598 } 599 } 600 601 func checkTime(time Time, test *ParseTest, t *testing.T) { 602 // The time should be Thu Feb 4 21:00:57 PST 2010 603 if test.yearSign >= 0 && test.yearSign*time.Year() != 2010 { 604 t.Errorf("%s: bad year: %d not %d", test.name, time.Year(), 2010) 605 } 606 if time.Month() != February { 607 t.Errorf("%s: bad month: %s not %s", test.name, time.Month(), February) 608 } 609 if time.Day() != 4 { 610 t.Errorf("%s: bad day: %d not %d", test.name, time.Day(), 4) 611 } 612 if time.Hour() != 21 { 613 t.Errorf("%s: bad hour: %d not %d", test.name, time.Hour(), 21) 614 } 615 if time.Minute() != 0 { 616 t.Errorf("%s: bad minute: %d not %d", test.name, time.Minute(), 0) 617 } 618 if time.Second() != 57 { 619 t.Errorf("%s: bad second: %d not %d", test.name, time.Second(), 57) 620 } 621 // Nanoseconds must be checked against the precision of the input. 622 nanosec, err := strconv.ParseUint("012345678"[:test.fracDigits]+"000000000"[:9-test.fracDigits], 10, 0) 623 if err != nil { 624 panic(err) 625 } 626 if time.Nanosecond() != int(nanosec) { 627 t.Errorf("%s: bad nanosecond: %d not %d", test.name, time.Nanosecond(), nanosec) 628 } 629 name, offset := time.Zone() 630 if test.hasTZ && offset != -28800 { 631 t.Errorf("%s: bad tz offset: %s %d not %d", test.name, name, offset, -28800) 632 } 633 if test.hasWD && time.Weekday() != Thursday { 634 t.Errorf("%s: bad weekday: %s not %s", test.name, time.Weekday(), Thursday) 635 } 636 } 637 638 func TestFormatAndParse(t *testing.T) { 639 const fmt = "Mon MST " + RFC3339 // all fields 640 f := func(sec int64) bool { 641 t1 := Unix(sec, 0) 642 if t1.Year() < 1000 || t1.Year() > 9999 { 643 // not required to work 644 return true 645 } 646 t2, err := Parse(fmt, t1.Format(fmt)) 647 if err != nil { 648 t.Errorf("error: %s", err) 649 return false 650 } 651 if t1.Unix() != t2.Unix() || t1.Nanosecond() != t2.Nanosecond() { 652 t.Errorf("FormatAndParse %d: %q(%d) %q(%d)", sec, t1, t1.Unix(), t2, t2.Unix()) 653 return false 654 } 655 return true 656 } 657 f32 := func(sec int32) bool { return f(int64(sec)) } 658 cfg := &quick.Config{MaxCount: 10000} 659 660 // Try a reasonable date first, then the huge ones. 661 if err := quick.Check(f32, cfg); err != nil { 662 t.Fatal(err) 663 } 664 if err := quick.Check(f, cfg); err != nil { 665 t.Fatal(err) 666 } 667 } 668 669 type ParseTimeZoneTest struct { 670 value string 671 length int 672 ok bool 673 } 674 675 var parseTimeZoneTests = []ParseTimeZoneTest{ 676 {"gmt hi there", 0, false}, 677 {"GMT hi there", 3, true}, 678 {"GMT+12 hi there", 6, true}, 679 {"GMT+00 hi there", 3, true}, // 0 or 00 is not a legal offset. 680 {"GMT-5 hi there", 5, true}, 681 {"GMT-51 hi there", 3, true}, 682 {"ChST hi there", 4, true}, 683 {"MSDx", 3, true}, 684 {"MSDY", 0, false}, // four letters must end in T. 685 {"ESAST hi", 5, true}, 686 {"ESASTT hi", 0, false}, // run of upper-case letters too long. 687 {"ESATY hi", 0, false}, // five letters must end in T. 688 } 689 690 func TestParseTimeZone(t *testing.T) { 691 for _, test := range parseTimeZoneTests { 692 length, ok := ParseTimeZone(test.value) 693 if ok != test.ok { 694 t.Errorf("expected %t for %q got %t", test.ok, test.value, ok) 695 } else if length != test.length { 696 t.Errorf("expected %d for %q got %d", test.length, test.value, length) 697 } 698 } 699 } 700 701 type ParseErrorTest struct { 702 format string 703 value string 704 expect string // must appear within the error 705 } 706 707 var parseErrorTests = []ParseErrorTest{ 708 {ANSIC, "Feb 4 21:00:60 2010", "cannot parse"}, // cannot parse Feb as Mon 709 {ANSIC, "Thu Feb 4 21:00:57 @2010", "cannot parse"}, 710 {ANSIC, "Thu Feb 4 21:00:60 2010", "second out of range"}, 711 {ANSIC, "Thu Feb 4 21:61:57 2010", "minute out of range"}, 712 {ANSIC, "Thu Feb 4 24:00:60 2010", "hour out of range"}, 713 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59x01 2010", "cannot parse"}, 714 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.xxx 2010", "cannot parse"}, 715 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.-123 2010", "fractional second out of range"}, 716 // issue 4502. StampNano requires exactly 9 digits of precision. 717 {StampNano, "Dec 7 11:22:01.000000", `cannot parse ".000000" as ".000000000"`}, 718 {StampNano, "Dec 7 11:22:01.0000000000", "extra text: 0"}, 719 // issue 4493. Helpful errors. 720 {RFC3339, "2006-01-02T15:04:05Z07:00", `parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00`}, 721 {RFC3339, "2006-01-02T15:04_abc", `parsing time "2006-01-02T15:04_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as ":"`}, 722 {RFC3339, "2006-01-02T15:04:05_abc", `parsing time "2006-01-02T15:04:05_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as "Z07:00"`}, 723 {RFC3339, "2006-01-02T15:04:05Z_abc", `parsing time "2006-01-02T15:04:05Z_abc": extra text: _abc`}, 724 } 725 726 func TestParseErrors(t *testing.T) { 727 for _, test := range parseErrorTests { 728 _, err := Parse(test.format, test.value) 729 if err == nil { 730 t.Errorf("expected error for %q %q", test.format, test.value) 731 } else if strings.Index(err.Error(), test.expect) < 0 { 732 t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err) 733 } 734 } 735 } 736 737 func TestNoonIs12PM(t *testing.T) { 738 noon := Date(0, January, 1, 12, 0, 0, 0, UTC) 739 const expect = "12:00PM" 740 got := noon.Format("3:04PM") 741 if got != expect { 742 t.Errorf("got %q; expect %q", got, expect) 743 } 744 got = noon.Format("03:04PM") 745 if got != expect { 746 t.Errorf("got %q; expect %q", got, expect) 747 } 748 } 749 750 func TestMidnightIs12AM(t *testing.T) { 751 midnight := Date(0, January, 1, 0, 0, 0, 0, UTC) 752 expect := "12:00AM" 753 got := midnight.Format("3:04PM") 754 if got != expect { 755 t.Errorf("got %q; expect %q", got, expect) 756 } 757 got = midnight.Format("03:04PM") 758 if got != expect { 759 t.Errorf("got %q; expect %q", got, expect) 760 } 761 } 762 763 func Test12PMIsNoon(t *testing.T) { 764 noon, err := Parse("3:04PM", "12:00PM") 765 if err != nil { 766 t.Fatal("error parsing date:", err) 767 } 768 if noon.Hour() != 12 { 769 t.Errorf("got %d; expect 12", noon.Hour()) 770 } 771 noon, err = Parse("03:04PM", "12:00PM") 772 if err != nil { 773 t.Fatal("error parsing date:", err) 774 } 775 if noon.Hour() != 12 { 776 t.Errorf("got %d; expect 12", noon.Hour()) 777 } 778 } 779 780 func Test12AMIsMidnight(t *testing.T) { 781 midnight, err := Parse("3:04PM", "12:00AM") 782 if err != nil { 783 t.Fatal("error parsing date:", err) 784 } 785 if midnight.Hour() != 0 { 786 t.Errorf("got %d; expect 0", midnight.Hour()) 787 } 788 midnight, err = Parse("03:04PM", "12:00AM") 789 if err != nil { 790 t.Fatal("error parsing date:", err) 791 } 792 if midnight.Hour() != 0 { 793 t.Errorf("got %d; expect 0", midnight.Hour()) 794 } 795 } 796 797 // Check that a time without a Zone still produces a (numeric) time zone 798 // when formatted with MST as a requested zone. 799 func TestMissingZone(t *testing.T) { 800 time, err := Parse(RubyDate, "Thu Feb 02 16:10:03 -0500 2006") 801 if err != nil { 802 t.Fatal("error parsing date:", err) 803 } 804 expect := "Thu Feb 2 16:10:03 -0500 2006" // -0500 not EST 805 str := time.Format(UnixDate) // uses MST as its time zone 806 if str != expect { 807 t.Errorf("got %s; expect %s", str, expect) 808 } 809 } 810 811 func TestMinutesInTimeZone(t *testing.T) { 812 time, err := Parse(RubyDate, "Mon Jan 02 15:04:05 +0123 2006") 813 if err != nil { 814 t.Fatal("error parsing date:", err) 815 } 816 expected := (1*60 + 23) * 60 817 _, offset := time.Zone() 818 if offset != expected { 819 t.Errorf("ZoneOffset = %d, want %d", offset, expected) 820 } 821 } 822 823 type SecondsTimeZoneOffsetTest struct { 824 format string 825 value string 826 expectedoffset int 827 } 828 829 var secondsTimeZoneOffsetTests = []SecondsTimeZoneOffsetTest{ 830 {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, 831 {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02-00:34:08", -(34*60 + 8)}, 832 {"2006-01-02T15:04:05-070000", "1871-01-01T05:33:02+003408", 34*60 + 8}, 833 {"2006-01-02T15:04:05-07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, 834 {"2006-01-02T15:04:05Z070000", "1871-01-01T05:33:02-003408", -(34*60 + 8)}, 835 {"2006-01-02T15:04:05Z07:00:00", "1871-01-01T05:33:02+00:34:08", 34*60 + 8}, 836 } 837 838 func TestParseSecondsInTimeZone(t *testing.T) { 839 // should accept timezone offsets with seconds like: Zone America/New_York -4:56:02 - LMT 1883 Nov 18 12:03:58 840 for _, test := range secondsTimeZoneOffsetTests { 841 time, err := Parse(test.format, test.value) 842 if err != nil { 843 t.Fatal("error parsing date:", err) 844 } 845 _, offset := time.Zone() 846 if offset != test.expectedoffset { 847 t.Errorf("ZoneOffset = %d, want %d", offset, test.expectedoffset) 848 } 849 } 850 } 851 852 func TestFormatSecondsInTimeZone(t *testing.T) { 853 d := Date(1871, 9, 17, 20, 4, 26, 0, FixedZone("LMT", -(34*60+8))) 854 timestr := d.Format("2006-01-02T15:04:05Z070000") 855 expected := "1871-09-17T20:04:26-003408" 856 if timestr != expected { 857 t.Errorf("Got %s, want %s", timestr, expected) 858 } 859 } 860 861 type ISOWeekTest struct { 862 year int // year 863 month, day int // month and day 864 yex int // expected year 865 wex int // expected week 866 } 867 868 var isoWeekTests = []ISOWeekTest{ 869 {1981, 1, 1, 1981, 1}, {1982, 1, 1, 1981, 53}, {1983, 1, 1, 1982, 52}, 870 {1984, 1, 1, 1983, 52}, {1985, 1, 1, 1985, 1}, {1986, 1, 1, 1986, 1}, 871 {1987, 1, 1, 1987, 1}, {1988, 1, 1, 1987, 53}, {1989, 1, 1, 1988, 52}, 872 {1990, 1, 1, 1990, 1}, {1991, 1, 1, 1991, 1}, {1992, 1, 1, 1992, 1}, 873 {1993, 1, 1, 1992, 53}, {1994, 1, 1, 1993, 52}, {1995, 1, 2, 1995, 1}, 874 {1996, 1, 1, 1996, 1}, {1996, 1, 7, 1996, 1}, {1996, 1, 8, 1996, 2}, 875 {1997, 1, 1, 1997, 1}, {1998, 1, 1, 1998, 1}, {1999, 1, 1, 1998, 53}, 876 {2000, 1, 1, 1999, 52}, {2001, 1, 1, 2001, 1}, {2002, 1, 1, 2002, 1}, 877 {2003, 1, 1, 2003, 1}, {2004, 1, 1, 2004, 1}, {2005, 1, 1, 2004, 53}, 878 {2006, 1, 1, 2005, 52}, {2007, 1, 1, 2007, 1}, {2008, 1, 1, 2008, 1}, 879 {2009, 1, 1, 2009, 1}, {2010, 1, 1, 2009, 53}, {2010, 1, 1, 2009, 53}, 880 {2011, 1, 1, 2010, 52}, {2011, 1, 2, 2010, 52}, {2011, 1, 3, 2011, 1}, 881 {2011, 1, 4, 2011, 1}, {2011, 1, 5, 2011, 1}, {2011, 1, 6, 2011, 1}, 882 {2011, 1, 7, 2011, 1}, {2011, 1, 8, 2011, 1}, {2011, 1, 9, 2011, 1}, 883 {2011, 1, 10, 2011, 2}, {2011, 1, 11, 2011, 2}, {2011, 6, 12, 2011, 23}, 884 {2011, 6, 13, 2011, 24}, {2011, 12, 25, 2011, 51}, {2011, 12, 26, 2011, 52}, 885 {2011, 12, 27, 2011, 52}, {2011, 12, 28, 2011, 52}, {2011, 12, 29, 2011, 52}, 886 {2011, 12, 30, 2011, 52}, {2011, 12, 31, 2011, 52}, {1995, 1, 1, 1994, 52}, 887 {2012, 1, 1, 2011, 52}, {2012, 1, 2, 2012, 1}, {2012, 1, 8, 2012, 1}, 888 {2012, 1, 9, 2012, 2}, {2012, 12, 23, 2012, 51}, {2012, 12, 24, 2012, 52}, 889 {2012, 12, 30, 2012, 52}, {2012, 12, 31, 2013, 1}, {2013, 1, 1, 2013, 1}, 890 {2013, 1, 6, 2013, 1}, {2013, 1, 7, 2013, 2}, {2013, 12, 22, 2013, 51}, 891 {2013, 12, 23, 2013, 52}, {2013, 12, 29, 2013, 52}, {2013, 12, 30, 2014, 1}, 892 {2014, 1, 1, 2014, 1}, {2014, 1, 5, 2014, 1}, {2014, 1, 6, 2014, 2}, 893 {2015, 1, 1, 2015, 1}, {2016, 1, 1, 2015, 53}, {2017, 1, 1, 2016, 52}, 894 {2018, 1, 1, 2018, 1}, {2019, 1, 1, 2019, 1}, {2020, 1, 1, 2020, 1}, 895 {2021, 1, 1, 2020, 53}, {2022, 1, 1, 2021, 52}, {2023, 1, 1, 2022, 52}, 896 {2024, 1, 1, 2024, 1}, {2025, 1, 1, 2025, 1}, {2026, 1, 1, 2026, 1}, 897 {2027, 1, 1, 2026, 53}, {2028, 1, 1, 2027, 52}, {2029, 1, 1, 2029, 1}, 898 {2030, 1, 1, 2030, 1}, {2031, 1, 1, 2031, 1}, {2032, 1, 1, 2032, 1}, 899 {2033, 1, 1, 2032, 53}, {2034, 1, 1, 2033, 52}, {2035, 1, 1, 2035, 1}, 900 {2036, 1, 1, 2036, 1}, {2037, 1, 1, 2037, 1}, {2038, 1, 1, 2037, 53}, 901 {2039, 1, 1, 2038, 52}, {2040, 1, 1, 2039, 52}, 902 } 903 904 func TestISOWeek(t *testing.T) { 905 // Selected dates and corner cases 906 for _, wt := range isoWeekTests { 907 dt := Date(wt.year, Month(wt.month), wt.day, 0, 0, 0, 0, UTC) 908 y, w := dt.ISOWeek() 909 if w != wt.wex || y != wt.yex { 910 t.Errorf("got %d/%d; expected %d/%d for %d-%02d-%02d", 911 y, w, wt.yex, wt.wex, wt.year, wt.month, wt.day) 912 } 913 } 914 915 // The only real invariant: Jan 04 is in week 1 916 for year := 1950; year < 2100; year++ { 917 if y, w := Date(year, January, 4, 0, 0, 0, 0, UTC).ISOWeek(); y != year || w != 1 { 918 t.Errorf("got %d/%d; expected %d/1 for Jan 04", y, w, year) 919 } 920 } 921 } 922 923 type YearDayTest struct { 924 year, month, day int 925 yday int 926 } 927 928 // Test YearDay in several different scenarios 929 // and corner cases 930 var yearDayTests = []YearDayTest{ 931 // Non-leap-year tests 932 {2007, 1, 1, 1}, 933 {2007, 1, 15, 15}, 934 {2007, 2, 1, 32}, 935 {2007, 2, 15, 46}, 936 {2007, 3, 1, 60}, 937 {2007, 3, 15, 74}, 938 {2007, 4, 1, 91}, 939 {2007, 12, 31, 365}, 940 941 // Leap-year tests 942 {2008, 1, 1, 1}, 943 {2008, 1, 15, 15}, 944 {2008, 2, 1, 32}, 945 {2008, 2, 15, 46}, 946 {2008, 3, 1, 61}, 947 {2008, 3, 15, 75}, 948 {2008, 4, 1, 92}, 949 {2008, 12, 31, 366}, 950 951 // Looks like leap-year (but isn't) tests 952 {1900, 1, 1, 1}, 953 {1900, 1, 15, 15}, 954 {1900, 2, 1, 32}, 955 {1900, 2, 15, 46}, 956 {1900, 3, 1, 60}, 957 {1900, 3, 15, 74}, 958 {1900, 4, 1, 91}, 959 {1900, 12, 31, 365}, 960 961 // Year one tests (non-leap) 962 {1, 1, 1, 1}, 963 {1, 1, 15, 15}, 964 {1, 2, 1, 32}, 965 {1, 2, 15, 46}, 966 {1, 3, 1, 60}, 967 {1, 3, 15, 74}, 968 {1, 4, 1, 91}, 969 {1, 12, 31, 365}, 970 971 // Year minus one tests (non-leap) 972 {-1, 1, 1, 1}, 973 {-1, 1, 15, 15}, 974 {-1, 2, 1, 32}, 975 {-1, 2, 15, 46}, 976 {-1, 3, 1, 60}, 977 {-1, 3, 15, 74}, 978 {-1, 4, 1, 91}, 979 {-1, 12, 31, 365}, 980 981 // 400 BC tests (leap-year) 982 {-400, 1, 1, 1}, 983 {-400, 1, 15, 15}, 984 {-400, 2, 1, 32}, 985 {-400, 2, 15, 46}, 986 {-400, 3, 1, 61}, 987 {-400, 3, 15, 75}, 988 {-400, 4, 1, 92}, 989 {-400, 12, 31, 366}, 990 991 // Special Cases 992 993 // Gregorian calendar change (no effect) 994 {1582, 10, 4, 277}, 995 {1582, 10, 15, 288}, 996 } 997 998 // Check to see if YearDay is location sensitive 999 var yearDayLocations = []*Location{ 1000 FixedZone("UTC-8", -8*60*60), 1001 FixedZone("UTC-4", -4*60*60), 1002 UTC, 1003 FixedZone("UTC+4", 4*60*60), 1004 FixedZone("UTC+8", 8*60*60), 1005 } 1006 1007 func TestYearDay(t *testing.T) { 1008 for _, loc := range yearDayLocations { 1009 for _, ydt := range yearDayTests { 1010 dt := Date(ydt.year, Month(ydt.month), ydt.day, 0, 0, 0, 0, loc) 1011 yday := dt.YearDay() 1012 if yday != ydt.yday { 1013 t.Errorf("got %d, expected %d for %d-%02d-%02d in %v", 1014 yday, ydt.yday, ydt.year, ydt.month, ydt.day, loc) 1015 } 1016 } 1017 } 1018 } 1019 1020 var durationTests = []struct { 1021 str string 1022 d Duration 1023 }{ 1024 {"0", 0}, 1025 {"1ns", 1 * Nanosecond}, 1026 {"1.1us", 1100 * Nanosecond}, 1027 {"2.2ms", 2200 * Microsecond}, 1028 {"3.3s", 3300 * Millisecond}, 1029 {"4m5s", 4*Minute + 5*Second}, 1030 {"4m5.001s", 4*Minute + 5001*Millisecond}, 1031 {"5h6m7.001s", 5*Hour + 6*Minute + 7001*Millisecond}, 1032 {"8m0.000000001s", 8*Minute + 1*Nanosecond}, 1033 {"2562047h47m16.854775807s", 1<<63 - 1}, 1034 {"-2562047h47m16.854775808s", -1 << 63}, 1035 } 1036 1037 func TestDurationString(t *testing.T) { 1038 for _, tt := range durationTests { 1039 if str := tt.d.String(); str != tt.str { 1040 t.Errorf("Duration(%d).String() = %s, want %s", int64(tt.d), str, tt.str) 1041 } 1042 if tt.d > 0 { 1043 if str := (-tt.d).String(); str != "-"+tt.str { 1044 t.Errorf("Duration(%d).String() = %s, want %s", int64(-tt.d), str, "-"+tt.str) 1045 } 1046 } 1047 } 1048 } 1049 1050 var dateTests = []struct { 1051 year, month, day, hour, min, sec, nsec int 1052 z *Location 1053 unix int64 1054 }{ 1055 {2011, 11, 6, 1, 0, 0, 0, Local, 1320566400}, // 1:00:00 PDT 1056 {2011, 11, 6, 1, 59, 59, 0, Local, 1320569999}, // 1:59:59 PDT 1057 {2011, 11, 6, 2, 0, 0, 0, Local, 1320573600}, // 2:00:00 PST 1058 1059 {2011, 3, 13, 1, 0, 0, 0, Local, 1300006800}, // 1:00:00 PST 1060 {2011, 3, 13, 1, 59, 59, 0, Local, 1300010399}, // 1:59:59 PST 1061 {2011, 3, 13, 3, 0, 0, 0, Local, 1300010400}, // 3:00:00 PDT 1062 {2011, 3, 13, 2, 30, 0, 0, Local, 1300008600}, // 2:30:00 PDT ≡ 1:30 PST 1063 1064 // Many names for Fri Nov 18 7:56:35 PST 2011 1065 {2011, 11, 18, 7, 56, 35, 0, Local, 1321631795}, // Nov 18 7:56:35 1066 {2011, 11, 19, -17, 56, 35, 0, Local, 1321631795}, // Nov 19 -17:56:35 1067 {2011, 11, 17, 31, 56, 35, 0, Local, 1321631795}, // Nov 17 31:56:35 1068 {2011, 11, 18, 6, 116, 35, 0, Local, 1321631795}, // Nov 18 6:116:35 1069 {2011, 10, 49, 7, 56, 35, 0, Local, 1321631795}, // Oct 49 7:56:35 1070 {2011, 11, 18, 7, 55, 95, 0, Local, 1321631795}, // Nov 18 7:55:95 1071 {2011, 11, 18, 7, 56, 34, 1e9, Local, 1321631795}, // Nov 18 7:56:34 + 10⁹ns 1072 {2011, 12, -12, 7, 56, 35, 0, Local, 1321631795}, // Dec -21 7:56:35 1073 {2012, 1, -43, 7, 56, 35, 0, Local, 1321631795}, // Jan -52 7:56:35 2012 1074 {2012, int(January - 2), 18, 7, 56, 35, 0, Local, 1321631795}, // (Jan-2) 18 7:56:35 2012 1075 {2010, int(December + 11), 18, 7, 56, 35, 0, Local, 1321631795}, // (Dec+11) 18 7:56:35 2010 1076 } 1077 1078 func TestDate(t *testing.T) { 1079 for _, tt := range dateTests { 1080 time := Date(tt.year, Month(tt.month), tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z) 1081 want := Unix(tt.unix, 0) 1082 if !time.Equal(want) { 1083 t.Errorf("Date(%d, %d, %d, %d, %d, %d, %d, %s) = %v, want %v", 1084 tt.year, tt.month, tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z, 1085 time, want) 1086 } 1087 } 1088 } 1089 1090 // Several ways of getting from 1091 // Fri Nov 18 7:56:35 PST 2011 1092 // to 1093 // Thu Mar 19 7:56:35 PST 2016 1094 var addDateTests = []struct { 1095 years, months, days int 1096 }{ 1097 {4, 4, 1}, 1098 {3, 16, 1}, 1099 {3, 15, 30}, 1100 {5, -6, -18 - 30 - 12}, 1101 } 1102 1103 func TestAddDate(t *testing.T) { 1104 t0 := Date(2011, 11, 18, 7, 56, 35, 0, UTC) 1105 t1 := Date(2016, 3, 19, 7, 56, 35, 0, UTC) 1106 for _, at := range addDateTests { 1107 time := t0.AddDate(at.years, at.months, at.days) 1108 if !time.Equal(t1) { 1109 t.Errorf("AddDate(%d, %d, %d) = %v, want %v", 1110 at.years, at.months, at.days, 1111 time, t1) 1112 } 1113 } 1114 } 1115 1116 var daysInTests = []struct { 1117 year, month, di int 1118 }{ 1119 {2011, 1, 31}, // January, first month, 31 days 1120 {2011, 2, 28}, // February, non-leap year, 28 days 1121 {2012, 2, 29}, // February, leap year, 29 days 1122 {2011, 6, 30}, // June, 30 days 1123 {2011, 12, 31}, // December, last month, 31 days 1124 } 1125 1126 func TestDaysIn(t *testing.T) { 1127 // The daysIn function is not exported. 1128 // Test the daysIn function via the `var DaysIn = daysIn` 1129 // statement in the internal_test.go file. 1130 for _, tt := range daysInTests { 1131 di := DaysIn(Month(tt.month), tt.year) 1132 if di != tt.di { 1133 t.Errorf("got %d; expected %d for %d-%02d", 1134 di, tt.di, tt.year, tt.month) 1135 } 1136 } 1137 } 1138 1139 func TestAddToExactSecond(t *testing.T) { 1140 // Add an amount to the current time to round it up to the next exact second. 1141 // This test checks that the nsec field still lies within the range [0, 999999999]. 1142 t1 := Now() 1143 t2 := t1.Add(Second - Duration(t1.Nanosecond())) 1144 sec := (t1.Second() + 1) % 60 1145 if t2.Second() != sec || t2.Nanosecond() != 0 { 1146 t.Errorf("sec = %d, nsec = %d, want sec = %d, nsec = 0", t2.Second(), t2.Nanosecond(), sec) 1147 } 1148 } 1149 1150 func equalTimeAndZone(a, b Time) bool { 1151 aname, aoffset := a.Zone() 1152 bname, boffset := b.Zone() 1153 return a.Equal(b) && aoffset == boffset && aname == bname 1154 } 1155 1156 var gobTests = []Time{ 1157 Date(0, 1, 2, 3, 4, 5, 6, UTC), 1158 Date(7, 8, 9, 10, 11, 12, 13, FixedZone("", 0)), 1159 Unix(81985467080890095, 0x76543210), // Time.sec: 0x0123456789ABCDEF 1160 {}, // nil location 1161 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", 32767*60)), 1162 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", -32768*60)), 1163 } 1164 1165 func TestTimeGob(t *testing.T) { 1166 var b bytes.Buffer 1167 enc := gob.NewEncoder(&b) 1168 dec := gob.NewDecoder(&b) 1169 for _, tt := range gobTests { 1170 var gobtt Time 1171 if err := enc.Encode(&tt); err != nil { 1172 t.Errorf("%v gob Encode error = %q, want nil", tt, err) 1173 } else if err := dec.Decode(&gobtt); err != nil { 1174 t.Errorf("%v gob Decode error = %q, want nil", tt, err) 1175 } else if !equalTimeAndZone(gobtt, tt) { 1176 t.Errorf("Decoded time = %v, want %v", gobtt, tt) 1177 } 1178 b.Reset() 1179 } 1180 } 1181 1182 var invalidEncodingTests = []struct { 1183 bytes []byte 1184 want string 1185 }{ 1186 {[]byte{}, "Time.UnmarshalBinary: no data"}, 1187 {[]byte{0, 2, 3}, "Time.UnmarshalBinary: unsupported version"}, 1188 {[]byte{1, 2, 3}, "Time.UnmarshalBinary: invalid length"}, 1189 } 1190 1191 func TestInvalidTimeGob(t *testing.T) { 1192 for _, tt := range invalidEncodingTests { 1193 var ignored Time 1194 err := ignored.GobDecode(tt.bytes) 1195 if err == nil || err.Error() != tt.want { 1196 t.Errorf("time.GobDecode(%#v) error = %v, want %v", tt.bytes, err, tt.want) 1197 } 1198 err = ignored.UnmarshalBinary(tt.bytes) 1199 if err == nil || err.Error() != tt.want { 1200 t.Errorf("time.UnmarshalBinary(%#v) error = %v, want %v", tt.bytes, err, tt.want) 1201 } 1202 } 1203 } 1204 1205 var notEncodableTimes = []struct { 1206 time Time 1207 want string 1208 }{ 1209 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 1)), "Time.MarshalBinary: zone offset has fractional minute"}, 1210 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -1*60)), "Time.MarshalBinary: unexpected zone offset"}, 1211 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -32769*60)), "Time.MarshalBinary: unexpected zone offset"}, 1212 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 32768*60)), "Time.MarshalBinary: unexpected zone offset"}, 1213 } 1214 1215 func TestNotGobEncodableTime(t *testing.T) { 1216 for _, tt := range notEncodableTimes { 1217 _, err := tt.time.GobEncode() 1218 if err == nil || err.Error() != tt.want { 1219 t.Errorf("%v GobEncode error = %v, want %v", tt.time, err, tt.want) 1220 } 1221 _, err = tt.time.MarshalBinary() 1222 if err == nil || err.Error() != tt.want { 1223 t.Errorf("%v MarshalBinary error = %v, want %v", tt.time, err, tt.want) 1224 } 1225 } 1226 } 1227 1228 var jsonTests = []struct { 1229 time Time 1230 json string 1231 }{ 1232 {Date(9999, 4, 12, 23, 20, 50, 520*1e6, UTC), `"9999-04-12T23:20:50.52Z"`}, 1233 {Date(1996, 12, 19, 16, 39, 57, 0, Local), `"1996-12-19T16:39:57-08:00"`}, 1234 {Date(0, 1, 1, 0, 0, 0, 1, FixedZone("", 1*60)), `"0000-01-01T00:00:00.000000001+00:01"`}, 1235 } 1236 1237 func TestTimeJSON(t *testing.T) { 1238 for _, tt := range jsonTests { 1239 var jsonTime Time 1240 1241 if jsonBytes, err := json.Marshal(tt.time); err != nil { 1242 t.Errorf("%v json.Marshal error = %v, want nil", tt.time, err) 1243 } else if string(jsonBytes) != tt.json { 1244 t.Errorf("%v JSON = %#q, want %#q", tt.time, string(jsonBytes), tt.json) 1245 } else if err = json.Unmarshal(jsonBytes, &jsonTime); err != nil { 1246 t.Errorf("%v json.Unmarshal error = %v, want nil", tt.time, err) 1247 } else if !equalTimeAndZone(jsonTime, tt.time) { 1248 t.Errorf("Unmarshaled time = %v, want %v", jsonTime, tt.time) 1249 } 1250 } 1251 } 1252 1253 func TestInvalidTimeJSON(t *testing.T) { 1254 var tt Time 1255 err := json.Unmarshal([]byte(`{"now is the time":"buddy"}`), &tt) 1256 _, isParseErr := err.(*ParseError) 1257 if !isParseErr { 1258 t.Errorf("expected *time.ParseError unmarshaling JSON, got %v", err) 1259 } 1260 } 1261 1262 var notJSONEncodableTimes = []struct { 1263 time Time 1264 want string 1265 }{ 1266 {Date(10000, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 1267 {Date(-1, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 1268 } 1269 1270 func TestNotJSONEncodableTime(t *testing.T) { 1271 for _, tt := range notJSONEncodableTimes { 1272 _, err := tt.time.MarshalJSON() 1273 if err == nil || err.Error() != tt.want { 1274 t.Errorf("%v MarshalJSON error = %v, want %v", tt.time, err, tt.want) 1275 } 1276 } 1277 } 1278 1279 var parseDurationTests = []struct { 1280 in string 1281 ok bool 1282 want Duration 1283 }{ 1284 // simple 1285 {"0", true, 0}, 1286 {"5s", true, 5 * Second}, 1287 {"30s", true, 30 * Second}, 1288 {"1478s", true, 1478 * Second}, 1289 // sign 1290 {"-5s", true, -5 * Second}, 1291 {"+5s", true, 5 * Second}, 1292 {"-0", true, 0}, 1293 {"+0", true, 0}, 1294 // decimal 1295 {"5.0s", true, 5 * Second}, 1296 {"5.6s", true, 5*Second + 600*Millisecond}, 1297 {"5.s", true, 5 * Second}, 1298 {".5s", true, 500 * Millisecond}, 1299 {"1.0s", true, 1 * Second}, 1300 {"1.00s", true, 1 * Second}, 1301 {"1.004s", true, 1*Second + 4*Millisecond}, 1302 {"1.0040s", true, 1*Second + 4*Millisecond}, 1303 {"100.00100s", true, 100*Second + 1*Millisecond}, 1304 // different units 1305 {"10ns", true, 10 * Nanosecond}, 1306 {"11us", true, 11 * Microsecond}, 1307 {"12µs", true, 12 * Microsecond}, // U+00B5 1308 {"12μs", true, 12 * Microsecond}, // U+03BC 1309 {"13ms", true, 13 * Millisecond}, 1310 {"14s", true, 14 * Second}, 1311 {"15m", true, 15 * Minute}, 1312 {"16h", true, 16 * Hour}, 1313 // composite durations 1314 {"3h30m", true, 3*Hour + 30*Minute}, 1315 {"10.5s4m", true, 4*Minute + 10*Second + 500*Millisecond}, 1316 {"-2m3.4s", true, -(2*Minute + 3*Second + 400*Millisecond)}, 1317 {"1h2m3s4ms5us6ns", true, 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond}, 1318 {"39h9m14.425s", true, 39*Hour + 9*Minute + 14*Second + 425*Millisecond}, 1319 // large value 1320 {"52763797000ns", true, 52763797000 * Nanosecond}, 1321 1322 // errors 1323 {"", false, 0}, 1324 {"3", false, 0}, 1325 {"-", false, 0}, 1326 {"s", false, 0}, 1327 {".", false, 0}, 1328 {"-.", false, 0}, 1329 {".s", false, 0}, 1330 {"+.s", false, 0}, 1331 } 1332 1333 func TestParseDuration(t *testing.T) { 1334 for _, tc := range parseDurationTests { 1335 d, err := ParseDuration(tc.in) 1336 if tc.ok && (err != nil || d != tc.want) { 1337 t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want) 1338 } else if !tc.ok && err == nil { 1339 t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in) 1340 } 1341 } 1342 } 1343 1344 func TestParseDurationRoundTrip(t *testing.T) { 1345 for i := 0; i < 100; i++ { 1346 // Resolutions finer than milliseconds will result in 1347 // imprecise round-trips. 1348 d0 := Duration(rand.Int31()) * Millisecond 1349 s := d0.String() 1350 d1, err := ParseDuration(s) 1351 if err != nil || d0 != d1 { 1352 t.Errorf("round-trip failed: %d => %q => %d, %v", d0, s, d1, err) 1353 } 1354 } 1355 } 1356 1357 // golang.org/issue/4622 1358 func TestLocationRace(t *testing.T) { 1359 ResetLocalOnceForTest() // reset the Once to trigger the race 1360 1361 c := make(chan string, 1) 1362 go func() { 1363 c <- Now().String() 1364 }() 1365 Now().String() 1366 <-c 1367 Sleep(100 * Millisecond) 1368 1369 // Back to Los Angeles for subsequent tests: 1370 ForceUSPacificForTesting() 1371 } 1372 1373 var ( 1374 t Time 1375 u int64 1376 ) 1377 1378 var mallocTest = []struct { 1379 count int 1380 desc string 1381 fn func() 1382 }{ 1383 {0, `time.Now()`, func() { t = Now() }}, 1384 {0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }}, 1385 } 1386 1387 func TestCountMallocs(t *testing.T) { 1388 if testing.Short() { 1389 t.Skip("skipping malloc count in short mode") 1390 } 1391 if runtime.GOMAXPROCS(0) > 1 { 1392 t.Skip("skipping; GOMAXPROCS>1") 1393 } 1394 for _, mt := range mallocTest { 1395 allocs := int(testing.AllocsPerRun(100, mt.fn)) 1396 if allocs > mt.count { 1397 t.Errorf("%s: %d allocs, want %d", mt.desc, allocs, mt.count) 1398 } 1399 } 1400 } 1401 1402 func TestLoadFixed(t *testing.T) { 1403 // Issue 4064: handle locations without any zone transitions. 1404 loc, err := LoadLocation("Etc/GMT+1") 1405 if err != nil { 1406 t.Fatal(err) 1407 } 1408 1409 // The tzdata name Etc/GMT+1 uses "east is negative", 1410 // but Go and most other systems use "east is positive". 1411 // So GMT+1 corresponds to -3600 in the Go zone, not +3600. 1412 name, offset := Now().In(loc).Zone() 1413 if name != "GMT+1" || offset != -1*60*60 { 1414 t.Errorf("Now().In(loc).Zone() = %q, %d, want %q, %d", name, offset, "GMT+1", -1*60*60) 1415 } 1416 } 1417 1418 const ( 1419 minDuration Duration = -1 << 63 1420 maxDuration Duration = 1<<63 - 1 1421 ) 1422 1423 var subTests = []struct { 1424 t Time 1425 u Time 1426 d Duration 1427 }{ 1428 {Time{}, Time{}, Duration(0)}, 1429 {Date(2009, 11, 23, 0, 0, 0, 1, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), Duration(1)}, 1430 {Date(2009, 11, 23, 0, 0, 0, 0, UTC), Date(2009, 11, 24, 0, 0, 0, 0, UTC), -24 * Hour}, 1431 {Date(2009, 11, 24, 0, 0, 0, 0, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour}, 1432 {Date(-2009, 11, 24, 0, 0, 0, 0, UTC), Date(-2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour}, 1433 {Time{}, Date(2109, 11, 23, 0, 0, 0, 0, UTC), Duration(minDuration)}, 1434 {Date(2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(maxDuration)}, 1435 {Time{}, Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Duration(maxDuration)}, 1436 {Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(minDuration)}, 1437 {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}, 1438 {Date(2300, 1, 1, 0, 0, 0, 0, UTC), Date(2000, 1, 1, 0, 0, 0, 0, UTC), Duration(maxDuration)}, 1439 {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}, 1440 {Date(2000, 1, 1, 0, 0, 0, 0, UTC), Date(2300, 1, 1, 0, 0, 0, 0, UTC), Duration(minDuration)}, 1441 } 1442 1443 func TestSub(t *testing.T) { 1444 for i, st := range subTests { 1445 got := st.t.Sub(st.u) 1446 if got != st.d { 1447 t.Errorf("#%d: Sub(%v, %v): got %v; want %v", i, st.t, st.u, got, st.d) 1448 } 1449 } 1450 } 1451 1452 func BenchmarkNow(b *testing.B) { 1453 for i := 0; i < b.N; i++ { 1454 t = Now() 1455 } 1456 } 1457 1458 func BenchmarkNowUnixNano(b *testing.B) { 1459 for i := 0; i < b.N; i++ { 1460 u = Now().UnixNano() 1461 } 1462 } 1463 1464 func BenchmarkFormat(b *testing.B) { 1465 t := Unix(1265346057, 0) 1466 for i := 0; i < b.N; i++ { 1467 t.Format("Mon Jan 2 15:04:05 2006") 1468 } 1469 } 1470 1471 func BenchmarkFormatNow(b *testing.B) { 1472 // Like BenchmarkFormat, but easier, because the time zone 1473 // lookup cache is optimized for the present. 1474 t := Now() 1475 for i := 0; i < b.N; i++ { 1476 t.Format("Mon Jan 2 15:04:05 2006") 1477 } 1478 } 1479 1480 func BenchmarkParse(b *testing.B) { 1481 for i := 0; i < b.N; i++ { 1482 Parse(ANSIC, "Mon Jan 2 15:04:05 2006") 1483 } 1484 } 1485 1486 func BenchmarkHour(b *testing.B) { 1487 t := Now() 1488 for i := 0; i < b.N; i++ { 1489 _ = t.Hour() 1490 } 1491 } 1492 1493 func BenchmarkSecond(b *testing.B) { 1494 t := Now() 1495 for i := 0; i < b.N; i++ { 1496 _ = t.Second() 1497 } 1498 } 1499 1500 func BenchmarkYear(b *testing.B) { 1501 t := Now() 1502 for i := 0; i < b.N; i++ { 1503 _ = t.Year() 1504 } 1505 } 1506 1507 func BenchmarkDay(b *testing.B) { 1508 t := Now() 1509 for i := 0; i < b.N; i++ { 1510 _ = t.Day() 1511 } 1512 }