github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/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 // Time stamps, Fractional seconds. 417 {"Stamp", Stamp, "Feb 4 21:00:57"}, 418 {"StampMilli", StampMilli, "Feb 4 21:00:57.012"}, 419 {"StampMicro", StampMicro, "Feb 4 21:00:57.012345"}, 420 {"StampNano", StampNano, "Feb 4 21:00:57.012345600"}, 421 } 422 423 func TestFormat(t *testing.T) { 424 // The numeric time represents Thu Feb 4 21:00:57.012345600 PST 2010 425 time := Unix(0, 1233810057012345600) 426 for _, test := range formatTests { 427 result := time.Format(test.format) 428 if result != test.result { 429 t.Errorf("%s expected %q got %q", test.name, test.result, result) 430 } 431 } 432 } 433 434 func TestFormatShortYear(t *testing.T) { 435 years := []int{ 436 -100001, -100000, -99999, 437 -10001, -10000, -9999, 438 -1001, -1000, -999, 439 -101, -100, -99, 440 -11, -10, -9, 441 -1, 0, 1, 442 9, 10, 11, 443 99, 100, 101, 444 999, 1000, 1001, 445 9999, 10000, 10001, 446 99999, 100000, 100001, 447 } 448 449 for _, y := range years { 450 time := Date(y, January, 1, 0, 0, 0, 0, UTC) 451 result := time.Format("2006.01.02") 452 var want string 453 if y < 0 { 454 // The 4 in %04d counts the - sign, so print -y instead 455 // and introduce our own - sign. 456 want = fmt.Sprintf("-%04d.%02d.%02d", -y, 1, 1) 457 } else { 458 want = fmt.Sprintf("%04d.%02d.%02d", y, 1, 1) 459 } 460 if result != want { 461 t.Errorf("(jan 1 %d).Format(\"2006.01.02\") = %q, want %q", y, result, want) 462 } 463 } 464 } 465 466 type ParseTest struct { 467 name string 468 format string 469 value string 470 hasTZ bool // contains a time zone 471 hasWD bool // contains a weekday 472 yearSign int // sign of year, -1 indicates the year is not present in the format 473 fracDigits int // number of digits of fractional second 474 } 475 476 var parseTests = []ParseTest{ 477 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 478 {"UnixDate", UnixDate, "Thu Feb 4 21:00:57 PST 2010", true, true, 1, 0}, 479 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, 480 {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57 PST", true, true, 1, 0}, 481 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57 PST", true, true, 1, 0}, 482 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 22:00:57 PDT", true, true, 1, 0}, 483 {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57 -0800", true, true, 1, 0}, 484 {"RFC3339", RFC3339, "2010-02-04T21:00:57-08:00", true, false, 1, 0}, 485 {"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}, 486 // Optional fractional seconds. 487 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57.0 2010", false, true, 1, 1}, 488 {"UnixDate", UnixDate, "Thu Feb 4 21:00:57.01 PST 2010", true, true, 1, 2}, 489 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57.012 -0800 2010", true, true, 1, 3}, 490 {"RFC850", RFC850, "Thursday, 04-Feb-10 21:00:57.0123 PST", true, true, 1, 4}, 491 {"RFC1123", RFC1123, "Thu, 04 Feb 2010 21:00:57.01234 PST", true, true, 1, 5}, 492 {"RFC1123Z", RFC1123Z, "Thu, 04 Feb 2010 21:00:57.01234 -0800", true, true, 1, 5}, 493 {"RFC3339", RFC3339, "2010-02-04T21:00:57.012345678-08:00", true, false, 1, 9}, 494 {"custom: \"2006-01-02 15:04:05\"", "2006-01-02 15:04:05", "2010-02-04 21:00:57.0", false, false, 1, 0}, 495 // Amount of white space should not matter. 496 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 497 {"ANSIC", ANSIC, "Thu Feb 4 21:00:57 2010", false, true, 1, 0}, 498 // Case should not matter 499 {"ANSIC", ANSIC, "THU FEB 4 21:00:57 2010", false, true, 1, 0}, 500 {"ANSIC", ANSIC, "thu feb 4 21:00:57 2010", false, true, 1, 0}, 501 // Fractional seconds. 502 {"millisecond", "Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 21:00:57.012 2010", false, true, 1, 3}, 503 {"microsecond", "Mon Jan _2 15:04:05.000000 2006", "Thu Feb 4 21:00:57.012345 2010", false, true, 1, 6}, 504 {"nanosecond", "Mon Jan _2 15:04:05.000000000 2006", "Thu Feb 4 21:00:57.012345678 2010", false, true, 1, 9}, 505 // Leading zeros in other places should not be taken as fractional seconds. 506 {"zero1", "2006.01.02.15.04.05.0", "2010.02.04.21.00.57.0", false, false, 1, 1}, 507 {"zero2", "2006.01.02.15.04.05.00", "2010.02.04.21.00.57.01", false, false, 1, 2}, 508 509 // Accept any number of fractional second digits (including none) for .999... 510 // In Go 1, .999... was completely ignored in the format, meaning the first two 511 // cases would succeed, but the next four would not. Go 1.1 accepts all six. 512 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, 513 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57 -0800 PST", true, false, 1, 0}, 514 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, 515 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.0123 -0800 PST", true, false, 1, 4}, 516 {"", "2006-01-02 15:04:05.9999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, 517 {"", "2006-01-02 15:04:05.999999999 -0700 MST", "2010-02-04 21:00:57.012345678 -0800 PST", true, false, 1, 9}, 518 519 // issue 4502. 520 {"", StampNano, "Feb 4 21:00:57.012345678", false, false, -1, 9}, 521 {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012300000", false, false, -1, 4}, 522 {"", "Jan _2 15:04:05.999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, 523 {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.0123", false, false, -1, 4}, 524 {"", "Jan _2 15:04:05.999999999", "Feb 4 21:00:57.012345678", false, false, -1, 9}, 525 } 526 527 func TestParse(t *testing.T) { 528 for _, test := range parseTests { 529 time, err := Parse(test.format, test.value) 530 if err != nil { 531 t.Errorf("%s error: %v", test.name, err) 532 } else { 533 checkTime(time, &test, t) 534 } 535 } 536 } 537 538 func TestParseInSydney(t *testing.T) { 539 loc, err := LoadLocation("Australia/Sydney") 540 if err != nil { 541 t.Fatal(err) 542 } 543 544 // Check that Parse (and ParseInLocation) understand 545 // that Feb EST and Aug EST are different time zones in Sydney 546 // even though both are called EST. 547 t1, err := ParseInLocation("Jan 02 2006 MST", "Feb 01 2013 EST", loc) 548 if err != nil { 549 t.Fatal(err) 550 } 551 t2 := Date(2013, February, 1, 00, 00, 00, 0, loc) 552 if t1 != t2 { 553 t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney) = %v, want %v", t1, t2) 554 } 555 _, offset := t1.Zone() 556 if offset != 11*60*60 { 557 t.Fatalf("ParseInLocation(Feb 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 11*60*60) 558 } 559 560 t1, err = ParseInLocation("Jan 02 2006 MST", "Aug 01 2013 EST", loc) 561 if err != nil { 562 t.Fatal(err) 563 } 564 t2 = Date(2013, August, 1, 00, 00, 00, 0, loc) 565 if t1 != t2 { 566 t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney) = %v, want %v", t1, t2) 567 } 568 _, offset = t1.Zone() 569 if offset != 10*60*60 { 570 t.Fatalf("ParseInLocation(Aug 01 2013 EST, Sydney).Zone = _, %d, want _, %d", offset, 10*60*60) 571 } 572 } 573 574 var rubyTests = []ParseTest{ 575 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0800 2010", true, true, 1, 0}, 576 // Ignore the time zone in the test. If it parses, it'll be OK. 577 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 -0000 2010", false, true, 1, 0}, 578 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +0000 2010", false, true, 1, 0}, 579 {"RubyDate", RubyDate, "Thu Feb 04 21:00:57 +1130 2010", false, true, 1, 0}, 580 } 581 582 // Problematic time zone format needs special tests. 583 func TestRubyParse(t *testing.T) { 584 for _, test := range rubyTests { 585 time, err := Parse(test.format, test.value) 586 if err != nil { 587 t.Errorf("%s error: %v", test.name, err) 588 } else { 589 checkTime(time, &test, t) 590 } 591 } 592 } 593 594 func checkTime(time Time, test *ParseTest, t *testing.T) { 595 // The time should be Thu Feb 4 21:00:57 PST 2010 596 if test.yearSign >= 0 && test.yearSign*time.Year() != 2010 { 597 t.Errorf("%s: bad year: %d not %d", test.name, time.Year(), 2010) 598 } 599 if time.Month() != February { 600 t.Errorf("%s: bad month: %s not %s", test.name, time.Month(), February) 601 } 602 if time.Day() != 4 { 603 t.Errorf("%s: bad day: %d not %d", test.name, time.Day(), 4) 604 } 605 if time.Hour() != 21 { 606 t.Errorf("%s: bad hour: %d not %d", test.name, time.Hour(), 21) 607 } 608 if time.Minute() != 0 { 609 t.Errorf("%s: bad minute: %d not %d", test.name, time.Minute(), 0) 610 } 611 if time.Second() != 57 { 612 t.Errorf("%s: bad second: %d not %d", test.name, time.Second(), 57) 613 } 614 // Nanoseconds must be checked against the precision of the input. 615 nanosec, err := strconv.ParseUint("012345678"[:test.fracDigits]+"000000000"[:9-test.fracDigits], 10, 0) 616 if err != nil { 617 panic(err) 618 } 619 if time.Nanosecond() != int(nanosec) { 620 t.Errorf("%s: bad nanosecond: %d not %d", test.name, time.Nanosecond(), nanosec) 621 } 622 name, offset := time.Zone() 623 if test.hasTZ && offset != -28800 { 624 t.Errorf("%s: bad tz offset: %s %d not %d", test.name, name, offset, -28800) 625 } 626 if test.hasWD && time.Weekday() != Thursday { 627 t.Errorf("%s: bad weekday: %s not %s", test.name, time.Weekday(), Thursday) 628 } 629 } 630 631 func TestFormatAndParse(t *testing.T) { 632 const fmt = "Mon MST " + RFC3339 // all fields 633 f := func(sec int64) bool { 634 t1 := Unix(sec, 0) 635 if t1.Year() < 1000 || t1.Year() > 9999 { 636 // not required to work 637 return true 638 } 639 t2, err := Parse(fmt, t1.Format(fmt)) 640 if err != nil { 641 t.Errorf("error: %s", err) 642 return false 643 } 644 if t1.Unix() != t2.Unix() || t1.Nanosecond() != t2.Nanosecond() { 645 t.Errorf("FormatAndParse %d: %q(%d) %q(%d)", sec, t1, t1.Unix(), t2, t2.Unix()) 646 return false 647 } 648 return true 649 } 650 f32 := func(sec int32) bool { return f(int64(sec)) } 651 cfg := &quick.Config{MaxCount: 10000} 652 653 // Try a reasonable date first, then the huge ones. 654 if err := quick.Check(f32, cfg); err != nil { 655 t.Fatal(err) 656 } 657 if err := quick.Check(f, cfg); err != nil { 658 t.Fatal(err) 659 } 660 } 661 662 type ParseErrorTest struct { 663 format string 664 value string 665 expect string // must appear within the error 666 } 667 668 var parseErrorTests = []ParseErrorTest{ 669 {ANSIC, "Feb 4 21:00:60 2010", "cannot parse"}, // cannot parse Feb as Mon 670 {ANSIC, "Thu Feb 4 21:00:57 @2010", "cannot parse"}, 671 {ANSIC, "Thu Feb 4 21:00:60 2010", "second out of range"}, 672 {ANSIC, "Thu Feb 4 21:61:57 2010", "minute out of range"}, 673 {ANSIC, "Thu Feb 4 24:00:60 2010", "hour out of range"}, 674 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59x01 2010", "cannot parse"}, 675 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.xxx 2010", "cannot parse"}, 676 {"Mon Jan _2 15:04:05.000 2006", "Thu Feb 4 23:00:59.-123 2010", "fractional second out of range"}, 677 // issue 4502. StampNano requires exactly 9 digits of precision. 678 {StampNano, "Dec 7 11:22:01.000000", `cannot parse ".000000" as ".000000000"`}, 679 {StampNano, "Dec 7 11:22:01.0000000000", "extra text: 0"}, 680 // issue 4493. Helpful errors. 681 {RFC3339, "2006-01-02T15:04:05Z07:00", `parsing time "2006-01-02T15:04:05Z07:00": extra text: 07:00`}, 682 {RFC3339, "2006-01-02T15:04_abc", `parsing time "2006-01-02T15:04_abc" as "2006-01-02T15:04:05Z07:00": cannot parse "_abc" as ":"`}, 683 {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"`}, 684 {RFC3339, "2006-01-02T15:04:05Z_abc", `parsing time "2006-01-02T15:04:05Z_abc": extra text: _abc`}, 685 } 686 687 func TestParseErrors(t *testing.T) { 688 for _, test := range parseErrorTests { 689 _, err := Parse(test.format, test.value) 690 if err == nil { 691 t.Errorf("expected error for %q %q", test.format, test.value) 692 } else if strings.Index(err.Error(), test.expect) < 0 { 693 t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err) 694 } 695 } 696 } 697 698 func TestNoonIs12PM(t *testing.T) { 699 noon := Date(0, January, 1, 12, 0, 0, 0, UTC) 700 const expect = "12:00PM" 701 got := noon.Format("3:04PM") 702 if got != expect { 703 t.Errorf("got %q; expect %q", got, expect) 704 } 705 got = noon.Format("03:04PM") 706 if got != expect { 707 t.Errorf("got %q; expect %q", got, expect) 708 } 709 } 710 711 func TestMidnightIs12AM(t *testing.T) { 712 midnight := Date(0, January, 1, 0, 0, 0, 0, UTC) 713 expect := "12:00AM" 714 got := midnight.Format("3:04PM") 715 if got != expect { 716 t.Errorf("got %q; expect %q", got, expect) 717 } 718 got = midnight.Format("03:04PM") 719 if got != expect { 720 t.Errorf("got %q; expect %q", got, expect) 721 } 722 } 723 724 func Test12PMIsNoon(t *testing.T) { 725 noon, err := Parse("3:04PM", "12:00PM") 726 if err != nil { 727 t.Fatal("error parsing date:", err) 728 } 729 if noon.Hour() != 12 { 730 t.Errorf("got %d; expect 12", noon.Hour()) 731 } 732 noon, err = Parse("03:04PM", "12:00PM") 733 if err != nil { 734 t.Fatal("error parsing date:", err) 735 } 736 if noon.Hour() != 12 { 737 t.Errorf("got %d; expect 12", noon.Hour()) 738 } 739 } 740 741 func Test12AMIsMidnight(t *testing.T) { 742 midnight, err := Parse("3:04PM", "12:00AM") 743 if err != nil { 744 t.Fatal("error parsing date:", err) 745 } 746 if midnight.Hour() != 0 { 747 t.Errorf("got %d; expect 0", midnight.Hour()) 748 } 749 midnight, err = Parse("03:04PM", "12:00AM") 750 if err != nil { 751 t.Fatal("error parsing date:", err) 752 } 753 if midnight.Hour() != 0 { 754 t.Errorf("got %d; expect 0", midnight.Hour()) 755 } 756 } 757 758 // Check that a time without a Zone still produces a (numeric) time zone 759 // when formatted with MST as a requested zone. 760 func TestMissingZone(t *testing.T) { 761 time, err := Parse(RubyDate, "Thu Feb 02 16:10:03 -0500 2006") 762 if err != nil { 763 t.Fatal("error parsing date:", err) 764 } 765 expect := "Thu Feb 2 16:10:03 -0500 2006" // -0500 not EST 766 str := time.Format(UnixDate) // uses MST as its time zone 767 if str != expect { 768 t.Errorf("got %s; expect %s", str, expect) 769 } 770 } 771 772 func TestMinutesInTimeZone(t *testing.T) { 773 time, err := Parse(RubyDate, "Mon Jan 02 15:04:05 +0123 2006") 774 if err != nil { 775 t.Fatal("error parsing date:", err) 776 } 777 expected := (1*60 + 23) * 60 778 _, offset := time.Zone() 779 if offset != expected { 780 t.Errorf("ZoneOffset = %d, want %d", offset, expected) 781 } 782 } 783 784 type ISOWeekTest struct { 785 year int // year 786 month, day int // month and day 787 yex int // expected year 788 wex int // expected week 789 } 790 791 var isoWeekTests = []ISOWeekTest{ 792 {1981, 1, 1, 1981, 1}, {1982, 1, 1, 1981, 53}, {1983, 1, 1, 1982, 52}, 793 {1984, 1, 1, 1983, 52}, {1985, 1, 1, 1985, 1}, {1986, 1, 1, 1986, 1}, 794 {1987, 1, 1, 1987, 1}, {1988, 1, 1, 1987, 53}, {1989, 1, 1, 1988, 52}, 795 {1990, 1, 1, 1990, 1}, {1991, 1, 1, 1991, 1}, {1992, 1, 1, 1992, 1}, 796 {1993, 1, 1, 1992, 53}, {1994, 1, 1, 1993, 52}, {1995, 1, 2, 1995, 1}, 797 {1996, 1, 1, 1996, 1}, {1996, 1, 7, 1996, 1}, {1996, 1, 8, 1996, 2}, 798 {1997, 1, 1, 1997, 1}, {1998, 1, 1, 1998, 1}, {1999, 1, 1, 1998, 53}, 799 {2000, 1, 1, 1999, 52}, {2001, 1, 1, 2001, 1}, {2002, 1, 1, 2002, 1}, 800 {2003, 1, 1, 2003, 1}, {2004, 1, 1, 2004, 1}, {2005, 1, 1, 2004, 53}, 801 {2006, 1, 1, 2005, 52}, {2007, 1, 1, 2007, 1}, {2008, 1, 1, 2008, 1}, 802 {2009, 1, 1, 2009, 1}, {2010, 1, 1, 2009, 53}, {2010, 1, 1, 2009, 53}, 803 {2011, 1, 1, 2010, 52}, {2011, 1, 2, 2010, 52}, {2011, 1, 3, 2011, 1}, 804 {2011, 1, 4, 2011, 1}, {2011, 1, 5, 2011, 1}, {2011, 1, 6, 2011, 1}, 805 {2011, 1, 7, 2011, 1}, {2011, 1, 8, 2011, 1}, {2011, 1, 9, 2011, 1}, 806 {2011, 1, 10, 2011, 2}, {2011, 1, 11, 2011, 2}, {2011, 6, 12, 2011, 23}, 807 {2011, 6, 13, 2011, 24}, {2011, 12, 25, 2011, 51}, {2011, 12, 26, 2011, 52}, 808 {2011, 12, 27, 2011, 52}, {2011, 12, 28, 2011, 52}, {2011, 12, 29, 2011, 52}, 809 {2011, 12, 30, 2011, 52}, {2011, 12, 31, 2011, 52}, {1995, 1, 1, 1994, 52}, 810 {2012, 1, 1, 2011, 52}, {2012, 1, 2, 2012, 1}, {2012, 1, 8, 2012, 1}, 811 {2012, 1, 9, 2012, 2}, {2012, 12, 23, 2012, 51}, {2012, 12, 24, 2012, 52}, 812 {2012, 12, 30, 2012, 52}, {2012, 12, 31, 2013, 1}, {2013, 1, 1, 2013, 1}, 813 {2013, 1, 6, 2013, 1}, {2013, 1, 7, 2013, 2}, {2013, 12, 22, 2013, 51}, 814 {2013, 12, 23, 2013, 52}, {2013, 12, 29, 2013, 52}, {2013, 12, 30, 2014, 1}, 815 {2014, 1, 1, 2014, 1}, {2014, 1, 5, 2014, 1}, {2014, 1, 6, 2014, 2}, 816 {2015, 1, 1, 2015, 1}, {2016, 1, 1, 2015, 53}, {2017, 1, 1, 2016, 52}, 817 {2018, 1, 1, 2018, 1}, {2019, 1, 1, 2019, 1}, {2020, 1, 1, 2020, 1}, 818 {2021, 1, 1, 2020, 53}, {2022, 1, 1, 2021, 52}, {2023, 1, 1, 2022, 52}, 819 {2024, 1, 1, 2024, 1}, {2025, 1, 1, 2025, 1}, {2026, 1, 1, 2026, 1}, 820 {2027, 1, 1, 2026, 53}, {2028, 1, 1, 2027, 52}, {2029, 1, 1, 2029, 1}, 821 {2030, 1, 1, 2030, 1}, {2031, 1, 1, 2031, 1}, {2032, 1, 1, 2032, 1}, 822 {2033, 1, 1, 2032, 53}, {2034, 1, 1, 2033, 52}, {2035, 1, 1, 2035, 1}, 823 {2036, 1, 1, 2036, 1}, {2037, 1, 1, 2037, 1}, {2038, 1, 1, 2037, 53}, 824 {2039, 1, 1, 2038, 52}, {2040, 1, 1, 2039, 52}, 825 } 826 827 func TestISOWeek(t *testing.T) { 828 // Selected dates and corner cases 829 for _, wt := range isoWeekTests { 830 dt := Date(wt.year, Month(wt.month), wt.day, 0, 0, 0, 0, UTC) 831 y, w := dt.ISOWeek() 832 if w != wt.wex || y != wt.yex { 833 t.Errorf("got %d/%d; expected %d/%d for %d-%02d-%02d", 834 y, w, wt.yex, wt.wex, wt.year, wt.month, wt.day) 835 } 836 } 837 838 // The only real invariant: Jan 04 is in week 1 839 for year := 1950; year < 2100; year++ { 840 if y, w := Date(year, January, 4, 0, 0, 0, 0, UTC).ISOWeek(); y != year || w != 1 { 841 t.Errorf("got %d/%d; expected %d/1 for Jan 04", y, w, year) 842 } 843 } 844 } 845 846 type YearDayTest struct { 847 year, month, day int 848 yday int 849 } 850 851 // Test YearDay in several different scenarios 852 // and corner cases 853 var yearDayTests = []YearDayTest{ 854 // Non-leap-year tests 855 {2007, 1, 1, 1}, 856 {2007, 1, 15, 15}, 857 {2007, 2, 1, 32}, 858 {2007, 2, 15, 46}, 859 {2007, 3, 1, 60}, 860 {2007, 3, 15, 74}, 861 {2007, 4, 1, 91}, 862 {2007, 12, 31, 365}, 863 864 // Leap-year tests 865 {2008, 1, 1, 1}, 866 {2008, 1, 15, 15}, 867 {2008, 2, 1, 32}, 868 {2008, 2, 15, 46}, 869 {2008, 3, 1, 61}, 870 {2008, 3, 15, 75}, 871 {2008, 4, 1, 92}, 872 {2008, 12, 31, 366}, 873 874 // Looks like leap-year (but isn't) tests 875 {1900, 1, 1, 1}, 876 {1900, 1, 15, 15}, 877 {1900, 2, 1, 32}, 878 {1900, 2, 15, 46}, 879 {1900, 3, 1, 60}, 880 {1900, 3, 15, 74}, 881 {1900, 4, 1, 91}, 882 {1900, 12, 31, 365}, 883 884 // Year one tests (non-leap) 885 {1, 1, 1, 1}, 886 {1, 1, 15, 15}, 887 {1, 2, 1, 32}, 888 {1, 2, 15, 46}, 889 {1, 3, 1, 60}, 890 {1, 3, 15, 74}, 891 {1, 4, 1, 91}, 892 {1, 12, 31, 365}, 893 894 // Year minus one tests (non-leap) 895 {-1, 1, 1, 1}, 896 {-1, 1, 15, 15}, 897 {-1, 2, 1, 32}, 898 {-1, 2, 15, 46}, 899 {-1, 3, 1, 60}, 900 {-1, 3, 15, 74}, 901 {-1, 4, 1, 91}, 902 {-1, 12, 31, 365}, 903 904 // 400 BC tests (leap-year) 905 {-400, 1, 1, 1}, 906 {-400, 1, 15, 15}, 907 {-400, 2, 1, 32}, 908 {-400, 2, 15, 46}, 909 {-400, 3, 1, 61}, 910 {-400, 3, 15, 75}, 911 {-400, 4, 1, 92}, 912 {-400, 12, 31, 366}, 913 914 // Special Cases 915 916 // Gregorian calendar change (no effect) 917 {1582, 10, 4, 277}, 918 {1582, 10, 15, 288}, 919 } 920 921 // Check to see if YearDay is location sensitive 922 var yearDayLocations = []*Location{ 923 FixedZone("UTC-8", -8*60*60), 924 FixedZone("UTC-4", -4*60*60), 925 UTC, 926 FixedZone("UTC+4", 4*60*60), 927 FixedZone("UTC+8", 8*60*60), 928 } 929 930 func TestYearDay(t *testing.T) { 931 for _, loc := range yearDayLocations { 932 for _, ydt := range yearDayTests { 933 dt := Date(ydt.year, Month(ydt.month), ydt.day, 0, 0, 0, 0, loc) 934 yday := dt.YearDay() 935 if yday != ydt.yday { 936 t.Errorf("got %d, expected %d for %d-%02d-%02d in %v", 937 yday, ydt.yday, ydt.year, ydt.month, ydt.day, loc) 938 } 939 } 940 } 941 } 942 943 var durationTests = []struct { 944 str string 945 d Duration 946 }{ 947 {"0", 0}, 948 {"1ns", 1 * Nanosecond}, 949 {"1.1us", 1100 * Nanosecond}, 950 {"2.2ms", 2200 * Microsecond}, 951 {"3.3s", 3300 * Millisecond}, 952 {"4m5s", 4*Minute + 5*Second}, 953 {"4m5.001s", 4*Minute + 5001*Millisecond}, 954 {"5h6m7.001s", 5*Hour + 6*Minute + 7001*Millisecond}, 955 {"8m0.000000001s", 8*Minute + 1*Nanosecond}, 956 {"2562047h47m16.854775807s", 1<<63 - 1}, 957 {"-2562047h47m16.854775808s", -1 << 63}, 958 } 959 960 func TestDurationString(t *testing.T) { 961 for _, tt := range durationTests { 962 if str := tt.d.String(); str != tt.str { 963 t.Errorf("Duration(%d).String() = %s, want %s", int64(tt.d), str, tt.str) 964 } 965 if tt.d > 0 { 966 if str := (-tt.d).String(); str != "-"+tt.str { 967 t.Errorf("Duration(%d).String() = %s, want %s", int64(-tt.d), str, "-"+tt.str) 968 } 969 } 970 } 971 } 972 973 var dateTests = []struct { 974 year, month, day, hour, min, sec, nsec int 975 z *Location 976 unix int64 977 }{ 978 {2011, 11, 6, 1, 0, 0, 0, Local, 1320566400}, // 1:00:00 PDT 979 {2011, 11, 6, 1, 59, 59, 0, Local, 1320569999}, // 1:59:59 PDT 980 {2011, 11, 6, 2, 0, 0, 0, Local, 1320573600}, // 2:00:00 PST 981 982 {2011, 3, 13, 1, 0, 0, 0, Local, 1300006800}, // 1:00:00 PST 983 {2011, 3, 13, 1, 59, 59, 0, Local, 1300010399}, // 1:59:59 PST 984 {2011, 3, 13, 3, 0, 0, 0, Local, 1300010400}, // 3:00:00 PDT 985 {2011, 3, 13, 2, 30, 0, 0, Local, 1300008600}, // 2:30:00 PDT ≡ 1:30 PST 986 987 // Many names for Fri Nov 18 7:56:35 PST 2011 988 {2011, 11, 18, 7, 56, 35, 0, Local, 1321631795}, // Nov 18 7:56:35 989 {2011, 11, 19, -17, 56, 35, 0, Local, 1321631795}, // Nov 19 -17:56:35 990 {2011, 11, 17, 31, 56, 35, 0, Local, 1321631795}, // Nov 17 31:56:35 991 {2011, 11, 18, 6, 116, 35, 0, Local, 1321631795}, // Nov 18 6:116:35 992 {2011, 10, 49, 7, 56, 35, 0, Local, 1321631795}, // Oct 49 7:56:35 993 {2011, 11, 18, 7, 55, 95, 0, Local, 1321631795}, // Nov 18 7:55:95 994 {2011, 11, 18, 7, 56, 34, 1e9, Local, 1321631795}, // Nov 18 7:56:34 + 10⁹ns 995 {2011, 12, -12, 7, 56, 35, 0, Local, 1321631795}, // Dec -21 7:56:35 996 {2012, 1, -43, 7, 56, 35, 0, Local, 1321631795}, // Jan -52 7:56:35 2012 997 {2012, int(January - 2), 18, 7, 56, 35, 0, Local, 1321631795}, // (Jan-2) 18 7:56:35 2012 998 {2010, int(December + 11), 18, 7, 56, 35, 0, Local, 1321631795}, // (Dec+11) 18 7:56:35 2010 999 } 1000 1001 func TestDate(t *testing.T) { 1002 for _, tt := range dateTests { 1003 time := Date(tt.year, Month(tt.month), tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z) 1004 want := Unix(tt.unix, 0) 1005 if !time.Equal(want) { 1006 t.Errorf("Date(%d, %d, %d, %d, %d, %d, %d, %s) = %v, want %v", 1007 tt.year, tt.month, tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z, 1008 time, want) 1009 } 1010 } 1011 } 1012 1013 // Several ways of getting from 1014 // Fri Nov 18 7:56:35 PST 2011 1015 // to 1016 // Thu Mar 19 7:56:35 PST 2016 1017 var addDateTests = []struct { 1018 years, months, days int 1019 }{ 1020 {4, 4, 1}, 1021 {3, 16, 1}, 1022 {3, 15, 30}, 1023 {5, -6, -18 - 30 - 12}, 1024 } 1025 1026 func TestAddDate(t *testing.T) { 1027 t0 := Date(2011, 11, 18, 7, 56, 35, 0, UTC) 1028 t1 := Date(2016, 3, 19, 7, 56, 35, 0, UTC) 1029 for _, at := range addDateTests { 1030 time := t0.AddDate(at.years, at.months, at.days) 1031 if !time.Equal(t1) { 1032 t.Errorf("AddDate(%d, %d, %d) = %v, want %v", 1033 at.years, at.months, at.days, 1034 time, t1) 1035 } 1036 } 1037 } 1038 1039 var daysInTests = []struct { 1040 year, month, di int 1041 }{ 1042 {2011, 1, 31}, // January, first month, 31 days 1043 {2011, 2, 28}, // February, non-leap year, 28 days 1044 {2012, 2, 29}, // February, leap year, 29 days 1045 {2011, 6, 30}, // June, 30 days 1046 {2011, 12, 31}, // December, last month, 31 days 1047 } 1048 1049 func TestDaysIn(t *testing.T) { 1050 // The daysIn function is not exported. 1051 // Test the daysIn function via the `var DaysIn = daysIn` 1052 // statement in the internal_test.go file. 1053 for _, tt := range daysInTests { 1054 di := DaysIn(Month(tt.month), tt.year) 1055 if di != tt.di { 1056 t.Errorf("got %d; expected %d for %d-%02d", 1057 di, tt.di, tt.year, tt.month) 1058 } 1059 } 1060 } 1061 1062 func TestAddToExactSecond(t *testing.T) { 1063 // Add an amount to the current time to round it up to the next exact second. 1064 // This test checks that the nsec field still lies within the range [0, 999999999]. 1065 t1 := Now() 1066 t2 := t1.Add(Second - Duration(t1.Nanosecond())) 1067 sec := (t1.Second() + 1) % 60 1068 if t2.Second() != sec || t2.Nanosecond() != 0 { 1069 t.Errorf("sec = %d, nsec = %d, want sec = %d, nsec = 0", t2.Second(), t2.Nanosecond(), sec) 1070 } 1071 } 1072 1073 func equalTimeAndZone(a, b Time) bool { 1074 aname, aoffset := a.Zone() 1075 bname, boffset := b.Zone() 1076 return a.Equal(b) && aoffset == boffset && aname == bname 1077 } 1078 1079 var gobTests = []Time{ 1080 Date(0, 1, 2, 3, 4, 5, 6, UTC), 1081 Date(7, 8, 9, 10, 11, 12, 13, FixedZone("", 0)), 1082 Unix(81985467080890095, 0x76543210), // Time.sec: 0x0123456789ABCDEF 1083 {}, // nil location 1084 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", 32767*60)), 1085 Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", -32768*60)), 1086 } 1087 1088 func TestTimeGob(t *testing.T) { 1089 var b bytes.Buffer 1090 enc := gob.NewEncoder(&b) 1091 dec := gob.NewDecoder(&b) 1092 for _, tt := range gobTests { 1093 var gobtt Time 1094 if err := enc.Encode(&tt); err != nil { 1095 t.Errorf("%v gob Encode error = %q, want nil", tt, err) 1096 } else if err := dec.Decode(&gobtt); err != nil { 1097 t.Errorf("%v gob Decode error = %q, want nil", tt, err) 1098 } else if !equalTimeAndZone(gobtt, tt) { 1099 t.Errorf("Decoded time = %v, want %v", gobtt, tt) 1100 } 1101 b.Reset() 1102 } 1103 } 1104 1105 var invalidEncodingTests = []struct { 1106 bytes []byte 1107 want string 1108 }{ 1109 {[]byte{}, "Time.GobDecode: no data"}, 1110 {[]byte{0, 2, 3}, "Time.GobDecode: unsupported version"}, 1111 {[]byte{1, 2, 3}, "Time.GobDecode: invalid length"}, 1112 } 1113 1114 func TestInvalidTimeGob(t *testing.T) { 1115 for _, tt := range invalidEncodingTests { 1116 var ignored Time 1117 err := ignored.GobDecode(tt.bytes) 1118 if err == nil || err.Error() != tt.want { 1119 t.Errorf("time.GobDecode(%#v) error = %v, want %v", tt.bytes, err, tt.want) 1120 } 1121 } 1122 } 1123 1124 var notEncodableTimes = []struct { 1125 time Time 1126 want string 1127 }{ 1128 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 1)), "Time.GobEncode: zone offset has fractional minute"}, 1129 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -1*60)), "Time.GobEncode: unexpected zone offset"}, 1130 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -32769*60)), "Time.GobEncode: unexpected zone offset"}, 1131 {Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 32768*60)), "Time.GobEncode: unexpected zone offset"}, 1132 } 1133 1134 func TestNotGobEncodableTime(t *testing.T) { 1135 for _, tt := range notEncodableTimes { 1136 _, err := tt.time.GobEncode() 1137 if err == nil || err.Error() != tt.want { 1138 t.Errorf("%v GobEncode error = %v, want %v", tt.time, err, tt.want) 1139 } 1140 } 1141 } 1142 1143 var jsonTests = []struct { 1144 time Time 1145 json string 1146 }{ 1147 {Date(9999, 4, 12, 23, 20, 50, 520*1e6, UTC), `"9999-04-12T23:20:50.52Z"`}, 1148 {Date(1996, 12, 19, 16, 39, 57, 0, Local), `"1996-12-19T16:39:57-08:00"`}, 1149 {Date(0, 1, 1, 0, 0, 0, 1, FixedZone("", 1*60)), `"0000-01-01T00:00:00.000000001+00:01"`}, 1150 } 1151 1152 func TestTimeJSON(t *testing.T) { 1153 for _, tt := range jsonTests { 1154 var jsonTime Time 1155 1156 if jsonBytes, err := json.Marshal(tt.time); err != nil { 1157 t.Errorf("%v json.Marshal error = %v, want nil", tt.time, err) 1158 } else if string(jsonBytes) != tt.json { 1159 t.Errorf("%v JSON = %#q, want %#q", tt.time, string(jsonBytes), tt.json) 1160 } else if err = json.Unmarshal(jsonBytes, &jsonTime); err != nil { 1161 t.Errorf("%v json.Unmarshal error = %v, want nil", tt.time, err) 1162 } else if !equalTimeAndZone(jsonTime, tt.time) { 1163 t.Errorf("Unmarshaled time = %v, want %v", jsonTime, tt.time) 1164 } 1165 } 1166 } 1167 1168 func TestInvalidTimeJSON(t *testing.T) { 1169 var tt Time 1170 err := json.Unmarshal([]byte(`{"now is the time":"buddy"}`), &tt) 1171 _, isParseErr := err.(*ParseError) 1172 if !isParseErr { 1173 t.Errorf("expected *time.ParseError unmarshaling JSON, got %v", err) 1174 } 1175 } 1176 1177 var notJSONEncodableTimes = []struct { 1178 time Time 1179 want string 1180 }{ 1181 {Date(10000, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 1182 {Date(-1, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"}, 1183 } 1184 1185 func TestNotJSONEncodableTime(t *testing.T) { 1186 for _, tt := range notJSONEncodableTimes { 1187 _, err := tt.time.MarshalJSON() 1188 if err == nil || err.Error() != tt.want { 1189 t.Errorf("%v MarshalJSON error = %v, want %v", tt.time, err, tt.want) 1190 } 1191 } 1192 } 1193 1194 var parseDurationTests = []struct { 1195 in string 1196 ok bool 1197 want Duration 1198 }{ 1199 // simple 1200 {"0", true, 0}, 1201 {"5s", true, 5 * Second}, 1202 {"30s", true, 30 * Second}, 1203 {"1478s", true, 1478 * Second}, 1204 // sign 1205 {"-5s", true, -5 * Second}, 1206 {"+5s", true, 5 * Second}, 1207 {"-0", true, 0}, 1208 {"+0", true, 0}, 1209 // decimal 1210 {"5.0s", true, 5 * Second}, 1211 {"5.6s", true, 5*Second + 600*Millisecond}, 1212 {"5.s", true, 5 * Second}, 1213 {".5s", true, 500 * Millisecond}, 1214 {"1.0s", true, 1 * Second}, 1215 {"1.00s", true, 1 * Second}, 1216 {"1.004s", true, 1*Second + 4*Millisecond}, 1217 {"1.0040s", true, 1*Second + 4*Millisecond}, 1218 {"100.00100s", true, 100*Second + 1*Millisecond}, 1219 // different units 1220 {"10ns", true, 10 * Nanosecond}, 1221 {"11us", true, 11 * Microsecond}, 1222 {"12µs", true, 12 * Microsecond}, // U+00B5 1223 {"12μs", true, 12 * Microsecond}, // U+03BC 1224 {"13ms", true, 13 * Millisecond}, 1225 {"14s", true, 14 * Second}, 1226 {"15m", true, 15 * Minute}, 1227 {"16h", true, 16 * Hour}, 1228 // composite durations 1229 {"3h30m", true, 3*Hour + 30*Minute}, 1230 {"10.5s4m", true, 4*Minute + 10*Second + 500*Millisecond}, 1231 {"-2m3.4s", true, -(2*Minute + 3*Second + 400*Millisecond)}, 1232 {"1h2m3s4ms5us6ns", true, 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond}, 1233 {"39h9m14.425s", true, 39*Hour + 9*Minute + 14*Second + 425*Millisecond}, 1234 // large value 1235 {"52763797000ns", true, 52763797000 * Nanosecond}, 1236 1237 // errors 1238 {"", false, 0}, 1239 {"3", false, 0}, 1240 {"-", false, 0}, 1241 {"s", false, 0}, 1242 {".", false, 0}, 1243 {"-.", false, 0}, 1244 {".s", false, 0}, 1245 {"+.s", false, 0}, 1246 } 1247 1248 func TestParseDuration(t *testing.T) { 1249 for _, tc := range parseDurationTests { 1250 d, err := ParseDuration(tc.in) 1251 if tc.ok && (err != nil || d != tc.want) { 1252 t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want) 1253 } else if !tc.ok && err == nil { 1254 t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in) 1255 } 1256 } 1257 } 1258 1259 func TestParseDurationRoundTrip(t *testing.T) { 1260 for i := 0; i < 100; i++ { 1261 // Resolutions finer than milliseconds will result in 1262 // imprecise round-trips. 1263 d0 := Duration(rand.Int31()) * Millisecond 1264 s := d0.String() 1265 d1, err := ParseDuration(s) 1266 if err != nil || d0 != d1 { 1267 t.Errorf("round-trip failed: %d => %q => %d, %v", d0, s, d1, err) 1268 } 1269 } 1270 } 1271 1272 // golang.org/issue/4622 1273 func TestLocationRace(t *testing.T) { 1274 ResetLocalOnceForTest() // reset the Once to trigger the race 1275 1276 c := make(chan string, 1) 1277 go func() { 1278 c <- Now().String() 1279 }() 1280 Now().String() 1281 <-c 1282 Sleep(100 * Millisecond) 1283 1284 // Back to Los Angeles for subsequent tests: 1285 ForceUSPacificForTesting() 1286 } 1287 1288 var ( 1289 t Time 1290 u int64 1291 ) 1292 1293 var mallocTest = []struct { 1294 count int 1295 desc string 1296 fn func() 1297 }{ 1298 {0, `time.Now()`, func() { t = Now() }}, 1299 {0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }}, 1300 } 1301 1302 func TestCountMallocs(t *testing.T) { 1303 if runtime.GOMAXPROCS(0) > 1 { 1304 t.Skip("skipping; GOMAXPROCS>1") 1305 } 1306 for _, mt := range mallocTest { 1307 allocs := int(testing.AllocsPerRun(100, mt.fn)) 1308 if allocs > mt.count { 1309 t.Errorf("%s: %d allocs, want %d", mt.desc, allocs, mt.count) 1310 } 1311 } 1312 } 1313 1314 func TestLoadFixed(t *testing.T) { 1315 // Issue 4064: handle locations without any zone transitions. 1316 loc, err := LoadLocation("Etc/GMT+1") 1317 if err != nil { 1318 t.Fatal(err) 1319 } 1320 1321 // The tzdata name Etc/GMT+1 uses "east is negative", 1322 // but Go and most other systems use "east is positive". 1323 // So GMT+1 corresponds to -3600 in the Go zone, not +3600. 1324 name, offset := Now().In(loc).Zone() 1325 if name != "GMT+1" || offset != -1*60*60 { 1326 t.Errorf("Now().In(loc).Zone() = %q, %d, want %q, %d", name, offset, "GMT+1", -1*60*60) 1327 } 1328 } 1329 1330 func BenchmarkNow(b *testing.B) { 1331 for i := 0; i < b.N; i++ { 1332 t = Now() 1333 } 1334 } 1335 1336 func BenchmarkNowUnixNano(b *testing.B) { 1337 for i := 0; i < b.N; i++ { 1338 u = Now().UnixNano() 1339 } 1340 } 1341 1342 func BenchmarkFormat(b *testing.B) { 1343 t := Unix(1265346057, 0) 1344 for i := 0; i < b.N; i++ { 1345 t.Format("Mon Jan 2 15:04:05 2006") 1346 } 1347 } 1348 1349 func BenchmarkFormatNow(b *testing.B) { 1350 // Like BenchmarkFormat, but easier, because the time zone 1351 // lookup cache is optimized for the present. 1352 t := Now() 1353 for i := 0; i < b.N; i++ { 1354 t.Format("Mon Jan 2 15:04:05 2006") 1355 } 1356 } 1357 1358 func BenchmarkParse(b *testing.B) { 1359 for i := 0; i < b.N; i++ { 1360 Parse(ANSIC, "Mon Jan 2 15:04:05 2006") 1361 } 1362 } 1363 1364 func BenchmarkHour(b *testing.B) { 1365 t := Now() 1366 for i := 0; i < b.N; i++ { 1367 _ = t.Hour() 1368 } 1369 } 1370 1371 func BenchmarkSecond(b *testing.B) { 1372 t := Now() 1373 for i := 0; i < b.N; i++ { 1374 _ = t.Second() 1375 } 1376 } 1377 1378 func BenchmarkYear(b *testing.B) { 1379 t := Now() 1380 for i := 0; i < b.N; i++ { 1381 _ = t.Year() 1382 } 1383 } 1384 1385 func BenchmarkDay(b *testing.B) { 1386 t := Now() 1387 for i := 0; i < b.N; i++ { 1388 _ = t.Day() 1389 } 1390 }