options_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*
  2. Copyright 2023 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "testing"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/docker/cli/cli/streams"
  24. "github.com/docker/compose/v2/pkg/mocks"
  25. "github.com/stretchr/testify/require"
  26. "go.uber.org/mock/gomock"
  27. )
  28. func TestApplyPlatforms_InferFromRuntime(t *testing.T) {
  29. makeProject := func() *types.Project {
  30. return &types.Project{
  31. Services: types.Services{
  32. "test": {
  33. Name: "test",
  34. Image: "foo",
  35. Build: &types.BuildConfig{
  36. Context: ".",
  37. Platforms: []string{
  38. "linux/amd64",
  39. "linux/arm64",
  40. "alice/32",
  41. },
  42. },
  43. Platform: "alice/32",
  44. },
  45. },
  46. }
  47. }
  48. t.Run("SinglePlatform", func(t *testing.T) {
  49. project := makeProject()
  50. require.NoError(t, applyPlatforms(project, true))
  51. require.EqualValues(t, []string{"alice/32"}, project.Services["test"].Build.Platforms)
  52. })
  53. t.Run("MultiPlatform", func(t *testing.T) {
  54. project := makeProject()
  55. require.NoError(t, applyPlatforms(project, false))
  56. require.EqualValues(t, []string{"linux/amd64", "linux/arm64", "alice/32"},
  57. project.Services["test"].Build.Platforms)
  58. })
  59. }
  60. func TestApplyPlatforms_DockerDefaultPlatform(t *testing.T) {
  61. makeProject := func() *types.Project {
  62. return &types.Project{
  63. Environment: map[string]string{
  64. "DOCKER_DEFAULT_PLATFORM": "linux/amd64",
  65. },
  66. Services: types.Services{
  67. "test": {
  68. Name: "test",
  69. Image: "foo",
  70. Build: &types.BuildConfig{
  71. Context: ".",
  72. Platforms: []string{
  73. "linux/amd64",
  74. "linux/arm64",
  75. },
  76. },
  77. },
  78. },
  79. }
  80. }
  81. t.Run("SinglePlatform", func(t *testing.T) {
  82. project := makeProject()
  83. require.NoError(t, applyPlatforms(project, true))
  84. require.EqualValues(t, []string{"linux/amd64"}, project.Services["test"].Build.Platforms)
  85. })
  86. t.Run("MultiPlatform", func(t *testing.T) {
  87. project := makeProject()
  88. require.NoError(t, applyPlatforms(project, false))
  89. require.EqualValues(t, []string{"linux/amd64", "linux/arm64"},
  90. project.Services["test"].Build.Platforms)
  91. })
  92. }
  93. func TestApplyPlatforms_UnsupportedPlatform(t *testing.T) {
  94. makeProject := func() *types.Project {
  95. return &types.Project{
  96. Environment: map[string]string{
  97. "DOCKER_DEFAULT_PLATFORM": "commodore/64",
  98. },
  99. Services: types.Services{
  100. "test": {
  101. Name: "test",
  102. Image: "foo",
  103. Build: &types.BuildConfig{
  104. Context: ".",
  105. Platforms: []string{
  106. "linux/amd64",
  107. "linux/arm64",
  108. },
  109. },
  110. },
  111. },
  112. }
  113. }
  114. t.Run("SinglePlatform", func(t *testing.T) {
  115. project := makeProject()
  116. require.EqualError(t, applyPlatforms(project, true),
  117. `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`)
  118. })
  119. t.Run("MultiPlatform", func(t *testing.T) {
  120. project := makeProject()
  121. require.EqualError(t, applyPlatforms(project, false),
  122. `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`)
  123. })
  124. }
  125. func TestIsRemoteConfig(t *testing.T) {
  126. ctrl := gomock.NewController(t)
  127. defer ctrl.Finish()
  128. cli := mocks.NewMockCli(ctrl)
  129. tests := []struct {
  130. name string
  131. configPaths []string
  132. want bool
  133. }{
  134. {
  135. name: "empty config paths",
  136. configPaths: []string{},
  137. want: false,
  138. },
  139. {
  140. name: "local file",
  141. configPaths: []string{"docker-compose.yaml"},
  142. want: false,
  143. },
  144. {
  145. name: "OCI reference",
  146. configPaths: []string{"oci://registry.example.com/stack:latest"},
  147. want: true,
  148. },
  149. {
  150. name: "GIT reference",
  151. configPaths: []string{"git://github.com/user/repo.git"},
  152. want: true,
  153. },
  154. }
  155. for _, tt := range tests {
  156. t.Run(tt.name, func(t *testing.T) {
  157. opts := buildOptions{
  158. ProjectOptions: &ProjectOptions{
  159. ConfigPaths: tt.configPaths,
  160. },
  161. }
  162. got := isRemoteConfig(cli, opts)
  163. require.Equal(t, tt.want, got)
  164. })
  165. }
  166. }
  167. func TestDisplayLocationRemoteStack(t *testing.T) {
  168. ctrl := gomock.NewController(t)
  169. defer ctrl.Finish()
  170. cli := mocks.NewMockCli(ctrl)
  171. buf := new(bytes.Buffer)
  172. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  173. project := &types.Project{
  174. Name: "test-project",
  175. WorkingDir: "/tmp/test",
  176. }
  177. options := buildOptions{
  178. ProjectOptions: &ProjectOptions{
  179. ConfigPaths: []string{"oci://registry.example.com/stack:latest"},
  180. },
  181. }
  182. displayLocationRemoteStack(cli, project, options)
  183. output := buf.String()
  184. require.Equal(t, output, fmt.Sprintf("Your compose stack %q is stored in %q\n", "oci://registry.example.com/stack:latest", "/tmp/test"))
  185. }
  186. func TestDisplayInterpolationVariables(t *testing.T) {
  187. ctrl := gomock.NewController(t)
  188. defer ctrl.Finish()
  189. // Create a temporary directory for the test
  190. tmpDir, err := os.MkdirTemp("", "compose-test")
  191. require.NoError(t, err)
  192. defer func() { _ = os.RemoveAll(tmpDir) }()
  193. // Create a temporary compose file
  194. composeContent := `
  195. services:
  196. app:
  197. image: nginx
  198. environment:
  199. - TEST_VAR=${TEST_VAR:?required} # required with default
  200. - API_KEY=${API_KEY:?} # required without default
  201. - DEBUG=${DEBUG:-true} # optional with default
  202. - UNSET_VAR # optional without default
  203. `
  204. composePath := filepath.Join(tmpDir, "docker-compose.yml")
  205. err = os.WriteFile(composePath, []byte(composeContent), 0o644)
  206. require.NoError(t, err)
  207. buf := new(bytes.Buffer)
  208. cli := mocks.NewMockCli(ctrl)
  209. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  210. // Create ProjectOptions with the temporary compose file
  211. projectOptions := &ProjectOptions{
  212. ConfigPaths: []string{composePath},
  213. }
  214. // Set up the context with necessary environment variables
  215. ctx := context.Background()
  216. _ = os.Setenv("TEST_VAR", "test-value")
  217. _ = os.Setenv("API_KEY", "123456")
  218. defer func() {
  219. _ = os.Unsetenv("TEST_VAR")
  220. _ = os.Unsetenv("API_KEY")
  221. }()
  222. // Extract variables from the model
  223. info, noVariables, err := extractInterpolationVariablesFromModel(ctx, cli, projectOptions, []string{})
  224. require.NoError(t, err)
  225. require.False(t, noVariables)
  226. // Display the variables
  227. displayInterpolationVariables(cli.Out(), info)
  228. // Expected output format with proper spacing
  229. expected := "\nFound the following variables in configuration:\n" +
  230. "VARIABLE VALUE SOURCE REQUIRED DEFAULT\n" +
  231. "API_KEY 123456 environment yes \n" +
  232. "DEBUG true compose file no true\n" +
  233. "TEST_VAR test-value environment yes \n"
  234. // Normalize spaces and newlines for comparison
  235. normalizeSpaces := func(s string) string {
  236. // Replace multiple spaces with a single space
  237. s = strings.Join(strings.Fields(strings.TrimSpace(s)), " ")
  238. return s
  239. }
  240. actualOutput := buf.String()
  241. // Compare normalized strings
  242. require.Equal(t,
  243. normalizeSpaces(expected),
  244. normalizeSpaces(actualOutput),
  245. "\nExpected:\n%s\nGot:\n%s", expected, actualOutput)
  246. }