test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. package storage
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "testing"
  11. "github.com/opencost/opencost/core/pkg/util/json"
  12. )
  13. type testFileContent struct {
  14. Field1 int `json:"field_1"`
  15. Field2 string `json:"field_2"`
  16. }
  17. var tfc = testFileContent{
  18. Field1: 101,
  19. Field2: "TEST_FILE_CONTENT",
  20. }
  21. const testpath = "opencost/storage/"
  22. func createFiles(files []string, testName string, store Storage) error {
  23. b, err := json.Marshal(tfc)
  24. if err != nil {
  25. return fmt.Errorf("failed to marshal file content: %w", err)
  26. }
  27. for _, fileName := range files {
  28. filePath := path.Join(testpath, testName, fileName)
  29. err = store.Write(filePath, b)
  30. if err != nil {
  31. return fmt.Errorf("failed to write file '%s': %w ", filePath, err)
  32. }
  33. }
  34. return nil
  35. }
  36. func cleanupFiles(files []string, testName string, store Storage) error {
  37. for _, fileName := range files {
  38. filePath := path.Join(testpath, testName, fileName)
  39. err := store.Remove(filePath)
  40. if err != nil {
  41. return fmt.Errorf("failed to remove file '%s': %w ", filePath, err)
  42. }
  43. }
  44. return nil
  45. }
  46. func TestStorageList(t *testing.T, store Storage) {
  47. testName := "list"
  48. fileNames := []string{
  49. "/file0.json",
  50. "/file1.json",
  51. "/dir0/file2.json",
  52. "/dir0/file3.json",
  53. }
  54. err := createFiles(fileNames, testName, store)
  55. if err != nil {
  56. t.Errorf("failed to create files: %s", err)
  57. }
  58. defer func() {
  59. err = cleanupFiles(fileNames, testName, store)
  60. if err != nil {
  61. t.Errorf("failed to clean up files: %s", err)
  62. }
  63. }()
  64. testCases := map[string]struct {
  65. path string
  66. expected []string
  67. expectErr bool
  68. }{
  69. "base dir files": {
  70. path: path.Join(testpath, testName),
  71. expected: []string{
  72. "file0.json",
  73. "file1.json",
  74. },
  75. expectErr: false,
  76. },
  77. "single nested dir files": {
  78. path: path.Join(testpath, testName, "dir0"),
  79. expected: []string{
  80. "file2.json",
  81. "file3.json",
  82. },
  83. expectErr: false,
  84. },
  85. "nonexistent dir files": {
  86. path: path.Join(testpath, testName, "dir1"),
  87. expected: []string{},
  88. expectErr: false,
  89. },
  90. }
  91. for name, tc := range testCases {
  92. t.Run(name, func(t *testing.T) {
  93. fileList, err := store.List(tc.path)
  94. if tc.expectErr == (err == nil) {
  95. if tc.expectErr {
  96. t.Errorf("expected error was not thrown")
  97. return
  98. }
  99. t.Errorf("unexpected error: %s", err.Error())
  100. return
  101. }
  102. if len(fileList) != len(tc.expected) {
  103. t.Errorf("file list length does not match expected length, actual: %d, expected: %d", len(fileList), len(tc.expected))
  104. }
  105. expectedSet := map[string]struct{}{}
  106. for _, expName := range tc.expected {
  107. expectedSet[expName] = struct{}{}
  108. }
  109. for _, file := range fileList {
  110. _, ok := expectedSet[file.Name]
  111. if !ok {
  112. t.Errorf("unexpect file in list %s", file.Name)
  113. }
  114. if file.Size == 0 {
  115. t.Errorf("file size is not set")
  116. }
  117. if file.ModTime.IsZero() {
  118. t.Errorf("file mod time is not set")
  119. }
  120. }
  121. })
  122. }
  123. }
  124. func TestStorageListDirectories(t *testing.T, store Storage) {
  125. testName := "list_directories"
  126. fileNames := []string{
  127. "/file0.json",
  128. "/dir0/file2.json",
  129. "/dir0/file3.json",
  130. "/dir0/dir1/file4.json",
  131. "/dir0/dir2/file5.json",
  132. }
  133. err := createFiles(fileNames, testName, store)
  134. if err != nil {
  135. t.Errorf("failed to create files: %s", err)
  136. }
  137. defer func() {
  138. err = cleanupFiles(fileNames, testName, store)
  139. if err != nil {
  140. t.Errorf("failed to clean up files: %s", err)
  141. }
  142. }()
  143. testCases := map[string]struct {
  144. path string
  145. expected []string
  146. expectErr bool
  147. }{
  148. "root dir dir": {
  149. path: "",
  150. expected: []string{
  151. strings.Split(testpath, "/")[0] + "/",
  152. },
  153. expectErr: false,
  154. },
  155. "base dir dir": {
  156. path: path.Join(testpath, testName),
  157. expected: []string{
  158. path.Join(testpath, testName, "dir0") + "/",
  159. },
  160. expectErr: false,
  161. },
  162. "single nested dir files": {
  163. path: path.Join(testpath, testName, "dir0"),
  164. expected: []string{
  165. path.Join(testpath, testName, "dir0", "dir1") + "/",
  166. path.Join(testpath, testName, "dir0", "dir2") + "/",
  167. },
  168. expectErr: false,
  169. },
  170. "dir with no sub dirs": {
  171. path: path.Join(testpath, testName, "dir0/dir1"),
  172. expected: []string{},
  173. expectErr: false,
  174. },
  175. "non-existent dir": {
  176. path: path.Join(testpath, testName, "dir1"),
  177. expected: []string{},
  178. expectErr: false,
  179. },
  180. }
  181. for name, tc := range testCases {
  182. t.Run(name, func(t *testing.T) {
  183. dirList, err := store.ListDirectories(tc.path)
  184. if tc.expectErr == (err == nil) {
  185. if tc.expectErr {
  186. t.Errorf("expected error was not thrown")
  187. return
  188. }
  189. t.Errorf("unexpected error: %s", err.Error())
  190. return
  191. }
  192. if len(dirList) != len(tc.expected) {
  193. t.Errorf("dir list length does not match expected length, actual: %d, expected: %d", len(dirList), len(tc.expected))
  194. }
  195. expectedSet := map[string]struct{}{}
  196. for _, expName := range tc.expected {
  197. expectedSet[expName] = struct{}{}
  198. }
  199. for _, dir := range dirList {
  200. _, ok := expectedSet[dir.Name]
  201. if !ok {
  202. t.Errorf("unexpect dir in list %s", dir.Name)
  203. }
  204. }
  205. })
  206. }
  207. }
  208. func TestStorageExists(t *testing.T, store Storage) {
  209. testName := "exists"
  210. fileNames := []string{
  211. "/file0.json",
  212. }
  213. err := createFiles(fileNames, testName, store)
  214. if err != nil {
  215. t.Errorf("failed to create files: %s", err)
  216. }
  217. defer func() {
  218. err = cleanupFiles(fileNames, testName, store)
  219. if err != nil {
  220. t.Errorf("failed to clean up files: %s", err)
  221. }
  222. }()
  223. testCases := map[string]struct {
  224. path string
  225. expected bool
  226. expectErr bool
  227. }{
  228. "file exists": {
  229. path: path.Join(testpath, testName, "file0.json"),
  230. expected: true,
  231. expectErr: false,
  232. },
  233. "file does not exist": {
  234. path: path.Join(testpath, testName, "file1.json"),
  235. expected: false,
  236. expectErr: false,
  237. },
  238. "dir does not exist": {
  239. path: path.Join(testpath, testName, "dir0/file.json"),
  240. expected: false,
  241. expectErr: false,
  242. },
  243. }
  244. for name, tc := range testCases {
  245. t.Run(name, func(t *testing.T) {
  246. exists, err := store.Exists(tc.path)
  247. if tc.expectErr == (err == nil) {
  248. if tc.expectErr {
  249. t.Errorf("expected error was not thrown")
  250. return
  251. }
  252. t.Errorf("unexpected error: %s", err.Error())
  253. return
  254. }
  255. if exists != tc.expected {
  256. t.Errorf("file exists output did not match expected")
  257. }
  258. })
  259. }
  260. }
  261. func TestStorageRead(t *testing.T, store Storage) {
  262. testName := "read"
  263. fileNames := []string{
  264. "/file0.json",
  265. }
  266. err := createFiles(fileNames, testName, store)
  267. if err != nil {
  268. t.Errorf("failed to create files: %s", err)
  269. }
  270. defer func() {
  271. err = cleanupFiles(fileNames, testName, store)
  272. if err != nil {
  273. t.Errorf("failed to clean up files: %s", err)
  274. }
  275. }()
  276. testCases := map[string]struct {
  277. path string
  278. expectErr bool
  279. }{
  280. "file exists": {
  281. path: path.Join(testpath, testName, "file0.json"),
  282. expectErr: false,
  283. },
  284. "file does not exist": {
  285. path: path.Join(testpath, testName, "file1.json"),
  286. expectErr: true,
  287. },
  288. "dir does not exist": {
  289. path: path.Join(testpath, testName, "dir0/file.json"),
  290. expectErr: true,
  291. },
  292. }
  293. for name, tc := range testCases {
  294. t.Run(name, func(t *testing.T) {
  295. b, err := store.Read(tc.path)
  296. if tc.expectErr && err != nil {
  297. return
  298. }
  299. if tc.expectErr == (err == nil) {
  300. if tc.expectErr {
  301. t.Errorf("expected error was not thrown")
  302. return
  303. }
  304. t.Errorf("unexpected error: %s", err.Error())
  305. return
  306. }
  307. var content testFileContent
  308. err = json.Unmarshal(b, &content)
  309. if err != nil {
  310. t.Errorf("could not unmarshal file content")
  311. return
  312. }
  313. if content != tfc {
  314. t.Errorf("file content did not match writen value")
  315. }
  316. })
  317. }
  318. }
  319. func TestStorageStat(t *testing.T, store Storage) {
  320. testName := "stat"
  321. fileNames := []string{
  322. "/file0.json",
  323. }
  324. err := createFiles(fileNames, testName, store)
  325. if err != nil {
  326. t.Errorf("failed to create files: %s", err)
  327. }
  328. defer func() {
  329. err = cleanupFiles(fileNames, testName, store)
  330. if err != nil {
  331. t.Errorf("failed to clean up files: %s", err)
  332. }
  333. }()
  334. testCases := map[string]struct {
  335. path string
  336. expected *StorageInfo
  337. expectErr bool
  338. }{
  339. "base dir": {
  340. path: path.Join(testpath, testName, "file0.json"),
  341. expected: &StorageInfo{
  342. Name: "file0.json",
  343. Size: 45,
  344. },
  345. expectErr: false,
  346. },
  347. "file does not exist": {
  348. path: path.Join(testpath, testName, "file1.json"),
  349. expected: nil,
  350. expectErr: true,
  351. },
  352. }
  353. for name, tc := range testCases {
  354. t.Run(name, func(t *testing.T) {
  355. status, err := store.Stat(tc.path)
  356. if tc.expectErr && err != nil {
  357. return
  358. }
  359. if tc.expectErr == (err == nil) {
  360. if tc.expectErr {
  361. t.Errorf("expected error was not thrown")
  362. return
  363. }
  364. t.Errorf("unexpected error: %s", err.Error())
  365. return
  366. }
  367. if status.Name != tc.expected.Name {
  368. t.Errorf("status name did name match expected, actual: %s, expected: %s", status.Name, tc.expected.Name)
  369. }
  370. if status.Size != tc.expected.Size {
  371. t.Errorf("status name did size match expected, actual: %d, expected: %d", status.Size, tc.expected.Size)
  372. }
  373. if status.ModTime.IsZero() {
  374. t.Errorf("status mod time is not set")
  375. }
  376. })
  377. }
  378. }
  379. func TestStorageReadToLocalFile(t *testing.T, store Storage) {
  380. testName := "read_to_local_file"
  381. fileNames := []string{
  382. "/file0.json",
  383. }
  384. err := createFiles(fileNames, testName, store)
  385. if err != nil {
  386. t.Fatalf("failed to create files: %s", err)
  387. }
  388. defer func() {
  389. err = cleanupFiles(fileNames, testName, store)
  390. if err != nil {
  391. t.Fatalf("failed to clean up files: %s", err)
  392. }
  393. }()
  394. testCases := map[string]struct {
  395. path string
  396. expectErr bool
  397. }{
  398. "file exists": {
  399. path: path.Join(testpath, testName, "file0.json"),
  400. expectErr: false,
  401. },
  402. "file does not exist": {
  403. path: path.Join(testpath, testName, "file1.json"),
  404. expectErr: true,
  405. },
  406. "dir does not exist": {
  407. path: path.Join(testpath, testName, "dir0/file.json"),
  408. expectErr: true,
  409. },
  410. }
  411. for name, tc := range testCases {
  412. t.Run(name, func(t *testing.T) {
  413. destPath := filepath.Join(t.TempDir(), "out.json")
  414. err := store.ReadToLocalFile(tc.path, destPath)
  415. if tc.expectErr {
  416. if err == nil {
  417. t.Fatalf("expected error was not thrown")
  418. }
  419. return
  420. }
  421. if err != nil {
  422. t.Fatalf("unexpected error: %s", err.Error())
  423. }
  424. b, err := os.ReadFile(destPath)
  425. if err != nil {
  426. t.Fatalf("reading destination file: %s", err)
  427. }
  428. var content testFileContent
  429. err = json.Unmarshal(b, &content)
  430. if err != nil {
  431. t.Fatalf("could not unmarshal file content: %s", err)
  432. }
  433. if content != tfc {
  434. t.Fatalf("file content did not match written value")
  435. }
  436. })
  437. }
  438. }
  439. func TestStorageWriteStream(t *testing.T, store Storage) {
  440. testName := "write_stream"
  441. testCases := map[string]struct {
  442. path string
  443. chunks [][]byte
  444. prewrite bool
  445. }{
  446. "single chunk": {
  447. path: path.Join(testpath, testName, "single.bin"),
  448. chunks: [][]byte{[]byte("single chunk data")},
  449. },
  450. "multi-chunk": {
  451. path: path.Join(testpath, testName, "multi.bin"),
  452. chunks: [][]byte{[]byte("alpha"), []byte("beta"), []byte("gamma")},
  453. },
  454. "nested path": {
  455. path: path.Join(testpath, testName, "sub/dir/data.bin"),
  456. chunks: [][]byte{[]byte("nested data")},
  457. },
  458. "empty content": {
  459. path: path.Join(testpath, testName, "empty.bin"),
  460. chunks: [][]byte{},
  461. },
  462. "overwrite existing": {
  463. path: path.Join(testpath, testName, "overwrite.bin"),
  464. chunks: [][]byte{[]byte("replaced content")},
  465. prewrite: true,
  466. },
  467. }
  468. for name, tc := range testCases {
  469. t.Run(name, func(t *testing.T) {
  470. defer store.Remove(tc.path)
  471. if tc.prewrite {
  472. b, err := json.Marshal(tfc)
  473. if err != nil {
  474. t.Fatalf("marshal fixture: %s", err)
  475. }
  476. if err = store.Write(tc.path, b); err != nil {
  477. t.Fatalf("pre-write: %s", err)
  478. }
  479. }
  480. var want []byte
  481. for _, chunk := range tc.chunks {
  482. want = append(want, chunk...)
  483. }
  484. w, err := store.WriteStream(tc.path)
  485. if err != nil {
  486. t.Fatalf("WriteStream: %s", err)
  487. }
  488. for _, chunk := range tc.chunks {
  489. n, writeErr := w.Write(chunk)
  490. if writeErr != nil {
  491. _ = w.Close()
  492. t.Fatalf("Write: %s", writeErr)
  493. }
  494. if n != len(chunk) {
  495. _ = w.Close()
  496. t.Fatalf("short write: wrote %d of %d bytes", n, len(chunk))
  497. }
  498. }
  499. if err = w.Close(); err != nil {
  500. t.Fatalf("Close: %s", err)
  501. }
  502. got, err := store.Read(tc.path)
  503. if err != nil {
  504. t.Fatalf("Read after WriteStream: %s", err)
  505. }
  506. if !bytes.Equal(got, want) {
  507. t.Errorf("content mismatch: got %q, want %q", got, want)
  508. }
  509. })
  510. }
  511. }
  512. func TestStorageReadStream(t *testing.T, store Storage) {
  513. testName := "read_stream"
  514. fileNames := []string{
  515. "/file0.json",
  516. }
  517. err := createFiles(fileNames, testName, store)
  518. if err != nil {
  519. t.Fatalf("failed to create files: %s", err)
  520. }
  521. defer func() {
  522. err = cleanupFiles(fileNames, testName, store)
  523. if err != nil {
  524. t.Fatalf("failed to clean up files: %s", err)
  525. }
  526. }()
  527. testCases := map[string]struct {
  528. path string
  529. expectErr bool
  530. }{
  531. "file exists": {
  532. path: path.Join(testpath, testName, "file0.json"),
  533. expectErr: false,
  534. },
  535. "file does not exist": {
  536. path: path.Join(testpath, testName, "file1.json"),
  537. expectErr: true,
  538. },
  539. "dir does not exist": {
  540. path: path.Join(testpath, testName, "dir0/file.json"),
  541. expectErr: true,
  542. },
  543. }
  544. for name, tc := range testCases {
  545. t.Run(name, func(t *testing.T) {
  546. r, err := store.ReadStream(tc.path)
  547. if tc.expectErr {
  548. if err == nil {
  549. if r != nil {
  550. _ = r.Close()
  551. }
  552. t.Fatalf("expected error was not thrown")
  553. }
  554. return
  555. }
  556. if err != nil {
  557. t.Fatalf("unexpected error: %s", err.Error())
  558. }
  559. defer r.Close()
  560. b, err := io.ReadAll(r)
  561. if err != nil {
  562. t.Fatalf("reading stream: %s", err)
  563. }
  564. var content testFileContent
  565. err = json.Unmarshal(b, &content)
  566. if err != nil {
  567. t.Fatalf("could not unmarshal file content: %s", err)
  568. }
  569. if content != tfc {
  570. t.Fatalf("file content did not match written value")
  571. }
  572. })
  573. }
  574. }