sarif_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. "github.com/zricethezav/gitleaks/v8/config"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func TestWriteSarif(t *testing.T) {
  11. tests := []struct {
  12. findings []Finding
  13. testReportName string
  14. expected string
  15. wantEmpty bool
  16. cfgName string
  17. }{
  18. {
  19. cfgName: "simple",
  20. testReportName: "simple",
  21. expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
  22. findings: []Finding{
  23. {
  24. RuleID: "test-rule",
  25. Description: "A test rule",
  26. Match: "line containing secret",
  27. Secret: "a secret",
  28. StartLine: 1,
  29. EndLine: 2,
  30. StartColumn: 1,
  31. EndColumn: 2,
  32. Message: "opps",
  33. File: "auth.py",
  34. Commit: "0000000000000000",
  35. Author: "John Doe",
  36. Email: "johndoe@gmail.com",
  37. Date: "10-19-2003",
  38. Tags: []string{"tag1", "tag2", "tag3"},
  39. },
  40. }},
  41. }
  42. for _, test := range tests {
  43. t.Run(test.cfgName, func(t *testing.T) {
  44. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
  45. require.NoError(t, err)
  46. defer tmpfile.Close()
  47. reporter := SarifReporter{
  48. OrderedRules: []config.Rule{
  49. {
  50. RuleID: "aws-access-key",
  51. Description: "AWS Access Key",
  52. },
  53. {
  54. RuleID: "pypi",
  55. Description: "PyPI upload token",
  56. },
  57. },
  58. }
  59. err = reporter.Write(tmpfile, test.findings)
  60. require.NoError(t, err)
  61. assert.FileExists(t, tmpfile.Name())
  62. got, err := os.ReadFile(tmpfile.Name())
  63. require.NoError(t, err)
  64. if test.wantEmpty {
  65. assert.Empty(t, got)
  66. return
  67. }
  68. want, err := os.ReadFile(test.expected)
  69. require.NoError(t, err)
  70. wantStr := lineEndingReplacer.Replace(string(want))
  71. gotStr := lineEndingReplacer.Replace(string(got))
  72. assert.Equal(t, wantStr, gotStr)
  73. })
  74. }
  75. }