window_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. package kubecost
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "testing"
  8. "time"
  9. "github.com/google/go-cmp/cmp"
  10. "github.com/opencost/opencost/pkg/util/timeutil"
  11. "github.com/opencost/opencost/pkg/env"
  12. )
  13. func TestRoundBack(t *testing.T) {
  14. boulder := time.FixedZone("Boulder", -7*60*60)
  15. beijing := time.FixedZone("Beijing", 8*60*60)
  16. to := time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)
  17. tb := RoundBack(to, 24*time.Hour)
  18. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)) {
  19. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00-07:00; actual %s", tb)
  20. }
  21. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, boulder)
  22. tb = RoundBack(to, 24*time.Hour)
  23. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)) {
  24. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00-07:00; actual %s", tb)
  25. }
  26. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, boulder)
  27. tb = RoundBack(to, 24*time.Hour)
  28. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)) {
  29. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00-07:00; actual %s", tb)
  30. }
  31. to = time.Date(2020, time.January, 1, 23, 37, 48, 0, boulder)
  32. tb = RoundBack(to, 24*time.Hour)
  33. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)) {
  34. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00-07:00; actual %s", tb)
  35. }
  36. to = time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)
  37. tb = RoundBack(to, 24*time.Hour)
  38. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)) {
  39. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00+08:00; actual %s", tb)
  40. }
  41. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, beijing)
  42. tb = RoundBack(to, 24*time.Hour)
  43. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)) {
  44. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00+08:00; actual %s", tb)
  45. }
  46. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, beijing)
  47. tb = RoundBack(to, 24*time.Hour)
  48. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)) {
  49. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00+08:00; actual %s", tb)
  50. }
  51. to = time.Date(2020, time.January, 1, 23, 59, 59, 0, beijing)
  52. tb = RoundBack(to, 24*time.Hour)
  53. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)) {
  54. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00+08:00; actual %s", tb)
  55. }
  56. to = time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
  57. tb = RoundBack(to, 24*time.Hour)
  58. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  59. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00Z; actual %s", tb)
  60. }
  61. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, time.UTC)
  62. tb = RoundBack(to, 24*time.Hour)
  63. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  64. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00Z; actual %s", tb)
  65. }
  66. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, time.UTC)
  67. tb = RoundBack(to, 24*time.Hour)
  68. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  69. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00Z; actual %s", tb)
  70. }
  71. to = time.Date(2020, time.January, 1, 23, 59, 0, 0, time.UTC)
  72. tb = RoundBack(to, 24*time.Hour)
  73. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  74. t.Fatalf("RoundBack: expected 2020-01-01T00:00:00Z; actual %s", tb)
  75. }
  76. to = time.Date(2020, time.January, 1, 23, 59, 0, 0, time.UTC)
  77. tb = RoundBack(to, timeutil.Week)
  78. if !tb.Equal(time.Date(2019, time.December, 29, 0, 0, 0, 0, time.UTC)) {
  79. t.Fatalf("RoundForward: expected 2019-12-29T00:00:00Z; actual %s", tb)
  80. }
  81. }
  82. func TestRoundForward(t *testing.T) {
  83. boulder := time.FixedZone("Boulder", -7*60*60)
  84. beijing := time.FixedZone("Beijing", 8*60*60)
  85. to := time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)
  86. tb := RoundForward(to, 24*time.Hour)
  87. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, boulder)) {
  88. t.Fatalf("RoundForward: expected 2020-01-01T00:00:00-07:00; actual %s", tb)
  89. }
  90. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, boulder)
  91. tb = RoundForward(to, 24*time.Hour)
  92. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, boulder)) {
  93. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00-07:00; actual %s", tb)
  94. }
  95. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, boulder)
  96. tb = RoundForward(to, 24*time.Hour)
  97. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, boulder)) {
  98. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00-07:00; actual %s", tb)
  99. }
  100. to = time.Date(2020, time.January, 1, 23, 37, 48, 0, boulder)
  101. tb = RoundForward(to, 24*time.Hour)
  102. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, boulder)) {
  103. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00-07:00; actual %s", tb)
  104. }
  105. to = time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)
  106. tb = RoundForward(to, 24*time.Hour)
  107. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, beijing)) {
  108. t.Fatalf("RoundForward: expected 2020-01-01T00:00:00+08:00; actual %s", tb)
  109. }
  110. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, beijing)
  111. tb = RoundForward(to, 24*time.Hour)
  112. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, beijing)) {
  113. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00+08:00; actual %s", tb)
  114. }
  115. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, beijing)
  116. tb = RoundForward(to, 24*time.Hour)
  117. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, beijing)) {
  118. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00+08:00; actual %s", tb)
  119. }
  120. to = time.Date(2020, time.January, 1, 23, 59, 59, 0, beijing)
  121. tb = RoundForward(to, 24*time.Hour)
  122. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, beijing)) {
  123. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00+08:00; actual %s", tb)
  124. }
  125. to = time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
  126. tb = RoundForward(to, 24*time.Hour)
  127. if !tb.Equal(time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)) {
  128. t.Fatalf("RoundForward: expected 2020-01-01T00:00:00Z; actual %s", tb)
  129. }
  130. to = time.Date(2020, time.January, 1, 0, 0, 1, 0, time.UTC)
  131. tb = RoundForward(to, 24*time.Hour)
  132. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, time.UTC)) {
  133. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00Z; actual %s", tb)
  134. }
  135. to = time.Date(2020, time.January, 1, 12, 37, 48, 0, time.UTC)
  136. tb = RoundForward(to, 24*time.Hour)
  137. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, time.UTC)) {
  138. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00Z; actual %s", tb)
  139. }
  140. to = time.Date(2020, time.January, 1, 23, 59, 0, 0, time.UTC)
  141. tb = RoundForward(to, 24*time.Hour)
  142. if !tb.Equal(time.Date(2020, time.January, 2, 0, 0, 0, 0, time.UTC)) {
  143. t.Fatalf("RoundForward: expected 2020-01-02T00:00:00Z; actual %s", tb)
  144. }
  145. to = time.Date(2020, time.January, 1, 23, 59, 0, 0, time.UTC)
  146. tb = RoundForward(to, timeutil.Week)
  147. if !tb.Equal(time.Date(2020, time.January, 5, 0, 0, 0, 0, time.UTC)) {
  148. t.Fatalf("RoundForward: expected 2020-01-05T00:00:00Z; actual %s", tb)
  149. }
  150. to = time.Date(2020, time.January, 5, 23, 59, 0, 0, time.UTC)
  151. tb = RoundForward(to, timeutil.Week)
  152. if !tb.Equal(time.Date(2020, time.January, 12, 0, 0, 0, 0, time.UTC)) {
  153. t.Fatalf("RoundForward: expected 2020-01-05T00:00:00Z; actual %s", tb)
  154. }
  155. to = time.Date(2020, time.January, 5, 0, 0, 0, 0, time.UTC)
  156. tb = RoundForward(to, timeutil.Week)
  157. if !tb.Equal(time.Date(2020, time.January, 5, 0, 0, 0, 0, time.UTC)) {
  158. t.Fatalf("RoundForward: expected 2020-01-05T00:00:00Z; actual %s", tb)
  159. }
  160. }
  161. func TestParseWindowUTC(t *testing.T) {
  162. now := time.Now().UTC()
  163. // "today" should span Now() and not produce an error
  164. today, err := ParseWindowUTC("today")
  165. if err != nil {
  166. t.Fatalf(`unexpected error parsing "today": %s`, err)
  167. }
  168. if today.Duration().Hours() != 24 {
  169. t.Fatalf(`expect: window "today" to have duration 24 hour; actual: %f hours`, today.Duration().Hours())
  170. }
  171. if !today.Contains(time.Now().UTC()) {
  172. t.Fatalf(`expect: window "today" to contain now; actual: %s`, today)
  173. }
  174. // "yesterday" should span Now() and not produce an error
  175. yesterday, err := ParseWindowUTC("yesterday")
  176. if err != nil {
  177. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  178. }
  179. if yesterday.Duration().Hours() != 24 {
  180. t.Fatalf(`expect: window "yesterday" to have duration 24 hour; actual: %f hours`, yesterday.Duration().Hours())
  181. }
  182. if !yesterday.End().Before(time.Now().UTC()) {
  183. t.Fatalf(`expect: window "yesterday" to end before now; actual: %s ends after %s`, yesterday, time.Now().UTC())
  184. }
  185. week, err := ParseWindowUTC("week")
  186. hoursThisWeek := float64(time.Now().UTC().Weekday()) * 24.0
  187. if err != nil {
  188. t.Fatalf(`unexpected error parsing "week": %s`, err)
  189. }
  190. if week.Duration().Hours() < hoursThisWeek {
  191. t.Fatalf(`expect: window "week" to have at least %f hours; actual: %f hours`, hoursThisWeek, week.Duration().Hours())
  192. }
  193. if week.End().After(time.Now().UTC()) {
  194. t.Fatalf(`expect: window "week" to end before now; actual: %s ends after %s`, week, time.Now().UTC())
  195. }
  196. month, err := ParseWindowUTC("month")
  197. hoursThisMonth := float64(time.Now().UTC().Day()) * 24.0
  198. if err != nil {
  199. t.Fatalf(`unexpected error parsing "month": %s`, err)
  200. }
  201. if month.Duration().Hours() > hoursThisMonth || month.Duration().Hours() < (hoursThisMonth-24.0) {
  202. t.Fatalf(`expect: window "month" to have approximately %f hours; actual: %f hours`, hoursThisMonth, month.Duration().Hours())
  203. }
  204. // this test fails periodically if execution is so fast that time.Now() during the condition
  205. // check is the same as the end of the current month time computed by ParseWindowUTC
  206. // so we add one nanosecond to sure time.Now() is later than when invoked earlier
  207. if !month.End().Before(time.Now().UTC().Add(time.Nanosecond)) {
  208. t.Fatalf(`expect: window "month" to end before now; actual: %s ends after %s`, month, time.Now().UTC())
  209. }
  210. // TODO lastweek
  211. lastmonth, err := ParseWindowUTC("lastmonth")
  212. monthMinHours := float64(24 * 28)
  213. monthMaxHours := float64(24 * 31)
  214. firstOfMonth := now.Truncate(time.Hour * 24).Add(-24 * time.Hour * time.Duration(now.Day()-1))
  215. if err != nil {
  216. t.Fatalf(`unexpected error parsing "lastmonth": %s`, err)
  217. }
  218. if lastmonth.Duration().Hours() > monthMaxHours || lastmonth.Duration().Hours() < monthMinHours {
  219. t.Fatalf(`expect: window "lastmonth" to have approximately %f hours; actual: %f hours`, hoursThisMonth, lastmonth.Duration().Hours())
  220. }
  221. if !lastmonth.End().Equal(firstOfMonth) {
  222. t.Fatalf(`expect: window "lastmonth" to end on the first of the current month; actual: %s doesn't end on %s`, lastmonth, firstOfMonth)
  223. }
  224. ago12h := time.Now().UTC().Add(-12 * time.Hour)
  225. ago24h := time.Now().UTC().Add(-24 * time.Hour)
  226. ago36h := time.Now().UTC().Add(-36 * time.Hour)
  227. ago60h := time.Now().UTC().Add(-60 * time.Hour)
  228. // "24h" should have 24 hour duration and not produce an error
  229. dur24h, err := ParseWindowUTC("24h")
  230. if err != nil {
  231. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  232. }
  233. if dur24h.Duration().Hours() != 24 {
  234. t.Fatalf(`expect: window "24h" to have duration 24 hour; actual: %f hours`, dur24h.Duration().Hours())
  235. }
  236. if !dur24h.Contains(ago12h) {
  237. t.Fatalf(`expect: window "24h" to contain 12 hours ago; actual: %s doesn't contain %s`, dur24h, ago12h)
  238. }
  239. if dur24h.Contains(ago36h) {
  240. t.Fatalf(`expect: window "24h" to not contain 36 hours ago; actual: %s contains %s`, dur24h, ago36h)
  241. }
  242. // "2d" should have 2 day duration and not produce an error
  243. dur2d, err := ParseWindowUTC("2d")
  244. if err != nil {
  245. t.Fatalf(`unexpected error parsing "2d": %s`, err)
  246. }
  247. if dur2d.Duration().Hours() != 48 {
  248. t.Fatalf(`expect: window "2d" to have duration 48 hour; actual: %f hours`, dur2d.Duration().Hours())
  249. }
  250. if !dur2d.Contains(ago24h) {
  251. t.Fatalf(`expect: window "2d" to contain 24 hours ago; actual: %s doesn't contain %s`, dur2d, ago24h)
  252. }
  253. if dur2d.Contains(ago60h) {
  254. t.Fatalf(`expect: window "2d" to not contain 60 hours ago; actual: %s contains %s`, dur2d, ago60h)
  255. }
  256. // "24h offset 14h" should have 24 hour duration and not produce an error
  257. dur24hOff14h, err := ParseWindowUTC("24h offset 14h")
  258. if err != nil {
  259. t.Fatalf(`unexpected error parsing "24h offset 14h": %s`, err)
  260. }
  261. if dur24hOff14h.Duration().Hours() != 24 {
  262. t.Fatalf(`expect: window "24h offset 14h" to have duration 24 hour; actual: %f hours`, dur24hOff14h.Duration().Hours())
  263. }
  264. if dur24hOff14h.Contains(ago12h) {
  265. t.Fatalf(`expect: window "24h offset 14h" not to contain 12 hours ago; actual: %s contains %s`, dur24hOff14h, ago12h)
  266. }
  267. if !dur24hOff14h.Contains(ago36h) {
  268. t.Fatalf(`expect: window "24h offset 14h" to contain 36 hours ago; actual: %s does not contain %s`, dur24hOff14h, ago36h)
  269. }
  270. april152020, _ := time.Parse(time.RFC3339, "2020-04-15T00:00:00Z")
  271. april102020, _ := time.Parse(time.RFC3339, "2020-04-10T00:00:00Z")
  272. april052020, _ := time.Parse(time.RFC3339, "2020-04-05T00:00:00Z")
  273. // "2020-04-08T00:00:00Z,2020-04-12T00:00:00Z" should have 96 hour duration and not produce an error
  274. april8to12, err := ParseWindowUTC("2020-04-08T00:00:00Z,2020-04-12T00:00:00Z")
  275. if err != nil {
  276. t.Fatalf(`unexpected error parsing "2020-04-08T00:00:00Z,2020-04-12T00:00:00Z": %s`, err)
  277. }
  278. if april8to12.Duration().Hours() != 96 {
  279. t.Fatalf(`expect: window %s to have duration 96 hour; actual: %f hours`, april8to12, april8to12.Duration().Hours())
  280. }
  281. if !april8to12.Contains(april102020) {
  282. t.Fatalf(`expect: window April 8-12 to contain April 10; actual: %s doesn't contain %s`, april8to12, april102020)
  283. }
  284. if april8to12.Contains(april052020) {
  285. t.Fatalf(`expect: window April 8-12 to not contain April 5; actual: %s contains %s`, april8to12, april052020)
  286. }
  287. if april8to12.Contains(april152020) {
  288. t.Fatalf(`expect: window April 8-12 to not contain April 15; actual: %s contains %s`, april8to12, april152020)
  289. }
  290. march152020, _ := time.Parse(time.RFC3339, "2020-03-15T00:00:00Z")
  291. march102020, _ := time.Parse(time.RFC3339, "2020-03-10T00:00:00Z")
  292. march052020, _ := time.Parse(time.RFC3339, "2020-03-05T00:00:00Z")
  293. // "1583712000,1583884800" should have 48 hour duration and not produce an error
  294. march9to11, err := ParseWindowUTC("1583712000,1583884800")
  295. if err != nil {
  296. t.Fatalf(`unexpected error parsing "2020-04-08T00:00:00Z,2020-04-12T00:00:00Z": %s`, err)
  297. }
  298. if march9to11.Duration().Hours() != 48 {
  299. t.Fatalf(`expect: window %s to have duration 48 hour; actual: %f hours`, march9to11, march9to11.Duration().Hours())
  300. }
  301. if !march9to11.Contains(march102020) {
  302. t.Fatalf(`expect: window March 9-11 to contain March 10; actual: %s doesn't contain %s`, march9to11, march102020)
  303. }
  304. if march9to11.Contains(march052020) {
  305. t.Fatalf(`expect: window March 9-11 to not contain March 5; actual: %s contains %s`, march9to11, march052020)
  306. }
  307. if march9to11.Contains(march152020) {
  308. t.Fatalf(`expect: window March 9-11 to not contain March 15; actual: %s contains %s`, march9to11, march152020)
  309. }
  310. }
  311. func BenchmarkParseWindowUTC(b *testing.B) {
  312. for n := 0; n < b.N; n++ {
  313. _, err := ParseWindowUTC("2020-04-08T00:00:00Z,2020-04-12T00:00:00Z")
  314. if err != nil {
  315. b.Fatalf("error running benchmark: %s", err.Error())
  316. }
  317. }
  318. }
  319. func TestParseWindowWithOffsetString(t *testing.T) {
  320. // ParseWindowWithOffsetString should equal ParseWindowUTC when location == "UTC"
  321. // for all window string formats
  322. todayUTC, err := ParseWindowUTC("today")
  323. if err != nil {
  324. t.Fatalf(`unexpected error parsing "today": %s`, err)
  325. }
  326. todayTZ, err := ParseWindowWithOffsetString("today", "UTC")
  327. if err != nil {
  328. t.Fatalf(`unexpected error parsing "today": %s`, err)
  329. }
  330. if !todayUTC.ApproximatelyEqual(todayTZ, time.Millisecond) {
  331. t.Fatalf(`expect: window "today" UTC to equal "today" with timezone "UTC"; actual: %s not equal %s`, todayUTC, todayTZ)
  332. }
  333. yesterdayUTC, err := ParseWindowUTC("yesterday")
  334. if err != nil {
  335. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  336. }
  337. yesterdayTZ, err := ParseWindowWithOffsetString("yesterday", "UTC")
  338. if err != nil {
  339. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  340. }
  341. if !yesterdayUTC.ApproximatelyEqual(yesterdayTZ, time.Millisecond) {
  342. t.Fatalf(`expect: window "yesterday" UTC to equal "yesterday" with timezone "UTC"; actual: %s not equal %s`, yesterdayUTC, yesterdayTZ)
  343. }
  344. weekUTC, err := ParseWindowUTC("week")
  345. if err != nil {
  346. t.Fatalf(`unexpected error parsing "week": %s`, err)
  347. }
  348. weekTZ, err := ParseWindowWithOffsetString("week", "UTC")
  349. if err != nil {
  350. t.Fatalf(`unexpected error parsing "week": %s`, err)
  351. }
  352. if !weekUTC.ApproximatelyEqual(weekTZ, time.Millisecond) {
  353. t.Fatalf(`expect: window "week" UTC to equal "week" with timezone "UTC"; actual: %s not equal %s`, weekUTC, weekTZ)
  354. }
  355. monthUTC, err := ParseWindowUTC("month")
  356. if err != nil {
  357. t.Fatalf(`unexpected error parsing "month": %s`, err)
  358. }
  359. monthTZ, err := ParseWindowWithOffsetString("month", "UTC")
  360. if err != nil {
  361. t.Fatalf(`unexpected error parsing "month": %s`, err)
  362. }
  363. if !monthUTC.ApproximatelyEqual(monthTZ, time.Millisecond) {
  364. t.Fatalf(`expect: window "month" UTC to equal "month" with timezone "UTC"; actual: %s not equal %s`, monthUTC, monthTZ)
  365. }
  366. lastweekUTC, err := ParseWindowUTC("lastweek")
  367. if err != nil {
  368. t.Fatalf(`unexpected error parsing "lastweek": %s`, err)
  369. }
  370. lastweekTZ, err := ParseWindowWithOffsetString("lastweek", "UTC")
  371. if err != nil {
  372. t.Fatalf(`unexpected error parsing "lastweek": %s`, err)
  373. }
  374. if !lastweekUTC.ApproximatelyEqual(lastweekTZ, time.Millisecond) {
  375. t.Fatalf(`expect: window "lastweek" UTC to equal "lastweek" with timezone "UTC"; actual: %s not equal %s`, lastweekUTC, lastweekTZ)
  376. }
  377. lastmonthUTC, err := ParseWindowUTC("lastmonth")
  378. if err != nil {
  379. t.Fatalf(`unexpected error parsing "lastmonth": %s`, err)
  380. }
  381. lastmonthTZ, err := ParseWindowWithOffsetString("lastmonth", "UTC")
  382. if err != nil {
  383. t.Fatalf(`unexpected error parsing "lastmonth": %s`, err)
  384. }
  385. if !lastmonthUTC.ApproximatelyEqual(lastmonthTZ, time.Millisecond) {
  386. t.Fatalf(`expect: window "lastmonth" UTC to equal "lastmonth" with timezone "UTC"; actual: %s not equal %s`, lastmonthUTC, lastmonthTZ)
  387. }
  388. dur10mUTC, err := ParseWindowUTC("10m")
  389. if err != nil {
  390. t.Fatalf(`unexpected error parsing "10m": %s`, err)
  391. }
  392. dur10mTZ, err := ParseWindowWithOffsetString("10m", "UTC")
  393. if err != nil {
  394. t.Fatalf(`unexpected error parsing "10m": %s`, err)
  395. }
  396. if !dur10mUTC.ApproximatelyEqual(dur10mTZ, time.Millisecond) {
  397. t.Fatalf(`expect: window "10m" UTC to equal "10m" with timezone "UTC"; actual: %s not equal %s`, dur10mUTC, dur10mTZ)
  398. }
  399. dur24hUTC, err := ParseWindowUTC("24h")
  400. if err != nil {
  401. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  402. }
  403. dur24hTZ, err := ParseWindowWithOffsetString("24h", "UTC")
  404. if err != nil {
  405. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  406. }
  407. if !dur24hUTC.ApproximatelyEqual(dur24hTZ, time.Millisecond) {
  408. t.Fatalf(`expect: window "24h" UTC to equal "24h" with timezone "UTC"; actual: %s not equal %s`, dur24hUTC, dur24hTZ)
  409. }
  410. dur37dUTC, err := ParseWindowUTC("37d")
  411. if err != nil {
  412. t.Fatalf(`unexpected error parsing "37d": %s`, err)
  413. }
  414. dur37dTZ, err := ParseWindowWithOffsetString("37d", "UTC")
  415. if err != nil {
  416. t.Fatalf(`unexpected error parsing "37d": %s`, err)
  417. }
  418. if !dur37dUTC.ApproximatelyEqual(dur37dTZ, time.Millisecond) {
  419. t.Fatalf(`expect: window "37d" UTC to equal "37d" with timezone "UTC"; actual: %s not equal %s`, dur37dUTC, dur37dTZ)
  420. }
  421. // ParseWindowWithOffsetString should be the correct relative to ParseWindowUTC; i.e.
  422. // - for durations, the times should match, but the representations should differ
  423. // by the number of hours offset
  424. // - for words like "today" and "yesterday", the times may not match, in which
  425. // case, for example, "today" UTC-08:00 might equal "yesterday" UTC
  426. // fmtWindow only compares date and time to the minute, not second or
  427. // timezone. Helper for comparing timezone shifted windows.
  428. fmtWindow := func(w Window) string {
  429. s := "nil"
  430. if w.start != nil {
  431. s = w.start.Format("2006-01-02T15:04")
  432. }
  433. e := "nil"
  434. if w.end != nil {
  435. e = w.end.Format("2006-01-02T15:04")
  436. }
  437. return fmt.Sprintf("[%s, %s]", s, e)
  438. }
  439. // Test UTC-08:00 (California), UTC+03:00 (Moscow), UTC+12:00 (New Zealand), and UTC itself
  440. for _, offsetHrs := range []int{-8, 3, 12, 0} {
  441. offStr := fmt.Sprintf("+%02d:00", offsetHrs)
  442. if offsetHrs < 0 {
  443. offStr = fmt.Sprintf("-%02d:00", -offsetHrs)
  444. }
  445. off := time.Duration(offsetHrs) * time.Hour
  446. dur10mTZ, err = ParseWindowWithOffsetString("10m", offStr)
  447. if err != nil {
  448. t.Fatalf(`unexpected error parsing "10m": %s`, err)
  449. }
  450. if !dur10mTZ.ApproximatelyEqual(dur10mUTC, time.Second) {
  451. t.Fatalf(`expect: window "10m" UTC to equal "10m" with timezone "%s"; actual: %s not equal %s`, offStr, dur10mUTC, dur10mTZ)
  452. }
  453. if fmtWindow(dur10mTZ.Shift(-off)) != fmtWindow(dur10mUTC) {
  454. t.Fatalf(`expect: date, hour, and minute of window "10m" UTC to equal that of "10m" %s shifted by %s; actual: %s not equal %s`, offStr, off, fmtWindow(dur10mUTC), fmtWindow(dur10mTZ.Shift(-off)))
  455. }
  456. dur24hTZ, err = ParseWindowWithOffsetString("24h", offStr)
  457. if err != nil {
  458. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  459. }
  460. if !dur24hTZ.ApproximatelyEqual(dur24hUTC, time.Second) {
  461. t.Fatalf(`expect: window "24h" UTC to equal "24h" with timezone "%s"; actual: %s not equal %s`, offStr, dur24hUTC, dur24hTZ)
  462. }
  463. if fmtWindow(dur24hTZ.Shift(-off)) != fmtWindow(dur24hUTC) {
  464. t.Fatalf(`expect: date, hour, and minute of window "24h" UTC to equal that of "24h" %s shifted by %s; actual: %s not equal %s`, offStr, off, fmtWindow(dur24hUTC), fmtWindow(dur24hTZ.Shift(-off)))
  465. }
  466. dur37dTZ, err = ParseWindowWithOffsetString("37d", offStr)
  467. if err != nil {
  468. t.Fatalf(`unexpected error parsing "37d": %s`, err)
  469. }
  470. if !dur37dTZ.ApproximatelyEqual(dur37dUTC, time.Second) {
  471. t.Fatalf(`expect: window "37d" UTC to equal "37d" with timezone "%s"; actual: %s not equal %s`, offStr, dur37dUTC, dur37dTZ)
  472. }
  473. if fmtWindow(dur37dTZ.Shift(-off)) != fmtWindow(dur37dUTC) {
  474. t.Fatalf(`expect: date, hour, and minute of window "37d" UTC to equal that of "37d" %s shifted by %s; actual: %s not equal %s`, offStr, off, fmtWindow(dur37dUTC), fmtWindow(dur37dTZ.Shift(-off)))
  475. }
  476. // "today" and "yesterday" should comply with the current day in each
  477. // respective timezone, depending on if it is ahead of, equal to, or
  478. // behind UTC at the given moment.
  479. todayTZ, err = ParseWindowWithOffsetString("today", offStr)
  480. if err != nil {
  481. t.Fatalf(`unexpected error parsing "today": %s`, err)
  482. }
  483. yesterdayTZ, err = ParseWindowWithOffsetString("yesterday", offStr)
  484. if err != nil {
  485. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  486. }
  487. hoursSinceYesterdayUTC := time.Now().UTC().Sub(time.Now().UTC().Truncate(24.0 * time.Hour)).Hours()
  488. hoursUntilTomorrowUTC := 24.0 - hoursSinceYesterdayUTC
  489. aheadOfUTC := float64(offsetHrs)-hoursUntilTomorrowUTC > 0
  490. behindUTC := float64(offsetHrs)+hoursSinceYesterdayUTC < 0
  491. // yesterday in this timezone should equal today UTC
  492. if aheadOfUTC {
  493. if fmtWindow(yesterdayTZ) != fmtWindow(todayUTC) {
  494. t.Fatalf(`expect: window "today" UTC to equal "yesterday" with timezone "%s"; actual: %s not equal %s`, offStr, yesterdayTZ, todayUTC)
  495. }
  496. }
  497. // today in this timezone should equal yesterday UTC
  498. if behindUTC {
  499. if fmtWindow(todayTZ) != fmtWindow(yesterdayUTC) {
  500. t.Fatalf(`expect: window "today" UTC to equal "yesterday" with timezone "%s"; actual: %s not equal %s`, offStr, todayTZ, yesterdayUTC)
  501. }
  502. }
  503. // today in this timezone should equal today UTC, likewise for yesterday
  504. if !aheadOfUTC && !behindUTC {
  505. if fmtWindow(todayTZ) != fmtWindow(todayUTC) {
  506. t.Fatalf(`expect: window "today" UTC to equal "today" with timezone "%s"; actual: %s not equal %s`, offStr, todayTZ, todayUTC)
  507. }
  508. // yesterday in this timezone should equal yesterday UTC
  509. if fmtWindow(yesterdayTZ) != fmtWindow(yesterdayUTC) {
  510. t.Fatalf(`expect: window "yesterday" UTC to equal "yesterday" with timezone "%s"; actual: %s not equal %s`, offStr, yesterdayTZ, yesterdayUTC)
  511. }
  512. }
  513. }
  514. }
  515. func TestWindow_DurationOffsetStrings(t *testing.T) {
  516. w, err := ParseWindowUTC("1d")
  517. if err != nil {
  518. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  519. }
  520. dur, off := w.DurationOffsetStrings()
  521. if dur != "1d" {
  522. t.Fatalf(`expect: window to be "1d"; actual: "%s"`, dur)
  523. }
  524. if off != "" {
  525. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  526. }
  527. w, err = ParseWindowUTC("3h")
  528. if err != nil {
  529. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  530. }
  531. dur, off = w.DurationOffsetStrings()
  532. if dur != "3h" {
  533. t.Fatalf(`expect: window to be "3h"; actual: "%s"`, dur)
  534. }
  535. if off != "" {
  536. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  537. }
  538. w, err = ParseWindowUTC("10m")
  539. if err != nil {
  540. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  541. }
  542. dur, off = w.DurationOffsetStrings()
  543. if dur != "10m" {
  544. t.Fatalf(`expect: window to be "10m"; actual: "%s"`, dur)
  545. }
  546. if off != "" {
  547. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  548. }
  549. w, err = ParseWindowUTC("1589448338,1589534798")
  550. if err != nil {
  551. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  552. }
  553. dur, off = w.DurationOffsetStrings()
  554. if dur != "1441m" {
  555. t.Fatalf(`expect: window to be "1441m"; actual: "%s"`, dur)
  556. }
  557. if off == "" {
  558. t.Fatalf(`expect: offset to not be ""; actual: "%s"`, off)
  559. }
  560. w, err = ParseWindowUTC("yesterday")
  561. if err != nil {
  562. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  563. }
  564. dur, _ = w.DurationOffsetStrings()
  565. if dur != "1d" {
  566. t.Fatalf(`expect: window to be "1d"; actual: "%s"`, dur)
  567. }
  568. }
  569. func TestWindow_DurationOffsetForPrometheus(t *testing.T) {
  570. // Set-up and tear-down
  571. thanosEnabled := env.GetBool(env.ThanosEnabledEnvVar, false)
  572. defer env.SetBool(env.ThanosEnabledEnvVar, thanosEnabled)
  573. // Test for Prometheus (env.IsThanosEnabled() == false)
  574. env.SetBool(env.ThanosEnabledEnvVar, false)
  575. if env.IsThanosEnabled() {
  576. t.Fatalf("expected env.IsThanosEnabled() == false")
  577. }
  578. now := time.Now().UTC()
  579. startOfToday := now.Truncate(timeutil.Day)
  580. w, err := parseWindow("1d", now)
  581. if err != nil {
  582. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  583. }
  584. dur, off, err := w.DurationOffsetForPrometheus()
  585. if err != nil {
  586. t.Fatalf("unexpected error: %s", err)
  587. }
  588. // We can get a response in seconds OR minutes. Check seconds first as it
  589. // is higher resolution.
  590. expDurSec := int(now.Sub(startOfToday).Seconds())
  591. expDurSecStr := fmt.Sprintf("%ds", expDurSec)
  592. expDurMin := int(now.Sub(startOfToday).Minutes())
  593. expDurMinStr := fmt.Sprintf("%dm", expDurMin)
  594. if dur != expDurSecStr && dur != expDurMinStr {
  595. t.Fatalf(`expect: window to be "%s" (or "%s"); actual: "%s"`, expDurSecStr, expDurMinStr, dur)
  596. }
  597. if off != "" {
  598. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  599. }
  600. w, err = ParseWindowUTC("2h")
  601. if err != nil {
  602. t.Fatalf(`unexpected error parsing "2h": %s`, err)
  603. }
  604. dur, off, err = w.DurationOffsetForPrometheus()
  605. if err != nil {
  606. t.Fatalf("unexpected error: %s", err)
  607. }
  608. if dur != "2h" {
  609. t.Fatalf(`expect: window to be "2h"; actual: "%s"`, dur)
  610. }
  611. if off != "" {
  612. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  613. }
  614. w, err = ParseWindowUTC("10m")
  615. if err != nil {
  616. t.Fatalf(`unexpected error parsing "10m": %s`, err)
  617. }
  618. dur, off, err = w.DurationOffsetForPrometheus()
  619. if err != nil {
  620. t.Fatalf("unexpected error: %s", err)
  621. }
  622. if dur != "10m" {
  623. t.Fatalf(`expect: window to be "10m"; actual: "%s"`, dur)
  624. }
  625. if off != "" {
  626. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  627. }
  628. w, err = ParseWindowUTC("1589448338,1589534798")
  629. if err != nil {
  630. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  631. }
  632. dur, off, err = w.DurationOffsetForPrometheus()
  633. if err != nil {
  634. t.Fatalf("unexpected error: %s", err)
  635. }
  636. if dur != "1441m" {
  637. t.Fatalf(`expect: window to be "1441m"; actual: "%s"`, dur)
  638. }
  639. if !strings.HasPrefix(off, " offset ") {
  640. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  641. }
  642. w, err = ParseWindowUTC("yesterday")
  643. if err != nil {
  644. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  645. }
  646. dur, off, err = w.DurationOffsetForPrometheus()
  647. if err != nil {
  648. t.Fatalf("unexpected error: %s", err)
  649. }
  650. if dur != "1d" {
  651. t.Fatalf(`expect: window to be "1d"; actual: "%s"`, dur)
  652. }
  653. if !strings.HasPrefix(off, " offset ") {
  654. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  655. }
  656. // Test for Thanos (env.IsThanosEnabled() == true)
  657. env.SetBool(env.ThanosEnabledEnvVar, true)
  658. if !env.IsThanosEnabled() {
  659. t.Fatalf("expected env.IsThanosEnabled() == true")
  660. }
  661. // Note - with the updated logic of 1d, 1w, etc. rounding the start and end times forward to the nearest midnight,
  662. // DurationOffsetForPrometheus may fail if not using a window using "Xh" as the string to parse
  663. w, err = ParseWindowUTC("24h")
  664. if err != nil {
  665. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  666. }
  667. dur, off, err = w.DurationOffsetForPrometheus()
  668. if err != nil {
  669. t.Fatalf("unexpected error: %s", err)
  670. }
  671. if dur != "21h" {
  672. t.Fatalf(`expect: window to be "21d"; actual: "%s"`, dur)
  673. }
  674. if off != " offset 3h" {
  675. t.Fatalf(`expect: offset to be " offset 3h"; actual: "%s"`, off)
  676. }
  677. w, err = ParseWindowUTC("2h")
  678. if err != nil {
  679. t.Fatalf(`unexpected error parsing "2h": %s`, err)
  680. }
  681. dur, off, err = w.DurationOffsetForPrometheus()
  682. if err == nil {
  683. t.Fatalf(`expected error (negative duration); got ("%s", "%s")`, dur, off)
  684. }
  685. w, err = ParseWindowUTC("10m")
  686. if err != nil {
  687. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  688. }
  689. dur, off, err = w.DurationOffsetForPrometheus()
  690. if err == nil {
  691. t.Fatalf(`expected error (negative duration); got ("%s", "%s")`, dur, off)
  692. }
  693. w, err = ParseWindowUTC("1589448338,1589534798")
  694. if err != nil {
  695. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  696. }
  697. dur, off, err = w.DurationOffsetForPrometheus()
  698. if err != nil {
  699. t.Fatalf("unexpected error: %s", err)
  700. }
  701. if dur != "1441m" {
  702. t.Fatalf(`expect: window to be "1441m"; actual: "%s"`, dur)
  703. }
  704. if !strings.HasPrefix(off, " offset ") {
  705. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  706. }
  707. }
  708. // TODO
  709. // func TestWindow_Overlaps(t *testing.T) {}
  710. // TODO
  711. // func TestWindow_Contains(t *testing.T) {}
  712. // TODO
  713. // func TestWindow_Duration(t *testing.T) {}
  714. // TODO
  715. // func TestWindow_End(t *testing.T) {}
  716. // TODO
  717. // func TestWindow_Equal(t *testing.T) {}
  718. // TODO
  719. // func TestWindow_ExpandStart(t *testing.T) {}
  720. // TODO
  721. // func TestWindow_ExpandEnd(t *testing.T) {}
  722. func TestWindow_Expand(t *testing.T) {
  723. t1 := time.Now().Round(time.Hour)
  724. t2 := t1.Add(34 * time.Minute)
  725. t3 := t1.Add(50 * time.Minute)
  726. t4 := t1.Add(84 * time.Minute)
  727. cases := []struct {
  728. windowToExpand Window
  729. windowArgument Window
  730. expected Window
  731. }{
  732. {
  733. windowToExpand: NewClosedWindow(t1, t2),
  734. windowArgument: NewClosedWindow(t3, t4),
  735. expected: NewClosedWindow(t1, t4),
  736. },
  737. {
  738. windowToExpand: NewClosedWindow(t3, t4),
  739. windowArgument: NewClosedWindow(t1, t2),
  740. expected: NewClosedWindow(t1, t4),
  741. },
  742. {
  743. windowToExpand: NewClosedWindow(t1, t3),
  744. windowArgument: NewClosedWindow(t2, t4),
  745. expected: NewClosedWindow(t1, t4),
  746. },
  747. {
  748. windowToExpand: NewClosedWindow(t2, t4),
  749. windowArgument: NewClosedWindow(t1, t3),
  750. expected: NewClosedWindow(t1, t4),
  751. },
  752. {
  753. windowToExpand: Window{},
  754. windowArgument: NewClosedWindow(t1, t2),
  755. expected: NewClosedWindow(t1, t2),
  756. },
  757. {
  758. windowToExpand: NewWindow(nil, &t2),
  759. windowArgument: NewWindow(nil, &t3),
  760. expected: NewWindow(nil, &t3),
  761. },
  762. {
  763. windowToExpand: NewWindow(&t2, nil),
  764. windowArgument: NewWindow(&t1, nil),
  765. expected: NewWindow(&t1, nil),
  766. },
  767. }
  768. for _, c := range cases {
  769. result := c.windowToExpand.Expand(c.windowArgument)
  770. if !result.Equal(c.expected) {
  771. t.Errorf("Expand %s with %s, expected %s but got %s", c.windowToExpand, c.windowArgument, c.expected, result)
  772. }
  773. }
  774. }
  775. // TODO
  776. // func TestWindow_Start(t *testing.T) {}
  777. // TODO
  778. // func TestWindow_String(t *testing.T) {}
  779. func TestWindow_GetPercentInWindow(t *testing.T) {
  780. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  781. dayEnd := dayStart.Add(timeutil.Day)
  782. window := NewClosedWindow(dayStart, dayEnd)
  783. testcases := map[string]struct {
  784. window Window
  785. itemStart time.Time
  786. itemEnd time.Time
  787. expected float64
  788. }{
  789. "matching start/matching end": {
  790. window: window,
  791. itemStart: dayStart,
  792. itemEnd: dayEnd,
  793. expected: 1.0,
  794. },
  795. "matching start/contained end": {
  796. window: window,
  797. itemStart: dayStart,
  798. itemEnd: dayEnd.Add(-time.Hour * 6),
  799. expected: 1.0,
  800. },
  801. "contained start/matching end": {
  802. window: window,
  803. itemStart: dayStart.Add(time.Hour * 6),
  804. itemEnd: dayEnd,
  805. expected: 1.0,
  806. },
  807. "contained start/contained end": {
  808. window: window,
  809. itemStart: dayStart.Add(time.Hour * 6),
  810. itemEnd: dayEnd.Add(-time.Hour * 6),
  811. expected: 1.0,
  812. },
  813. "before start/contained end": {
  814. window: window,
  815. itemStart: dayStart.Add(-time.Hour * 12),
  816. itemEnd: dayEnd.Add(-time.Hour * 12),
  817. expected: 0.5,
  818. },
  819. "before start/before end": {
  820. window: window,
  821. itemStart: dayStart.Add(-time.Hour * 24),
  822. itemEnd: dayEnd.Add(-time.Hour * 24),
  823. expected: 0.0,
  824. },
  825. "contained start/after end": {
  826. window: window,
  827. itemStart: dayStart.Add(time.Hour * 12),
  828. itemEnd: dayEnd.Add(time.Hour * 12),
  829. expected: 0.5,
  830. },
  831. "after start/after end": {
  832. window: window,
  833. itemStart: dayStart.Add(time.Hour * 24),
  834. itemEnd: dayEnd.Add(time.Hour * 24),
  835. expected: 0.0,
  836. },
  837. "before start/after end": {
  838. window: window,
  839. itemStart: dayStart.Add(-time.Hour * 12),
  840. itemEnd: dayEnd.Add(time.Hour * 12),
  841. expected: 0.5,
  842. },
  843. }
  844. for name, tc := range testcases {
  845. t.Run(name, func(t *testing.T) {
  846. thatWindow := NewWindow(&tc.itemStart, &tc.itemEnd)
  847. if actual := tc.window.GetPercentInWindow(thatWindow); actual != tc.expected {
  848. t.Errorf("GetPercentInWindow() = %v, want %v", actual, tc.expected)
  849. }
  850. })
  851. }
  852. }
  853. func TestWindow_GetWindows(t *testing.T) {
  854. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  855. dayEnd := dayStart.Add(timeutil.Day)
  856. loc, _ := time.LoadLocation("America/Vancouver")
  857. testCases := map[string]struct {
  858. start time.Time
  859. end time.Time
  860. windowSize time.Duration
  861. expected []Window
  862. expectedErr bool
  863. }{
  864. "mismatching tz": {
  865. start: dayStart,
  866. end: dayEnd.In(loc),
  867. windowSize: time.Hour,
  868. expected: nil,
  869. expectedErr: true,
  870. },
  871. "hour windows over 1 hours": {
  872. start: dayStart,
  873. end: dayStart.Add(time.Hour),
  874. windowSize: time.Hour,
  875. expected: []Window{
  876. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  877. },
  878. expectedErr: false,
  879. },
  880. "hour windows over 3 hours": {
  881. start: dayStart,
  882. end: dayStart.Add(time.Hour * 3),
  883. windowSize: time.Hour,
  884. expected: []Window{
  885. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  886. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Hour*2)),
  887. NewClosedWindow(dayStart.Add(time.Hour*2), dayStart.Add(time.Hour*3)),
  888. },
  889. expectedErr: false,
  890. },
  891. "hour windows off hour grid": {
  892. start: dayStart.Add(time.Minute),
  893. end: dayEnd.Add(time.Minute),
  894. windowSize: time.Hour,
  895. expected: nil,
  896. expectedErr: true,
  897. },
  898. "hour windows range not divisible by hour": {
  899. start: dayStart,
  900. end: dayStart.Add(time.Minute * 90),
  901. windowSize: time.Hour,
  902. expected: nil,
  903. expectedErr: true,
  904. },
  905. "day windows over 1 day": {
  906. start: dayStart,
  907. end: dayEnd,
  908. windowSize: timeutil.Day,
  909. expected: []Window{
  910. NewClosedWindow(dayStart, dayEnd),
  911. },
  912. expectedErr: false,
  913. },
  914. "day windows over 3 days": {
  915. start: dayStart,
  916. end: dayStart.Add(timeutil.Day * 3),
  917. windowSize: timeutil.Day,
  918. expected: []Window{
  919. NewClosedWindow(dayStart, dayStart.Add(timeutil.Day)),
  920. NewClosedWindow(dayStart.Add(timeutil.Day), dayStart.Add(timeutil.Day*2)),
  921. NewClosedWindow(dayStart.Add(timeutil.Day*2), dayStart.Add(timeutil.Day*3)),
  922. },
  923. expectedErr: false,
  924. },
  925. "day windows off day grid": {
  926. start: dayStart.Add(time.Hour),
  927. end: dayEnd.Add(time.Hour),
  928. windowSize: timeutil.Day,
  929. expected: nil,
  930. expectedErr: true,
  931. },
  932. "day windows range not divisible by day": {
  933. start: dayStart,
  934. end: dayEnd.Add(time.Hour),
  935. windowSize: timeutil.Day,
  936. expected: nil,
  937. expectedErr: true,
  938. },
  939. }
  940. for name, tc := range testCases {
  941. t.Run(name, func(t *testing.T) {
  942. actual, err := GetWindows(tc.start, tc.end, tc.windowSize)
  943. if (err != nil) != tc.expectedErr {
  944. t.Errorf("GetWindows() error = %v, expectedErr %v", err, tc.expectedErr)
  945. return
  946. }
  947. if len(tc.expected) != len(actual) {
  948. t.Errorf("GetWindows() []window has incorrect length expected: %d, actual: %d", len(tc.expected), len(actual))
  949. }
  950. for i, actualWindow := range actual {
  951. expectedWindow := tc.expected[i]
  952. if !actualWindow.Equal(expectedWindow) {
  953. t.Errorf("GetWindow() window at index %d were not equal expected: %s, actual %s", i, expectedWindow.String(), actualWindow)
  954. }
  955. }
  956. })
  957. }
  958. }
  959. func TestWindow_GetWindowsForQueryWindow(t *testing.T) {
  960. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  961. dayEnd := dayStart.Add(timeutil.Day)
  962. loc, _ := time.LoadLocation("America/Vancouver")
  963. testCases := map[string]struct {
  964. start time.Time
  965. end time.Time
  966. windowSize time.Duration
  967. expected []Window
  968. expectedErr bool
  969. }{
  970. "mismatching tz": {
  971. start: dayStart,
  972. end: dayEnd.In(loc),
  973. windowSize: time.Hour,
  974. expected: nil,
  975. expectedErr: true,
  976. },
  977. "hour windows over 1 hours": {
  978. start: dayStart,
  979. end: dayStart.Add(time.Hour),
  980. windowSize: time.Hour,
  981. expected: []Window{
  982. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  983. },
  984. expectedErr: false,
  985. },
  986. "hour windows over 3 hours": {
  987. start: dayStart,
  988. end: dayStart.Add(time.Hour * 3),
  989. windowSize: time.Hour,
  990. expected: []Window{
  991. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  992. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Hour*2)),
  993. NewClosedWindow(dayStart.Add(time.Hour*2), dayStart.Add(time.Hour*3)),
  994. },
  995. expectedErr: false,
  996. },
  997. "hour windows off hour grid": {
  998. start: dayStart.Add(time.Minute),
  999. end: dayStart.Add(time.Minute * 61),
  1000. windowSize: time.Hour,
  1001. expected: []Window{
  1002. NewClosedWindow(dayStart.Add(time.Minute), dayStart.Add(time.Minute*61)),
  1003. },
  1004. expectedErr: false,
  1005. },
  1006. "hour windows range not divisible by hour": {
  1007. start: dayStart,
  1008. end: dayStart.Add(time.Minute * 90),
  1009. windowSize: time.Hour,
  1010. expected: []Window{
  1011. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  1012. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Minute*90)),
  1013. },
  1014. expectedErr: false,
  1015. },
  1016. "day windows over 1 day": {
  1017. start: dayStart,
  1018. end: dayEnd,
  1019. windowSize: timeutil.Day,
  1020. expected: []Window{
  1021. NewClosedWindow(dayStart, dayEnd),
  1022. },
  1023. expectedErr: false,
  1024. },
  1025. "day windows over 3 days": {
  1026. start: dayStart,
  1027. end: dayStart.Add(timeutil.Day * 3),
  1028. windowSize: timeutil.Day,
  1029. expected: []Window{
  1030. NewClosedWindow(dayStart, dayStart.Add(timeutil.Day)),
  1031. NewClosedWindow(dayStart.Add(timeutil.Day), dayStart.Add(timeutil.Day*2)),
  1032. NewClosedWindow(dayStart.Add(timeutil.Day*2), dayStart.Add(timeutil.Day*3)),
  1033. },
  1034. expectedErr: false,
  1035. },
  1036. "day windows off day grid": {
  1037. start: dayStart.Add(time.Hour),
  1038. end: dayEnd.Add(time.Hour),
  1039. windowSize: timeutil.Day,
  1040. expected: []Window{
  1041. NewClosedWindow(dayStart.Add(time.Hour), dayEnd.Add(time.Hour)),
  1042. },
  1043. expectedErr: false,
  1044. },
  1045. "day windows range not divisible by day": {
  1046. start: dayStart,
  1047. end: dayEnd.Add(time.Hour),
  1048. windowSize: timeutil.Day,
  1049. expected: []Window{
  1050. NewClosedWindow(dayStart, dayEnd),
  1051. NewClosedWindow(dayEnd, dayEnd.Add(time.Hour)),
  1052. },
  1053. expectedErr: false,
  1054. },
  1055. }
  1056. for name, tc := range testCases {
  1057. t.Run(name, func(t *testing.T) {
  1058. actual, err := GetWindowsForQueryWindow(tc.start, tc.end, tc.windowSize)
  1059. if (err != nil) != tc.expectedErr {
  1060. t.Errorf("GetWindowsForQueryWindow() error = %v, expectedErr %v", err, tc.expectedErr)
  1061. return
  1062. }
  1063. if len(tc.expected) != len(actual) {
  1064. t.Errorf("GetWindowsForQueryWindow() []window has incorrect length expected: %d, actual: %d", len(tc.expected), len(actual))
  1065. }
  1066. for i, actualWindow := range actual {
  1067. expectedWindow := tc.expected[i]
  1068. if !actualWindow.Equal(expectedWindow) {
  1069. t.Errorf("GetWindowsForQueryWindow() window at index %d were not equal expected: %s, actual %s", i, expectedWindow.String(), actualWindow)
  1070. }
  1071. }
  1072. })
  1073. }
  1074. }
  1075. func TestMarshalUnmarshal(t *testing.T) {
  1076. t1 := time.Date(2023, 03, 11, 01, 29, 15, 0, time.UTC)
  1077. t2 := t1.Add(8 * time.Minute)
  1078. cases := []struct {
  1079. w Window
  1080. }{
  1081. {
  1082. w: NewClosedWindow(t1, t2),
  1083. },
  1084. {
  1085. w: NewWindow(&t1, nil),
  1086. },
  1087. {
  1088. w: NewWindow(nil, &t2),
  1089. },
  1090. {
  1091. w: NewWindow(nil, nil),
  1092. },
  1093. }
  1094. for _, c := range cases {
  1095. name := c.w.String()
  1096. t.Run(name, func(t *testing.T) {
  1097. marshaled, err := json.Marshal(c.w)
  1098. if err != nil {
  1099. t.Fatalf("marshaling: %s", err)
  1100. }
  1101. var unmarshaledW Window
  1102. err = json.Unmarshal(marshaled, &unmarshaledW)
  1103. if err != nil {
  1104. t.Fatalf("unmarshaling: %s", err)
  1105. }
  1106. if diff := cmp.Diff(c.w, unmarshaledW); len(diff) > 0 {
  1107. t.Errorf(diff)
  1108. }
  1109. })
  1110. }
  1111. }
  1112. func TestBoundaryErrorIs(t *testing.T) {
  1113. baseError := &BoundaryError{Message: "cde"}
  1114. singleWrapError := fmt.Errorf("wrap: %w", &BoundaryError{Message: "abc"})
  1115. if errors.Is(singleWrapError, baseError) {
  1116. t.Logf("Single wrap success")
  1117. } else {
  1118. t.Errorf("Single wrap failure: %s != %s", baseError, singleWrapError)
  1119. }
  1120. multiWrapError := fmt.Errorf("wrap: %w", &BoundaryError{Message: "abc"})
  1121. multiWrapError = fmt.Errorf("wrap x2: %w", multiWrapError)
  1122. multiWrapError = fmt.Errorf("wrap x3: %w", multiWrapError)
  1123. if errors.Is(multiWrapError, baseError) {
  1124. t.Logf("Multi wrap success")
  1125. } else {
  1126. t.Errorf("Multi wrap failure: %s != %s", baseError, multiWrapError)
  1127. }
  1128. }