window_test.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. expDur := int(now.Sub(startOfToday).Seconds())
  586. expDurStr := fmt.Sprintf("%ds", expDur)
  587. if err != nil {
  588. t.Fatalf("unexpected error: %s", err)
  589. }
  590. if dur != expDurStr {
  591. t.Fatalf(`expect: window to be "%s"; actual: "%s"`, expDurStr, dur)
  592. }
  593. if off != "" {
  594. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  595. }
  596. w, err = ParseWindowUTC("2h")
  597. if err != nil {
  598. t.Fatalf(`unexpected error parsing "2h": %s`, err)
  599. }
  600. dur, off, err = w.DurationOffsetForPrometheus()
  601. if err != nil {
  602. t.Fatalf("unexpected error: %s", err)
  603. }
  604. if dur != "2h" {
  605. t.Fatalf(`expect: window to be "2h"; actual: "%s"`, dur)
  606. }
  607. if off != "" {
  608. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  609. }
  610. w, err = ParseWindowUTC("10m")
  611. if err != nil {
  612. t.Fatalf(`unexpected error parsing "10m": %s`, err)
  613. }
  614. dur, off, err = w.DurationOffsetForPrometheus()
  615. if err != nil {
  616. t.Fatalf("unexpected error: %s", err)
  617. }
  618. if dur != "10m" {
  619. t.Fatalf(`expect: window to be "10m"; actual: "%s"`, dur)
  620. }
  621. if off != "" {
  622. t.Fatalf(`expect: offset to be ""; actual: "%s"`, off)
  623. }
  624. w, err = ParseWindowUTC("1589448338,1589534798")
  625. if err != nil {
  626. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  627. }
  628. dur, off, err = w.DurationOffsetForPrometheus()
  629. if err != nil {
  630. t.Fatalf("unexpected error: %s", err)
  631. }
  632. if dur != "1441m" {
  633. t.Fatalf(`expect: window to be "1441m"; actual: "%s"`, dur)
  634. }
  635. if !strings.HasPrefix(off, " offset ") {
  636. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  637. }
  638. w, err = ParseWindowUTC("yesterday")
  639. if err != nil {
  640. t.Fatalf(`unexpected error parsing "yesterday": %s`, err)
  641. }
  642. dur, off, err = w.DurationOffsetForPrometheus()
  643. if err != nil {
  644. t.Fatalf("unexpected error: %s", err)
  645. }
  646. if dur != "1d" {
  647. t.Fatalf(`expect: window to be "1d"; actual: "%s"`, dur)
  648. }
  649. if !strings.HasPrefix(off, " offset ") {
  650. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  651. }
  652. // Test for Thanos (env.IsThanosEnabled() == true)
  653. env.SetBool(env.ThanosEnabledEnvVar, true)
  654. if !env.IsThanosEnabled() {
  655. t.Fatalf("expected env.IsThanosEnabled() == true")
  656. }
  657. // Note - with the updated logic of 1d, 1w, etc. rounding the start and end times forward to the nearest midnight,
  658. // DurationOffsetForPrometheus may fail if not using a window using "Xh" as the string to parse
  659. w, err = ParseWindowUTC("24h")
  660. if err != nil {
  661. t.Fatalf(`unexpected error parsing "24h": %s`, err)
  662. }
  663. dur, off, err = w.DurationOffsetForPrometheus()
  664. if err != nil {
  665. t.Fatalf("unexpected error: %s", err)
  666. }
  667. if dur != "21h" {
  668. t.Fatalf(`expect: window to be "21d"; actual: "%s"`, dur)
  669. }
  670. if off != " offset 3h" {
  671. t.Fatalf(`expect: offset to be " offset 3h"; actual: "%s"`, off)
  672. }
  673. w, err = ParseWindowUTC("2h")
  674. if err != nil {
  675. t.Fatalf(`unexpected error parsing "2h": %s`, err)
  676. }
  677. dur, off, err = w.DurationOffsetForPrometheus()
  678. if err == nil {
  679. t.Fatalf(`expected error (negative duration); got ("%s", "%s")`, dur, off)
  680. }
  681. w, err = ParseWindowUTC("10m")
  682. if err != nil {
  683. t.Fatalf(`unexpected error parsing "1d": %s`, err)
  684. }
  685. dur, off, err = w.DurationOffsetForPrometheus()
  686. if err == nil {
  687. t.Fatalf(`expected error (negative duration); got ("%s", "%s")`, dur, off)
  688. }
  689. w, err = ParseWindowUTC("1589448338,1589534798")
  690. if err != nil {
  691. t.Fatalf(`unexpected error parsing "1589448338,1589534798": %s`, err)
  692. }
  693. dur, off, err = w.DurationOffsetForPrometheus()
  694. if err != nil {
  695. t.Fatalf("unexpected error: %s", err)
  696. }
  697. if dur != "1441m" {
  698. t.Fatalf(`expect: window to be "1441m"; actual: "%s"`, dur)
  699. }
  700. if !strings.HasPrefix(off, " offset ") {
  701. t.Fatalf(`expect: offset to start with " offset "; actual: "%s"`, off)
  702. }
  703. }
  704. // TODO
  705. // func TestWindow_Overlaps(t *testing.T) {}
  706. // TODO
  707. // func TestWindow_Contains(t *testing.T) {}
  708. // TODO
  709. // func TestWindow_Duration(t *testing.T) {}
  710. // TODO
  711. // func TestWindow_End(t *testing.T) {}
  712. // TODO
  713. // func TestWindow_Equal(t *testing.T) {}
  714. // TODO
  715. // func TestWindow_ExpandStart(t *testing.T) {}
  716. // TODO
  717. // func TestWindow_ExpandEnd(t *testing.T) {}
  718. func TestWindow_Expand(t *testing.T) {
  719. t1 := time.Now().Round(time.Hour)
  720. t2 := t1.Add(34 * time.Minute)
  721. t3 := t1.Add(50 * time.Minute)
  722. t4 := t1.Add(84 * time.Minute)
  723. cases := []struct {
  724. windowToExpand Window
  725. windowArgument Window
  726. expected Window
  727. }{
  728. {
  729. windowToExpand: NewClosedWindow(t1, t2),
  730. windowArgument: NewClosedWindow(t3, t4),
  731. expected: NewClosedWindow(t1, t4),
  732. },
  733. {
  734. windowToExpand: NewClosedWindow(t3, t4),
  735. windowArgument: NewClosedWindow(t1, t2),
  736. expected: NewClosedWindow(t1, t4),
  737. },
  738. {
  739. windowToExpand: NewClosedWindow(t1, t3),
  740. windowArgument: NewClosedWindow(t2, t4),
  741. expected: NewClosedWindow(t1, t4),
  742. },
  743. {
  744. windowToExpand: NewClosedWindow(t2, t4),
  745. windowArgument: NewClosedWindow(t1, t3),
  746. expected: NewClosedWindow(t1, t4),
  747. },
  748. {
  749. windowToExpand: Window{},
  750. windowArgument: NewClosedWindow(t1, t2),
  751. expected: NewClosedWindow(t1, t2),
  752. },
  753. {
  754. windowToExpand: NewWindow(nil, &t2),
  755. windowArgument: NewWindow(nil, &t3),
  756. expected: NewWindow(nil, &t3),
  757. },
  758. {
  759. windowToExpand: NewWindow(&t2, nil),
  760. windowArgument: NewWindow(&t1, nil),
  761. expected: NewWindow(&t1, nil),
  762. },
  763. }
  764. for _, c := range cases {
  765. result := c.windowToExpand.Expand(c.windowArgument)
  766. if !result.Equal(c.expected) {
  767. t.Errorf("Expand %s with %s, expected %s but got %s", c.windowToExpand, c.windowArgument, c.expected, result)
  768. }
  769. }
  770. }
  771. // TODO
  772. // func TestWindow_Start(t *testing.T) {}
  773. // TODO
  774. // func TestWindow_String(t *testing.T) {}
  775. func TestWindow_GetPercentInWindow(t *testing.T) {
  776. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  777. dayEnd := dayStart.Add(timeutil.Day)
  778. window := NewClosedWindow(dayStart, dayEnd)
  779. testcases := map[string]struct {
  780. window Window
  781. itemStart time.Time
  782. itemEnd time.Time
  783. expected float64
  784. }{
  785. "matching start/matching end": {
  786. window: window,
  787. itemStart: dayStart,
  788. itemEnd: dayEnd,
  789. expected: 1.0,
  790. },
  791. "matching start/contained end": {
  792. window: window,
  793. itemStart: dayStart,
  794. itemEnd: dayEnd.Add(-time.Hour * 6),
  795. expected: 1.0,
  796. },
  797. "contained start/matching end": {
  798. window: window,
  799. itemStart: dayStart.Add(time.Hour * 6),
  800. itemEnd: dayEnd,
  801. expected: 1.0,
  802. },
  803. "contained start/contained end": {
  804. window: window,
  805. itemStart: dayStart.Add(time.Hour * 6),
  806. itemEnd: dayEnd.Add(-time.Hour * 6),
  807. expected: 1.0,
  808. },
  809. "before start/contained end": {
  810. window: window,
  811. itemStart: dayStart.Add(-time.Hour * 12),
  812. itemEnd: dayEnd.Add(-time.Hour * 12),
  813. expected: 0.5,
  814. },
  815. "before start/before end": {
  816. window: window,
  817. itemStart: dayStart.Add(-time.Hour * 24),
  818. itemEnd: dayEnd.Add(-time.Hour * 24),
  819. expected: 0.0,
  820. },
  821. "contained start/after end": {
  822. window: window,
  823. itemStart: dayStart.Add(time.Hour * 12),
  824. itemEnd: dayEnd.Add(time.Hour * 12),
  825. expected: 0.5,
  826. },
  827. "after start/after end": {
  828. window: window,
  829. itemStart: dayStart.Add(time.Hour * 24),
  830. itemEnd: dayEnd.Add(time.Hour * 24),
  831. expected: 0.0,
  832. },
  833. "before start/after end": {
  834. window: window,
  835. itemStart: dayStart.Add(-time.Hour * 12),
  836. itemEnd: dayEnd.Add(time.Hour * 12),
  837. expected: 0.5,
  838. },
  839. }
  840. for name, tc := range testcases {
  841. t.Run(name, func(t *testing.T) {
  842. thatWindow := NewWindow(&tc.itemStart, &tc.itemEnd)
  843. if actual := tc.window.GetPercentInWindow(thatWindow); actual != tc.expected {
  844. t.Errorf("GetPercentInWindow() = %v, want %v", actual, tc.expected)
  845. }
  846. })
  847. }
  848. }
  849. func TestWindow_GetWindows(t *testing.T) {
  850. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  851. dayEnd := dayStart.Add(timeutil.Day)
  852. loc, _ := time.LoadLocation("America/Vancouver")
  853. testCases := map[string]struct {
  854. start time.Time
  855. end time.Time
  856. windowSize time.Duration
  857. expected []Window
  858. expectedErr bool
  859. }{
  860. "mismatching tz": {
  861. start: dayStart,
  862. end: dayEnd.In(loc),
  863. windowSize: time.Hour,
  864. expected: nil,
  865. expectedErr: true,
  866. },
  867. "hour windows over 1 hours": {
  868. start: dayStart,
  869. end: dayStart.Add(time.Hour),
  870. windowSize: time.Hour,
  871. expected: []Window{
  872. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  873. },
  874. expectedErr: false,
  875. },
  876. "hour windows over 3 hours": {
  877. start: dayStart,
  878. end: dayStart.Add(time.Hour * 3),
  879. windowSize: time.Hour,
  880. expected: []Window{
  881. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  882. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Hour*2)),
  883. NewClosedWindow(dayStart.Add(time.Hour*2), dayStart.Add(time.Hour*3)),
  884. },
  885. expectedErr: false,
  886. },
  887. "hour windows off hour grid": {
  888. start: dayStart.Add(time.Minute),
  889. end: dayEnd.Add(time.Minute),
  890. windowSize: time.Hour,
  891. expected: nil,
  892. expectedErr: true,
  893. },
  894. "hour windows range not divisible by hour": {
  895. start: dayStart,
  896. end: dayStart.Add(time.Minute * 90),
  897. windowSize: time.Hour,
  898. expected: nil,
  899. expectedErr: true,
  900. },
  901. "day windows over 1 day": {
  902. start: dayStart,
  903. end: dayEnd,
  904. windowSize: timeutil.Day,
  905. expected: []Window{
  906. NewClosedWindow(dayStart, dayEnd),
  907. },
  908. expectedErr: false,
  909. },
  910. "day windows over 3 days": {
  911. start: dayStart,
  912. end: dayStart.Add(timeutil.Day * 3),
  913. windowSize: timeutil.Day,
  914. expected: []Window{
  915. NewClosedWindow(dayStart, dayStart.Add(timeutil.Day)),
  916. NewClosedWindow(dayStart.Add(timeutil.Day), dayStart.Add(timeutil.Day*2)),
  917. NewClosedWindow(dayStart.Add(timeutil.Day*2), dayStart.Add(timeutil.Day*3)),
  918. },
  919. expectedErr: false,
  920. },
  921. "day windows off day grid": {
  922. start: dayStart.Add(time.Hour),
  923. end: dayEnd.Add(time.Hour),
  924. windowSize: timeutil.Day,
  925. expected: nil,
  926. expectedErr: true,
  927. },
  928. "day windows range not divisible by day": {
  929. start: dayStart,
  930. end: dayEnd.Add(time.Hour),
  931. windowSize: timeutil.Day,
  932. expected: nil,
  933. expectedErr: true,
  934. },
  935. }
  936. for name, tc := range testCases {
  937. t.Run(name, func(t *testing.T) {
  938. actual, err := GetWindows(tc.start, tc.end, tc.windowSize)
  939. if (err != nil) != tc.expectedErr {
  940. t.Errorf("GetWindows() error = %v, expectedErr %v", err, tc.expectedErr)
  941. return
  942. }
  943. if len(tc.expected) != len(actual) {
  944. t.Errorf("GetWindows() []window has incorrect length expected: %d, actual: %d", len(tc.expected), len(actual))
  945. }
  946. for i, actualWindow := range actual {
  947. expectedWindow := tc.expected[i]
  948. if !actualWindow.Equal(expectedWindow) {
  949. t.Errorf("GetWindow() window at index %d were not equal expected: %s, actual %s", i, expectedWindow.String(), actualWindow)
  950. }
  951. }
  952. })
  953. }
  954. }
  955. func TestWindow_GetWindowsForQueryWindow(t *testing.T) {
  956. dayStart := time.Date(2022, 12, 6, 0, 0, 0, 0, time.UTC)
  957. dayEnd := dayStart.Add(timeutil.Day)
  958. loc, _ := time.LoadLocation("America/Vancouver")
  959. testCases := map[string]struct {
  960. start time.Time
  961. end time.Time
  962. windowSize time.Duration
  963. expected []Window
  964. expectedErr bool
  965. }{
  966. "mismatching tz": {
  967. start: dayStart,
  968. end: dayEnd.In(loc),
  969. windowSize: time.Hour,
  970. expected: nil,
  971. expectedErr: true,
  972. },
  973. "hour windows over 1 hours": {
  974. start: dayStart,
  975. end: dayStart.Add(time.Hour),
  976. windowSize: time.Hour,
  977. expected: []Window{
  978. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  979. },
  980. expectedErr: false,
  981. },
  982. "hour windows over 3 hours": {
  983. start: dayStart,
  984. end: dayStart.Add(time.Hour * 3),
  985. windowSize: time.Hour,
  986. expected: []Window{
  987. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  988. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Hour*2)),
  989. NewClosedWindow(dayStart.Add(time.Hour*2), dayStart.Add(time.Hour*3)),
  990. },
  991. expectedErr: false,
  992. },
  993. "hour windows off hour grid": {
  994. start: dayStart.Add(time.Minute),
  995. end: dayStart.Add(time.Minute * 61),
  996. windowSize: time.Hour,
  997. expected: []Window{
  998. NewClosedWindow(dayStart.Add(time.Minute), dayStart.Add(time.Minute*61)),
  999. },
  1000. expectedErr: false,
  1001. },
  1002. "hour windows range not divisible by hour": {
  1003. start: dayStart,
  1004. end: dayStart.Add(time.Minute * 90),
  1005. windowSize: time.Hour,
  1006. expected: []Window{
  1007. NewClosedWindow(dayStart, dayStart.Add(time.Hour)),
  1008. NewClosedWindow(dayStart.Add(time.Hour), dayStart.Add(time.Minute*90)),
  1009. },
  1010. expectedErr: false,
  1011. },
  1012. "day windows over 1 day": {
  1013. start: dayStart,
  1014. end: dayEnd,
  1015. windowSize: timeutil.Day,
  1016. expected: []Window{
  1017. NewClosedWindow(dayStart, dayEnd),
  1018. },
  1019. expectedErr: false,
  1020. },
  1021. "day windows over 3 days": {
  1022. start: dayStart,
  1023. end: dayStart.Add(timeutil.Day * 3),
  1024. windowSize: timeutil.Day,
  1025. expected: []Window{
  1026. NewClosedWindow(dayStart, dayStart.Add(timeutil.Day)),
  1027. NewClosedWindow(dayStart.Add(timeutil.Day), dayStart.Add(timeutil.Day*2)),
  1028. NewClosedWindow(dayStart.Add(timeutil.Day*2), dayStart.Add(timeutil.Day*3)),
  1029. },
  1030. expectedErr: false,
  1031. },
  1032. "day windows off day grid": {
  1033. start: dayStart.Add(time.Hour),
  1034. end: dayEnd.Add(time.Hour),
  1035. windowSize: timeutil.Day,
  1036. expected: []Window{
  1037. NewClosedWindow(dayStart.Add(time.Hour), dayEnd.Add(time.Hour)),
  1038. },
  1039. expectedErr: false,
  1040. },
  1041. "day windows range not divisible by day": {
  1042. start: dayStart,
  1043. end: dayEnd.Add(time.Hour),
  1044. windowSize: timeutil.Day,
  1045. expected: []Window{
  1046. NewClosedWindow(dayStart, dayEnd),
  1047. NewClosedWindow(dayEnd, dayEnd.Add(time.Hour)),
  1048. },
  1049. expectedErr: false,
  1050. },
  1051. }
  1052. for name, tc := range testCases {
  1053. t.Run(name, func(t *testing.T) {
  1054. actual, err := GetWindowsForQueryWindow(tc.start, tc.end, tc.windowSize)
  1055. if (err != nil) != tc.expectedErr {
  1056. t.Errorf("GetWindowsForQueryWindow() error = %v, expectedErr %v", err, tc.expectedErr)
  1057. return
  1058. }
  1059. if len(tc.expected) != len(actual) {
  1060. t.Errorf("GetWindowsForQueryWindow() []window has incorrect length expected: %d, actual: %d", len(tc.expected), len(actual))
  1061. }
  1062. for i, actualWindow := range actual {
  1063. expectedWindow := tc.expected[i]
  1064. if !actualWindow.Equal(expectedWindow) {
  1065. t.Errorf("GetWindowsForQueryWindow() window at index %d were not equal expected: %s, actual %s", i, expectedWindow.String(), actualWindow)
  1066. }
  1067. }
  1068. })
  1069. }
  1070. }
  1071. func TestMarshalUnmarshal(t *testing.T) {
  1072. t1 := time.Date(2023, 03, 11, 01, 29, 15, 0, time.UTC)
  1073. t2 := t1.Add(8 * time.Minute)
  1074. cases := []struct {
  1075. w Window
  1076. }{
  1077. {
  1078. w: NewClosedWindow(t1, t2),
  1079. },
  1080. {
  1081. w: NewWindow(&t1, nil),
  1082. },
  1083. {
  1084. w: NewWindow(nil, &t2),
  1085. },
  1086. {
  1087. w: NewWindow(nil, nil),
  1088. },
  1089. }
  1090. for _, c := range cases {
  1091. name := c.w.String()
  1092. t.Run(name, func(t *testing.T) {
  1093. marshaled, err := json.Marshal(c.w)
  1094. if err != nil {
  1095. t.Fatalf("marshaling: %s", err)
  1096. }
  1097. var unmarshaledW Window
  1098. err = json.Unmarshal(marshaled, &unmarshaledW)
  1099. if err != nil {
  1100. t.Fatalf("unmarshaling: %s", err)
  1101. }
  1102. if diff := cmp.Diff(c.w, unmarshaledW); len(diff) > 0 {
  1103. t.Errorf(diff)
  1104. }
  1105. })
  1106. }
  1107. }
  1108. func TestBoundaryErrorIs(t *testing.T) {
  1109. baseError := &BoundaryError{Message: "cde"}
  1110. singleWrapError := fmt.Errorf("wrap: %w", &BoundaryError{Message: "abc"})
  1111. if errors.Is(singleWrapError, baseError) {
  1112. t.Logf("Single wrap success")
  1113. } else {
  1114. t.Errorf("Single wrap failure: %s != %s", baseError, singleWrapError)
  1115. }
  1116. multiWrapError := fmt.Errorf("wrap: %w", &BoundaryError{Message: "abc"})
  1117. multiWrapError = fmt.Errorf("wrap x2: %w", multiWrapError)
  1118. multiWrapError = fmt.Errorf("wrap x3: %w", multiWrapError)
  1119. if errors.Is(multiWrapError, baseError) {
  1120. t.Logf("Multi wrap success")
  1121. } else {
  1122. t.Errorf("Multi wrap failure: %s != %s", baseError, multiWrapError)
  1123. }
  1124. }