csv_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. Commit: "0000000000000000",
  30. Author: "John Doe",
  31. Email: "johndoe@gmail.com",
  32. Date: "10-19-2003",
  33. },
  34. }},
  35. {
  36. wantEmpty: true,
  37. testReportName: "empty",
  38. expected: filepath.Join(expectPath, "report", "this_should_not_exist.csv"),
  39. findings: []*Finding{}},
  40. }
  41. for _, test := range tests {
  42. tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".csv"))
  43. if err != nil {
  44. os.Remove(tmpfile.Name())
  45. t.Error(err)
  46. }
  47. err = writeCsv(test.findings, tmpfile)
  48. if err != nil {
  49. os.Remove(tmpfile.Name())
  50. t.Error(err)
  51. }
  52. got, err := os.ReadFile(tmpfile.Name())
  53. if err != nil {
  54. os.Remove(tmpfile.Name())
  55. t.Error(err)
  56. }
  57. if test.wantEmpty {
  58. if len(got) > 0 {
  59. t.Errorf("Expected empty file, got %s", got)
  60. }
  61. os.Remove(tmpfile.Name())
  62. continue
  63. }
  64. want, err := os.ReadFile(test.expected)
  65. if err != nil {
  66. os.Remove(tmpfile.Name())
  67. t.Error(err)
  68. }
  69. if string(got) != string(want) {
  70. err = os.WriteFile(strings.Replace(test.expected, ".csv", ".got.csv", 1), got, 0644)
  71. if err != nil {
  72. t.Error(err)
  73. }
  74. t.Errorf("got %s, want %s", string(got), string(want))
  75. }
  76. os.Remove(tmpfile.Name())
  77. }
  78. }