Source file src/time/time_test.go

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

View as plain text