env_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package opts // import "github.com/docker/docker/opts"
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "testing"
  7. "gotest.tools/v3/assert"
  8. )
  9. func TestValidateEnv(t *testing.T) {
  10. type testCase struct {
  11. value string
  12. expected string
  13. err error
  14. }
  15. tests := []testCase{
  16. {
  17. value: "a",
  18. expected: "a",
  19. },
  20. {
  21. value: "something",
  22. expected: "something",
  23. },
  24. {
  25. value: "_=a",
  26. expected: "_=a",
  27. },
  28. {
  29. value: "env1=value1",
  30. expected: "env1=value1",
  31. },
  32. {
  33. value: "_env1=value1",
  34. expected: "_env1=value1",
  35. },
  36. {
  37. value: "env2=value2=value3",
  38. expected: "env2=value2=value3",
  39. },
  40. {
  41. value: "env3=abc!qwe",
  42. expected: "env3=abc!qwe",
  43. },
  44. {
  45. value: "env_4=value 4",
  46. expected: "env_4=value 4",
  47. },
  48. {
  49. value: "PATH",
  50. expected: fmt.Sprintf("PATH=%v", os.Getenv("PATH")),
  51. },
  52. {
  53. value: "=a",
  54. err: fmt.Errorf("invalid environment variable: =a"),
  55. },
  56. {
  57. value: "PATH=",
  58. expected: "PATH=",
  59. },
  60. {
  61. value: "PATH=something",
  62. expected: "PATH=something",
  63. },
  64. {
  65. value: "asd!qwe",
  66. expected: "asd!qwe",
  67. },
  68. {
  69. value: "1asd",
  70. expected: "1asd",
  71. },
  72. {
  73. value: "123",
  74. expected: "123",
  75. },
  76. {
  77. value: "some space",
  78. expected: "some space",
  79. },
  80. {
  81. value: " some space before",
  82. expected: " some space before",
  83. },
  84. {
  85. value: "some space after ",
  86. expected: "some space after ",
  87. },
  88. {
  89. value: "=",
  90. err: fmt.Errorf("invalid environment variable: ="),
  91. },
  92. }
  93. if runtime.GOOS == "windows" {
  94. // Environment variables are case in-sensitive on Windows
  95. tests = append(tests, testCase{
  96. value: "PaTh",
  97. expected: fmt.Sprintf("PaTh=%v", os.Getenv("PATH")),
  98. err: nil,
  99. })
  100. }
  101. for _, tc := range tests {
  102. tc := tc
  103. t.Run(tc.value, func(t *testing.T) {
  104. actual, err := ValidateEnv(tc.value)
  105. if tc.err == nil {
  106. assert.NilError(t, err)
  107. } else {
  108. assert.Error(t, err, tc.err.Error())
  109. }
  110. assert.Equal(t, actual, tc.expected)
  111. })
  112. }
  113. }