template_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. func TestWriteTemplate(t *testing.T) {
  10. tests := []struct {
  11. findings []Finding
  12. testReportName string
  13. expected string
  14. wantEmpty bool
  15. }{
  16. {
  17. testReportName: "markdown",
  18. expected: filepath.Join(expectPath, "report", "template_markdown.md"),
  19. findings: []Finding{
  20. {
  21. RuleID: "test-rule",
  22. Description: "A 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. Commit: "0000000000000000",
  32. Author: "John Doe",
  33. Email: "johndoe@gmail.com",
  34. Date: "10-19-2003",
  35. Tags: []string{"tag1", "tag2", "tag3"},
  36. },
  37. },
  38. },
  39. {
  40. testReportName: "jsonextra",
  41. expected: filepath.Join(expectPath, "report", "template_jsonextra.json"),
  42. findings: []Finding{
  43. {
  44. RuleID: "test-rule",
  45. Description: "A test rule",
  46. Line: "whole line containing secret",
  47. Match: "line containing secret",
  48. Secret: "a secret",
  49. StartLine: 1,
  50. EndLine: 2,
  51. StartColumn: 1,
  52. EndColumn: 2,
  53. Message: "opps",
  54. File: "auth.py",
  55. Commit: "0000000000000000",
  56. Author: "John Doe",
  57. Email: "johndoe@gmail.com",
  58. Date: "10-19-2003",
  59. Tags: []string{"tag1", "tag2", "tag3"},
  60. },
  61. },
  62. },
  63. }
  64. for _, test := range tests {
  65. t.Run(test.testReportName, func(t *testing.T) {
  66. reporter, err := NewTemplateReporter(templatePath + test.testReportName + ".tmpl")
  67. require.NoError(t, err)
  68. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+filepath.Ext(test.expected)))
  69. require.NoError(t, err)
  70. err = reporter.Write(tmpfile, test.findings)
  71. require.NoError(t, err)
  72. assert.FileExists(t, tmpfile.Name())
  73. got, err := os.ReadFile(tmpfile.Name())
  74. require.NoError(t, err)
  75. if test.wantEmpty {
  76. assert.Empty(t, got)
  77. return
  78. }
  79. want, err := os.ReadFile(test.expected)
  80. require.NoError(t, err)
  81. assert.Equal(t, string(want), string(got))
  82. })
  83. }
  84. }