window_test.go 41 KB

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