4
0

json_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. defer tmpfile.Close()
  51. err = reporter.Write(tmpfile, test.findings)
  52. require.NoError(t, err)
  53. assert.FileExists(t, tmpfile.Name())
  54. got, err := os.ReadFile(tmpfile.Name())
  55. require.NoError(t, err)
  56. if test.wantEmpty {
  57. assert.Empty(t, got)
  58. return
  59. }
  60. want, err := os.ReadFile(test.expected)
  61. require.NoError(t, err)
  62. wantStr := lineEndingReplacer.Replace(string(want))
  63. gotStr := lineEndingReplacer.Replace(string(got))
  64. assert.Equal(t, wantStr, gotStr)
  65. })
  66. }
  67. }