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