expand_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package csstring_test
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/crowdsecurity/crowdsec/pkg/csstring"
  7. )
  8. func TestStrictExpand(t *testing.T) {
  9. t.Parallel()
  10. testenv := func(key string) (string, bool) {
  11. switch key {
  12. case "USER":
  13. return "testuser", true
  14. case "HOME":
  15. return "/home/testuser", true
  16. case "empty":
  17. return "", true
  18. default:
  19. return "", false
  20. }
  21. }
  22. home, _ := testenv("HOME")
  23. user, _ := testenv("USER")
  24. tests := []struct {
  25. input string
  26. expected string
  27. }{
  28. {
  29. input: "$HOME",
  30. expected: home,
  31. },
  32. {
  33. input: "${USER}",
  34. expected: user,
  35. },
  36. {
  37. input: "Hello, $USER!",
  38. expected: fmt.Sprintf("Hello, %s!", user),
  39. },
  40. {
  41. input: "My home directory is ${HOME}",
  42. expected: fmt.Sprintf("My home directory is %s", home),
  43. },
  44. {
  45. input: "This is a $SINGLE_VAR string with ${HOME}",
  46. expected: fmt.Sprintf("This is a $SINGLE_VAR string with %s", home),
  47. },
  48. {
  49. input: "This is a $SINGLE_VAR string with $HOME",
  50. expected: fmt.Sprintf("This is a $SINGLE_VAR string with %s", home),
  51. },
  52. {
  53. input: "This variable does not exist: $NON_EXISTENT_VAR",
  54. expected: "This variable does not exist: $NON_EXISTENT_VAR",
  55. },
  56. {
  57. input: "This is a $MULTI_VAR string with ${HOME} and ${USER}",
  58. expected: fmt.Sprintf("This is a $MULTI_VAR string with %s and %s", home, user),
  59. },
  60. {
  61. input: "This is a ${MULTI_VAR} string with $HOME and $USER",
  62. expected: fmt.Sprintf("This is a ${MULTI_VAR} string with %s and %s", home, user),
  63. },
  64. {
  65. input: "This is a plain string with no variables",
  66. expected: "This is a plain string with no variables",
  67. },
  68. {
  69. input: "$empty",
  70. expected: "",
  71. },
  72. {
  73. input: "",
  74. expected: "",
  75. },
  76. {
  77. input: "$USER:$empty:$HOME",
  78. expected: fmt.Sprintf("%s::%s", user, home),
  79. },
  80. }
  81. for _, tc := range tests {
  82. tc := tc
  83. t.Run(tc.input, func(t *testing.T) {
  84. t.Parallel()
  85. output := csstring.StrictExpand(tc.input, testenv)
  86. assert.Equal(t, tc.expected, output)
  87. })
  88. }
  89. }