Source file src/time/time_test.go

Documentation: time

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

View as plain text