json_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. SymlinkFile: "",
  31. Commit: "0000000000000000",
  32. Author: "John Doe",
  33. Email: "johndoe@gmail.com",
  34. Date: "10-19-2003",
  35. Tags: []string{},
  36. },
  37. }},
  38. {
  39. testReportName: "empty",
  40. expected: filepath.Join(expectPath, "report", "empty.json"),
  41. findings: []Finding{}},
  42. }
  43. for _, test := range tests {
  44. // create tmp file using os.TempDir()
  45. tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
  46. if err != nil {
  47. os.Remove(tmpfile.Name())
  48. t.Error(err)
  49. }
  50. err = writeJson(test.findings, tmpfile)
  51. if err != nil {
  52. os.Remove(tmpfile.Name())
  53. t.Error(err)
  54. }
  55. got, err := os.ReadFile(tmpfile.Name())
  56. if err != nil {
  57. os.Remove(tmpfile.Name())
  58. t.Error(err)
  59. }
  60. if test.wantEmpty {
  61. if len(got) > 0 {
  62. os.Remove(tmpfile.Name())
  63. t.Errorf("Expected empty file, got %s", got)
  64. }
  65. os.Remove(tmpfile.Name())
  66. continue
  67. }
  68. want, err := os.ReadFile(test.expected)
  69. if err != nil {
  70. os.Remove(tmpfile.Name())
  71. t.Error(err)
  72. }
  73. if string(got) != string(want) {
  74. err = os.WriteFile(strings.Replace(test.expected, ".json", ".got.json", 1), got, 0644)
  75. if err != nil {
  76. t.Error(err)
  77. }
  78. t.Errorf("got %s, want %s", string(got), string(want))
  79. }
  80. os.Remove(tmpfile.Name())
  81. }
  82. }