sarif_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package report
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. "github.com/spf13/viper"
  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{},
  41. },
  42. }},
  43. }
  44. for _, test := range tests {
  45. // create tmp file using os.TempDir()
  46. tmpfile, err := os.Create(filepath.Join(tmpPath, test.testReportName+".json"))
  47. if err != nil {
  48. os.Remove(tmpfile.Name())
  49. t.Error(err)
  50. }
  51. viper.Reset()
  52. viper.AddConfigPath(configPath)
  53. viper.SetConfigName(test.cfgName)
  54. viper.SetConfigType("toml")
  55. err = viper.ReadInConfig()
  56. if err != nil {
  57. t.Error(err)
  58. }
  59. var vc config.ViperConfig
  60. err = viper.Unmarshal(&vc)
  61. if err != nil {
  62. t.Error(err)
  63. }
  64. cfg, err := vc.Translate()
  65. if err != nil {
  66. t.Error(err)
  67. }
  68. err = writeSarif(cfg, test.findings, tmpfile)
  69. fmt.Println(cfg)
  70. if err != nil {
  71. os.Remove(tmpfile.Name())
  72. t.Error(err)
  73. }
  74. got, err := os.ReadFile(tmpfile.Name())
  75. if err != nil {
  76. os.Remove(tmpfile.Name())
  77. t.Error(err)
  78. }
  79. if test.wantEmpty {
  80. if len(got) > 0 {
  81. os.Remove(tmpfile.Name())
  82. t.Errorf("Expected empty file, got %s", got)
  83. }
  84. os.Remove(tmpfile.Name())
  85. continue
  86. }
  87. want, err := os.ReadFile(test.expected)
  88. if err != nil {
  89. os.Remove(tmpfile.Name())
  90. t.Error(err)
  91. }
  92. if string(got) != string(want) {
  93. err = os.WriteFile(strings.Replace(test.expected, ".sarif", ".got.sarif", 1), got, 0644)
  94. if err != nil {
  95. t.Error(err)
  96. }
  97. t.Errorf("got %s, want %s", string(got), string(want))
  98. }
  99. os.Remove(tmpfile.Name())
  100. }
  101. }