sarif_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. "github.com/spf13/viper"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. "github.com/zricethezav/gitleaks/v8/config"
  10. )
  11. const configPath = "../testdata/config/"
  12. func TestWriteSarif(t *testing.T) {
  13. tests := []struct {
  14. findings []Finding
  15. testReportName string
  16. expected string
  17. wantEmpty bool
  18. cfgName string
  19. }{
  20. {
  21. cfgName: "simple",
  22. testReportName: "simple",
  23. expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
  24. findings: []Finding{
  25. {
  26. Description: "A test rule",
  27. RuleID: "test-rule",
  28. Match: "line containing secret",
  29. Secret: "a secret",
  30. StartLine: 1,
  31. EndLine: 2,
  32. StartColumn: 1,
  33. EndColumn: 2,
  34. Message: "opps",
  35. File: "auth.py",
  36. Commit: "0000000000000000",
  37. Author: "John Doe",
  38. Email: "johndoe@gmail.com",
  39. Date: "10-19-2003",
  40. Tags: []string{"tag1", "tag2", "tag3"},
  41. },
  42. }},
  43. }
  44. for _, test := range tests {
  45. t.Run(test.cfgName, func(t *testing.T) {
  46. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
  47. require.NoError(t, err)
  48. viper.Reset()
  49. viper.AddConfigPath(configPath)
  50. viper.SetConfigName(test.cfgName)
  51. viper.SetConfigType("toml")
  52. err = viper.ReadInConfig()
  53. require.NoError(t, err)
  54. var vc config.ViperConfig
  55. err = viper.Unmarshal(&vc)
  56. require.NoError(t, err)
  57. cfg, err := vc.Translate()
  58. require.NoError(t, err)
  59. err = writeSarif(cfg, test.findings, tmpfile)
  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. assert.Equal(t, string(want), string(got))
  71. })
  72. }
  73. }