sarif_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "github.com/spf13/viper"
  8. "github.com/zricethezav/gitleaks/v8/config"
  9. )
  10. const configPath = "../testdata/config/"
  11. func TestWriteSarif(t *testing.T) {
  12. tests := []struct {
  13. findings []Finding
  14. testReportName string
  15. expected string
  16. wantEmpty bool
  17. cfgName string
  18. }{
  19. {
  20. cfgName: "simple",
  21. testReportName: "simple",
  22. expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
  23. findings: []Finding{
  24. {
  25. Description: "",
  26. RuleID: "test-rule",
  27. Match: "line containing secret",
  28. Secret: "a secret",
  29. StartLine: 1,
  30. EndLine: 2,
  31. StartColumn: 1,
  32. EndColumn: 2,
  33. Message: "opps",
  34. File: "auth.py",
  35. Commit: "0000000000000000",
  36. Author: "John Doe",
  37. Email: "johndoe@gmail.com",
  38. Date: "10-19-2003",
  39. Tags: []string{},
  40. },
  41. }},
  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. 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. if err != nil {
  69. os.Remove(tmpfile.Name())
  70. t.Error(err)
  71. }
  72. got, err := os.ReadFile(tmpfile.Name())
  73. if err != nil {
  74. os.Remove(tmpfile.Name())
  75. t.Error(err)
  76. }
  77. if test.wantEmpty {
  78. if len(got) > 0 {
  79. os.Remove(tmpfile.Name())
  80. t.Errorf("Expected empty file, got %s", got)
  81. }
  82. os.Remove(tmpfile.Name())
  83. continue
  84. }
  85. want, err := os.ReadFile(test.expected)
  86. if err != nil {
  87. os.Remove(tmpfile.Name())
  88. t.Error(err)
  89. }
  90. if string(got) != string(want) {
  91. err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
  92. if err != nil {
  93. t.Error(err)
  94. }
  95. t.Errorf("got %s, want %s", string(got), string(want))
  96. }
  97. os.Remove(tmpfile.Name())
  98. }
  99. }