json_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package report
  2. import (
  3. "bytes"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. )
  9. func TestWriteJSON(t *testing.T) {
  10. tests := []struct {
  11. findings []Finding
  12. testReportName string
  13. expected string
  14. wantEmpty bool
  15. }{
  16. {
  17. testReportName: "simple",
  18. expected: filepath.Join(expectPath, "report", "json_simple.json"),
  19. findings: []Finding{
  20. {
  21. Description: "",
  22. RuleID: "test-rule",
  23. Match: "line containing secret",
  24. Secret: "a secret",
  25. StartLine: 1,
  26. EndLine: 2,
  27. StartColumn: 1,
  28. EndColumn: 2,
  29. Message: "opps",
  30. File: "auth.py",
  31. SymlinkFile: "",
  32. Commit: "0000000000000000",
  33. Author: "John Doe",
  34. Email: "johndoe@gmail.com",
  35. Date: "10-19-2003",
  36. Tags: []string{},
  37. },
  38. }},
  39. {
  40. testReportName: "empty",
  41. expected: filepath.Join(expectPath, "report", "empty.json"),
  42. findings: []Finding{}},
  43. }
  44. for _, test := range tests {
  45. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
  46. if err != nil {
  47. t.Error(err)
  48. }
  49. err = writeJson(test.findings, tmpfile)
  50. if err != nil {
  51. t.Error(err)
  52. }
  53. got, err := os.ReadFile(tmpfile.Name())
  54. if err != nil {
  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. continue
  62. }
  63. want, err := os.ReadFile(test.expected)
  64. if err != nil {
  65. t.Error(err)
  66. }
  67. if !bytes.Equal(got, want) {
  68. err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644)
  69. if err != nil {
  70. t.Error(err)
  71. }
  72. t.Errorf("got %s, want %s", string(got), string(want))
  73. }
  74. }
  75. }