sarif_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package report
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "testing"
  9. "github.com/spf13/viper"
  10. "github.com/zricethezav/gitleaks/v8/config"
  11. )
  12. const configPath = "../testdata/config/"
  13. func TestWriteSarif(t *testing.T) {
  14. tests := []struct {
  15. findings []Finding
  16. testReportName string
  17. expected string
  18. wantEmpty bool
  19. cfgName string
  20. }{
  21. {
  22. cfgName: "simple",
  23. testReportName: "simple",
  24. expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
  25. findings: []Finding{
  26. {
  27. Description: "A test rule",
  28. RuleID: "test-rule",
  29. Match: "line containing secret",
  30. Secret: "a secret",
  31. StartLine: 1,
  32. EndLine: 2,
  33. StartColumn: 1,
  34. EndColumn: 2,
  35. Message: "opps",
  36. File: "auth.py",
  37. Commit: "0000000000000000",
  38. Author: "John Doe",
  39. Email: "johndoe@gmail.com",
  40. Date: "10-19-2003",
  41. Tags: []string{"tag1", "tag2", "tag3"},
  42. },
  43. }},
  44. }
  45. for _, test := range tests {
  46. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
  47. if err != nil {
  48. t.Error(err)
  49. }
  50. viper.Reset()
  51. viper.AddConfigPath(configPath)
  52. viper.SetConfigName(test.cfgName)
  53. viper.SetConfigType("toml")
  54. err = viper.ReadInConfig()
  55. if err != nil {
  56. t.Error(err)
  57. }
  58. var vc config.ViperConfig
  59. err = viper.Unmarshal(&vc)
  60. if err != nil {
  61. t.Error(err)
  62. }
  63. cfg, err := vc.Translate()
  64. if err != nil {
  65. t.Error(err)
  66. }
  67. err = writeSarif(cfg, test.findings, tmpfile)
  68. fmt.Println(cfg)
  69. if err != nil {
  70. t.Error(err)
  71. }
  72. got, err := os.ReadFile(tmpfile.Name())
  73. if err != nil {
  74. t.Error(err)
  75. }
  76. if test.wantEmpty {
  77. if len(got) > 0 {
  78. t.Errorf("Expected empty file, got %s", got)
  79. }
  80. continue
  81. }
  82. want, err := os.ReadFile(test.expected)
  83. if err != nil {
  84. t.Error(err)
  85. }
  86. if !bytes.Equal(got, want) {
  87. err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
  88. if err != nil {
  89. t.Error(err)
  90. }
  91. t.Errorf("got %s, want %s", string(got), string(want))
  92. }
  93. }
  94. }