csv_test.go 1.8 KB

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