json_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. )
  8. func TestWriteJSON(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", "json_simple.json"),
  18. findings: []Finding{
  19. {
  20. Description: "",
  21. RuleID: "test-rule",
  22. Match: "line containing secret",
  23. Secret: "a secret",
  24. StartLine: 1,
  25. EndLine: 2,
  26. StartColumn: 1,
  27. EndColumn: 2,
  28. Message: "opps",
  29. File: "auth.py",
  30. Commit: "0000000000000000",
  31. Author: "John Doe",
  32. Email: "johndoe@gmail.com",
  33. Date: "10-19-2003",
  34. Tags: []string{},
  35. },
  36. }},
  37. {
  38. testReportName: "empty",
  39. expected: filepath.Join(expectPath, "report", "empty.json"),
  40. findings: []Finding{}},
  41. }
  42. for _, test := range tests {
  43. // create tmp file using os.TempDir()
  44. tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
  45. if err != nil {
  46. os.Remove(tmpfile.Name())
  47. t.Error(err)
  48. }
  49. err = writeJson(test.findings, tmpfile)
  50. if err != nil {
  51. os.Remove(tmpfile.Name())
  52. t.Error(err)
  53. }
  54. got, err := os.ReadFile(tmpfile.Name())
  55. if err != nil {
  56. os.Remove(tmpfile.Name())
  57. t.Error(err)
  58. }
  59. if test.wantEmpty {
  60. if len(got) > 0 {
  61. os.Remove(tmpfile.Name())
  62. t.Errorf("Expected empty file, got %s", got)
  63. }
  64. os.Remove(tmpfile.Name())
  65. continue
  66. }
  67. want, err := os.ReadFile(test.expected)
  68. if err != nil {
  69. os.Remove(tmpfile.Name())
  70. t.Error(err)
  71. }
  72. if string(got) != string(want) {
  73. err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644)
  74. if err != nil {
  75. t.Error(err)
  76. }
  77. t.Errorf("got %s, want %s", string(got), string(want))
  78. }
  79. os.Remove(tmpfile.Name())
  80. }
  81. }