...
Run Format

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  	"internal/race"
    13  	"math/big"
    14  	"math/rand"
    15  	"os"
    16  	"runtime"
    17  	"strings"
    18  	"sync"
    19  	"testing"
    20  	"testing/quick"
    21  	. "time"
    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 _, 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("got %d, expected %d for %d-%02d-%02d in %v",
   531  					yday, ydt.yday, ydt.year, ydt.month, ydt.day, loc)
   532  			}
   533  		}
   534  	}
   535  }
   536  
   537  var durationTests = []struct {
   538  	str string
   539  	d   Duration
   540  }{
   541  	{"0s", 0},
   542  	{"1ns", 1 * Nanosecond},
   543  	{"1.1µs", 1100 * Nanosecond},
   544  	{"2.2ms", 2200 * Microsecond},
   545  	{"3.3s", 3300 * Millisecond},
   546  	{"4m5s", 4*Minute + 5*Second},
   547  	{"4m5.001s", 4*Minute + 5001*Millisecond},
   548  	{"5h6m7.001s", 5*Hour + 6*Minute + 7001*Millisecond},
   549  	{"8m0.000000001s", 8*Minute + 1*Nanosecond},
   550  	{"2562047h47m16.854775807s", 1<<63 - 1},
   551  	{"-2562047h47m16.854775808s", -1 << 63},
   552  }
   553  
   554  func TestDurationString(t *testing.T) {
   555  	for _, tt := range durationTests {
   556  		if str := tt.d.String(); str != tt.str {
   557  			t.Errorf("Duration(%d).String() = %s, want %s", int64(tt.d), str, tt.str)
   558  		}
   559  		if tt.d > 0 {
   560  			if str := (-tt.d).String(); str != "-"+tt.str {
   561  				t.Errorf("Duration(%d).String() = %s, want %s", int64(-tt.d), str, "-"+tt.str)
   562  			}
   563  		}
   564  	}
   565  }
   566  
   567  var dateTests = []struct {
   568  	year, month, day, hour, min, sec, nsec int
   569  	z                                      *Location
   570  	unix                                   int64
   571  }{
   572  	{2011, 11, 6, 1, 0, 0, 0, Local, 1320566400},   // 1:00:00 PDT
   573  	{2011, 11, 6, 1, 59, 59, 0, Local, 1320569999}, // 1:59:59 PDT
   574  	{2011, 11, 6, 2, 0, 0, 0, Local, 1320573600},   // 2:00:00 PST
   575  
   576  	{2011, 3, 13, 1, 0, 0, 0, Local, 1300006800},   // 1:00:00 PST
   577  	{2011, 3, 13, 1, 59, 59, 0, Local, 1300010399}, // 1:59:59 PST
   578  	{2011, 3, 13, 3, 0, 0, 0, Local, 1300010400},   // 3:00:00 PDT
   579  	{2011, 3, 13, 2, 30, 0, 0, Local, 1300008600},  // 2:30:00 PDT ≡ 1:30 PST
   580  	{2012, 12, 24, 0, 0, 0, 0, Local, 1356336000},  // Leap year
   581  
   582  	// Many names for Fri Nov 18 7:56:35 PST 2011
   583  	{2011, 11, 18, 7, 56, 35, 0, Local, 1321631795},                 // Nov 18 7:56:35
   584  	{2011, 11, 19, -17, 56, 35, 0, Local, 1321631795},               // Nov 19 -17:56:35
   585  	{2011, 11, 17, 31, 56, 35, 0, Local, 1321631795},                // Nov 17 31:56:35
   586  	{2011, 11, 18, 6, 116, 35, 0, Local, 1321631795},                // Nov 18 6:116:35
   587  	{2011, 10, 49, 7, 56, 35, 0, Local, 1321631795},                 // Oct 49 7:56:35
   588  	{2011, 11, 18, 7, 55, 95, 0, Local, 1321631795},                 // Nov 18 7:55:95
   589  	{2011, 11, 18, 7, 56, 34, 1e9, Local, 1321631795},               // Nov 18 7:56:34 + 10⁹ns
   590  	{2011, 12, -12, 7, 56, 35, 0, Local, 1321631795},                // Dec -21 7:56:35
   591  	{2012, 1, -43, 7, 56, 35, 0, Local, 1321631795},                 // Jan -52 7:56:35 2012
   592  	{2012, int(January - 2), 18, 7, 56, 35, 0, Local, 1321631795},   // (Jan-2) 18 7:56:35 2012
   593  	{2010, int(December + 11), 18, 7, 56, 35, 0, Local, 1321631795}, // (Dec+11) 18 7:56:35 2010
   594  }
   595  
   596  func TestDate(t *testing.T) {
   597  	for _, tt := range dateTests {
   598  		time := Date(tt.year, Month(tt.month), tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z)
   599  		want := Unix(tt.unix, 0)
   600  		if !time.Equal(want) {
   601  			t.Errorf("Date(%d, %d, %d, %d, %d, %d, %d, %s) = %v, want %v",
   602  				tt.year, tt.month, tt.day, tt.hour, tt.min, tt.sec, tt.nsec, tt.z,
   603  				time, want)
   604  		}
   605  	}
   606  }
   607  
   608  // Several ways of getting from
   609  // Fri Nov 18 7:56:35 PST 2011
   610  // to
   611  // Thu Mar 19 7:56:35 PST 2016
   612  var addDateTests = []struct {
   613  	years, months, days int
   614  }{
   615  	{4, 4, 1},
   616  	{3, 16, 1},
   617  	{3, 15, 30},
   618  	{5, -6, -18 - 30 - 12},
   619  }
   620  
   621  func TestAddDate(t *testing.T) {
   622  	t0 := Date(2011, 11, 18, 7, 56, 35, 0, UTC)
   623  	t1 := Date(2016, 3, 19, 7, 56, 35, 0, UTC)
   624  	for _, at := range addDateTests {
   625  		time := t0.AddDate(at.years, at.months, at.days)
   626  		if !time.Equal(t1) {
   627  			t.Errorf("AddDate(%d, %d, %d) = %v, want %v",
   628  				at.years, at.months, at.days,
   629  				time, t1)
   630  		}
   631  	}
   632  }
   633  
   634  var daysInTests = []struct {
   635  	year, month, di int
   636  }{
   637  	{2011, 1, 31},  // January, first month, 31 days
   638  	{2011, 2, 28},  // February, non-leap year, 28 days
   639  	{2012, 2, 29},  // February, leap year, 29 days
   640  	{2011, 6, 30},  // June, 30 days
   641  	{2011, 12, 31}, // December, last month, 31 days
   642  }
   643  
   644  func TestDaysIn(t *testing.T) {
   645  	// The daysIn function is not exported.
   646  	// Test the daysIn function via the `var DaysIn = daysIn`
   647  	// statement in the internal_test.go file.
   648  	for _, tt := range daysInTests {
   649  		di := DaysIn(Month(tt.month), tt.year)
   650  		if di != tt.di {
   651  			t.Errorf("got %d; expected %d for %d-%02d",
   652  				di, tt.di, tt.year, tt.month)
   653  		}
   654  	}
   655  }
   656  
   657  func TestAddToExactSecond(t *testing.T) {
   658  	// Add an amount to the current time to round it up to the next exact second.
   659  	// This test checks that the nsec field still lies within the range [0, 999999999].
   660  	t1 := Now()
   661  	t2 := t1.Add(Second - Duration(t1.Nanosecond()))
   662  	sec := (t1.Second() + 1) % 60
   663  	if t2.Second() != sec || t2.Nanosecond() != 0 {
   664  		t.Errorf("sec = %d, nsec = %d, want sec = %d, nsec = 0", t2.Second(), t2.Nanosecond(), sec)
   665  	}
   666  }
   667  
   668  func equalTimeAndZone(a, b Time) bool {
   669  	aname, aoffset := a.Zone()
   670  	bname, boffset := b.Zone()
   671  	return a.Equal(b) && aoffset == boffset && aname == bname
   672  }
   673  
   674  var gobTests = []Time{
   675  	Date(0, 1, 2, 3, 4, 5, 6, UTC),
   676  	Date(7, 8, 9, 10, 11, 12, 13, FixedZone("", 0)),
   677  	Unix(81985467080890095, 0x76543210), // Time.sec: 0x0123456789ABCDEF
   678  	{},                                  // nil location
   679  	Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", 32767*60)),
   680  	Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", -32768*60)),
   681  }
   682  
   683  func TestTimeGob(t *testing.T) {
   684  	var b bytes.Buffer
   685  	enc := gob.NewEncoder(&b)
   686  	dec := gob.NewDecoder(&b)
   687  	for _, tt := range gobTests {
   688  		var gobtt Time
   689  		if err := enc.Encode(&tt); err != nil {
   690  			t.Errorf("%v gob Encode error = %q, want nil", tt, err)
   691  		} else if err := dec.Decode(&gobtt); err != nil {
   692  			t.Errorf("%v gob Decode error = %q, want nil", tt, err)
   693  		} else if !equalTimeAndZone(gobtt, tt) {
   694  			t.Errorf("Decoded time = %v, want %v", gobtt, tt)
   695  		}
   696  		b.Reset()
   697  	}
   698  }
   699  
   700  var invalidEncodingTests = []struct {
   701  	bytes []byte
   702  	want  string
   703  }{
   704  	{[]byte{}, "Time.UnmarshalBinary: no data"},
   705  	{[]byte{0, 2, 3}, "Time.UnmarshalBinary: unsupported version"},
   706  	{[]byte{1, 2, 3}, "Time.UnmarshalBinary: invalid length"},
   707  }
   708  
   709  func TestInvalidTimeGob(t *testing.T) {
   710  	for _, tt := range invalidEncodingTests {
   711  		var ignored Time
   712  		err := ignored.GobDecode(tt.bytes)
   713  		if err == nil || err.Error() != tt.want {
   714  			t.Errorf("time.GobDecode(%#v) error = %v, want %v", tt.bytes, err, tt.want)
   715  		}
   716  		err = ignored.UnmarshalBinary(tt.bytes)
   717  		if err == nil || err.Error() != tt.want {
   718  			t.Errorf("time.UnmarshalBinary(%#v) error = %v, want %v", tt.bytes, err, tt.want)
   719  		}
   720  	}
   721  }
   722  
   723  var notEncodableTimes = []struct {
   724  	time Time
   725  	want string
   726  }{
   727  	{Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 1)), "Time.MarshalBinary: zone offset has fractional minute"},
   728  	{Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -1*60)), "Time.MarshalBinary: unexpected zone offset"},
   729  	{Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", -32769*60)), "Time.MarshalBinary: unexpected zone offset"},
   730  	{Date(0, 1, 2, 3, 4, 5, 6, FixedZone("", 32768*60)), "Time.MarshalBinary: unexpected zone offset"},
   731  }
   732  
   733  func TestNotGobEncodableTime(t *testing.T) {
   734  	for _, tt := range notEncodableTimes {
   735  		_, err := tt.time.GobEncode()
   736  		if err == nil || err.Error() != tt.want {
   737  			t.Errorf("%v GobEncode error = %v, want %v", tt.time, err, tt.want)
   738  		}
   739  		_, err = tt.time.MarshalBinary()
   740  		if err == nil || err.Error() != tt.want {
   741  			t.Errorf("%v MarshalBinary error = %v, want %v", tt.time, err, tt.want)
   742  		}
   743  	}
   744  }
   745  
   746  var jsonTests = []struct {
   747  	time Time
   748  	json string
   749  }{
   750  	{Date(9999, 4, 12, 23, 20, 50, 520*1e6, UTC), `"9999-04-12T23:20:50.52Z"`},
   751  	{Date(1996, 12, 19, 16, 39, 57, 0, Local), `"1996-12-19T16:39:57-08:00"`},
   752  	{Date(0, 1, 1, 0, 0, 0, 1, FixedZone("", 1*60)), `"0000-01-01T00:00:00.000000001+00:01"`},
   753  }
   754  
   755  func TestTimeJSON(t *testing.T) {
   756  	for _, tt := range jsonTests {
   757  		var jsonTime Time
   758  
   759  		if jsonBytes, err := json.Marshal(tt.time); err != nil {
   760  			t.Errorf("%v json.Marshal error = %v, want nil", tt.time, err)
   761  		} else if string(jsonBytes) != tt.json {
   762  			t.Errorf("%v JSON = %#q, want %#q", tt.time, string(jsonBytes), tt.json)
   763  		} else if err = json.Unmarshal(jsonBytes, &jsonTime); err != nil {
   764  			t.Errorf("%v json.Unmarshal error = %v, want nil", tt.time, err)
   765  		} else if !equalTimeAndZone(jsonTime, tt.time) {
   766  			t.Errorf("Unmarshaled time = %v, want %v", jsonTime, tt.time)
   767  		}
   768  	}
   769  }
   770  
   771  func TestInvalidTimeJSON(t *testing.T) {
   772  	var tt Time
   773  	err := json.Unmarshal([]byte(`{"now is the time":"buddy"}`), &tt)
   774  	_, isParseErr := err.(*ParseError)
   775  	if !isParseErr {
   776  		t.Errorf("expected *time.ParseError unmarshaling JSON, got %v", err)
   777  	}
   778  }
   779  
   780  var notJSONEncodableTimes = []struct {
   781  	time Time
   782  	want string
   783  }{
   784  	{Date(10000, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"},
   785  	{Date(-1, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"},
   786  }
   787  
   788  func TestNotJSONEncodableTime(t *testing.T) {
   789  	for _, tt := range notJSONEncodableTimes {
   790  		_, err := tt.time.MarshalJSON()
   791  		if err == nil || err.Error() != tt.want {
   792  			t.Errorf("%v MarshalJSON error = %v, want %v", tt.time, err, tt.want)
   793  		}
   794  	}
   795  }
   796  
   797  var parseDurationTests = []struct {
   798  	in   string
   799  	ok   bool
   800  	want Duration
   801  }{
   802  	// simple
   803  	{"0", true, 0},
   804  	{"5s", true, 5 * Second},
   805  	{"30s", true, 30 * Second},
   806  	{"1478s", true, 1478 * Second},
   807  	// sign
   808  	{"-5s", true, -5 * Second},
   809  	{"+5s", true, 5 * Second},
   810  	{"-0", true, 0},
   811  	{"+0", true, 0},
   812  	// decimal
   813  	{"5.0s", true, 5 * Second},
   814  	{"5.6s", true, 5*Second + 600*Millisecond},
   815  	{"5.s", true, 5 * Second},
   816  	{".5s", true, 500 * Millisecond},
   817  	{"1.0s", true, 1 * Second},
   818  	{"1.00s", true, 1 * Second},
   819  	{"1.004s", true, 1*Second + 4*Millisecond},
   820  	{"1.0040s", true, 1*Second + 4*Millisecond},
   821  	{"100.00100s", true, 100*Second + 1*Millisecond},
   822  	// different units
   823  	{"10ns", true, 10 * Nanosecond},
   824  	{"11us", true, 11 * Microsecond},
   825  	{"12µs", true, 12 * Microsecond}, // U+00B5
   826  	{"12μs", true, 12 * Microsecond}, // U+03BC
   827  	{"13ms", true, 13 * Millisecond},
   828  	{"14s", true, 14 * Second},
   829  	{"15m", true, 15 * Minute},
   830  	{"16h", true, 16 * Hour},
   831  	// composite durations
   832  	{"3h30m", true, 3*Hour + 30*Minute},
   833  	{"10.5s4m", true, 4*Minute + 10*Second + 500*Millisecond},
   834  	{"-2m3.4s", true, -(2*Minute + 3*Second + 400*Millisecond)},
   835  	{"1h2m3s4ms5us6ns", true, 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond},
   836  	{"39h9m14.425s", true, 39*Hour + 9*Minute + 14*Second + 425*Millisecond},
   837  	// large value
   838  	{"52763797000ns", true, 52763797000 * Nanosecond},
   839  	// more than 9 digits after decimal point, see https://golang.org/issue/6617
   840  	{"0.3333333333333333333h", true, 20 * Minute},
   841  	// 9007199254740993 = 1<<53+1 cannot be stored precisely in a float64
   842  	{"9007199254740993ns", true, (1<<53 + 1) * Nanosecond},
   843  	// largest duration that can be represented by int64 in nanoseconds
   844  	{"9223372036854775807ns", true, (1<<63 - 1) * Nanosecond},
   845  	{"9223372036854775.807us", true, (1<<63 - 1) * Nanosecond},
   846  	{"9223372036s854ms775us807ns", true, (1<<63 - 1) * Nanosecond},
   847  	// large negative value
   848  	{"-9223372036854775807ns", true, -1<<63 + 1*Nanosecond},
   849  	// huge string; issue 15011.
   850  	{"0.100000000000000000000h", true, 6 * Minute},
   851  	// This value tests the first overflow check in leadingFraction.
   852  	{"0.830103483285477580700h", true, 49*Minute + 48*Second + 372539827*Nanosecond},
   853  
   854  	// errors
   855  	{"", false, 0},
   856  	{"3", false, 0},
   857  	{"-", false, 0},
   858  	{"s", false, 0},
   859  	{".", false, 0},
   860  	{"-.", false, 0},
   861  	{".s", false, 0},
   862  	{"+.s", false, 0},
   863  	{"3000000h", false, 0},                  // overflow
   864  	{"9223372036854775808ns", false, 0},     // overflow
   865  	{"9223372036854775.808us", false, 0},    // overflow
   866  	{"9223372036854ms775us808ns", false, 0}, // overflow
   867  	// largest negative value of type int64 in nanoseconds should fail
   868  	// see https://go-review.googlesource.com/#/c/2461/
   869  	{"-9223372036854775808ns", false, 0},
   870  }
   871  
   872  func TestParseDuration(t *testing.T) {
   873  	for _, tc := range parseDurationTests {
   874  		d, err := ParseDuration(tc.in)
   875  		if tc.ok && (err != nil || d != tc.want) {
   876  			t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want)
   877  		} else if !tc.ok && err == nil {
   878  			t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in)
   879  		}
   880  	}
   881  }
   882  
   883  func TestParseDurationRoundTrip(t *testing.T) {
   884  	for i := 0; i < 100; i++ {
   885  		// Resolutions finer than milliseconds will result in
   886  		// imprecise round-trips.
   887  		d0 := Duration(rand.Int31()) * Millisecond
   888  		s := d0.String()
   889  		d1, err := ParseDuration(s)
   890  		if err != nil || d0 != d1 {
   891  			t.Errorf("round-trip failed: %d => %q => %d, %v", d0, s, d1, err)
   892  		}
   893  	}
   894  }
   895  
   896  // golang.org/issue/4622
   897  func TestLocationRace(t *testing.T) {
   898  	ResetLocalOnceForTest() // reset the Once to trigger the race
   899  
   900  	c := make(chan string, 1)
   901  	go func() {
   902  		c <- Now().String()
   903  	}()
   904  	_ = Now().String()
   905  	<-c
   906  	Sleep(100 * Millisecond)
   907  
   908  	// Back to Los Angeles for subsequent tests:
   909  	ForceUSPacificForTesting()
   910  }
   911  
   912  var (
   913  	t Time
   914  	u int64
   915  )
   916  
   917  var mallocTest = []struct {
   918  	count int
   919  	desc  string
   920  	fn    func()
   921  }{
   922  	{0, `time.Now()`, func() { t = Now() }},
   923  	{0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }},
   924  }
   925  
   926  func TestCountMallocs(t *testing.T) {
   927  	if testing.Short() {
   928  		t.Skip("skipping malloc count in short mode")
   929  	}
   930  	if runtime.GOMAXPROCS(0) > 1 {
   931  		t.Skip("skipping; GOMAXPROCS>1")
   932  	}
   933  	for _, mt := range mallocTest {
   934  		allocs := int(testing.AllocsPerRun(100, mt.fn))
   935  		if allocs > mt.count {
   936  			t.Errorf("%s: %d allocs, want %d", mt.desc, allocs, mt.count)
   937  		}
   938  	}
   939  }
   940  
   941  func TestLoadFixed(t *testing.T) {
   942  	// Issue 4064: handle locations without any zone transitions.
   943  	loc, err := LoadLocation("Etc/GMT+1")
   944  	if err != nil {
   945  		t.Fatal(err)
   946  	}
   947  
   948  	// The tzdata name Etc/GMT+1 uses "east is negative",
   949  	// but Go and most other systems use "east is positive".
   950  	// So GMT+1 corresponds to -3600 in the Go zone, not +3600.
   951  	name, offset := Now().In(loc).Zone()
   952  	// The zone abbreviation is "-01" since tzdata-2016g, and "GMT+1"
   953  	// on earlier versions; we accept both. (Issue #17276).
   954  	if !(name == "GMT+1" || name == "-01") || offset != -1*60*60 {
   955  		t.Errorf("Now().In(loc).Zone() = %q, %d, want %q or %q, %d",
   956  			name, offset, "GMT+1", "-01", -1*60*60)
   957  	}
   958  }
   959  
   960  const (
   961  	minDuration Duration = -1 << 63
   962  	maxDuration Duration = 1<<63 - 1
   963  )
   964  
   965  var subTests = []struct {
   966  	t Time
   967  	u Time
   968  	d Duration
   969  }{
   970  	{Time{}, Time{}, Duration(0)},
   971  	{Date(2009, 11, 23, 0, 0, 0, 1, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), Duration(1)},
   972  	{Date(2009, 11, 23, 0, 0, 0, 0, UTC), Date(2009, 11, 24, 0, 0, 0, 0, UTC), -24 * Hour},
   973  	{Date(2009, 11, 24, 0, 0, 0, 0, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour},
   974  	{Date(-2009, 11, 24, 0, 0, 0, 0, UTC), Date(-2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour},
   975  	{Time{}, Date(2109, 11, 23, 0, 0, 0, 0, UTC), Duration(minDuration)},
   976  	{Date(2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(maxDuration)},
   977  	{Time{}, Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Duration(maxDuration)},
   978  	{Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, Duration(minDuration)},
   979  	{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},
   980  	{Date(2300, 1, 1, 0, 0, 0, 0, UTC), Date(2000, 1, 1, 0, 0, 0, 0, UTC), Duration(maxDuration)},
   981  	{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},
   982  	{Date(2000, 1, 1, 0, 0, 0, 0, UTC), Date(2300, 1, 1, 0, 0, 0, 0, UTC), Duration(minDuration)},
   983  	{MinMonoTime, MaxMonoTime, minDuration},
   984  	{MaxMonoTime, MinMonoTime, maxDuration},
   985  }
   986  
   987  func TestSub(t *testing.T) {
   988  	for i, st := range subTests {
   989  		got := st.t.Sub(st.u)
   990  		if got != st.d {
   991  			t.Errorf("#%d: Sub(%v, %v): got %v; want %v", i, st.t, st.u, got, st.d)
   992  		}
   993  	}
   994  }
   995  
   996  var nsDurationTests = []struct {
   997  	d    Duration
   998  	want int64
   999  }{
  1000  	{Duration(-1000), -1000},
  1001  	{Duration(-1), -1},
  1002  	{Duration(1), 1},
  1003  	{Duration(1000), 1000},
  1004  }
  1005  
  1006  func TestDurationNanoseconds(t *testing.T) {
  1007  	for _, tt := range nsDurationTests {
  1008  		if got := tt.d.Nanoseconds(); got != tt.want {
  1009  			t.Errorf("d.Nanoseconds() = %d; want: %d", got, tt.want)
  1010  		}
  1011  	}
  1012  }
  1013  
  1014  var secDurationTests = []struct {
  1015  	d    Duration
  1016  	want float64
  1017  }{
  1018  	{Duration(300000000), 0.3},
  1019  }
  1020  
  1021  func TestDurationSeconds(t *testing.T) {
  1022  	for _, tt := range secDurationTests {
  1023  		if got := tt.d.Seconds(); got != tt.want {
  1024  			t.Errorf("d.Seconds() = %g; want: %g", got, tt.want)
  1025  		}
  1026  	}
  1027  }
  1028  
  1029  var minDurationTests = []struct {
  1030  	d    Duration
  1031  	want float64
  1032  }{
  1033  	{Duration(-60000000000), -1},
  1034  	{Duration(-1), -1 / 60e9},
  1035  	{Duration(1), 1 / 60e9},
  1036  	{Duration(60000000000), 1},
  1037  	{Duration(3000), 5e-8},
  1038  }
  1039  
  1040  func TestDurationMinutes(t *testing.T) {
  1041  	for _, tt := range minDurationTests {
  1042  		if got := tt.d.Minutes(); got != tt.want {
  1043  			t.Errorf("d.Minutes() = %g; want: %g", got, tt.want)
  1044  		}
  1045  	}
  1046  }
  1047  
  1048  var hourDurationTests = []struct {
  1049  	d    Duration
  1050  	want float64
  1051  }{
  1052  	{Duration(-3600000000000), -1},
  1053  	{Duration(-1), -1 / 3600e9},
  1054  	{Duration(1), 1 / 3600e9},
  1055  	{Duration(3600000000000), 1},
  1056  	{Duration(36), 1e-11},
  1057  }
  1058  
  1059  func TestDurationHours(t *testing.T) {
  1060  	for _, tt := range hourDurationTests {
  1061  		if got := tt.d.Hours(); got != tt.want {
  1062  			t.Errorf("d.Hours() = %g; want: %g", got, tt.want)
  1063  		}
  1064  	}
  1065  }
  1066  
  1067  var durationTruncateTests = []struct {
  1068  	d    Duration
  1069  	m    Duration
  1070  	want Duration
  1071  }{
  1072  	{0, Second, 0},
  1073  	{Minute, -7 * Second, Minute},
  1074  	{Minute, 0, Minute},
  1075  	{Minute, 1, Minute},
  1076  	{Minute + 10*Second, 10 * Second, Minute + 10*Second},
  1077  	{2*Minute + 10*Second, Minute, 2 * Minute},
  1078  	{10*Minute + 10*Second, 3 * Minute, 9 * Minute},
  1079  	{Minute + 10*Second, Minute + 10*Second + 1, 0},
  1080  	{Minute + 10*Second, Hour, 0},
  1081  	{-Minute, Second, -Minute},
  1082  	{-10 * Minute, 3 * Minute, -9 * Minute},
  1083  	{-10 * Minute, Hour, 0},
  1084  }
  1085  
  1086  func TestDurationTruncate(t *testing.T) {
  1087  	for _, tt := range durationTruncateTests {
  1088  		if got := tt.d.Truncate(tt.m); got != tt.want {
  1089  			t.Errorf("Duration(%s).Truncate(%s) = %s; want: %s", tt.d, tt.m, got, tt.want)
  1090  		}
  1091  	}
  1092  }
  1093  
  1094  var durationRoundTests = []struct {
  1095  	d    Duration
  1096  	m    Duration
  1097  	want Duration
  1098  }{
  1099  	{0, Second, 0},
  1100  	{Minute, -11 * Second, Minute},
  1101  	{Minute, 0, Minute},
  1102  	{Minute, 1, Minute},
  1103  	{2 * Minute, Minute, 2 * Minute},
  1104  	{2*Minute + 10*Second, Minute, 2 * Minute},
  1105  	{2*Minute + 30*Second, Minute, 3 * Minute},
  1106  	{2*Minute + 50*Second, Minute, 3 * Minute},
  1107  	{-Minute, 1, -Minute},
  1108  	{-2 * Minute, Minute, -2 * Minute},
  1109  	{-2*Minute - 10*Second, Minute, -2 * Minute},
  1110  	{-2*Minute - 30*Second, Minute, -3 * Minute},
  1111  	{-2*Minute - 50*Second, Minute, -3 * Minute},
  1112  	{8e18, 3e18, 9e18},
  1113  	{9e18, 5e18, 1<<63 - 1},
  1114  	{-8e18, 3e18, -9e18},
  1115  	{-9e18, 5e18, -1 << 63},
  1116  	{3<<61 - 1, 3 << 61, 3 << 61},
  1117  }
  1118  
  1119  func TestDurationRound(t *testing.T) {
  1120  	for _, tt := range durationRoundTests {
  1121  		if got := tt.d.Round(tt.m); got != tt.want {
  1122  			t.Errorf("Duration(%s).Round(%s) = %s; want: %s", tt.d, tt.m, got, tt.want)
  1123  		}
  1124  	}
  1125  }
  1126  
  1127  var defaultLocTests = []struct {
  1128  	name string
  1129  	f    func(t1, t2 Time) bool
  1130  }{
  1131  	{"After", func(t1, t2 Time) bool { return t1.After(t2) == t2.After(t1) }},
  1132  	{"Before", func(t1, t2 Time) bool { return t1.Before(t2) == t2.Before(t1) }},
  1133  	{"Equal", func(t1, t2 Time) bool { return t1.Equal(t2) == t2.Equal(t1) }},
  1134  
  1135  	{"IsZero", func(t1, t2 Time) bool { return t1.IsZero() == t2.IsZero() }},
  1136  	{"Date", func(t1, t2 Time) bool {
  1137  		a1, b1, c1 := t1.Date()
  1138  		a2, b2, c2 := t2.Date()
  1139  		return a1 == a2 && b1 == b2 && c1 == c2
  1140  	}},
  1141  	{"Year", func(t1, t2 Time) bool { return t1.Year() == t2.Year() }},
  1142  	{"Month", func(t1, t2 Time) bool { return t1.Month() == t2.Month() }},
  1143  	{"Day", func(t1, t2 Time) bool { return t1.Day() == t2.Day() }},
  1144  	{"Weekday", func(t1, t2 Time) bool { return t1.Weekday() == t2.Weekday() }},
  1145  	{"ISOWeek", func(t1, t2 Time) bool {
  1146  		a1, b1 := t1.ISOWeek()
  1147  		a2, b2 := t2.ISOWeek()
  1148  		return a1 == a2 && b1 == b2
  1149  	}},
  1150  	{"Clock", func(t1, t2 Time) bool {
  1151  		a1, b1, c1 := t1.Clock()
  1152  		a2, b2, c2 := t2.Clock()
  1153  		return a1 == a2 && b1 == b2 && c1 == c2
  1154  	}},
  1155  	{"Hour", func(t1, t2 Time) bool { return t1.Hour() == t2.Hour() }},
  1156  	{"Minute", func(t1, t2 Time) bool { return t1.Minute() == t2.Minute() }},
  1157  	{"Second", func(t1, t2 Time) bool { return t1.Second() == t2.Second() }},
  1158  	{"Nanosecond", func(t1, t2 Time) bool { return t1.Hour() == t2.Hour() }},
  1159  	{"YearDay", func(t1, t2 Time) bool { return t1.YearDay() == t2.YearDay() }},
  1160  
  1161  	// Using Equal since Add don't modify loc using "==" will cause a fail
  1162  	{"Add", func(t1, t2 Time) bool { return t1.Add(Hour).Equal(t2.Add(Hour)) }},
  1163  	{"Sub", func(t1, t2 Time) bool { return t1.Sub(t2) == t2.Sub(t1) }},
  1164  
  1165  	//Original caus for this test case bug 15852
  1166  	{"AddDate", func(t1, t2 Time) bool { return t1.AddDate(1991, 9, 3) == t2.AddDate(1991, 9, 3) }},
  1167  
  1168  	{"UTC", func(t1, t2 Time) bool { return t1.UTC() == t2.UTC() }},
  1169  	{"Local", func(t1, t2 Time) bool { return t1.Local() == t2.Local() }},
  1170  	{"In", func(t1, t2 Time) bool { return t1.In(UTC) == t2.In(UTC) }},
  1171  
  1172  	{"Local", func(t1, t2 Time) bool { return t1.Local() == t2.Local() }},
  1173  	{"Zone", func(t1, t2 Time) bool {
  1174  		a1, b1 := t1.Zone()
  1175  		a2, b2 := t2.Zone()
  1176  		return a1 == a2 && b1 == b2
  1177  	}},
  1178  
  1179  	{"Unix", func(t1, t2 Time) bool { return t1.Unix() == t2.Unix() }},
  1180  	{"UnixNano", func(t1, t2 Time) bool { return t1.UnixNano() == t2.UnixNano() }},
  1181  
  1182  	{"MarshalBinary", func(t1, t2 Time) bool {
  1183  		a1, b1 := t1.MarshalBinary()
  1184  		a2, b2 := t2.MarshalBinary()
  1185  		return bytes.Equal(a1, a2) && b1 == b2
  1186  	}},
  1187  	{"GobEncode", func(t1, t2 Time) bool {
  1188  		a1, b1 := t1.GobEncode()
  1189  		a2, b2 := t2.GobEncode()
  1190  		return bytes.Equal(a1, a2) && b1 == b2
  1191  	}},
  1192  	{"MarshalJSON", func(t1, t2 Time) bool {
  1193  		a1, b1 := t1.MarshalJSON()
  1194  		a2, b2 := t2.MarshalJSON()
  1195  		return bytes.Equal(a1, a2) && b1 == b2
  1196  	}},
  1197  	{"MarshalText", func(t1, t2 Time) bool {
  1198  		a1, b1 := t1.MarshalText()
  1199  		a2, b2 := t2.MarshalText()
  1200  		return bytes.Equal(a1, a2) && b1 == b2
  1201  	}},
  1202  
  1203  	{"Truncate", func(t1, t2 Time) bool { return t1.Truncate(Hour).Equal(t2.Truncate(Hour)) }},
  1204  	{"Round", func(t1, t2 Time) bool { return t1.Round(Hour).Equal(t2.Round(Hour)) }},
  1205  
  1206  	{"== Time{}", func(t1, t2 Time) bool { return (t1 == Time{}) == (t2 == Time{}) }},
  1207  }
  1208  
  1209  func TestDefaultLoc(t *testing.T) {
  1210  	// Verify that all of Time's methods behave identically if loc is set to
  1211  	// nil or UTC.
  1212  	for _, tt := range defaultLocTests {
  1213  		t1 := Time{}
  1214  		t2 := Time{}.UTC()
  1215  		if !tt.f(t1, t2) {
  1216  			t.Errorf("Time{} and Time{}.UTC() behave differently for %s", tt.name)
  1217  		}
  1218  	}
  1219  }
  1220  
  1221  func BenchmarkNow(b *testing.B) {
  1222  	for i := 0; i < b.N; i++ {
  1223  		t = Now()
  1224  	}
  1225  }
  1226  
  1227  func BenchmarkNowUnixNano(b *testing.B) {
  1228  	for i := 0; i < b.N; i++ {
  1229  		u = Now().UnixNano()
  1230  	}
  1231  }
  1232  
  1233  func BenchmarkFormat(b *testing.B) {
  1234  	t := Unix(1265346057, 0)
  1235  	for i := 0; i < b.N; i++ {
  1236  		t.Format("Mon Jan  2 15:04:05 2006")
  1237  	}
  1238  }
  1239  
  1240  func BenchmarkFormatNow(b *testing.B) {
  1241  	// Like BenchmarkFormat, but easier, because the time zone
  1242  	// lookup cache is optimized for the present.
  1243  	t := Now()
  1244  	for i := 0; i < b.N; i++ {
  1245  		t.Format("Mon Jan  2 15:04:05 2006")
  1246  	}
  1247  }
  1248  
  1249  func BenchmarkMarshalJSON(b *testing.B) {
  1250  	t := Now()
  1251  	for i := 0; i < b.N; i++ {
  1252  		t.MarshalJSON()
  1253  	}
  1254  }
  1255  
  1256  func BenchmarkMarshalText(b *testing.B) {
  1257  	t := Now()
  1258  	for i := 0; i < b.N; i++ {
  1259  		t.MarshalText()
  1260  	}
  1261  }
  1262  
  1263  func BenchmarkParse(b *testing.B) {
  1264  	for i := 0; i < b.N; i++ {
  1265  		Parse(ANSIC, "Mon Jan  2 15:04:05 2006")
  1266  	}
  1267  }
  1268  
  1269  func BenchmarkParseDuration(b *testing.B) {
  1270  	for i := 0; i < b.N; i++ {
  1271  		ParseDuration("9007199254.740993ms")
  1272  		ParseDuration("9007199254740993ns")
  1273  	}
  1274  }
  1275  
  1276  func BenchmarkHour(b *testing.B) {
  1277  	t := Now()
  1278  	for i := 0; i < b.N; i++ {
  1279  		_ = t.Hour()
  1280  	}
  1281  }
  1282  
  1283  func BenchmarkSecond(b *testing.B) {
  1284  	t := Now()
  1285  	for i := 0; i < b.N; i++ {
  1286  		_ = t.Second()
  1287  	}
  1288  }
  1289  
  1290  func BenchmarkYear(b *testing.B) {
  1291  	t := Now()
  1292  	for i := 0; i < b.N; i++ {
  1293  		_ = t.Year()
  1294  	}
  1295  }
  1296  
  1297  func BenchmarkDay(b *testing.B) {
  1298  	t := Now()
  1299  	for i := 0; i < b.N; i++ {
  1300  		_ = t.Day()
  1301  	}
  1302  }
  1303  
  1304  func TestMarshalBinaryZeroTime(t *testing.T) {
  1305  	t0 := Time{}
  1306  	enc, err := t0.MarshalBinary()
  1307  	if err != nil {
  1308  		t.Fatal(err)
  1309  	}
  1310  	t1 := Now() // not zero
  1311  	if err := t1.UnmarshalBinary(enc); err != nil {
  1312  		t.Fatal(err)
  1313  	}
  1314  	if t1 != t0 {
  1315  		t.Errorf("t0=%#v\nt1=%#v\nwant identical structures", t0, t1)
  1316  	}
  1317  }
  1318  
  1319  // Issue 17720: Zero value of time.Month fails to print
  1320  func TestZeroMonthString(t *testing.T) {
  1321  	if got, want := Month(0).String(), "%!Month(0)"; got != want {
  1322  		t.Errorf("zero month = %q; want %q", got, want)
  1323  	}
  1324  }
  1325  
  1326  // Issue 24692: Out of range weekday panics
  1327  func TestWeekdayString(t *testing.T) {
  1328  	if got, want := Weekday(Tuesday).String(), "Tuesday"; got != want {
  1329  		t.Errorf("Tuesday weekday = %q; want %q", got, want)
  1330  	}
  1331  	if got, want := Weekday(14).String(), "%!Weekday(14)"; got != want {
  1332  		t.Errorf("14th weekday = %q; want %q", got, want)
  1333  	}
  1334  }
  1335  
  1336  func TestReadFileLimit(t *testing.T) {
  1337  	const zero = "/dev/zero"
  1338  	if _, err := os.Stat(zero); err != nil {
  1339  		t.Skip("skipping test without a /dev/zero")
  1340  	}
  1341  	_, err := ReadFile(zero)
  1342  	if err == nil || !strings.Contains(err.Error(), "is too large") {
  1343  		t.Errorf("readFile(%q) error = %v; want error containing 'is too large'", zero, err)
  1344  	}
  1345  }
  1346  
  1347  // Issue 25686: hard crash on concurrent timer access.
  1348  // This test deliberately invokes a race condition.
  1349  // We are testing that we don't crash with "fatal error: panic holding locks".
  1350  func TestConcurrentTimerReset(t *testing.T) {
  1351  	if race.Enabled {
  1352  		t.Skip("skipping test under race detector")
  1353  	}
  1354  
  1355  	// We expect this code to panic rather than crash.
  1356  	// Don't worry if it doesn't panic.
  1357  	catch := func(i int) {
  1358  		if e := recover(); e != nil {
  1359  			t.Logf("panic in goroutine %d, as expected, with %q", i, e)
  1360  		} else {
  1361  			t.Logf("no panic in goroutine %d", i)
  1362  		}
  1363  	}
  1364  
  1365  	const goroutines = 8
  1366  	const tries = 1000
  1367  	var wg sync.WaitGroup
  1368  	wg.Add(goroutines)
  1369  	timer := NewTimer(Hour)
  1370  	for i := 0; i < goroutines; i++ {
  1371  		go func(i int) {
  1372  			defer wg.Done()
  1373  			defer catch(i)
  1374  			for j := 0; j < tries; j++ {
  1375  				timer.Reset(Hour + Duration(i*j))
  1376  			}
  1377  		}(i)
  1378  	}
  1379  	wg.Wait()
  1380  }
  1381  

View as plain text