sarif_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. viper.Unmarshal(&vc)
  60. cfg, err := vc.Translate()
  61. if err != nil {
  62. t.Error(err)
  63. }
  64. err = writeSarif(cfg, test.findings, tmpfile)
  65. if err != nil {
  66. os.Remove(tmpfile.Name())
  67. t.Error(err)
  68. }
  69. got, err := os.ReadFile(tmpfile.Name())
  70. if err != nil {
  71. os.Remove(tmpfile.Name())
  72. t.Error(err)
  73. }
  74. if test.wantEmpty {
  75. if len(got) > 0 {
  76. os.Remove(tmpfile.Name())
  77. t.Errorf("Expected empty file, got %s", got)
  78. }
  79. os.Remove(tmpfile.Name())
  80. continue
  81. }
  82. want, err := os.ReadFile(test.expected)
  83. if err != nil {
  84. os.Remove(tmpfile.Name())
  85. t.Error(err)
  86. }
  87. if string(got) != string(want) {
  88. err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
  89. if err != nil {
  90. t.Error(err)
  91. }
  92. t.Errorf("got %s, want %s", string(got), string(want))
  93. }
  94. os.Remove(tmpfile.Name())
  95. }
  96. }