time_test.go 48 KB

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