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, 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(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  	{Date(2020, 1, 1, 0, 0, 0, 0, FixedZone("", 23*60*60+59*60)), `"2020-01-01T00:00:00+23:59"`},
   808  }
   809  
   810  func TestTimeJSON(t *testing.T) {
   811  	for _, tt := range jsonTests {
   812  		var jsonTime Time
   813  
   814  		if jsonBytes, err := json.Marshal(tt.time); err != nil {
   815  			t.Errorf("%v json.Marshal error = %v, want nil", tt.time, err)
   816  		} else if string(jsonBytes) != tt.json {
   817  			t.Errorf("%v JSON = %#q, want %#q", tt.time, string(jsonBytes), tt.json)
   818  		} else if err = json.Unmarshal(jsonBytes, &jsonTime); err != nil {
   819  			t.Errorf("%v json.Unmarshal error = %v, want nil", tt.time, err)
   820  		} else if !equalTimeAndZone(jsonTime, tt.time) {
   821  			t.Errorf("Unmarshaled time = %v, want %v", jsonTime, tt.time)
   822  		}
   823  	}
   824  }
   825  
   826  func TestUnmarshalInvalidTimes(t *testing.T) {
   827  	tests := []struct {
   828  		in   string
   829  		want string
   830  	}{
   831  		{`{}`, "Time.UnmarshalJSON: input is not a JSON string"},
   832  		{`[]`, "Time.UnmarshalJSON: input is not a JSON string"},
   833  		{`"2000-01-01T1:12:34Z"`, `<nil>`},
   834  		{`"2000-01-01T00:00:00,000Z"`, `<nil>`},
   835  		{`"2000-01-01T00:00:00+24:00"`, `<nil>`},
   836  		{`"2000-01-01T00:00:00+00:60"`, `<nil>`},
   837  		{`"2000-01-01T00:00:00+123:45"`, `parsing time "2000-01-01T00:00:00+123:45" as "2006-01-02T15:04:05Z07:00": cannot parse "+123:45" as "Z07:00"`},
   838  	}
   839  
   840  	for _, tt := range tests {
   841  		var ts Time
   842  
   843  		want := tt.want
   844  		err := json.Unmarshal([]byte(tt.in), &ts)
   845  		if fmt.Sprint(err) != want {
   846  			t.Errorf("Time.UnmarshalJSON(%s) = %v, want %v", tt.in, err, want)
   847  		}
   848  
   849  		if strings.HasPrefix(tt.in, `"`) && strings.HasSuffix(tt.in, `"`) {
   850  			err = ts.UnmarshalText([]byte(strings.Trim(tt.in, `"`)))
   851  			if fmt.Sprint(err) != want {
   852  				t.Errorf("Time.UnmarshalText(%s) = %v, want %v", tt.in, err, want)
   853  			}
   854  		}
   855  	}
   856  }
   857  
   858  func TestMarshalInvalidTimes(t *testing.T) {
   859  	tests := []struct {
   860  		time Time
   861  		want string
   862  	}{
   863  		{Date(10000, 1, 1, 0, 0, 0, 0, UTC), "Time.MarshalJSON: year outside of range [0,9999]"},
   864  		{Date(-998, 1, 1, 0, 0, 0, 0, UTC).Add(-Second), "Time.MarshalJSON: year outside of range [0,9999]"},
   865  		{Date(0, 1, 1, 0, 0, 0, 0, UTC).Add(-Nanosecond), "Time.MarshalJSON: year outside of range [0,9999]"},
   866  		{Date(2020, 1, 1, 0, 0, 0, 0, FixedZone("", 24*60*60)), "Time.MarshalJSON: timezone hour outside of range [0,23]"},
   867  		{Date(2020, 1, 1, 0, 0, 0, 0, FixedZone("", 123*60*60)), "Time.MarshalJSON: timezone hour outside of range [0,23]"},
   868  	}
   869  
   870  	for _, tt := range tests {
   871  		want := tt.want
   872  		b, err := tt.time.MarshalJSON()
   873  		switch {
   874  		case b != nil:
   875  			t.Errorf("(%v).MarshalText() = %q, want nil", tt.time, b)
   876  		case err == nil || err.Error() != want:
   877  			t.Errorf("(%v).MarshalJSON() error = %v, want %v", tt.time, err, want)
   878  		}
   879  
   880  		want = strings.ReplaceAll(tt.want, "JSON", "Text")
   881  		b, err = tt.time.MarshalText()
   882  		switch {
   883  		case b != nil:
   884  			t.Errorf("(%v).MarshalText() = %q, want nil", tt.time, b)
   885  		case err == nil || err.Error() != want:
   886  			t.Errorf("(%v).MarshalText() error = %v, want %v", tt.time, err, want)
   887  		}
   888  	}
   889  }
   890  
   891  var parseDurationTests = []struct {
   892  	in   string
   893  	want Duration
   894  }{
   895  	// simple
   896  	{"0", 0},
   897  	{"5s", 5 * Second},
   898  	{"30s", 30 * Second},
   899  	{"1478s", 1478 * Second},
   900  	// sign
   901  	{"-5s", -5 * Second},
   902  	{"+5s", 5 * Second},
   903  	{"-0", 0},
   904  	{"+0", 0},
   905  	// decimal
   906  	{"5.0s", 5 * Second},
   907  	{"5.6s", 5*Second + 600*Millisecond},
   908  	{"5.s", 5 * Second},
   909  	{".5s", 500 * Millisecond},
   910  	{"1.0s", 1 * Second},
   911  	{"1.00s", 1 * Second},
   912  	{"1.004s", 1*Second + 4*Millisecond},
   913  	{"1.0040s", 1*Second + 4*Millisecond},
   914  	{"100.00100s", 100*Second + 1*Millisecond},
   915  	// different units
   916  	{"10ns", 10 * Nanosecond},
   917  	{"11us", 11 * Microsecond},
   918  	{"12µs", 12 * Microsecond}, // U+00B5
   919  	{"12μs", 12 * Microsecond}, // U+03BC
   920  	{"13ms", 13 * Millisecond},
   921  	{"14s", 14 * Second},
   922  	{"15m", 15 * Minute},
   923  	{"16h", 16 * Hour},
   924  	// composite durations
   925  	{"3h30m", 3*Hour + 30*Minute},
   926  	{"10.5s4m", 4*Minute + 10*Second + 500*Millisecond},
   927  	{"-2m3.4s", -(2*Minute + 3*Second + 400*Millisecond)},
   928  	{"1h2m3s4ms5us6ns", 1*Hour + 2*Minute + 3*Second + 4*Millisecond + 5*Microsecond + 6*Nanosecond},
   929  	{"39h9m14.425s", 39*Hour + 9*Minute + 14*Second + 425*Millisecond},
   930  	// large value
   931  	{"52763797000ns", 52763797000 * Nanosecond},
   932  	// more than 9 digits after decimal point, see https://golang.org/issue/6617
   933  	{"0.3333333333333333333h", 20 * Minute},
   934  	// 9007199254740993 = 1<<53+1 cannot be stored precisely in a float64
   935  	{"9007199254740993ns", (1<<53 + 1) * Nanosecond},
   936  	// largest duration that can be represented by int64 in nanoseconds
   937  	{"9223372036854775807ns", (1<<63 - 1) * Nanosecond},
   938  	{"9223372036854775.807us", (1<<63 - 1) * Nanosecond},
   939  	{"9223372036s854ms775us807ns", (1<<63 - 1) * Nanosecond},
   940  	{"-9223372036854775808ns", -1 << 63 * Nanosecond},
   941  	{"-9223372036854775.808us", -1 << 63 * Nanosecond},
   942  	{"-9223372036s854ms775us808ns", -1 << 63 * Nanosecond},
   943  	// largest negative value
   944  	{"-9223372036854775808ns", -1 << 63 * Nanosecond},
   945  	// largest negative round trip value, see https://golang.org/issue/48629
   946  	{"-2562047h47m16.854775808s", -1 << 63 * Nanosecond},
   947  	// huge string; issue 15011.
   948  	{"0.100000000000000000000h", 6 * Minute},
   949  	// This value tests the first overflow check in leadingFraction.
   950  	{"0.830103483285477580700h", 49*Minute + 48*Second + 372539827*Nanosecond},
   951  }
   952  
   953  func TestParseDuration(t *testing.T) {
   954  	for _, tc := range parseDurationTests {
   955  		d, err := ParseDuration(tc.in)
   956  		if err != nil || d != tc.want {
   957  			t.Errorf("ParseDuration(%q) = %v, %v, want %v, nil", tc.in, d, err, tc.want)
   958  		}
   959  	}
   960  }
   961  
   962  var parseDurationErrorTests = []struct {
   963  	in     string
   964  	expect string
   965  }{
   966  	// invalid
   967  	{"", `""`},
   968  	{"3", `"3"`},
   969  	{"-", `"-"`},
   970  	{"s", `"s"`},
   971  	{".", `"."`},
   972  	{"-.", `"-."`},
   973  	{".s", `".s"`},
   974  	{"+.s", `"+.s"`},
   975  	{"1d", `"1d"`},
   976  	{"\x85\x85", `"\x85\x85"`},
   977  	{"\xffff", `"\xffff"`},
   978  	{"hello \xffff world", `"hello \xffff world"`},
   979  	{"\uFFFD", `"\xef\xbf\xbd"`},                                             // utf8.RuneError
   980  	{"\uFFFD hello \uFFFD world", `"\xef\xbf\xbd hello \xef\xbf\xbd world"`}, // utf8.RuneError
   981  	// overflow
   982  	{"9223372036854775810ns", `"9223372036854775810ns"`},
   983  	{"9223372036854775808ns", `"9223372036854775808ns"`},
   984  	{"-9223372036854775809ns", `"-9223372036854775809ns"`},
   985  	{"9223372036854776us", `"9223372036854776us"`},
   986  	{"3000000h", `"3000000h"`},
   987  	{"9223372036854775.808us", `"9223372036854775.808us"`},
   988  	{"9223372036854ms775us808ns", `"9223372036854ms775us808ns"`},
   989  }
   990  
   991  func TestParseDurationErrors(t *testing.T) {
   992  	for _, tc := range parseDurationErrorTests {
   993  		_, err := ParseDuration(tc.in)
   994  		if err == nil {
   995  			t.Errorf("ParseDuration(%q) = _, nil, want _, non-nil", tc.in)
   996  		} else if !strings.Contains(err.Error(), tc.expect) {
   997  			t.Errorf("ParseDuration(%q) = _, %q, error does not contain %q", tc.in, err, tc.expect)
   998  		}
   999  	}
  1000  }
  1001  
  1002  func TestParseDurationRoundTrip(t *testing.T) {
  1003  	// https://golang.org/issue/48629
  1004  	max0 := Duration(math.MaxInt64)
  1005  	max1, err := ParseDuration(max0.String())
  1006  	if err != nil || max0 != max1 {
  1007  		t.Errorf("round-trip failed: %d => %q => %d, %v", max0, max0.String(), max1, err)
  1008  	}
  1009  
  1010  	min0 := Duration(math.MinInt64)
  1011  	min1, err := ParseDuration(min0.String())
  1012  	if err != nil || min0 != min1 {
  1013  		t.Errorf("round-trip failed: %d => %q => %d, %v", min0, min0.String(), min1, err)
  1014  	}
  1015  
  1016  	for i := 0; i < 100; i++ {
  1017  		// Resolutions finer than milliseconds will result in
  1018  		// imprecise round-trips.
  1019  		d0 := Duration(rand.Int31()) * Millisecond
  1020  		s := d0.String()
  1021  		d1, err := ParseDuration(s)
  1022  		if err != nil || d0 != d1 {
  1023  			t.Errorf("round-trip failed: %d => %q => %d, %v", d0, s, d1, err)
  1024  		}
  1025  	}
  1026  }
  1027  
  1028  // golang.org/issue/4622
  1029  func TestLocationRace(t *testing.T) {
  1030  	ResetLocalOnceForTest() // reset the Once to trigger the race
  1031  
  1032  	c := make(chan string, 1)
  1033  	go func() {
  1034  		c <- Now().String()
  1035  	}()
  1036  	_ = Now().String()
  1037  	<-c
  1038  	Sleep(100 * Millisecond)
  1039  
  1040  	// Back to Los Angeles for subsequent tests:
  1041  	ForceUSPacificForTesting()
  1042  }
  1043  
  1044  var (
  1045  	t Time
  1046  	u int64
  1047  )
  1048  
  1049  var mallocTest = []struct {
  1050  	count int
  1051  	desc  string
  1052  	fn    func()
  1053  }{
  1054  	{0, `time.Now()`, func() { t = Now() }},
  1055  	{0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }},
  1056  	{0, `time.Now().UnixMilli()`, func() { u = Now().UnixMilli() }},
  1057  	{0, `time.Now().UnixMicro()`, func() { u = Now().UnixMicro() }},
  1058  }
  1059  
  1060  func TestCountMallocs(t *testing.T) {
  1061  	if testing.Short() {
  1062  		t.Skip("skipping malloc count in short mode")
  1063  	}
  1064  	if runtime.GOMAXPROCS(0) > 1 {
  1065  		t.Skip("skipping; GOMAXPROCS>1")
  1066  	}
  1067  	for _, mt := range mallocTest {
  1068  		allocs := int(testing.AllocsPerRun(100, mt.fn))
  1069  		if allocs > mt.count {
  1070  			t.Errorf("%s: %d allocs, want %d", mt.desc, allocs, mt.count)
  1071  		}
  1072  	}
  1073  }
  1074  
  1075  func TestLoadFixed(t *testing.T) {
  1076  	// Issue 4064: handle locations without any zone transitions.
  1077  	loc, err := LoadLocation("Etc/GMT+1")
  1078  	if err != nil {
  1079  		t.Fatal(err)
  1080  	}
  1081  
  1082  	// The tzdata name Etc/GMT+1 uses "east is negative",
  1083  	// but Go and most other systems use "east is positive".
  1084  	// So GMT+1 corresponds to -3600 in the Go zone, not +3600.
  1085  	name, offset := Now().In(loc).Zone()
  1086  	// The zone abbreviation is "-01" since tzdata-2016g, and "GMT+1"
  1087  	// on earlier versions; we accept both. (Issue #17276).
  1088  	if !(name == "GMT+1" || name == "-01") || offset != -1*60*60 {
  1089  		t.Errorf("Now().In(loc).Zone() = %q, %d, want %q or %q, %d",
  1090  			name, offset, "GMT+1", "-01", -1*60*60)
  1091  	}
  1092  }
  1093  
  1094  const (
  1095  	minDuration Duration = -1 << 63
  1096  	maxDuration Duration = 1<<63 - 1
  1097  )
  1098  
  1099  var subTests = []struct {
  1100  	t Time
  1101  	u Time
  1102  	d Duration
  1103  }{
  1104  	{Time{}, Time{}, Duration(0)},
  1105  	{Date(2009, 11, 23, 0, 0, 0, 1, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), Duration(1)},
  1106  	{Date(2009, 11, 23, 0, 0, 0, 0, UTC), Date(2009, 11, 24, 0, 0, 0, 0, UTC), -24 * Hour},
  1107  	{Date(2009, 11, 24, 0, 0, 0, 0, UTC), Date(2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour},
  1108  	{Date(-2009, 11, 24, 0, 0, 0, 0, UTC), Date(-2009, 11, 23, 0, 0, 0, 0, UTC), 24 * Hour},
  1109  	{Time{}, Date(2109, 11, 23, 0, 0, 0, 0, UTC), minDuration},
  1110  	{Date(2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, maxDuration},
  1111  	{Time{}, Date(-2109, 11, 23, 0, 0, 0, 0, UTC), maxDuration},
  1112  	{Date(-2109, 11, 23, 0, 0, 0, 0, UTC), Time{}, minDuration},
  1113  	{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},
  1114  	{Date(2300, 1, 1, 0, 0, 0, 0, UTC), Date(2000, 1, 1, 0, 0, 0, 0, UTC), maxDuration},
  1115  	{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},
  1116  	{Date(2000, 1, 1, 0, 0, 0, 0, UTC), Date(2300, 1, 1, 0, 0, 0, 0, UTC), minDuration},
  1117  	{Date(2311, 11, 26, 02, 16, 47, 63535996, UTC), Date(2019, 8, 16, 2, 29, 30, 268436582, UTC), 9223372036795099414},
  1118  	{MinMonoTime, MaxMonoTime, minDuration},
  1119  	{MaxMonoTime, MinMonoTime, maxDuration},
  1120  }
  1121  
  1122  func TestSub(t *testing.T) {
  1123  	for i, st := range subTests {
  1124  		got := st.t.Sub(st.u)
  1125  		if got != st.d {
  1126  			t.Errorf("#%d: Sub(%v, %v): got %v; want %v", i, st.t, st.u, got, st.d)
  1127  		}
  1128  	}
  1129  }
  1130  
  1131  var nsDurationTests = []struct {
  1132  	d    Duration
  1133  	want int64
  1134  }{
  1135  	{Duration(-1000), -1000},
  1136  	{Duration(-1), -1},
  1137  	{Duration(1), 1},
  1138  	{Duration(1000), 1000},
  1139  }
  1140  
  1141  func TestDurationNanoseconds(t *testing.T) {
  1142  	for _, tt := range nsDurationTests {
  1143  		if got := tt.d.Nanoseconds(); got != tt.want {
  1144  			t.Errorf("Duration(%s).Nanoseconds() = %d; want: %d", tt.d, got, tt.want)
  1145  		}
  1146  	}
  1147  }
  1148  
  1149  var usDurationTests = []struct {
  1150  	d    Duration
  1151  	want int64
  1152  }{
  1153  	{Duration(-1000), -1},
  1154  	{Duration(1000), 1},
  1155  }
  1156  
  1157  func TestDurationMicroseconds(t *testing.T) {
  1158  	for _, tt := range usDurationTests {
  1159  		if got := tt.d.Microseconds(); got != tt.want {
  1160  			t.Errorf("Duration(%s).Microseconds() = %d; want: %d", tt.d, got, tt.want)
  1161  		}
  1162  	}
  1163  }
  1164  
  1165  var msDurationTests = []struct {
  1166  	d    Duration
  1167  	want int64
  1168  }{
  1169  	{Duration(-1000000), -1},
  1170  	{Duration(1000000), 1},
  1171  }
  1172  
  1173  func TestDurationMilliseconds(t *testing.T) {
  1174  	for _, tt := range msDurationTests {
  1175  		if got := tt.d.Milliseconds(); got != tt.want {
  1176  			t.Errorf("Duration(%s).Milliseconds() = %d; want: %d", tt.d, got, tt.want)
  1177  		}
  1178  	}
  1179  }
  1180  
  1181  var secDurationTests = []struct {
  1182  	d    Duration
  1183  	want float64
  1184  }{
  1185  	{Duration(300000000), 0.3},
  1186  }
  1187  
  1188  func TestDurationSeconds(t *testing.T) {
  1189  	for _, tt := range secDurationTests {
  1190  		if got := tt.d.Seconds(); got != tt.want {
  1191  			t.Errorf("Duration(%s).Seconds() = %g; want: %g", tt.d, got, tt.want)
  1192  		}
  1193  	}
  1194  }
  1195  
  1196  var minDurationTests = []struct {
  1197  	d    Duration
  1198  	want float64
  1199  }{
  1200  	{Duration(-60000000000), -1},
  1201  	{Duration(-1), -1 / 60e9},
  1202  	{Duration(1), 1 / 60e9},
  1203  	{Duration(60000000000), 1},
  1204  	{Duration(3000), 5e-8},
  1205  }
  1206  
  1207  func TestDurationMinutes(t *testing.T) {
  1208  	for _, tt := range minDurationTests {
  1209  		if got := tt.d.Minutes(); got != tt.want {
  1210  			t.Errorf("Duration(%s).Minutes() = %g; want: %g", tt.d, got, tt.want)
  1211  		}
  1212  	}
  1213  }
  1214  
  1215  var hourDurationTests = []struct {
  1216  	d    Duration
  1217  	want float64
  1218  }{
  1219  	{Duration(-3600000000000), -1},
  1220  	{Duration(-1), -1 / 3600e9},
  1221  	{Duration(1), 1 / 3600e9},
  1222  	{Duration(3600000000000), 1},
  1223  	{Duration(36), 1e-11},
  1224  }
  1225  
  1226  func TestDurationHours(t *testing.T) {
  1227  	for _, tt := range hourDurationTests {
  1228  		if got := tt.d.Hours(); got != tt.want {
  1229  			t.Errorf("Duration(%s).Hours() = %g; want: %g", tt.d, got, tt.want)
  1230  		}
  1231  	}
  1232  }
  1233  
  1234  var durationTruncateTests = []struct {
  1235  	d    Duration
  1236  	m    Duration
  1237  	want Duration
  1238  }{
  1239  	{0, Second, 0},
  1240  	{Minute, -7 * Second, Minute},
  1241  	{Minute, 0, Minute},
  1242  	{Minute, 1, Minute},
  1243  	{Minute + 10*Second, 10 * Second, Minute + 10*Second},
  1244  	{2*Minute + 10*Second, Minute, 2 * Minute},
  1245  	{10*Minute + 10*Second, 3 * Minute, 9 * Minute},
  1246  	{Minute + 10*Second, Minute + 10*Second + 1, 0},
  1247  	{Minute + 10*Second, Hour, 0},
  1248  	{-Minute, Second, -Minute},
  1249  	{-10 * Minute, 3 * Minute, -9 * Minute},
  1250  	{-10 * Minute, Hour, 0},
  1251  }
  1252  
  1253  func TestDurationTruncate(t *testing.T) {
  1254  	for _, tt := range durationTruncateTests {
  1255  		if got := tt.d.Truncate(tt.m); got != tt.want {
  1256  			t.Errorf("Duration(%s).Truncate(%s) = %s; want: %s", tt.d, tt.m, got, tt.want)
  1257  		}
  1258  	}
  1259  }
  1260  
  1261  var durationRoundTests = []struct {
  1262  	d    Duration
  1263  	m    Duration
  1264  	want Duration
  1265  }{
  1266  	{0, Second, 0},
  1267  	{Minute, -11 * Second, Minute},
  1268  	{Minute, 0, Minute},
  1269  	{Minute, 1, Minute},
  1270  	{2 * Minute, Minute, 2 * Minute},
  1271  	{2*Minute + 10*Second, Minute, 2 * Minute},
  1272  	{2*Minute + 30*Second, Minute, 3 * Minute},
  1273  	{2*Minute + 50*Second, Minute, 3 * Minute},
  1274  	{-Minute, 1, -Minute},
  1275  	{-2 * Minute, Minute, -2 * Minute},
  1276  	{-2*Minute - 10*Second, Minute, -2 * Minute},
  1277  	{-2*Minute - 30*Second, Minute, -3 * Minute},
  1278  	{-2*Minute - 50*Second, Minute, -3 * Minute},
  1279  	{8e18, 3e18, 9e18},
  1280  	{9e18, 5e18, 1<<63 - 1},
  1281  	{-8e18, 3e18, -9e18},
  1282  	{-9e18, 5e18, -1 << 63},
  1283  	{3<<61 - 1, 3 << 61, 3 << 61},
  1284  }
  1285  
  1286  func TestDurationRound(t *testing.T) {
  1287  	for _, tt := range durationRoundTests {
  1288  		if got := tt.d.Round(tt.m); got != tt.want {
  1289  			t.Errorf("Duration(%s).Round(%s) = %s; want: %s", tt.d, tt.m, got, tt.want)
  1290  		}
  1291  	}
  1292  }
  1293  
  1294  var durationAbsTests = []struct {
  1295  	d    Duration
  1296  	want Duration
  1297  }{
  1298  	{0, 0},
  1299  	{1, 1},
  1300  	{-1, 1},
  1301  	{1 * Minute, 1 * Minute},
  1302  	{-1 * Minute, 1 * Minute},
  1303  	{minDuration, maxDuration},
  1304  	{minDuration + 1, maxDuration},
  1305  	{minDuration + 2, maxDuration - 1},
  1306  	{maxDuration, maxDuration},
  1307  	{maxDuration - 1, maxDuration - 1},
  1308  }
  1309  
  1310  func TestDurationAbs(t *testing.T) {
  1311  	for _, tt := range durationAbsTests {
  1312  		if got := tt.d.Abs(); got != tt.want {
  1313  			t.Errorf("Duration(%s).Abs() = %s; want: %s", tt.d, got, tt.want)
  1314  		}
  1315  	}
  1316  }
  1317  
  1318  var defaultLocTests = []struct {
  1319  	name string
  1320  	f    func(t1, t2 Time) bool
  1321  }{
  1322  	{"After", func(t1, t2 Time) bool { return t1.After(t2) == t2.After(t1) }},
  1323  	{"Before", func(t1, t2 Time) bool { return t1.Before(t2) == t2.Before(t1) }},
  1324  	{"Equal", func(t1, t2 Time) bool { return t1.Equal(t2) == t2.Equal(t1) }},
  1325  	{"Compare", func(t1, t2 Time) bool { return t1.Compare(t2) == t2.Compare(t1) }},
  1326  
  1327  	{"IsZero", func(t1, t2 Time) bool { return t1.IsZero() == t2.IsZero() }},
  1328  	{"Date", func(t1, t2 Time) bool {
  1329  		a1, b1, c1 := t1.Date()
  1330  		a2, b2, c2 := t2.Date()
  1331  		return a1 == a2 && b1 == b2 && c1 == c2
  1332  	}},
  1333  	{"Year", func(t1, t2 Time) bool { return t1.Year() == t2.Year() }},
  1334  	{"Month", func(t1, t2 Time) bool { return t1.Month() == t2.Month() }},
  1335  	{"Day", func(t1, t2 Time) bool { return t1.Day() == t2.Day() }},
  1336  	{"Weekday", func(t1, t2 Time) bool { return t1.Weekday() == t2.Weekday() }},
  1337  	{"ISOWeek", func(t1, t2 Time) bool {
  1338  		a1, b1 := t1.ISOWeek()
  1339  		a2, b2 := t2.ISOWeek()
  1340  		return a1 == a2 && b1 == b2
  1341  	}},
  1342  	{"Clock", func(t1, t2 Time) bool {
  1343  		a1, b1, c1 := t1.Clock()
  1344  		a2, b2, c2 := t2.Clock()
  1345  		return a1 == a2 && b1 == b2 && c1 == c2
  1346  	}},
  1347  	{"Hour", func(t1, t2 Time) bool { return t1.Hour() == t2.Hour() }},
  1348  	{"Minute", func(t1, t2 Time) bool { return t1.Minute() == t2.Minute() }},
  1349  	{"Second", func(t1, t2 Time) bool { return t1.Second() == t2.Second() }},
  1350  	{"Nanosecond", func(t1, t2 Time) bool { return t1.Hour() == t2.Hour() }},
  1351  	{"YearDay", func(t1, t2 Time) bool { return t1.YearDay() == t2.YearDay() }},
  1352  
  1353  	// Using Equal since Add don't modify loc using "==" will cause a fail
  1354  	{"Add", func(t1, t2 Time) bool { return t1.Add(Hour).Equal(t2.Add(Hour)) }},
  1355  	{"Sub", func(t1, t2 Time) bool { return t1.Sub(t2) == t2.Sub(t1) }},
  1356  
  1357  	//Original caus for this test case bug 15852
  1358  	{"AddDate", func(t1, t2 Time) bool { return t1.AddDate(1991, 9, 3) == t2.AddDate(1991, 9, 3) }},
  1359  
  1360  	{"UTC", func(t1, t2 Time) bool { return t1.UTC() == t2.UTC() }},
  1361  	{"Local", func(t1, t2 Time) bool { return t1.Local() == t2.Local() }},
  1362  	{"In", func(t1, t2 Time) bool { return t1.In(UTC) == t2.In(UTC) }},
  1363  
  1364  	{"Local", func(t1, t2 Time) bool { return t1.Local() == t2.Local() }},
  1365  	{"Zone", func(t1, t2 Time) bool {
  1366  		a1, b1 := t1.Zone()
  1367  		a2, b2 := t2.Zone()
  1368  		return a1 == a2 && b1 == b2
  1369  	}},
  1370  
  1371  	{"Unix", func(t1, t2 Time) bool { return t1.Unix() == t2.Unix() }},
  1372  	{"UnixNano", func(t1, t2 Time) bool { return t1.UnixNano() == t2.UnixNano() }},
  1373  	{"UnixMilli", func(t1, t2 Time) bool { return t1.UnixMilli() == t2.UnixMilli() }},
  1374  	{"UnixMicro", func(t1, t2 Time) bool { return t1.UnixMicro() == t2.UnixMicro() }},
  1375  
  1376  	{"MarshalBinary", func(t1, t2 Time) bool {
  1377  		a1, b1 := t1.MarshalBinary()
  1378  		a2, b2 := t2.MarshalBinary()
  1379  		return bytes.Equal(a1, a2) && b1 == b2
  1380  	}},
  1381  	{"GobEncode", func(t1, t2 Time) bool {
  1382  		a1, b1 := t1.GobEncode()
  1383  		a2, b2 := t2.GobEncode()
  1384  		return bytes.Equal(a1, a2) && b1 == b2
  1385  	}},
  1386  	{"MarshalJSON", func(t1, t2 Time) bool {
  1387  		a1, b1 := t1.MarshalJSON()
  1388  		a2, b2 := t2.MarshalJSON()
  1389  		return bytes.Equal(a1, a2) && b1 == b2
  1390  	}},
  1391  	{"MarshalText", func(t1, t2 Time) bool {
  1392  		a1, b1 := t1.MarshalText()
  1393  		a2, b2 := t2.MarshalText()
  1394  		return bytes.Equal(a1, a2) && b1 == b2
  1395  	}},
  1396  
  1397  	{"Truncate", func(t1, t2 Time) bool { return t1.Truncate(Hour).Equal(t2.Truncate(Hour)) }},
  1398  	{"Round", func(t1, t2 Time) bool { return t1.Round(Hour).Equal(t2.Round(Hour)) }},
  1399  
  1400  	{"== Time{}", func(t1, t2 Time) bool { return (t1 == Time{}) == (t2 == Time{}) }},
  1401  }
  1402  
  1403  func TestDefaultLoc(t *testing.T) {
  1404  	// Verify that all of Time's methods behave identically if loc is set to
  1405  	// nil or UTC.
  1406  	for _, tt := range defaultLocTests {
  1407  		t1 := Time{}
  1408  		t2 := Time{}.UTC()
  1409  		if !tt.f(t1, t2) {
  1410  			t.Errorf("Time{} and Time{}.UTC() behave differently for %s", tt.name)
  1411  		}
  1412  	}
  1413  }
  1414  
  1415  func BenchmarkNow(b *testing.B) {
  1416  	for i := 0; i < b.N; i++ {
  1417  		t = Now()
  1418  	}
  1419  }
  1420  
  1421  func BenchmarkNowUnixNano(b *testing.B) {
  1422  	for i := 0; i < b.N; i++ {
  1423  		u = Now().UnixNano()
  1424  	}
  1425  }
  1426  
  1427  func BenchmarkNowUnixMilli(b *testing.B) {
  1428  	for i := 0; i < b.N; i++ {
  1429  		u = Now().UnixMilli()
  1430  	}
  1431  }
  1432  
  1433  func BenchmarkNowUnixMicro(b *testing.B) {
  1434  	for i := 0; i < b.N; i++ {
  1435  		u = Now().UnixMicro()
  1436  	}
  1437  }
  1438  
  1439  func BenchmarkFormat(b *testing.B) {
  1440  	t := Unix(1265346057, 0)
  1441  	for i := 0; i < b.N; i++ {
  1442  		t.Format("Mon Jan  2 15:04:05 2006")
  1443  	}
  1444  }
  1445  
  1446  func BenchmarkFormatRFC3339(b *testing.B) {
  1447  	t := Unix(1265346057, 0)
  1448  	for i := 0; i < b.N; i++ {
  1449  		t.Format("2006-01-02T15:04:05Z07:00")
  1450  	}
  1451  }
  1452  
  1453  func BenchmarkFormatRFC3339Nano(b *testing.B) {
  1454  	t := Unix(1265346057, 0)
  1455  	for i := 0; i < b.N; i++ {
  1456  		t.Format("2006-01-02T15:04:05.999999999Z07:00")
  1457  	}
  1458  }
  1459  
  1460  func BenchmarkFormatNow(b *testing.B) {
  1461  	// Like BenchmarkFormat, but easier, because the time zone
  1462  	// lookup cache is optimized for the present.
  1463  	t := Now()
  1464  	for i := 0; i < b.N; i++ {
  1465  		t.Format("Mon Jan  2 15:04:05 2006")
  1466  	}
  1467  }
  1468  
  1469  func BenchmarkMarshalJSON(b *testing.B) {
  1470  	t := Now()
  1471  	for i := 0; i < b.N; i++ {
  1472  		t.MarshalJSON()
  1473  	}
  1474  }
  1475  
  1476  func BenchmarkMarshalText(b *testing.B) {
  1477  	t := Now()
  1478  	for i := 0; i < b.N; i++ {
  1479  		t.MarshalText()
  1480  	}
  1481  }
  1482  
  1483  func BenchmarkParse(b *testing.B) {
  1484  	for i := 0; i < b.N; i++ {
  1485  		Parse(ANSIC, "Mon Jan  2 15:04:05 2006")
  1486  	}
  1487  }
  1488  
  1489  const testdataRFC3339UTC = "2020-08-22T11:27:43.123456789Z"
  1490  
  1491  func BenchmarkParseRFC3339UTC(b *testing.B) {
  1492  	for i := 0; i < b.N; i++ {
  1493  		Parse(RFC3339, testdataRFC3339UTC)
  1494  	}
  1495  }
  1496  
  1497  var testdataRFC3339UTCBytes = []byte(testdataRFC3339UTC)
  1498  
  1499  func BenchmarkParseRFC3339UTCBytes(b *testing.B) {
  1500  	for i := 0; i < b.N; i++ {
  1501  		Parse(RFC3339, string(testdataRFC3339UTCBytes))
  1502  	}
  1503  }
  1504  
  1505  const testdataRFC3339TZ = "2020-08-22T11:27:43.123456789-02:00"
  1506  
  1507  func BenchmarkParseRFC3339TZ(b *testing.B) {
  1508  	for i := 0; i < b.N; i++ {
  1509  		Parse(RFC3339, testdataRFC3339TZ)
  1510  	}
  1511  }
  1512  
  1513  var testdataRFC3339TZBytes = []byte(testdataRFC3339TZ)
  1514  
  1515  func BenchmarkParseRFC3339TZBytes(b *testing.B) {
  1516  	for i := 0; i < b.N; i++ {
  1517  		Parse(RFC3339, string(testdataRFC3339TZBytes))
  1518  	}
  1519  }
  1520  
  1521  func BenchmarkParseDuration(b *testing.B) {
  1522  	for i := 0; i < b.N; i++ {
  1523  		ParseDuration("9007199254.740993ms")
  1524  		ParseDuration("9007199254740993ns")
  1525  	}
  1526  }
  1527  
  1528  func BenchmarkHour(b *testing.B) {
  1529  	t := Now()
  1530  	for i := 0; i < b.N; i++ {
  1531  		_ = t.Hour()
  1532  	}
  1533  }
  1534  
  1535  func BenchmarkSecond(b *testing.B) {
  1536  	t := Now()
  1537  	for i := 0; i < b.N; i++ {
  1538  		_ = t.Second()
  1539  	}
  1540  }
  1541  
  1542  func BenchmarkDate(b *testing.B) {
  1543  	t := Now()
  1544  	for i := 0; i < b.N; i++ {
  1545  		_, _, _ = t.Date()
  1546  	}
  1547  }
  1548  
  1549  func BenchmarkYear(b *testing.B) {
  1550  	t := Now()
  1551  	for i := 0; i < b.N; i++ {
  1552  		_ = t.Year()
  1553  	}
  1554  }
  1555  
  1556  func BenchmarkYearDay(b *testing.B) {
  1557  	t := Now()
  1558  	for i := 0; i < b.N; i++ {
  1559  		_ = t.YearDay()
  1560  	}
  1561  }
  1562  
  1563  func BenchmarkMonth(b *testing.B) {
  1564  	t := Now()
  1565  	for i := 0; i < b.N; i++ {
  1566  		_ = t.Month()
  1567  	}
  1568  }
  1569  
  1570  func BenchmarkDay(b *testing.B) {
  1571  	t := Now()
  1572  	for i := 0; i < b.N; i++ {
  1573  		_ = t.Day()
  1574  	}
  1575  }
  1576  
  1577  func BenchmarkISOWeek(b *testing.B) {
  1578  	t := Now()
  1579  	for i := 0; i < b.N; i++ {
  1580  		_, _ = t.ISOWeek()
  1581  	}
  1582  }
  1583  
  1584  func BenchmarkGoString(b *testing.B) {
  1585  	t := Now()
  1586  	for i := 0; i < b.N; i++ {
  1587  		_ = t.GoString()
  1588  	}
  1589  }
  1590  
  1591  func BenchmarkDateFunc(b *testing.B) {
  1592  	var t Time
  1593  	for range b.N {
  1594  		t = Date(2020, 8, 22, 11, 27, 43, 123456789, UTC)
  1595  	}
  1596  	_ = t
  1597  }
  1598  
  1599  func BenchmarkUnmarshalText(b *testing.B) {
  1600  	var t Time
  1601  	in := []byte("2020-08-22T11:27:43.123456789-02:00")
  1602  	for i := 0; i < b.N; i++ {
  1603  		t.UnmarshalText(in)
  1604  	}
  1605  }
  1606  
  1607  func TestMarshalBinaryZeroTime(t *testing.T) {
  1608  	t0 := Time{}
  1609  	enc, err := t0.MarshalBinary()
  1610  	if err != nil {
  1611  		t.Fatal(err)
  1612  	}
  1613  	t1 := Now() // not zero
  1614  	if err := t1.UnmarshalBinary(enc); err != nil {
  1615  		t.Fatal(err)
  1616  	}
  1617  	if t1 != t0 {
  1618  		t.Errorf("t0=%#v\nt1=%#v\nwant identical structures", t0, t1)
  1619  	}
  1620  }
  1621  
  1622  func TestMarshalBinaryVersion2(t *testing.T) {
  1623  	t0, err := Parse(RFC3339, "1880-01-01T00:00:00Z")
  1624  	if err != nil {
  1625  		t.Errorf("Failed to parse time, error = %v", err)
  1626  	}
  1627  	loc, err := LoadLocation("US/Eastern")
  1628  	if err != nil {
  1629  		t.Errorf("Failed to load location, error = %v", err)
  1630  	}
  1631  	t1 := t0.In(loc)
  1632  	b, err := t1.MarshalBinary()
  1633  	if err != nil {
  1634  		t.Errorf("Failed to Marshal, error = %v", err)
  1635  	}
  1636  
  1637  	t2 := Time{}
  1638  	err = t2.UnmarshalBinary(b)
  1639  	if err != nil {
  1640  		t.Errorf("Failed to Unmarshal, error = %v", err)
  1641  	}
  1642  
  1643  	if !(t0.Equal(t1) && t1.Equal(t2)) {
  1644  		if !t0.Equal(t1) {
  1645  			t.Errorf("The result t1: %+v after Marshal is not matched original t0: %+v", t1, t0)
  1646  		}
  1647  		if !t1.Equal(t2) {
  1648  			t.Errorf("The result t2: %+v after Unmarshal is not matched original t1: %+v", t2, t1)
  1649  		}
  1650  	}
  1651  }
  1652  
  1653  func TestUnmarshalTextAllocations(t *testing.T) {
  1654  	in := []byte(testdataRFC3339UTC) // short enough to be stack allocated
  1655  	if allocs := testing.AllocsPerRun(100, func() {
  1656  		var t Time
  1657  		t.UnmarshalText(in)
  1658  	}); allocs != 0 {
  1659  		t.Errorf("got %v allocs, want 0 allocs", allocs)
  1660  	}
  1661  }
  1662  
  1663  // Issue 17720: Zero value of time.Month fails to print
  1664  func TestZeroMonthString(t *testing.T) {
  1665  	if got, want := Month(0).String(), "%!Month(0)"; got != want {
  1666  		t.Errorf("zero month = %q; want %q", got, want)
  1667  	}
  1668  }
  1669  
  1670  // Issue 24692: Out of range weekday panics
  1671  func TestWeekdayString(t *testing.T) {
  1672  	if got, want := Tuesday.String(), "Tuesday"; got != want {
  1673  		t.Errorf("Tuesday weekday = %q; want %q", got, want)
  1674  	}
  1675  	if got, want := Weekday(14).String(), "%!Weekday(14)"; got != want {
  1676  		t.Errorf("14th weekday = %q; want %q", got, want)
  1677  	}
  1678  }
  1679  
  1680  func TestReadFileLimit(t *testing.T) {
  1681  	const zero = "/dev/zero"
  1682  	if _, err := os.Stat(zero); err != nil {
  1683  		t.Skip("skipping test without a /dev/zero")
  1684  	}
  1685  	_, err := ReadFile(zero)
  1686  	if err == nil || !strings.Contains(err.Error(), "is too large") {
  1687  		t.Errorf("readFile(%q) error = %v; want error containing 'is too large'", zero, err)
  1688  	}
  1689  }
  1690  
  1691  // Issue 25686: hard crash on concurrent timer access.
  1692  // Issue 37400: panic with "racy use of timers"
  1693  // This test deliberately invokes a race condition.
  1694  // We are testing that we don't crash with "fatal error: panic holding locks",
  1695  // and that we also don't panic.
  1696  func TestConcurrentTimerReset(t *testing.T) {
  1697  	const goroutines = 8
  1698  	const tries = 1000
  1699  	var wg sync.WaitGroup
  1700  	wg.Add(goroutines)
  1701  	timer := NewTimer(Hour)
  1702  	for i := 0; i < goroutines; i++ {
  1703  		go func(i int) {
  1704  			defer wg.Done()
  1705  			for j := 0; j < tries; j++ {
  1706  				timer.Reset(Hour + Duration(i*j))
  1707  			}
  1708  		}(i)
  1709  	}
  1710  	wg.Wait()
  1711  }
  1712  
  1713  // Issue 37400: panic with "racy use of timers".
  1714  func TestConcurrentTimerResetStop(t *testing.T) {
  1715  	const goroutines = 8
  1716  	const tries = 1000
  1717  	var wg sync.WaitGroup
  1718  	wg.Add(goroutines * 2)
  1719  	timer := NewTimer(Hour)
  1720  	for i := 0; i < goroutines; i++ {
  1721  		go func(i int) {
  1722  			defer wg.Done()
  1723  			for j := 0; j < tries; j++ {
  1724  				timer.Reset(Hour + Duration(i*j))
  1725  			}
  1726  		}(i)
  1727  		go func(i int) {
  1728  			defer wg.Done()
  1729  			timer.Stop()
  1730  		}(i)
  1731  	}
  1732  	wg.Wait()
  1733  }
  1734  
  1735  func TestTimeIsDST(t *testing.T) {
  1736  	undo := DisablePlatformSources()
  1737  	defer undo()
  1738  
  1739  	tzWithDST, err := LoadLocation("Australia/Sydney")
  1740  	if err != nil {
  1741  		t.Fatalf("could not load tz 'Australia/Sydney': %v", err)
  1742  	}
  1743  	tzWithoutDST, err := LoadLocation("Australia/Brisbane")
  1744  	if err != nil {
  1745  		t.Fatalf("could not load tz 'Australia/Brisbane': %v", err)
  1746  	}
  1747  	tzFixed := FixedZone("FIXED_TIME", 12345)
  1748  
  1749  	tests := [...]struct {
  1750  		time Time
  1751  		want bool
  1752  	}{
  1753  		0: {Date(2009, 1, 1, 12, 0, 0, 0, UTC), false},
  1754  		1: {Date(2009, 6, 1, 12, 0, 0, 0, UTC), false},
  1755  		2: {Date(2009, 1, 1, 12, 0, 0, 0, tzWithDST), true},
  1756  		3: {Date(2009, 6, 1, 12, 0, 0, 0, tzWithDST), false},
  1757  		4: {Date(2009, 1, 1, 12, 0, 0, 0, tzWithoutDST), false},
  1758  		5: {Date(2009, 6, 1, 12, 0, 0, 0, tzWithoutDST), false},
  1759  		6: {Date(2009, 1, 1, 12, 0, 0, 0, tzFixed), false},
  1760  		7: {Date(2009, 6, 1, 12, 0, 0, 0, tzFixed), false},
  1761  	}
  1762  
  1763  	for i, tt := range tests {
  1764  		got := tt.time.IsDST()
  1765  		if got != tt.want {
  1766  			t.Errorf("#%d:: (%#v).IsDST()=%t, want %t", i, tt.time.Format(RFC3339), got, tt.want)
  1767  		}
  1768  	}
  1769  }
  1770  
  1771  func TestTimeAddSecOverflow(t *testing.T) {
  1772  	// Test it with positive delta.
  1773  	var maxInt64 int64 = 1<<63 - 1
  1774  	timeExt := maxInt64 - UnixToInternal - 50
  1775  	notMonoTime := Unix(timeExt, 0)
  1776  	for i := int64(0); i < 100; i++ {
  1777  		sec := notMonoTime.Unix()
  1778  		notMonoTime = notMonoTime.Add(Duration(i * 1e9))
  1779  		if newSec := notMonoTime.Unix(); newSec != sec+i && newSec+UnixToInternal != maxInt64 {
  1780  			t.Fatalf("time ext: %d overflows with positive delta, overflow threshold: %d", newSec, maxInt64)
  1781  		}
  1782  	}
  1783  
  1784  	// Test it with negative delta.
  1785  	maxInt64 = -maxInt64
  1786  	notMonoTime = NotMonoNegativeTime
  1787  	for i := int64(0); i > -100; i-- {
  1788  		sec := notMonoTime.Unix()
  1789  		notMonoTime = notMonoTime.Add(Duration(i * 1e9))
  1790  		if newSec := notMonoTime.Unix(); newSec != sec+i && newSec+UnixToInternal != maxInt64 {
  1791  			t.Fatalf("time ext: %d overflows with positive delta, overflow threshold: %d", newSec, maxInt64)
  1792  		}
  1793  	}
  1794  }
  1795  
  1796  // Issue 49284: time: ParseInLocation incorrectly because of Daylight Saving Time
  1797  func TestTimeWithZoneTransition(t *testing.T) {
  1798  	undo := DisablePlatformSources()
  1799  	defer undo()
  1800  
  1801  	loc, err := LoadLocation("Asia/Shanghai")
  1802  	if err != nil {
  1803  		t.Fatal(err)
  1804  	}
  1805  
  1806  	tests := [...]struct {
  1807  		give Time
  1808  		want Time
  1809  	}{
  1810  		// 14 Apr 1991 - Daylight Saving Time Started
  1811  		// When time of "Asia/Shanghai" was about to reach
  1812  		// Sunday, 14 April 1991, 02:00:00 clocks were turned forward 1 hour to
  1813  		// Sunday, 14 April 1991, 03:00:00 local daylight time instead.
  1814  		// The UTC time was 13 April 1991, 18:00:00
  1815  		0: {Date(1991, April, 13, 17, 50, 0, 0, loc), Date(1991, April, 13, 9, 50, 0, 0, UTC)},
  1816  		1: {Date(1991, April, 13, 18, 0, 0, 0, loc), Date(1991, April, 13, 10, 0, 0, 0, UTC)},
  1817  		2: {Date(1991, April, 14, 1, 50, 0, 0, loc), Date(1991, April, 13, 17, 50, 0, 0, UTC)},
  1818  		3: {Date(1991, April, 14, 3, 0, 0, 0, loc), Date(1991, April, 13, 18, 0, 0, 0, UTC)},
  1819  
  1820  		// 15 Sep 1991 - Daylight Saving Time Ended
  1821  		// When local daylight time of "Asia/Shanghai" was about to reach
  1822  		// Sunday, 15 September 1991, 02:00:00 clocks were turned backward 1 hour to
  1823  		// Sunday, 15 September 1991, 01:00:00 local standard time instead.
  1824  		// The UTC time was 14 September 1991, 17:00:00
  1825  		4: {Date(1991, September, 14, 16, 50, 0, 0, loc), Date(1991, September, 14, 7, 50, 0, 0, UTC)},
  1826  		5: {Date(1991, September, 14, 17, 0, 0, 0, loc), Date(1991, September, 14, 8, 0, 0, 0, UTC)},
  1827  		6: {Date(1991, September, 15, 0, 50, 0, 0, loc), Date(1991, September, 14, 15, 50, 0, 0, UTC)},
  1828  		7: {Date(1991, September, 15, 2, 00, 0, 0, loc), Date(1991, September, 14, 18, 00, 0, 0, UTC)},
  1829  	}
  1830  
  1831  	for i, tt := range tests {
  1832  		if !tt.give.Equal(tt.want) {
  1833  			t.Errorf("#%d:: %#v is not equal to %#v", i, tt.give.Format(RFC3339), tt.want.Format(RFC3339))
  1834  		}
  1835  	}
  1836  }
  1837  
  1838  func TestZoneBounds(t *testing.T) {
  1839  	undo := DisablePlatformSources()
  1840  	defer undo()
  1841  	loc, err := LoadLocation("Asia/Shanghai")
  1842  	if err != nil {
  1843  		t.Fatal(err)
  1844  	}
  1845  
  1846  	// The ZoneBounds of a UTC location would just return two zero Time.
  1847  	for _, test := range utctests {
  1848  		sec := test.seconds
  1849  		golden := &test.golden
  1850  		tm := Unix(sec, 0).UTC()
  1851  		start, end := tm.ZoneBounds()
  1852  		if !(start.IsZero() && end.IsZero()) {
  1853  			t.Errorf("ZoneBounds of %+v expects two zero Time, got:\n  start=%v\n  end=%v", *golden, start, end)
  1854  		}
  1855  	}
  1856  
  1857  	// If the zone begins at the beginning of time, start will be returned as a zero Time.
  1858  	// Use math.MinInt32 to avoid overflow of int arguments on 32-bit systems.
  1859  	beginTime := Date(math.MinInt32, January, 1, 0, 0, 0, 0, loc)
  1860  	start, end := beginTime.ZoneBounds()
  1861  	if !start.IsZero() || end.IsZero() {
  1862  		t.Errorf("ZoneBounds of %v expects start is zero Time, got:\n  start=%v\n  end=%v", beginTime, start, end)
  1863  	}
  1864  
  1865  	// If the zone goes on forever, end will be returned as a zero Time.
  1866  	// Use math.MaxInt32 to avoid overflow of int arguments on 32-bit systems.
  1867  	foreverTime := Date(math.MaxInt32, January, 1, 0, 0, 0, 0, loc)
  1868  	start, end = foreverTime.ZoneBounds()
  1869  	if start.IsZero() || !end.IsZero() {
  1870  		t.Errorf("ZoneBounds of %v expects end is zero Time, got:\n  start=%v\n  end=%v", foreverTime, start, end)
  1871  	}
  1872  
  1873  	// Check some real-world cases to make sure we're getting the right bounds.
  1874  	boundOne := Date(1990, September, 16, 1, 0, 0, 0, loc)
  1875  	boundTwo := Date(1991, April, 14, 3, 0, 0, 0, loc)
  1876  	boundThree := Date(1991, September, 15, 1, 0, 0, 0, loc)
  1877  	makeLocalTime := func(sec int64) Time { return Unix(sec, 0) }
  1878  	realTests := [...]struct {
  1879  		giveTime  Time
  1880  		wantStart Time
  1881  		wantEnd   Time
  1882  	}{
  1883  		// The ZoneBounds of "Asia/Shanghai" Daylight Saving Time
  1884  		0: {Date(1991, April, 13, 17, 50, 0, 0, loc), boundOne, boundTwo},
  1885  		1: {Date(1991, April, 13, 18, 0, 0, 0, loc), boundOne, boundTwo},
  1886  		2: {Date(1991, April, 14, 1, 50, 0, 0, loc), boundOne, boundTwo},
  1887  		3: {boundTwo, boundTwo, boundThree},
  1888  		4: {Date(1991, September, 14, 16, 50, 0, 0, loc), boundTwo, boundThree},
  1889  		5: {Date(1991, September, 14, 17, 0, 0, 0, loc), boundTwo, boundThree},
  1890  		6: {Date(1991, September, 15, 0, 50, 0, 0, loc), boundTwo, boundThree},
  1891  
  1892  		// The ZoneBounds of a "Asia/Shanghai" after the last transition (Standard Time)
  1893  		7:  {boundThree, boundThree, Time{}},
  1894  		8:  {Date(1991, December, 15, 1, 50, 0, 0, loc), boundThree, Time{}},
  1895  		9:  {Date(1992, April, 13, 17, 50, 0, 0, loc), boundThree, Time{}},
  1896  		10: {Date(1992, April, 13, 18, 0, 0, 0, loc), boundThree, Time{}},
  1897  		11: {Date(1992, April, 14, 1, 50, 0, 0, loc), boundThree, Time{}},
  1898  		12: {Date(1992, September, 14, 16, 50, 0, 0, loc), boundThree, Time{}},
  1899  		13: {Date(1992, September, 14, 17, 0, 0, 0, loc), boundThree, Time{}},
  1900  		14: {Date(1992, September, 15, 0, 50, 0, 0, loc), boundThree, Time{}},
  1901  
  1902  		// The ZoneBounds of a local time would return two local Time.
  1903  		// Note: We preloaded "America/Los_Angeles" as time.Local for testing
  1904  		15: {makeLocalTime(0), makeLocalTime(-5756400), makeLocalTime(9972000)},
  1905  		16: {makeLocalTime(1221681866), makeLocalTime(1205056800), makeLocalTime(1225616400)},
  1906  		17: {makeLocalTime(2152173599), makeLocalTime(2145916800), makeLocalTime(2152173600)},
  1907  		18: {makeLocalTime(2152173600), makeLocalTime(2152173600), makeLocalTime(2172733200)},
  1908  		19: {makeLocalTime(2152173601), makeLocalTime(2152173600), makeLocalTime(2172733200)},
  1909  		20: {makeLocalTime(2159200800), makeLocalTime(2152173600), makeLocalTime(2172733200)},
  1910  		21: {makeLocalTime(2172733199), makeLocalTime(2152173600), makeLocalTime(2172733200)},
  1911  		22: {makeLocalTime(2172733200), makeLocalTime(2172733200), makeLocalTime(2177452800)},
  1912  	}
  1913  	for i, tt := range realTests {
  1914  		start, end := tt.giveTime.ZoneBounds()
  1915  		if !start.Equal(tt.wantStart) || !end.Equal(tt.wantEnd) {
  1916  			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",
  1917  				i, tt.giveTime, start, tt.wantStart, end, tt.wantEnd)
  1918  		}
  1919  	}
  1920  }
  1921  

View as plain text