asset_test.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. package kubecost
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "reflect"
  7. "testing"
  8. "time"
  9. "github.com/opencost/opencost/pkg/util"
  10. )
  11. var start1 = time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC)
  12. var start2 = start1.Add(day)
  13. var start3 = start2.Add(day)
  14. var start4 = start2.Add(day)
  15. var windows = []Window{
  16. NewWindow(&start1, &start2),
  17. NewWindow(&start2, &start3),
  18. NewWindow(&start3, &start4),
  19. }
  20. func assertAssetSet(t *testing.T, as *AssetSet, msg string, window Window, exps map[string]float64, err error) {
  21. if err != nil {
  22. t.Fatalf("AssetSet.AggregateBy[%s]: unexpected error: %s", msg, err)
  23. }
  24. if as.Length() != len(exps) {
  25. t.Fatalf("AssetSet.AggregateBy[%s]: expected set of length %d, actual %d", msg, len(exps), as.Length())
  26. }
  27. if !as.Window.Equal(window) {
  28. t.Fatalf("AssetSet.AggregateBy[%s]: expected window %s, actual %s", msg, window, as.Window)
  29. }
  30. for key, a := range as.Assets {
  31. if exp, ok := exps[key]; ok {
  32. if math.Round(a.TotalCost()*100) != math.Round(exp*100) {
  33. t.Fatalf("AssetSet.AggregateBy[%s]: key %s expected total cost %.2f, actual %.2f", msg, key, exp, a.TotalCost())
  34. }
  35. if !a.GetWindow().Equal(window) {
  36. t.Fatalf("AssetSet.AggregateBy[%s]: key %s expected window %s, actual %s", msg, key, window, a.GetWindow())
  37. }
  38. } else {
  39. t.Fatalf("AssetSet.AggregateBy[%s]: unexpected asset: %s", msg, key)
  40. }
  41. }
  42. }
  43. func printAssetSet(msg string, as *AssetSet) {
  44. fmt.Printf("--- %s ---\n", msg)
  45. for key, a := range as.Assets {
  46. fmt.Printf(" > %s: %s\n", key, a)
  47. }
  48. }
  49. func TestAny_Add(t *testing.T) {
  50. any1 := NewAsset(*windows[0].start, *windows[0].end, windows[0])
  51. any1.SetProperties(&AssetProperties{
  52. Name: "any1",
  53. Cluster: "cluster1",
  54. ProviderID: "any1",
  55. })
  56. any1.Cost = 9.0
  57. any1.SetAdjustment(1.0)
  58. any2 := NewAsset(*windows[0].start, *windows[0].end, windows[0])
  59. any2.SetProperties(&AssetProperties{
  60. Name: "any2",
  61. Cluster: "cluster1",
  62. ProviderID: "any2",
  63. })
  64. any2.Cost = 4.0
  65. any2.SetAdjustment(1.0)
  66. any3 := any1.Add(any2)
  67. // Check that the sums and properties are correct
  68. if any3.TotalCost() != 15.0 {
  69. t.Fatalf("Any.Add: expected %f; got %f", 15.0, any3.TotalCost())
  70. }
  71. if any3.GetAdjustment() != 2.0 {
  72. t.Fatalf("Any.Add: expected %f; got %f", 2.0, any3.GetAdjustment())
  73. }
  74. if any3.GetProperties().Cluster != "cluster1" {
  75. t.Fatalf("Any.Add: expected %s; got %s", "cluster1", any3.GetProperties().Cluster)
  76. }
  77. if any3.Type() != AnyAssetType {
  78. t.Fatalf("Any.Add: expected %s; got %s", AnyAssetType, any3.Type())
  79. }
  80. if any3.GetProperties().ProviderID != "" {
  81. t.Fatalf("Any.Add: expected %s; got %s", "", any3.GetProperties().ProviderID)
  82. }
  83. if any3.GetProperties().Name != "" {
  84. t.Fatalf("Any.Add: expected %s; got %s", "", any3.GetProperties().Name)
  85. }
  86. // Check that the original assets are unchanged
  87. if any1.TotalCost() != 10.0 {
  88. t.Fatalf("Any.Add: expected %f; got %f", 10.0, any1.TotalCost())
  89. }
  90. if any1.Adjustment != 1.0 {
  91. t.Fatalf("Any.Add: expected %f; got %f", 1.0, any1.Adjustment)
  92. }
  93. if any2.TotalCost() != 5.0 {
  94. t.Fatalf("Any.Add: expected %f; got %f", 5.0, any2.TotalCost())
  95. }
  96. if any2.Adjustment != 1.0 {
  97. t.Fatalf("Any.Add: expected %f; got %f", 1.0, any2.Adjustment)
  98. }
  99. }
  100. func TestAny_Clone(t *testing.T) {
  101. any1 := NewAsset(*windows[0].start, *windows[0].end, windows[0])
  102. any1.SetProperties(&AssetProperties{
  103. Name: "any1",
  104. Cluster: "cluster1",
  105. ProviderID: "any1",
  106. })
  107. any1.Cost = 9.0
  108. any1.SetAdjustment(1.0)
  109. any2 := any1.Clone()
  110. any1.Cost = 18.0
  111. any1.SetAdjustment(2.0)
  112. // any2 should match any1, even after mutating any1
  113. if any2.TotalCost() != 10.0 {
  114. t.Fatalf("Any.Clone: expected %f; got %f", 10.0, any2.TotalCost())
  115. }
  116. if any2.GetAdjustment() != 1.0 {
  117. t.Fatalf("Any.Clone: expected %f; got %f", 1.0, any2.GetAdjustment())
  118. }
  119. }
  120. func TestAny_MarshalJSON(t *testing.T) {
  121. any1 := NewAsset(*windows[0].start, *windows[0].end, windows[0])
  122. any1.SetProperties(&AssetProperties{
  123. Name: "any1",
  124. Cluster: "cluster1",
  125. ProviderID: "any1",
  126. })
  127. any1.Cost = 9.0
  128. any1.SetAdjustment(1.0)
  129. _, err := json.Marshal(any1)
  130. if err != nil {
  131. t.Fatalf("Any.MarshalJSON: unexpected error: %s", err)
  132. }
  133. any2 := NewAsset(*windows[0].start, *windows[0].end, windows[0])
  134. any2.SetProperties(&AssetProperties{
  135. Name: "any2",
  136. Cluster: "cluster1",
  137. ProviderID: "any2",
  138. })
  139. any2.Cost = math.NaN()
  140. any2.SetAdjustment(1.0)
  141. _, err = json.Marshal(any2)
  142. if err != nil {
  143. t.Fatalf("Any.MarshalJSON: unexpected error: %s", err)
  144. }
  145. }
  146. func TestDisk_Add(t *testing.T) {
  147. // 1. aggregate: add size, local
  148. // 2. accumulate: don't add size, local
  149. hours := windows[0].Duration().Hours()
  150. // Aggregate: two disks, one window
  151. disk1 := NewDisk("disk1", "cluster1", "disk1", *windows[0].start, *windows[0].end, windows[0])
  152. disk1.ByteHours = 100.0 * gb * hours
  153. disk1.Cost = 9.0
  154. disk1.SetAdjustment(1.0)
  155. if disk1.Bytes() != 100.0*gb {
  156. t.Fatalf("Disk.Add: expected %f; got %f", 100.0*gb, disk1.Bytes())
  157. }
  158. disk2 := NewDisk("disk2", "cluster1", "disk2", *windows[0].start, *windows[0].end, windows[0])
  159. disk2.ByteHours = 60.0 * gb * hours
  160. disk2.Cost = 4.0
  161. disk2.Local = 1.0
  162. disk2.SetAdjustment(1.0)
  163. if disk2.Bytes() != 60.0*gb {
  164. t.Fatalf("Disk.Add: expected %f; got %f", 60.0*gb, disk2.Bytes())
  165. }
  166. diskT := disk1.Add(disk2).(*Disk)
  167. // Check that the sums and properties are correct
  168. if diskT.TotalCost() != 15.0 {
  169. t.Fatalf("Disk.Add: expected %f; got %f", 15.0, diskT.TotalCost())
  170. }
  171. if diskT.Adjustment != 2.0 {
  172. t.Fatalf("Disk.Add: expected %f; got %f", 2.0, diskT.Adjustment)
  173. }
  174. if diskT.Properties.Cluster != "cluster1" {
  175. t.Fatalf("Disk.Add: expected %s; got %s", "cluster1", diskT.Properties.Cluster)
  176. }
  177. if diskT.Type() != DiskAssetType {
  178. t.Fatalf("Disk.Add: expected %s; got %s", AnyAssetType, diskT.Type())
  179. }
  180. if diskT.Properties.ProviderID != "" {
  181. t.Fatalf("Disk.Add: expected %s; got %s", "", diskT.Properties.ProviderID)
  182. }
  183. if diskT.Properties.Name != "" {
  184. t.Fatalf("Disk.Add: expected %s; got %s", "", diskT.Properties.Name)
  185. }
  186. if diskT.Bytes() != 160.0*gb {
  187. t.Fatalf("Disk.Add: expected %f; got %f", 160.0*gb, diskT.Bytes())
  188. }
  189. if !util.IsApproximately(diskT.Local, 0.333333) {
  190. t.Fatalf("Disk.Add: expected %f; got %f", 0.333333, diskT.Local)
  191. }
  192. // Check that the original assets are unchanged
  193. if disk1.TotalCost() != 10.0 {
  194. t.Fatalf("Disk.Add: expected %f; got %f", 10.0, disk1.TotalCost())
  195. }
  196. if disk1.Adjustment != 1.0 {
  197. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, disk1.Adjustment)
  198. }
  199. if disk1.Local != 0.0 {
  200. t.Fatalf("Disk.Add: expected %f; got %f", 0.0, disk1.Local)
  201. }
  202. if disk2.TotalCost() != 5.0 {
  203. t.Fatalf("Disk.Add: expected %f; got %f", 5.0, disk2.TotalCost())
  204. }
  205. if disk2.Adjustment != 1.0 {
  206. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, disk2.Adjustment)
  207. }
  208. if disk2.Local != 1.0 {
  209. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, disk2.Local)
  210. }
  211. disk3 := NewDisk("disk3", "cluster1", "disk3", *windows[0].start, *windows[0].end, windows[0])
  212. disk3.ByteHours = 0.0 * hours
  213. disk3.Cost = 0.0
  214. disk3.Local = 0.0
  215. disk3.SetAdjustment(0.0)
  216. disk4 := NewDisk("disk4", "cluster1", "disk4", *windows[0].start, *windows[0].end, windows[0])
  217. disk4.ByteHours = 0.0 * hours
  218. disk4.Cost = 0.0
  219. disk4.Local = 1.0
  220. disk4.SetAdjustment(0.0)
  221. diskT = disk3.Add(disk4).(*Disk)
  222. if diskT.TotalCost() != 0.0 {
  223. t.Fatalf("Disk.Add: expected %f; got %f", 0.0, diskT.TotalCost())
  224. }
  225. if diskT.Local != 0.5 {
  226. t.Fatalf("Disk.Add: expected %f; got %f", 0.5, diskT.Local)
  227. }
  228. // Accumulate: one disks, two windows
  229. diskA1 := NewDisk("diskA1", "cluster1", "diskA1", *windows[0].start, *windows[0].end, windows[0])
  230. diskA1.ByteHours = 100 * gb * hours
  231. diskA1.Cost = 9.0
  232. diskA1.SetAdjustment(1.0)
  233. diskA2 := NewDisk("diskA2", "cluster1", "diskA2", *windows[1].start, *windows[1].end, windows[1])
  234. diskA2.ByteHours = 100 * gb * hours
  235. diskA2.Cost = 9.0
  236. diskA2.SetAdjustment(1.0)
  237. diskAT := diskA1.Add(diskA2).(*Disk)
  238. // Check that the sums and properties are correct
  239. if diskAT.TotalCost() != 20.0 {
  240. t.Fatalf("Disk.Add: expected %f; got %f", 20.0, diskAT.TotalCost())
  241. }
  242. if diskAT.Adjustment != 2.0 {
  243. t.Fatalf("Disk.Add: expected %f; got %f", 2.0, diskAT.Adjustment)
  244. }
  245. if diskAT.Properties.Cluster != "cluster1" {
  246. t.Fatalf("Disk.Add: expected %s; got %s", "cluster1", diskAT.Properties.Cluster)
  247. }
  248. if diskAT.Type() != DiskAssetType {
  249. t.Fatalf("Disk.Add: expected %s; got %s", AnyAssetType, diskAT.Type())
  250. }
  251. if diskAT.Properties.ProviderID != "" {
  252. t.Fatalf("Disk.Add: expected %s; got %s", "", diskAT.Properties.ProviderID)
  253. }
  254. if diskAT.Properties.Name != "" {
  255. t.Fatalf("Disk.Add: expected %s; got %s", "", diskAT.Properties.Name)
  256. }
  257. if diskAT.Bytes() != 100.0*gb {
  258. t.Fatalf("Disk.Add: expected %f; got %f", 100.0*gb, diskT.Bytes())
  259. }
  260. if diskAT.Local != 0.0 {
  261. t.Fatalf("Disk.Add: expected %f; got %f", 0.0, diskAT.Local)
  262. }
  263. // Check that the original assets are unchanged
  264. if diskA1.TotalCost() != 10.0 {
  265. t.Fatalf("Disk.Add: expected %f; got %f", 10.0, diskA1.TotalCost())
  266. }
  267. if diskA1.Adjustment != 1.0 {
  268. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, diskA1.Adjustment)
  269. }
  270. if diskA1.Local != 0.0 {
  271. t.Fatalf("Disk.Add: expected %f; got %f", 0.0, diskA1.Local)
  272. }
  273. if diskA2.TotalCost() != 10.0 {
  274. t.Fatalf("Disk.Add: expected %f; got %f", 10.0, diskA2.TotalCost())
  275. }
  276. if diskA2.Adjustment != 1.0 {
  277. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, diskA2.Adjustment)
  278. }
  279. if diskA2.Local != 0.0 {
  280. t.Fatalf("Disk.Add: expected %f; got %f", 0.0, diskA2.Local)
  281. }
  282. }
  283. func TestDisk_Clone(t *testing.T) {
  284. disk1 := NewDisk("disk1", "cluster1", "disk1", *windows[0].start, *windows[0].end, windows[0])
  285. disk1.Local = 0.0
  286. disk1.Cost = 9.0
  287. disk1.SetAdjustment(1.0)
  288. disk2 := disk1.Clone().(*Disk)
  289. disk2.Local = 1.0
  290. disk1.Cost = 18.0
  291. disk1.SetAdjustment(2.0)
  292. // disk2 should match disk1, even after mutating disk1
  293. if disk2.TotalCost() != 10.0 {
  294. t.Fatalf("Any.Clone: expected %f; got %f", 10.0, disk2.TotalCost())
  295. }
  296. if disk2.Adjustment != 1.0 {
  297. t.Fatalf("Any.Clone: expected %f; got %f", 1.0, disk2.Adjustment)
  298. }
  299. if disk2.Local != 1.0 {
  300. t.Fatalf("Disk.Add: expected %f; got %f", 1.0, disk2.Local)
  301. }
  302. }
  303. func TestDisk_MarshalJSON(t *testing.T) {
  304. disk := NewDisk("disk", "cluster", "providerID", *windows[0].start, *windows[0].end, windows[0])
  305. disk.SetLabels(AssetLabels{
  306. "label": "value",
  307. })
  308. disk.Cost = 9.0
  309. disk.SetAdjustment(1.0)
  310. _, err := json.Marshal(disk)
  311. if err != nil {
  312. t.Fatalf("Disk.MarshalJSON: unexpected error: %s", err)
  313. }
  314. }
  315. func TestNode_Add(t *testing.T) {
  316. // 1. aggregate: add size, local
  317. // 2. accumulate: don't add size, local
  318. hours := windows[0].Duration().Hours()
  319. // Aggregate: two nodes, one window
  320. node1 := NewNode("node1", "cluster1", "node1", *windows[0].start, *windows[0].end, windows[0])
  321. node1.CPUCoreHours = 1.0 * hours
  322. node1.RAMByteHours = 2.0 * gb * hours
  323. node1.GPUHours = 0.0 * hours
  324. node1.GPUCost = 0.0
  325. node1.CPUCost = 8.0
  326. node1.RAMCost = 4.0
  327. node1.Discount = 0.3
  328. node1.CPUBreakdown = &Breakdown{
  329. Idle: 0.6,
  330. System: 0.2,
  331. User: 0.2,
  332. Other: 0.0,
  333. }
  334. node1.RAMBreakdown = &Breakdown{
  335. Idle: 0.6,
  336. System: 0.2,
  337. User: 0.2,
  338. Other: 0.0,
  339. }
  340. node1.SetAdjustment(1.6)
  341. node2 := NewNode("node2", "cluster1", "node2", *windows[0].start, *windows[0].end, windows[0])
  342. node2.CPUCoreHours = 1.0 * hours
  343. node2.RAMByteHours = 2.0 * gb * hours
  344. node2.GPUHours = 0.0 * hours
  345. node2.GPUCost = 0.0
  346. node2.CPUCost = 3.0
  347. node2.RAMCost = 1.0
  348. node2.Discount = 0.0
  349. node1.CPUBreakdown = &Breakdown{
  350. Idle: 0.9,
  351. System: 0.05,
  352. User: 0.0,
  353. Other: 0.05,
  354. }
  355. node1.RAMBreakdown = &Breakdown{
  356. Idle: 0.9,
  357. System: 0.05,
  358. User: 0.0,
  359. Other: 0.05,
  360. }
  361. node2.SetAdjustment(1.0)
  362. nodeT := node1.Add(node2).(*Node)
  363. // Check that the sums and properties are correct
  364. if !util.IsApproximately(nodeT.TotalCost(), 15.0) {
  365. t.Fatalf("Node.Add: expected %f; got %f", 15.0, nodeT.TotalCost())
  366. }
  367. if nodeT.Adjustment != 2.6 {
  368. t.Fatalf("Node.Add: expected %f; got %f", 2.6, nodeT.Adjustment)
  369. }
  370. if nodeT.Properties.Cluster != "cluster1" {
  371. t.Fatalf("Node.Add: expected %s; got %s", "cluster1", nodeT.Properties.Cluster)
  372. }
  373. if nodeT.Type() != NodeAssetType {
  374. t.Fatalf("Node.Add: expected %s; got %s", AnyAssetType, nodeT.Type())
  375. }
  376. if nodeT.Properties.ProviderID != "" {
  377. t.Fatalf("Node.Add: expected %s; got %s", "", nodeT.Properties.ProviderID)
  378. }
  379. if nodeT.Properties.Name != "" {
  380. t.Fatalf("Node.Add: expected %s; got %s", "", nodeT.Properties.Name)
  381. }
  382. if nodeT.CPUCores() != 2.0 {
  383. t.Fatalf("Node.Add: expected %f; got %f", 2.0, nodeT.CPUCores())
  384. }
  385. if nodeT.RAMBytes() != 4.0*gb {
  386. t.Fatalf("Node.Add: expected %f; got %f", 4.0*gb, nodeT.RAMBytes())
  387. }
  388. // Check that the original assets are unchanged
  389. if !util.IsApproximately(node1.TotalCost(), 10.0) {
  390. t.Fatalf("Node.Add: expected %f; got %f", 10.0, node1.TotalCost())
  391. }
  392. if node1.Adjustment != 1.6 {
  393. t.Fatalf("Node.Add: expected %f; got %f", 1.0, node1.Adjustment)
  394. }
  395. if !util.IsApproximately(node2.TotalCost(), 5.0) {
  396. t.Fatalf("Node.Add: expected %f; got %f", 5.0, node2.TotalCost())
  397. }
  398. if node2.Adjustment != 1.0 {
  399. t.Fatalf("Node.Add: expected %f; got %f", 1.0, node2.Adjustment)
  400. }
  401. // Check that we don't divide by zero computing Local
  402. node3 := NewNode("node3", "cluster1", "node3", *windows[0].start, *windows[0].end, windows[0])
  403. node3.CPUCoreHours = 0 * hours
  404. node3.RAMByteHours = 0 * hours
  405. node3.GPUHours = 0.0 * hours
  406. node3.GPUCost = 0
  407. node3.CPUCost = 0.0
  408. node3.RAMCost = 0.0
  409. node3.Discount = 0.3
  410. node3.SetAdjustment(0.0)
  411. node4 := NewNode("node4", "cluster1", "node4", *windows[0].start, *windows[0].end, windows[0])
  412. node4.CPUCoreHours = 0 * hours
  413. node4.RAMByteHours = 0 * hours
  414. node4.GPUHours = 0.0 * hours
  415. node4.GPUCost = 0
  416. node4.CPUCost = 0.0
  417. node4.RAMCost = 0.0
  418. node4.Discount = 0.1
  419. node4.SetAdjustment(0.0)
  420. nodeT = node3.Add(node4).(*Node)
  421. // Check that the sums and properties are correct and without NaNs
  422. if nodeT.TotalCost() != 0.0 {
  423. t.Fatalf("Node.Add: expected %f; got %f", 0.0, nodeT.TotalCost())
  424. }
  425. if nodeT.Discount != 0.2 {
  426. t.Fatalf("Node.Add: expected %f; got %f", 0.2, nodeT.Discount)
  427. }
  428. // Accumulate: one nodes, two window
  429. nodeA1 := NewNode("nodeA1", "cluster1", "nodeA1", *windows[0].start, *windows[0].end, windows[0])
  430. nodeA1.CPUCoreHours = 1.0 * hours
  431. nodeA1.RAMByteHours = 2.0 * gb * hours
  432. nodeA1.GPUHours = 0.0 * hours
  433. nodeA1.GPUCost = 0.0
  434. nodeA1.CPUCost = 8.0
  435. nodeA1.RAMCost = 4.0
  436. nodeA1.Discount = 0.3
  437. nodeA1.SetAdjustment(1.6)
  438. nodeA2 := NewNode("nodeA2", "cluster1", "nodeA2", *windows[1].start, *windows[1].end, windows[1])
  439. nodeA2.CPUCoreHours = 1.0 * hours
  440. nodeA2.RAMByteHours = 2.0 * gb * hours
  441. nodeA2.GPUHours = 0.0 * hours
  442. nodeA2.GPUCost = 0.0
  443. nodeA2.CPUCost = 3.0
  444. nodeA2.RAMCost = 1.0
  445. nodeA2.Discount = 0.0
  446. nodeA2.SetAdjustment(1.0)
  447. nodeAT := nodeA1.Add(nodeA2).(*Node)
  448. // Check that the sums and properties are correct
  449. if !util.IsApproximately(nodeAT.TotalCost(), 15.0) {
  450. t.Fatalf("Node.Add: expected %f; got %f", 15.0, nodeAT.TotalCost())
  451. }
  452. if nodeAT.Adjustment != 2.6 {
  453. t.Fatalf("Node.Add: expected %f; got %f", 2.6, nodeAT.Adjustment)
  454. }
  455. if nodeAT.Properties.Cluster != "cluster1" {
  456. t.Fatalf("Node.Add: expected %s; got %s", "cluster1", nodeAT.Properties.Cluster)
  457. }
  458. if nodeAT.Type() != NodeAssetType {
  459. t.Fatalf("Node.Add: expected %s; got %s", AnyAssetType, nodeAT.Type())
  460. }
  461. if nodeAT.Properties.ProviderID != "" {
  462. t.Fatalf("Node.Add: expected %s; got %s", "", nodeAT.Properties.ProviderID)
  463. }
  464. if nodeAT.Properties.Name != "" {
  465. t.Fatalf("Node.Add: expected %s; got %s", "", nodeAT.Properties.Name)
  466. }
  467. if nodeAT.CPUCores() != 1.0 {
  468. t.Fatalf("Node.Add: expected %f; got %f", 1.0, nodeAT.CPUCores())
  469. }
  470. if nodeAT.RAMBytes() != 2.0*gb {
  471. t.Fatalf("Node.Add: expected %f; got %f", 2.0*gb, nodeAT.RAMBytes())
  472. }
  473. if nodeAT.GPUs() != 0.0 {
  474. t.Fatalf("Node.Add: expected %f; got %f", 0.0, nodeAT.GPUs())
  475. }
  476. // Check that the original assets are unchanged
  477. if !util.IsApproximately(nodeA1.TotalCost(), 10.0) {
  478. t.Fatalf("Node.Add: expected %f; got %f", 10.0, nodeA1.TotalCost())
  479. }
  480. if nodeA1.Adjustment != 1.6 {
  481. t.Fatalf("Node.Add: expected %f; got %f", 1.0, nodeA1.Adjustment)
  482. }
  483. if !util.IsApproximately(nodeA2.TotalCost(), 5.0) {
  484. t.Fatalf("Node.Add: expected %f; got %f", 5.0, nodeA2.TotalCost())
  485. }
  486. if nodeA2.Adjustment != 1.0 {
  487. t.Fatalf("Node.Add: expected %f; got %f", 1.0, nodeA2.Adjustment)
  488. }
  489. }
  490. func TestNode_Clone(t *testing.T) {
  491. // TODO
  492. }
  493. func TestNode_MarshalJSON(t *testing.T) {
  494. node := NewNode("node", "cluster", "providerID", *windows[0].start, *windows[0].end, windows[0])
  495. node.SetLabels(AssetLabels{
  496. "label": "value",
  497. })
  498. node.CPUCost = 9.0
  499. node.RAMCost = 0.0
  500. node.RAMCost = 21.0
  501. node.CPUCoreHours = 123.0
  502. node.RAMByteHours = 13323.0
  503. node.GPUHours = 123.0
  504. node.SetAdjustment(1.0)
  505. _, err := json.Marshal(node)
  506. if err != nil {
  507. t.Fatalf("Node.MarshalJSON: unexpected error: %s", err)
  508. }
  509. }
  510. func TestClusterManagement_Add(t *testing.T) {
  511. cm1 := NewClusterManagement(GCPProvider, "cluster1", windows[0])
  512. cm1.Cost = 9.0
  513. cm2 := NewClusterManagement(GCPProvider, "cluster1", windows[0])
  514. cm2.Cost = 4.0
  515. cm3 := cm1.Add(cm2)
  516. // Check that the sums and properties are correct
  517. if cm3.TotalCost() != 13.0 {
  518. t.Fatalf("ClusterManagement.Add: expected %f; got %f", 13.0, cm3.TotalCost())
  519. }
  520. if cm3.GetProperties().Cluster != "cluster1" {
  521. t.Fatalf("ClusterManagement.Add: expected %s; got %s", "cluster1", cm3.GetProperties().Cluster)
  522. }
  523. if cm3.Type() != ClusterManagementAssetType {
  524. t.Fatalf("ClusterManagement.Add: expected %s; got %s", ClusterManagementAssetType, cm3.Type())
  525. }
  526. // Check that the original assets are unchanged
  527. if cm1.TotalCost() != 9.0 {
  528. t.Fatalf("ClusterManagement.Add: expected %f; got %f", 9.0, cm1.TotalCost())
  529. }
  530. if cm2.TotalCost() != 4.0 {
  531. t.Fatalf("ClusterManagement.Add: expected %f; got %f", 4.0, cm2.TotalCost())
  532. }
  533. }
  534. func TestClusterManagement_Clone(t *testing.T) {
  535. // TODO
  536. }
  537. func TestCloudAny_Add(t *testing.T) {
  538. ca1 := NewCloud(ComputeCategory, "ca1", *windows[0].start, *windows[0].end, windows[0])
  539. ca1.Cost = 9.0
  540. ca1.SetAdjustment(1.0)
  541. ca2 := NewCloud(StorageCategory, "ca2", *windows[0].start, *windows[0].end, windows[0])
  542. ca2.Cost = 4.0
  543. ca2.SetAdjustment(1.0)
  544. ca3 := ca1.Add(ca2)
  545. // Check that the sums and properties are correct
  546. if ca3.TotalCost() != 15.0 {
  547. t.Fatalf("Any.Add: expected %f; got %f", 15.0, ca3.TotalCost())
  548. }
  549. if ca3.GetAdjustment() != 2.0 {
  550. t.Fatalf("Any.Add: expected %f; got %f", 2.0, ca3.GetAdjustment())
  551. }
  552. if ca3.Type() != CloudAssetType {
  553. t.Fatalf("Any.Add: expected %s; got %s", CloudAssetType, ca3.Type())
  554. }
  555. // Check that the original assets are unchanged
  556. if ca1.TotalCost() != 10.0 {
  557. t.Fatalf("Any.Add: expected %f; got %f", 10.0, ca1.TotalCost())
  558. }
  559. if ca1.Adjustment != 1.0 {
  560. t.Fatalf("Any.Add: expected %f; got %f", 1.0, ca1.Adjustment)
  561. }
  562. if ca2.TotalCost() != 5.0 {
  563. t.Fatalf("Any.Add: expected %f; got %f", 5.0, ca2.TotalCost())
  564. }
  565. if ca2.Adjustment != 1.0 {
  566. t.Fatalf("Any.Add: expected %f; got %f", 1.0, ca2.Adjustment)
  567. }
  568. }
  569. func TestCloudAny_Clone(t *testing.T) {
  570. // TODO
  571. }
  572. func TestAssetSet_AggregateBy(t *testing.T) {
  573. endYesterday := time.Now().UTC().Truncate(day)
  574. startYesterday := endYesterday.Add(-day)
  575. window := NewWindow(&startYesterday, &endYesterday)
  576. // Scenarios to test:
  577. // 1 Single-aggregation
  578. // 1a []AssetProperty=[Cluster]
  579. // 1b []AssetProperty=[Type]
  580. // 1c []AssetProperty=[Nil]
  581. // 1d []AssetProperty=nil
  582. // 1e aggregateBy []string=["label:test"]
  583. // 2 Multi-aggregation
  584. // 2a []AssetProperty=[Cluster,Type]
  585. // 3 Share resources
  586. // 3a Shared hourly cost > 0.0
  587. // Definitions and set-up:
  588. var as *AssetSet
  589. var err error
  590. // Tests:
  591. // 1 Single-aggregation
  592. // 1a []AssetProperty=[Cluster]
  593. as = GenerateMockAssetSet(startYesterday, day)
  594. err = as.AggregateBy([]string{string(AssetClusterProp)}, nil)
  595. if err != nil {
  596. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  597. }
  598. assertAssetSet(t, as, "1a", window, map[string]float64{
  599. "cluster1": 26.0,
  600. "cluster2": 15.0,
  601. "cluster3": 19.0,
  602. }, nil)
  603. // 1b []AssetProperty=[Type]
  604. as = GenerateMockAssetSet(startYesterday, day)
  605. err = as.AggregateBy([]string{string(AssetTypeProp)}, nil)
  606. if err != nil {
  607. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  608. }
  609. assertAssetSet(t, as, "1b", window, map[string]float64{
  610. "Node": 49.0,
  611. "Disk": 8.0,
  612. "ClusterManagement": 3.0,
  613. }, nil)
  614. // 1c []AssetProperty=[Nil]
  615. as = GenerateMockAssetSet(startYesterday, day)
  616. err = as.AggregateBy([]string{}, nil)
  617. if err != nil {
  618. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  619. }
  620. assertAssetSet(t, as, "1c", window, map[string]float64{
  621. "": 60.0,
  622. }, nil)
  623. // 1d []AssetProperty=nil
  624. as = GenerateMockAssetSet(startYesterday, day)
  625. err = as.AggregateBy(nil, nil)
  626. if err != nil {
  627. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  628. }
  629. assertAssetSet(t, as, "1d", window, map[string]float64{
  630. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node1/node1": 7.00,
  631. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node2/node2": 5.50,
  632. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node3/node3": 6.50,
  633. "__undefined__/__undefined__/__undefined__/Storage/cluster1/Disk/Kubernetes/gcp-disk1/disk1": 2.50,
  634. "__undefined__/__undefined__/__undefined__/Storage/cluster1/Disk/Kubernetes/gcp-disk2/disk2": 1.50,
  635. "GCP/__undefined__/__undefined__/Management/cluster1/ClusterManagement/Kubernetes/__undefined__/__undefined__": 3.00,
  636. "__undefined__/__undefined__/__undefined__/Compute/cluster2/Node/Kubernetes/gcp-node4/node4": 11.00,
  637. "__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk3/disk3": 2.50,
  638. "__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk4/disk4": 1.50,
  639. "GCP/__undefined__/__undefined__/Management/cluster2/ClusterManagement/Kubernetes/__undefined__/__undefined__": 0.00,
  640. "__undefined__/__undefined__/__undefined__/Compute/cluster3/Node/Kubernetes/aws-node5/node5": 19.00,
  641. }, nil)
  642. // 1e aggregateBy []string=["label:test"]
  643. as = GenerateMockAssetSet(startYesterday, day)
  644. err = as.AggregateBy([]string{"label:test"}, nil)
  645. if err != nil {
  646. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  647. }
  648. assertAssetSet(t, as, "1e", window, map[string]float64{
  649. "__undefined__": 53.00,
  650. "test=test": 7.00,
  651. }, nil)
  652. // 2 Multi-aggregation
  653. // 2a []AssetProperty=[Cluster,Type]
  654. as = GenerateMockAssetSet(startYesterday, day)
  655. err = as.AggregateBy([]string{string(AssetClusterProp), string(AssetTypeProp)}, nil)
  656. if err != nil {
  657. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  658. }
  659. assertAssetSet(t, as, "2a", window, map[string]float64{
  660. "cluster1/Node": 19.0,
  661. "cluster1/Disk": 4.0,
  662. "cluster1/ClusterManagement": 3.0,
  663. "cluster2/Node": 11.0,
  664. "cluster2/Disk": 4.0,
  665. "cluster2/ClusterManagement": 0.0,
  666. "cluster3/Node": 19.0,
  667. }, nil)
  668. // 3 Share resources
  669. // 3a Shared hourly cost > 0.0
  670. as = GenerateMockAssetSet(startYesterday, day)
  671. err = as.AggregateBy([]string{string(AssetTypeProp)}, &AssetAggregationOptions{
  672. SharedHourlyCosts: map[string]float64{"shared1": 0.5},
  673. })
  674. if err != nil {
  675. t.Fatalf("AssetSet.AggregateBy: unexpected error: %s", err)
  676. }
  677. assertAssetSet(t, as, "1a", window, map[string]float64{
  678. "Node": 49.0,
  679. "Disk": 8.0,
  680. "ClusterManagement": 3.0,
  681. "Shared": 12.0,
  682. }, nil)
  683. }
  684. func TestAssetSet_FindMatch(t *testing.T) {
  685. endYesterday := time.Now().UTC().Truncate(day)
  686. startYesterday := endYesterday.Add(-day)
  687. s, e := startYesterday, endYesterday
  688. w := NewWindow(&s, &e)
  689. var query, match Asset
  690. var as *AssetSet
  691. var err error
  692. // Assert success of a simple match of Type and ProviderID
  693. as = GenerateMockAssetSet(startYesterday, day)
  694. query = NewNode("", "", "gcp-node3", s, e, w)
  695. match, err = as.FindMatch(query, []string{string(AssetTypeProp), string(AssetProviderIDProp)}, nil)
  696. if err != nil {
  697. t.Fatalf("AssetSet.FindMatch: unexpected error: %s", err)
  698. }
  699. // Assert error of a simple non-match of Type and ProviderID
  700. as = GenerateMockAssetSet(startYesterday, day)
  701. query = NewNode("", "", "aws-node3", s, e, w)
  702. match, err = as.FindMatch(query, []string{string(AssetTypeProp), string(AssetProviderIDProp)}, nil)
  703. if err == nil {
  704. t.Fatalf("AssetSet.FindMatch: expected error (no match); found %s", match)
  705. }
  706. // Assert error of matching ProviderID, but not Type
  707. as = GenerateMockAssetSet(startYesterday, day)
  708. query = NewCloud(ComputeCategory, "gcp-node3", s, e, w)
  709. match, err = as.FindMatch(query, []string{string(AssetTypeProp), string(AssetProviderIDProp)}, nil)
  710. if err == nil {
  711. t.Fatalf("AssetSet.FindMatch: expected error (no match); found %s", match)
  712. }
  713. }
  714. // Asserts that all Assets within an AssetSet have a Window that
  715. // matches that of the AssetSet.
  716. func TestAssetSet_InsertMatchingWindow(t *testing.T) {
  717. setStart := time.Now().Round(time.Hour)
  718. setEnd := setStart.Add(1 * time.Hour)
  719. a1WindowStart := setStart.Add(5 * time.Minute)
  720. a1WindowEnd := setStart.Add(50 * time.Minute)
  721. a2WindowStart := setStart.Add(17 * time.Minute)
  722. a2WindowEnd := setStart.Add(34 * time.Minute)
  723. a1 := &Node{}
  724. a1.SetProperties(&AssetProperties{
  725. Name: "asset-1",
  726. })
  727. a1.Window = NewClosedWindow(a1WindowStart, a1WindowEnd)
  728. a2 := &Disk{}
  729. a2.SetProperties(&AssetProperties{
  730. Name: "asset-2",
  731. })
  732. a2.Window = NewClosedWindow(a2WindowStart, a2WindowEnd)
  733. as := NewAssetSet(setStart, setEnd)
  734. as.Insert(a1, nil)
  735. as.Insert(a2, nil)
  736. if as.Length() != 2 {
  737. t.Errorf("AS length got %d, expected %d", as.Length(), 2)
  738. }
  739. for _, a := range as.Assets {
  740. if !(*a.GetWindow().Start()).Equal(setStart) {
  741. t.Errorf("Asset %s window start is %s, expected %s", a.GetProperties().Name, *a.GetWindow().Start(), setStart)
  742. }
  743. if !(*a.GetWindow().End()).Equal(setEnd) {
  744. t.Errorf("Asset %s window end is %s, expected %s", a.GetProperties().Name, *a.GetWindow().End(), setEnd)
  745. }
  746. }
  747. }
  748. func TestAssetSet_ReconciliationMatchMap(t *testing.T) {
  749. endYesterday := time.Now().UTC().Truncate(day)
  750. startYesterday := endYesterday.Add(-day)
  751. as := GenerateMockAssetSet(startYesterday, day)
  752. matchMap := as.ReconciliationMatchMap()
  753. // Determine the number of assets by provider ID
  754. assetCountByProviderId := make(map[string]int, len(matchMap))
  755. for _, a := range as.Assets {
  756. if a == nil || a.GetProperties() == nil || a.GetProperties().ProviderID == "" {
  757. return
  758. }
  759. if _, ok := assetCountByProviderId[a.GetProperties().ProviderID]; !ok {
  760. assetCountByProviderId[a.GetProperties().ProviderID] = 0
  761. }
  762. assetCountByProviderId[a.GetProperties().ProviderID] += 1
  763. }
  764. for k, count := range assetCountByProviderId {
  765. if len(matchMap[k]) != count {
  766. t.Errorf("AssetSet.ReconciliationMatchMap: incorrect asset count for provider id: %s", k)
  767. }
  768. }
  769. }
  770. func TestAssetSetRange_AccumulateToAssetSet(t *testing.T) {
  771. endYesterday := time.Now().UTC().Truncate(day)
  772. startYesterday := endYesterday.Add(-day)
  773. startD2 := startYesterday
  774. startD1 := startD2.Add(-day)
  775. startD0 := startD1.Add(-day)
  776. window := NewWindow(&startD0, &endYesterday)
  777. var asr *AssetSetRange
  778. var as *AssetSet
  779. var err error
  780. asr = NewAssetSetRange(
  781. GenerateMockAssetSet(startD0, day),
  782. GenerateMockAssetSet(startD1, day),
  783. GenerateMockAssetSet(startD2, day),
  784. )
  785. err = asr.AggregateBy(nil, nil)
  786. as, err = asr.AccumulateToAssetSet()
  787. if err != nil {
  788. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  789. }
  790. assertAssetSet(t, as, "1a", window, map[string]float64{
  791. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node1/node1": 21.00,
  792. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node2/node2": 16.50,
  793. "__undefined__/__undefined__/__undefined__/Compute/cluster1/Node/Kubernetes/gcp-node3/node3": 19.50,
  794. "__undefined__/__undefined__/__undefined__/Storage/cluster1/Disk/Kubernetes/gcp-disk1/disk1": 7.50,
  795. "__undefined__/__undefined__/__undefined__/Storage/cluster1/Disk/Kubernetes/gcp-disk2/disk2": 4.50,
  796. "GCP/__undefined__/__undefined__/Management/cluster1/ClusterManagement/Kubernetes/__undefined__/__undefined__": 9.00,
  797. "__undefined__/__undefined__/__undefined__/Compute/cluster2/Node/Kubernetes/gcp-node4/node4": 33.00,
  798. "__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk3/disk3": 7.50,
  799. "__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk4/disk4": 4.50,
  800. "GCP/__undefined__/__undefined__/Management/cluster2/ClusterManagement/Kubernetes/__undefined__/__undefined__": 0.00,
  801. "__undefined__/__undefined__/__undefined__/Compute/cluster3/Node/Kubernetes/aws-node5/node5": 57.00,
  802. }, nil)
  803. asr = NewAssetSetRange(
  804. GenerateMockAssetSet(startD0, day),
  805. GenerateMockAssetSet(startD1, day),
  806. GenerateMockAssetSet(startD2, day),
  807. )
  808. err = asr.AggregateBy([]string{}, nil)
  809. as, err = asr.AccumulateToAssetSet()
  810. if err != nil {
  811. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  812. }
  813. assertAssetSet(t, as, "1b", window, map[string]float64{
  814. "": 180.00,
  815. }, nil)
  816. asr = NewAssetSetRange(
  817. GenerateMockAssetSet(startD0, day),
  818. GenerateMockAssetSet(startD1, day),
  819. GenerateMockAssetSet(startD2, day),
  820. )
  821. err = asr.AggregateBy([]string{string(AssetTypeProp)}, nil)
  822. if err != nil {
  823. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  824. }
  825. as, err = asr.AccumulateToAssetSet()
  826. if err != nil {
  827. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  828. }
  829. assertAssetSet(t, as, "1c", window, map[string]float64{
  830. "Node": 147.0,
  831. "Disk": 24.0,
  832. "ClusterManagement": 9.0,
  833. }, nil)
  834. asr = NewAssetSetRange(
  835. GenerateMockAssetSet(startD0, day),
  836. GenerateMockAssetSet(startD1, day),
  837. GenerateMockAssetSet(startD2, day),
  838. )
  839. err = asr.AggregateBy([]string{string(AssetClusterProp)}, nil)
  840. if err != nil {
  841. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  842. }
  843. as, err = asr.AccumulateToAssetSet()
  844. if err != nil {
  845. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  846. }
  847. assertAssetSet(t, as, "1c", window, map[string]float64{
  848. "cluster1": 78.0,
  849. "cluster2": 45.0,
  850. "cluster3": 57.0,
  851. }, nil)
  852. // Accumulation with aggregation should work, even when the first AssetSet
  853. // is empty (this was previously an issue)
  854. asr = NewAssetSetRange(
  855. NewAssetSet(startD0, startD1),
  856. GenerateMockAssetSet(startD1, day),
  857. GenerateMockAssetSet(startD2, day),
  858. )
  859. err = asr.AggregateBy([]string{string(AssetTypeProp)}, nil)
  860. as, err = asr.AccumulateToAssetSet()
  861. if err != nil {
  862. t.Fatalf("AssetSetRange.AggregateBy: unexpected error: %s", err)
  863. }
  864. assertAssetSet(t, as, "1d", window, map[string]float64{
  865. "Node": 98.00,
  866. "Disk": 16.00,
  867. "ClusterManagement": 6.00,
  868. }, nil)
  869. }
  870. func TestAssetToExternalAllocation(t *testing.T) {
  871. var asset Asset
  872. var alloc *Allocation
  873. var err error
  874. labelConfig := NewLabelConfig()
  875. _, err = AssetToExternalAllocation(asset, []string{"namespace"}, labelConfig)
  876. if err == nil {
  877. t.Fatalf("expected error due to nil asset; no error returned")
  878. }
  879. // Consider this Asset:
  880. // Cloud {
  881. // TotalCost: 10.00,
  882. // Labels{
  883. // "kubernetes_namespace":"monitoring",
  884. // "env":"prod"
  885. // }
  886. // }
  887. cloud := NewCloud(ComputeCategory, "abc123", start1, start2, windows[0])
  888. cloud.SetLabels(map[string]string{
  889. "kubernetes_namespace": "monitoring",
  890. "env": "prod",
  891. "app": "cost-analyzer",
  892. "kubernetes_label_app": "app",
  893. "kubernetes_label_department": "department",
  894. "kubernetes_label_env": "env",
  895. "kubernetes_label_owner": "owner",
  896. "kubernetes_label_team": "team",
  897. })
  898. cloud.Cost = 10.00
  899. asset = cloud
  900. _, err = AssetToExternalAllocation(asset, []string{"namespace"}, nil)
  901. if err != nil {
  902. t.Fatalf("unexpected error: %s", err)
  903. }
  904. _, err = AssetToExternalAllocation(asset, nil, nil)
  905. if err == nil {
  906. t.Fatalf("expected error due to nil aggregateBy; no error returned")
  907. }
  908. // Given the following parameters, we expect to return:
  909. //
  910. // 1) single-prop full match
  911. // aggregateBy = ["namespace"]
  912. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  913. // => Allocation{Name: "monitoring", ExternalCost: 10.00, TotalCost: 10.00}, nil
  914. //
  915. // 2) multi-prop full match
  916. // aggregateBy = ["namespace", "label:env"]
  917. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  918. // => Allocation{Name: "monitoring/env=prod", ExternalCost: 10.00, TotalCost: 10.00}, nil
  919. //
  920. // 3) multi-prop partial match
  921. // aggregateBy = ["namespace", "label:foo"]
  922. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  923. // => Allocation{Name: "monitoring/__unallocated__", ExternalCost: 10.00, TotalCost: 10.00}, nil
  924. //
  925. // 4) label alias match(es)
  926. // aggregateBy = ["product", "deployment", "environment", "owner", "team"]
  927. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  928. // => Allocation{Name: "app/department/env/owner/team", ExternalCost: 10.00, TotalCost: 10.00}, nil
  929. //
  930. // 5) no match
  931. // aggregateBy = ["cluster"]
  932. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  933. // => nil, err
  934. // 1) single-prop full match
  935. alloc, err = AssetToExternalAllocation(asset, []string{"namespace"}, nil)
  936. if err != nil {
  937. t.Fatalf("unexpected error: %s", err)
  938. }
  939. if alloc.Name != "monitoring/__external__" {
  940. t.Fatalf("expected external allocation with name '%s'; got '%s'", "monitoring/__external__", alloc.Name)
  941. }
  942. if ns := alloc.Properties.Namespace; ns != "monitoring" {
  943. t.Fatalf("expected external allocation with AllocationProperties.Namespace '%s'; got '%s'", "monitoring", ns)
  944. }
  945. if alloc.ExternalCost != 10.00 {
  946. t.Fatalf("expected external allocation with ExternalCost %f; got %f", 10.00, alloc.ExternalCost)
  947. }
  948. if alloc.TotalCost() != 10.00 {
  949. t.Fatalf("expected external allocation with TotalCost %f; got %f", 10.00, alloc.TotalCost())
  950. }
  951. // 2) multi-prop full match
  952. alloc, err = AssetToExternalAllocation(asset, []string{"namespace", "label:env"}, nil)
  953. if err != nil {
  954. t.Fatalf("unexpected error: %s", err)
  955. }
  956. if alloc.Name != "monitoring/env=prod/__external__" {
  957. t.Fatalf("expected external allocation with name '%s'; got '%s'", "monitoring/env=prod/__external__", alloc.Name)
  958. }
  959. if ns := alloc.Properties.Namespace; ns != "monitoring" {
  960. t.Fatalf("expected external allocation with AllocationProperties.Namespace '%s'; got '%s' (%s)", "monitoring", ns, err)
  961. }
  962. if ls := alloc.Properties.Labels; len(ls) == 0 || ls["env"] != "prod" {
  963. t.Fatalf("expected external allocation with AllocationProperties.Labels[\"env\"] '%s'; got '%s' (%s)", "prod", ls["env"], err)
  964. }
  965. if alloc.ExternalCost != 10.00 {
  966. t.Fatalf("expected external allocation with ExternalCost %f; got %f", 10.00, alloc.ExternalCost)
  967. }
  968. if alloc.TotalCost() != 10.00 {
  969. t.Fatalf("expected external allocation with TotalCost %f; got %f", 10.00, alloc.TotalCost())
  970. }
  971. // 3) multi-prop partial match
  972. alloc, err = AssetToExternalAllocation(asset, []string{"namespace", "label:foo"}, nil)
  973. if err != nil {
  974. t.Fatalf("unexpected error: %s", err)
  975. }
  976. if alloc.Name != "monitoring/__unallocated__/__external__" {
  977. t.Fatalf("expected external allocation with name '%s'; got '%s'", "monitoring/__unallocated__/__external__", alloc.Name)
  978. }
  979. if ns := alloc.Properties.Namespace; ns != "monitoring" {
  980. t.Fatalf("expected external allocation with AllocationProperties.Namespace '%s'; got '%s' (%s)", "monitoring", ns, err)
  981. }
  982. if alloc.ExternalCost != 10.00 {
  983. t.Fatalf("expected external allocation with ExternalCost %f; got %f", 10.00, alloc.ExternalCost)
  984. }
  985. if alloc.TotalCost() != 10.00 {
  986. t.Fatalf("expected external allocation with TotalCost %f; got %f", 10.00, alloc.TotalCost())
  987. }
  988. // 4) label alias match(es)
  989. alloc, err = AssetToExternalAllocation(asset, []string{"product", "department", "environment", "owner", "team"}, nil)
  990. if err != nil {
  991. t.Fatalf("unexpected error: %s", err)
  992. }
  993. if alloc.Name != "app/department/env/owner/team/__external__" {
  994. t.Fatalf("expected external allocation with name '%s'; got '%s'", "app/department/env/owner/team/__external__", alloc.Name)
  995. }
  996. if alloc.Properties.Labels[labelConfig.ProductLabel] != "app" {
  997. t.Fatalf("expected external allocation with label %s equal to %s; got %s", labelConfig.ProductLabel, "app", alloc.Properties.Labels[labelConfig.ProductLabel])
  998. }
  999. if alloc.Properties.Labels[labelConfig.DepartmentLabel] != "department" {
  1000. t.Fatalf("expected external allocation with label %s equal to %s; got %s", labelConfig.DepartmentLabel, "department", alloc.Properties.Labels[labelConfig.DepartmentLabel])
  1001. }
  1002. if alloc.Properties.Labels[labelConfig.EnvironmentLabel] != "env" {
  1003. t.Fatalf("expected external allocation with label %s equal to %s; got %s", labelConfig.EnvironmentLabel, "env", alloc.Properties.Labels[labelConfig.EnvironmentLabel])
  1004. }
  1005. if alloc.Properties.Labels[labelConfig.OwnerLabel] != "owner" {
  1006. t.Fatalf("expected external allocation with label %s equal to %s; got %s", labelConfig.OwnerLabel, "owner", alloc.Properties.Labels[labelConfig.OwnerLabel])
  1007. }
  1008. if alloc.Properties.Labels[labelConfig.TeamLabel] != "team" {
  1009. t.Fatalf("expected external allocation with label %s equal to %s; got %s", labelConfig.TeamLabel, "team", alloc.Properties.Labels[labelConfig.TeamLabel])
  1010. }
  1011. if alloc.ExternalCost != 10.00 {
  1012. t.Fatalf("expected external allocation with ExternalCost %f; got %f", 10.00, alloc.ExternalCost)
  1013. }
  1014. if alloc.TotalCost() != 10.00 {
  1015. t.Fatalf("expected external allocation with TotalCost %f; got %f", 10.00, alloc.TotalCost())
  1016. }
  1017. // 5) no match
  1018. _, err = AssetToExternalAllocation(asset, []string{"cluster"}, nil)
  1019. if err == nil {
  1020. t.Fatalf("expected 'no match' error")
  1021. }
  1022. // other cases
  1023. alloc, err = AssetToExternalAllocation(asset, []string{"namespace", "label:app"}, nil)
  1024. if err != nil {
  1025. t.Fatalf("unexpected error: %s", err)
  1026. }
  1027. if alloc.ExternalCost != 10.00 {
  1028. t.Fatalf("expected external allocation with ExternalCost %f; got %f", 10.00, alloc.ExternalCost)
  1029. }
  1030. if alloc.TotalCost() != 10.00 {
  1031. t.Fatalf("expected external allocation with TotalCost %f; got %f", 10.00, alloc.TotalCost())
  1032. }
  1033. }
  1034. func TestAssetSetRange_Start(t *testing.T) {
  1035. tests := []struct {
  1036. name string
  1037. arg *AssetSetRange
  1038. expectError bool
  1039. expected time.Time
  1040. }{
  1041. {
  1042. name: "Empty ASR",
  1043. arg: nil,
  1044. expectError: true,
  1045. },
  1046. {
  1047. name: "Single asset",
  1048. arg: &AssetSetRange{
  1049. Assets: []*AssetSet{
  1050. {
  1051. Assets: map[string]Asset{
  1052. "a": &Node{
  1053. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1054. },
  1055. },
  1056. },
  1057. },
  1058. },
  1059. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1060. },
  1061. {
  1062. name: "Two assets",
  1063. arg: &AssetSetRange{
  1064. Assets: []*AssetSet{
  1065. {
  1066. Assets: map[string]Asset{
  1067. "a": &Node{
  1068. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1069. },
  1070. "b": &Node{
  1071. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1072. },
  1073. },
  1074. },
  1075. },
  1076. },
  1077. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1078. },
  1079. {
  1080. name: "Two AssetSets",
  1081. arg: &AssetSetRange{
  1082. Assets: []*AssetSet{
  1083. {
  1084. Assets: map[string]Asset{
  1085. "a": &Node{
  1086. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1087. },
  1088. },
  1089. },
  1090. {
  1091. Assets: map[string]Asset{
  1092. "b": &Node{
  1093. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1094. },
  1095. },
  1096. },
  1097. },
  1098. },
  1099. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1100. },
  1101. }
  1102. for _, test := range tests {
  1103. result, err := test.arg.Start()
  1104. if test.expectError && err != nil {
  1105. continue
  1106. }
  1107. if test.expectError && err == nil {
  1108. t.Errorf("%s: expected error and got none", test.name)
  1109. } else if result != test.expected {
  1110. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  1111. }
  1112. }
  1113. }
  1114. func TestAssetSetRange_End(t *testing.T) {
  1115. tests := []struct {
  1116. name string
  1117. arg *AssetSetRange
  1118. expectError bool
  1119. expected time.Time
  1120. }{
  1121. {
  1122. name: "Empty ASR",
  1123. arg: nil,
  1124. expectError: true,
  1125. },
  1126. {
  1127. name: "Single asset",
  1128. arg: &AssetSetRange{
  1129. Assets: []*AssetSet{
  1130. {
  1131. Assets: map[string]Asset{
  1132. "a": &Node{
  1133. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1134. },
  1135. },
  1136. },
  1137. },
  1138. },
  1139. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1140. },
  1141. {
  1142. name: "Two assets",
  1143. arg: &AssetSetRange{
  1144. Assets: []*AssetSet{
  1145. {
  1146. Assets: map[string]Asset{
  1147. "a": &Node{
  1148. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1149. },
  1150. "b": &Node{
  1151. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1152. },
  1153. },
  1154. },
  1155. },
  1156. },
  1157. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1158. },
  1159. {
  1160. name: "Two AssetSets",
  1161. arg: &AssetSetRange{
  1162. Assets: []*AssetSet{
  1163. {
  1164. Assets: map[string]Asset{
  1165. "a": &Node{
  1166. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1167. },
  1168. },
  1169. },
  1170. {
  1171. Assets: map[string]Asset{
  1172. "b": &Node{
  1173. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1174. },
  1175. },
  1176. },
  1177. },
  1178. },
  1179. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1180. },
  1181. }
  1182. for _, test := range tests {
  1183. result, err := test.arg.End()
  1184. if test.expectError && err != nil {
  1185. continue
  1186. }
  1187. if test.expectError && err == nil {
  1188. t.Errorf("%s: expected error and got none", test.name)
  1189. } else if result != test.expected {
  1190. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  1191. }
  1192. }
  1193. }
  1194. func TestAssetSetRange_Minutes(t *testing.T) {
  1195. tests := []struct {
  1196. name string
  1197. arg *AssetSetRange
  1198. expected float64
  1199. }{
  1200. {
  1201. name: "Empty ASR",
  1202. arg: nil,
  1203. expected: 0,
  1204. },
  1205. {
  1206. name: "Single asset",
  1207. arg: &AssetSetRange{
  1208. Assets: []*AssetSet{
  1209. {
  1210. Assets: map[string]Asset{
  1211. "a": &Node{
  1212. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1213. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1214. },
  1215. },
  1216. },
  1217. },
  1218. },
  1219. expected: 24 * 60,
  1220. },
  1221. {
  1222. name: "Two assets",
  1223. arg: &AssetSetRange{
  1224. Assets: []*AssetSet{
  1225. {
  1226. Assets: map[string]Asset{
  1227. "a": &Node{
  1228. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1229. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1230. },
  1231. "b": &Node{
  1232. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1233. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  1234. },
  1235. },
  1236. },
  1237. },
  1238. },
  1239. expected: 2 * 24 * 60,
  1240. },
  1241. {
  1242. name: "Two AssetSets",
  1243. arg: &AssetSetRange{
  1244. Assets: []*AssetSet{
  1245. {
  1246. Assets: map[string]Asset{
  1247. "a": &Node{
  1248. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  1249. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1250. },
  1251. },
  1252. },
  1253. {
  1254. Assets: map[string]Asset{
  1255. "b": &Node{
  1256. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  1257. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  1258. },
  1259. },
  1260. },
  1261. },
  1262. },
  1263. expected: 2 * 24 * 60,
  1264. },
  1265. }
  1266. for _, test := range tests {
  1267. result := test.arg.Minutes()
  1268. if result != test.expected {
  1269. t.Errorf("%s: expected %f but got %f", test.name, test.expected, result)
  1270. }
  1271. }
  1272. }
  1273. func TestAssetSetRange_MarshalJSON(t *testing.T) {
  1274. tests := []struct {
  1275. name string
  1276. arg *AssetSetRange
  1277. expected *AssetSetRange
  1278. }{
  1279. {
  1280. name: "Nil ASR",
  1281. arg: nil,
  1282. },
  1283. {
  1284. name: "Nil AS in ASR",
  1285. arg: NewAssetSetRange(nil),
  1286. },
  1287. {
  1288. name: "Normal ASR",
  1289. arg: &AssetSetRange{
  1290. Assets: []*AssetSet{
  1291. {
  1292. Assets: map[string]Asset{
  1293. "a": &Any{
  1294. Start: time.Now().UTC().Truncate(day),
  1295. },
  1296. },
  1297. },
  1298. },
  1299. },
  1300. },
  1301. }
  1302. for _, test := range tests {
  1303. bytes, err := json.Marshal(test.arg)
  1304. if err != nil {
  1305. t.Fatalf("ASR Marshal: test %s, unexpected error: %s", test.name, err)
  1306. }
  1307. var testASR []*AssetSet
  1308. marshaled := &testASR
  1309. err = json.Unmarshal(bytes, marshaled)
  1310. if err != nil {
  1311. t.Fatalf("ASR Unmarshal: test %s: unexpected error: %s", test.name, err)
  1312. }
  1313. if test.arg.Length() != len(testASR) {
  1314. t.Fatalf("ASR Unmarshal: test %s: length mutated in encoding: expected %d but got %d", test.name, test.arg.Length(), len(testASR))
  1315. }
  1316. // asset don't unmarshal back from json
  1317. }
  1318. }
  1319. func TestAssetSetRange_AccumulateBy_None(t *testing.T) {
  1320. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1321. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1322. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1323. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1324. today := time.Now().UTC().Truncate(day)
  1325. ago4dAS := GenerateMockAssetSet(ago4d, day)
  1326. ago3dAS := GenerateMockAssetSet(ago3d, day)
  1327. ago2dAS := GenerateMockAssetSet(ago2d, day)
  1328. yesterdayAS := GenerateMockAssetSet(yesterday, day)
  1329. todayAS := GenerateMockAssetSet(today, day)
  1330. asr := NewAssetSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1331. asr, err := asr.Accumulate(AccumulateOptionNone)
  1332. if err != nil {
  1333. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1334. }
  1335. if len(asr.Assets) != 5 {
  1336. t.Fatalf("expected 5 asset sets, got:%d", len(asr.Assets))
  1337. }
  1338. }
  1339. func TestAssetSetRange_AccumulateBy_All(t *testing.T) {
  1340. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1341. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1342. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1343. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1344. today := time.Now().UTC().Truncate(day)
  1345. ago4dAS := GenerateMockAssetSet(ago4d, day)
  1346. ago3dAS := GenerateMockAssetSet(ago3d, day)
  1347. ago2dAS := GenerateMockAssetSet(ago2d, day)
  1348. yesterdayAS := GenerateMockAssetSet(yesterday, day)
  1349. todayAS := GenerateMockAssetSet(today, day)
  1350. asr := NewAssetSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1351. asr, err := asr.Accumulate(AccumulateOptionAll)
  1352. if err != nil {
  1353. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1354. }
  1355. if len(asr.Assets) != 1 {
  1356. t.Fatalf("expected 1 asset set, got:%d", len(asr.Assets))
  1357. }
  1358. }
  1359. func TestAssetSetRange_AccumulateBy_Hour(t *testing.T) {
  1360. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1361. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1362. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1363. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1364. currentHour := time.Now().UTC().Truncate(time.Hour)
  1365. ago4hAS := GenerateMockAssetSet(ago4h, time.Hour)
  1366. ago3hAS := GenerateMockAssetSet(ago3h, time.Hour)
  1367. ago2hAS := GenerateMockAssetSet(ago2h, time.Hour)
  1368. ago1hAS := GenerateMockAssetSet(ago1h, time.Hour)
  1369. currentHourAS := GenerateMockAssetSet(currentHour, time.Hour)
  1370. asr := NewAssetSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1371. asr, err := asr.Accumulate(AccumulateOptionHour)
  1372. if err != nil {
  1373. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1374. }
  1375. if len(asr.Assets) != 5 {
  1376. t.Fatalf("expected 5 asset sets, got:%d", len(asr.Assets))
  1377. }
  1378. allocMap := asr.Assets[0].Assets
  1379. alloc := allocMap["__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk4/disk4"]
  1380. if alloc.Minutes() != 60.0 {
  1381. t.Errorf("accumulating asset set range: expected %f minutes; actual %f", 60.0, alloc.Minutes())
  1382. }
  1383. }
  1384. func TestAssetSetRange_AccumulateBy_Day_From_Day(t *testing.T) {
  1385. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1386. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1387. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1388. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1389. today := time.Now().UTC().Truncate(day)
  1390. ago4dAS := GenerateMockAssetSet(ago4d, day)
  1391. ago3dAS := GenerateMockAssetSet(ago3d, day)
  1392. ago2dAS := GenerateMockAssetSet(ago2d, day)
  1393. yesterdayAS := GenerateMockAssetSet(yesterday, day)
  1394. todayAS := GenerateMockAssetSet(today, day)
  1395. asr := NewAssetSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1396. asr, err := asr.Accumulate(AccumulateOptionDay)
  1397. if err != nil {
  1398. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1399. }
  1400. if len(asr.Assets) != 5 {
  1401. t.Fatalf("expected 5 asset sets, got:%d", len(asr.Assets))
  1402. }
  1403. allocMap := asr.Assets[0].Assets
  1404. alloc := allocMap["__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk4/disk4"]
  1405. if alloc.Minutes() != 1440.0 {
  1406. t.Errorf("accumulating asset set range: expected %f minutes; actual %f", 1440.0, alloc.Minutes())
  1407. }
  1408. }
  1409. func TestAssetSetRange_AccumulateBy_Day_From_Hours(t *testing.T) {
  1410. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1411. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1412. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1413. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1414. currentHour := time.Now().UTC().Truncate(time.Hour)
  1415. ago4hAS := GenerateMockAssetSet(ago4h, time.Hour)
  1416. ago3hAS := GenerateMockAssetSet(ago3h, time.Hour)
  1417. ago2hAS := GenerateMockAssetSet(ago2h, time.Hour)
  1418. ago1hAS := GenerateMockAssetSet(ago1h, time.Hour)
  1419. currentHourAS := GenerateMockAssetSet(currentHour, time.Hour)
  1420. asr := NewAssetSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1421. asr, err := asr.Accumulate(AccumulateOptionDay)
  1422. if err != nil {
  1423. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1424. }
  1425. if len(asr.Assets) != 1 && len(asr.Assets) != 2 {
  1426. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Assets))
  1427. }
  1428. allocMap := asr.Assets[0].Assets
  1429. alloc := allocMap["__undefined__/__undefined__/__undefined__/Storage/cluster2/Disk/Kubernetes/gcp-disk4/disk4"]
  1430. if alloc.Minutes() > 300.0 {
  1431. t.Errorf("accumulating AllocationSetRange: expected %f or less minutes; actual %f", 300.0, alloc.Minutes())
  1432. }
  1433. }
  1434. func TestAssetSetRange_AccumulateBy_Week(t *testing.T) {
  1435. ago9d := time.Now().UTC().Truncate(day).Add(-9 * day)
  1436. ago8d := time.Now().UTC().Truncate(day).Add(-8 * day)
  1437. ago7d := time.Now().UTC().Truncate(day).Add(-7 * day)
  1438. ago6d := time.Now().UTC().Truncate(day).Add(-6 * day)
  1439. ago5d := time.Now().UTC().Truncate(day).Add(-5 * day)
  1440. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1441. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1442. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1443. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1444. today := time.Now().UTC().Truncate(day)
  1445. ago9dAS := GenerateMockAssetSet(ago9d, day)
  1446. ago8dAS := GenerateMockAssetSet(ago8d, day)
  1447. ago7dAS := GenerateMockAssetSet(ago7d, day)
  1448. ago6dAS := GenerateMockAssetSet(ago6d, day)
  1449. ago5dAS := GenerateMockAssetSet(ago5d, day)
  1450. ago4dAS := GenerateMockAssetSet(ago4d, day)
  1451. ago3dAS := GenerateMockAssetSet(ago3d, day)
  1452. ago2dAS := GenerateMockAssetSet(ago2d, day)
  1453. yesterdayAS := GenerateMockAssetSet(yesterday, day)
  1454. todayAS := GenerateMockAssetSet(today, day)
  1455. asr := NewAssetSetRange(ago9dAS, ago8dAS, ago7dAS, ago6dAS, ago5dAS, ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1456. asr, err := asr.Accumulate(AccumulateOptionWeek)
  1457. if err != nil {
  1458. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1459. }
  1460. if len(asr.Assets) != 2 && len(asr.Assets) != 3 {
  1461. t.Fatalf("expected 2 or 3 asset sets, got:%d", len(asr.Assets))
  1462. }
  1463. for _, as := range asr.Assets {
  1464. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*7 {
  1465. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  1466. }
  1467. }
  1468. }
  1469. func TestAssetSetRange_AccumulateBy_Month(t *testing.T) {
  1470. prevMonth1stDay := time.Date(2020, 01, 29, 0, 0, 0, 0, time.UTC)
  1471. prevMonth2ndDay := time.Date(2020, 01, 30, 0, 0, 0, 0, time.UTC)
  1472. prevMonth3ndDay := time.Date(2020, 01, 31, 0, 0, 0, 0, time.UTC)
  1473. nextMonth1stDay := time.Date(2020, 02, 01, 0, 0, 0, 0, time.UTC)
  1474. prev1AS := GenerateMockAssetSet(prevMonth1stDay, day)
  1475. prev2AS := GenerateMockAssetSet(prevMonth2ndDay, day)
  1476. prev3AS := GenerateMockAssetSet(prevMonth3ndDay, day)
  1477. nextAS := GenerateMockAssetSet(nextMonth1stDay, day)
  1478. asr := NewAssetSetRange(prev1AS, prev2AS, prev3AS, nextAS)
  1479. asr, err := asr.Accumulate(AccumulateOptionMonth)
  1480. if err != nil {
  1481. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1482. }
  1483. if len(asr.Assets) != 2 {
  1484. t.Fatalf("expected 2 assets sets, got:%d", len(asr.Assets))
  1485. }
  1486. for _, as := range asr.Assets {
  1487. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*31 {
  1488. t.Fatalf("expected window duration to be between 1 and 31 days, got:%s", as.Window.Duration().String())
  1489. }
  1490. }
  1491. }
  1492. func TestAny_SanitizeNaN(t *testing.T) {
  1493. any := getMockAny(math.NaN())
  1494. any.SanitizeNaN()
  1495. v := reflect.ValueOf(any)
  1496. checkAllFloat64sForNaN(t, v, "TestAny_SanitizeNaN")
  1497. }
  1498. func getMockAny(f float64) Any {
  1499. return Any{
  1500. Adjustment: f,
  1501. Cost: f,
  1502. }
  1503. }
  1504. func TestCloud_SanitizeNaN(t *testing.T) {
  1505. cloud := getMockCloud(math.NaN())
  1506. cloud.SanitizeNaN()
  1507. v := reflect.ValueOf(cloud)
  1508. checkAllFloat64sForNaN(t, v, "TestCloud_SanitizeNaN")
  1509. }
  1510. func getMockCloud(f float64) Cloud {
  1511. return Cloud{
  1512. Adjustment: f,
  1513. Cost: f,
  1514. Credit: f,
  1515. }
  1516. }
  1517. func TestClusterManagement_SanitizeNaN(t *testing.T) {
  1518. cm := getMockClusterManagement(math.NaN())
  1519. cm.SanitizeNaN()
  1520. v := reflect.ValueOf(cm)
  1521. checkAllFloat64sForNaN(t, v, "TestClusterManagement_SanitizeNaN")
  1522. }
  1523. func getMockClusterManagement(f float64) ClusterManagement {
  1524. return ClusterManagement{
  1525. Cost: f,
  1526. Adjustment: f,
  1527. }
  1528. }
  1529. func TestDisk_SanitizeNaN(t *testing.T) {
  1530. disk := getMockDisk(math.NaN())
  1531. disk.SanitizeNaN()
  1532. v := reflect.ValueOf(disk)
  1533. checkAllFloat64sForNaN(t, v, "TestDisk_SanitizeNaN")
  1534. vBreakdown := reflect.ValueOf(*disk.Breakdown)
  1535. checkAllFloat64sForNaN(t, vBreakdown, "TestDisk_SanitizeNaN")
  1536. }
  1537. func getMockDisk(f float64) Disk {
  1538. bhu := f
  1539. bum := f
  1540. breakdown := getMockBreakdown(f)
  1541. return Disk{
  1542. Adjustment: f,
  1543. Cost: f,
  1544. ByteHours: f,
  1545. Local: f,
  1546. Breakdown: &breakdown,
  1547. ByteHoursUsed: &bhu,
  1548. ByteUsageMax: &bum,
  1549. }
  1550. }
  1551. func TestBreakdown_SanitizeNaN(t *testing.T) {
  1552. b := getMockBreakdown(math.NaN())
  1553. b.SanitizeNaN()
  1554. v := reflect.ValueOf(b)
  1555. checkAllFloat64sForNaN(t, v, "TestBreakdown_SanitizeNaN")
  1556. }
  1557. func getMockBreakdown(f float64) Breakdown {
  1558. return Breakdown{
  1559. Idle: f,
  1560. Other: f,
  1561. System: f,
  1562. User: f,
  1563. }
  1564. }
  1565. func TestNetwork_SanitizeNaN(t *testing.T) {
  1566. n := getMockNetwork(math.NaN())
  1567. n.SanitizeNaN()
  1568. v := reflect.ValueOf(n)
  1569. checkAllFloat64sForNaN(t, v, "TestNetwork_SanitizeNaN")
  1570. }
  1571. func getMockNetwork(f float64) Network {
  1572. return Network{
  1573. Adjustment: f,
  1574. Cost: f,
  1575. }
  1576. }
  1577. func TestNodeOverhead_SanitizeNaN(t *testing.T) {
  1578. n := getMockNodeOverhead(math.NaN())
  1579. n.SanitizeNaN()
  1580. v := reflect.ValueOf(n)
  1581. checkAllFloat64sForNaN(t, v, "TestNodeOverhead_SanitizeNaN")
  1582. }
  1583. func getMockNodeOverhead(f float64) NodeOverhead {
  1584. return NodeOverhead{
  1585. CpuOverheadFraction: f,
  1586. RamOverheadFraction: f,
  1587. OverheadCostFraction: f,
  1588. }
  1589. }
  1590. func TestNode_SanitizeNaN(t *testing.T) {
  1591. n := getMockNode(math.NaN())
  1592. n.SanitizeNaN()
  1593. v := reflect.ValueOf(n)
  1594. checkAllFloat64sForNaN(t, v, "TestNode_SanitizeNaN")
  1595. vCpu := reflect.ValueOf(*n.CPUBreakdown)
  1596. checkAllFloat64sForNaN(t, vCpu, "TestNode_SanitizeNaN")
  1597. vRam := reflect.ValueOf(*n.RAMBreakdown)
  1598. checkAllFloat64sForNaN(t, vRam, "TestNode_SanitizeNaN")
  1599. vOverhead := reflect.ValueOf(*n.Overhead)
  1600. checkAllFloat64sForNaN(t, vOverhead, "TestNode_SanitizeNaN")
  1601. }
  1602. func getMockNode(f float64) Node {
  1603. cpuBreakdown := getMockBreakdown(f)
  1604. ramBreakdown := getMockBreakdown(f)
  1605. overhead := getMockNodeOverhead(f)
  1606. return Node{
  1607. Adjustment: f,
  1608. CPUCoreHours: f,
  1609. RAMByteHours: f,
  1610. GPUHours: f,
  1611. CPUBreakdown: &cpuBreakdown,
  1612. RAMBreakdown: &ramBreakdown,
  1613. CPUCost: f,
  1614. GPUCost: f,
  1615. GPUCount: f,
  1616. RAMCost: f,
  1617. Discount: f,
  1618. Preemptible: f,
  1619. Overhead: &overhead,
  1620. }
  1621. }
  1622. func TestLoadBalancer_SanitizeNaN(t *testing.T) {
  1623. lb := getMockLoadBalancer(math.NaN())
  1624. lb.SanitizeNaN()
  1625. v := reflect.ValueOf(lb)
  1626. checkAllFloat64sForNaN(t, v, "TestLoadBalancer_SanitizeNaN")
  1627. }
  1628. func getMockLoadBalancer(f float64) LoadBalancer {
  1629. return LoadBalancer{
  1630. Adjustment: f,
  1631. Cost: f,
  1632. }
  1633. }
  1634. func TestSharedAsset_SanitizeNaN(t *testing.T) {
  1635. sa := getMockSharedAsset(math.NaN())
  1636. sa.SanitizeNaN()
  1637. v := reflect.ValueOf(sa)
  1638. checkAllFloat64sForNaN(t, v, "TestSharedAsset_SanitizeNaN")
  1639. }
  1640. func getMockSharedAsset(f float64) SharedAsset {
  1641. return SharedAsset{
  1642. Cost: f,
  1643. }
  1644. }
  1645. func TestAssetSet_SanitizeNaN(t *testing.T) {
  1646. testCaseName := "TestAssetSet_SanitizeNaN"
  1647. as := getMockAssetSet(math.NaN())
  1648. as.SanitizeNaN()
  1649. v := reflect.ValueOf(as)
  1650. checkAllFloat64sForNaN(t, v, testCaseName)
  1651. for _, a := range as.Assets {
  1652. if math.IsNaN(a.TotalCost()) {
  1653. t.Fatalf("TestAssetSet_SanitizeNaN: Asset: expected not NaN for TotalCost(): expected NaN, got:%f", a.TotalCost())
  1654. }
  1655. if math.IsNaN(a.GetAdjustment()) {
  1656. t.Fatalf("TestAssetSet_SanitizeNaN: Asset: expected not NaN for GetAdjustment(): expected NaN, got:%f", a.GetAdjustment())
  1657. }
  1658. }
  1659. for _, any := range as.Any {
  1660. vAny := reflect.ValueOf(*any)
  1661. checkAllFloat64sForNaN(t, vAny, testCaseName)
  1662. }
  1663. for _, cloud := range as.Cloud {
  1664. vCloud := reflect.ValueOf(*cloud)
  1665. checkAllFloat64sForNaN(t, vCloud, testCaseName)
  1666. }
  1667. for _, cm := range as.ClusterManagement {
  1668. vCM := reflect.ValueOf(*cm)
  1669. checkAllFloat64sForNaN(t, vCM, testCaseName)
  1670. }
  1671. for _, disk := range as.Disks {
  1672. vDisk := reflect.ValueOf(*disk)
  1673. checkAllFloat64sForNaN(t, vDisk, testCaseName)
  1674. }
  1675. for _, network := range as.Network {
  1676. vNetwork := reflect.ValueOf(*network)
  1677. checkAllFloat64sForNaN(t, vNetwork, testCaseName)
  1678. }
  1679. for _, node := range as.Nodes {
  1680. vNode := reflect.ValueOf(*node)
  1681. checkAllFloat64sForNaN(t, vNode, testCaseName)
  1682. }
  1683. for _, sa := range as.SharedAssets {
  1684. vSA := reflect.ValueOf(*sa)
  1685. checkAllFloat64sForNaN(t, vSA, testCaseName)
  1686. }
  1687. }
  1688. func getMockAssetSet(f float64) AssetSet {
  1689. any := getMockAny(f)
  1690. cloud := getMockCloud(f)
  1691. cm := getMockClusterManagement(f)
  1692. disk := getMockDisk(f)
  1693. network := getMockNetwork(f)
  1694. node := getMockNode(f)
  1695. lb := getMockLoadBalancer(f)
  1696. sa := getMockSharedAsset(f)
  1697. assets := map[string]Asset{"any": &any, "cloud": &cloud}
  1698. as := AssetSet{
  1699. Assets: assets,
  1700. Any: map[string]*Any{"NaN": &any},
  1701. Cloud: map[string]*Cloud{"NaN": &cloud},
  1702. ClusterManagement: map[string]*ClusterManagement{"NaN": &cm},
  1703. Disks: map[string]*Disk{"NaN": &disk},
  1704. Network: map[string]*Network{"NaN": &network},
  1705. Nodes: map[string]*Node{"NaN": &node},
  1706. LoadBalancers: map[string]*LoadBalancer{"NaN": &lb},
  1707. SharedAssets: map[string]*SharedAsset{"NaN": &sa},
  1708. }
  1709. return as
  1710. }