junit_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package report
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. )
  8. func TestWriteJunit(t *testing.T) {
  9. tests := []struct {
  10. findings []Finding
  11. testReportName string
  12. expected string
  13. wantEmpty bool
  14. }{
  15. {
  16. testReportName: "simple",
  17. expected: filepath.Join(expectPath, "report", "junit_simple.xml"),
  18. findings: []Finding{
  19. {
  20. Description: "Test Rule",
  21. RuleID: "test-rule",
  22. Match: "line containing secret",
  23. Secret: "a secret",
  24. StartLine: 1,
  25. EndLine: 2,
  26. StartColumn: 1,
  27. EndColumn: 2,
  28. Message: "opps",
  29. File: "auth.py",
  30. Commit: "0000000000000000",
  31. Author: "John Doe",
  32. Email: "johndoe@gmail.com",
  33. Date: "10-19-2003",
  34. Tags: []string{},
  35. },
  36. {
  37. Description: "Test Rule",
  38. RuleID: "test-rule",
  39. Match: "line containing secret",
  40. Secret: "a secret",
  41. StartLine: 2,
  42. EndLine: 3,
  43. StartColumn: 1,
  44. EndColumn: 2,
  45. Message: "",
  46. File: "auth.py",
  47. Commit: "",
  48. Author: "",
  49. Email: "",
  50. Date: "",
  51. Tags: []string{},
  52. },
  53. },
  54. },
  55. {
  56. testReportName: "empty",
  57. expected: filepath.Join(expectPath, "report", "junit_empty.xml"),
  58. findings: []Finding{},
  59. },
  60. }
  61. for _, test := range tests {
  62. // create tmp file using os.TempDir()
  63. tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".xml"))
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. err = writeJunit(test.findings, tmpfile)
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. got, err := os.ReadFile(tmpfile.Name())
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. if test.wantEmpty {
  76. if len(got) > 0 {
  77. t.Errorf("Expected empty file, got %s", got)
  78. }
  79. continue
  80. }
  81. want, err := os.ReadFile(test.expected)
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. if string(got) != string(want) {
  86. err = os.WriteFile(strings.Replace(test.expected, ".xml", ".got.xml", 1), got, 0644)
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. t.Errorf("got %s, want %s", string(got), string(want))
  91. }
  92. }
  93. }