window_test.go 42 KB

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