json_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/require"
  8. )
  9. var simpleFinding = Finding{
  10. Description: "",
  11. RuleID: "test-rule",
  12. Match: "line containing secret",
  13. Secret: "a secret",
  14. StartLine: 1,
  15. EndLine: 2,
  16. StartColumn: 1,
  17. EndColumn: 2,
  18. Message: "opps",
  19. File: "auth.py",
  20. SymlinkFile: "",
  21. Commit: "0000000000000000",
  22. Author: "John Doe",
  23. Email: "johndoe@gmail.com",
  24. Date: "10-19-2003",
  25. Tags: []string{},
  26. }
  27. func TestWriteJSON(t *testing.T) {
  28. tests := []struct {
  29. findings []Finding
  30. testReportName string
  31. expected string
  32. wantEmpty bool
  33. }{
  34. {
  35. testReportName: "simple",
  36. expected: filepath.Join(expectPath, "report", "json_simple.json"),
  37. findings: []Finding{
  38. simpleFinding,
  39. }},
  40. {
  41. testReportName: "empty",
  42. expected: filepath.Join(expectPath, "report", "empty.json"),
  43. findings: []Finding{}},
  44. }
  45. reporter := JsonReporter{}
  46. for _, test := range tests {
  47. t.Run(test.testReportName, func(t *testing.T) {
  48. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
  49. require.NoError(t, err)
  50. err = reporter.Write(tmpfile, test.findings)
  51. require.NoError(t, err)
  52. assert.FileExists(t, tmpfile.Name())
  53. got, err := os.ReadFile(tmpfile.Name())
  54. require.NoError(t, err)
  55. if test.wantEmpty {
  56. assert.Empty(t, got)
  57. return
  58. }
  59. want, err := os.ReadFile(test.expected)
  60. require.NoError(t, err)
  61. assert.Equal(t, string(want), string(got))
  62. })
  63. }
  64. }