csv_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. )
  8. func TestWriteCSV(t *testing.T) {
  9. tests := []struct {
  10. findings []Finding
  11. testReportName string
  12. expected string
  13. wantEmpty bool
  14. }{
  15. {
  16. testReportName: "simple",
  17. expected: filepath.Join(expectPath, "report", "csv_simple.csv"),
  18. findings: []Finding{
  19. {
  20. RuleID: "test-rule",
  21. Match: "line containing secret",
  22. Secret: "a secret",
  23. StartLine: 1,
  24. EndLine: 2,
  25. StartColumn: 1,
  26. EndColumn: 2,
  27. Message: "opps",
  28. File: "auth.py",
  29. SymlinkFile: "",
  30. Commit: "0000000000000000",
  31. Author: "John Doe",
  32. Email: "johndoe@gmail.com",
  33. Date: "10-19-2003",
  34. Fingerprint: "fingerprint",
  35. },
  36. }},
  37. {
  38. wantEmpty: true,
  39. testReportName: "empty",
  40. expected: filepath.Join(expectPath, "report", "this_should_not_exist.csv"),
  41. findings: []Finding{}},
  42. }
  43. for _, test := range tests {
  44. tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".csv"))
  45. if err != nil {
  46. os.Remove(tmpfile.Name())
  47. t.Error(err)
  48. }
  49. err = writeCsv(test.findings, tmpfile)
  50. if err != nil {
  51. os.Remove(tmpfile.Name())
  52. t.Error(err)
  53. }
  54. got, err := os.ReadFile(tmpfile.Name())
  55. if err != nil {
  56. os.Remove(tmpfile.Name())
  57. t.Error(err)
  58. }
  59. if test.wantEmpty {
  60. if len(got) > 0 {
  61. t.Errorf("Expected empty file, got %s", got)
  62. }
  63. os.Remove(tmpfile.Name())
  64. continue
  65. }
  66. want, err := os.ReadFile(test.expected)
  67. if err != nil {
  68. os.Remove(tmpfile.Name())
  69. t.Error(err)
  70. }
  71. if string(got) != string(want) {
  72. err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644)
  73. if err != nil {
  74. t.Error(err)
  75. }
  76. t.Errorf("got %s, want %s", string(got), string(want))
  77. }
  78. os.Remove(tmpfile.Name())
  79. }
  80. }