1
0

options_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "fmt"
  17. "io"
  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/stretchr/testify/require"
  25. "go.uber.org/mock/gomock"
  26. "github.com/docker/compose/v5/pkg/mocks"
  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. tmpDir := t.TempDir()
  190. // Create a temporary compose file
  191. composeContent := `
  192. services:
  193. app:
  194. image: nginx
  195. environment:
  196. - TEST_VAR=${TEST_VAR:?required} # required with default
  197. - API_KEY=${API_KEY:?} # required without default
  198. - DEBUG=${DEBUG:-true} # optional with default
  199. - UNSET_VAR # optional without default
  200. `
  201. composePath := filepath.Join(tmpDir, "docker-compose.yml")
  202. require.NoError(t, os.WriteFile(composePath, []byte(composeContent), 0o644))
  203. buf := new(bytes.Buffer)
  204. cli := mocks.NewMockCli(ctrl)
  205. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  206. // Create ProjectOptions with the temporary compose file
  207. projectOptions := &ProjectOptions{
  208. ConfigPaths: []string{composePath},
  209. }
  210. // Set up the context with necessary environment variables
  211. t.Setenv("TEST_VAR", "test-value")
  212. t.Setenv("API_KEY", "123456")
  213. // Extract variables from the model
  214. info, noVariables, err := extractInterpolationVariablesFromModel(t.Context(), cli, projectOptions, []string{})
  215. require.NoError(t, err)
  216. require.False(t, noVariables)
  217. // Display the variables
  218. displayInterpolationVariables(cli.Out(), info)
  219. // Expected output format with proper spacing
  220. expected := "\nFound the following variables in configuration:\n" +
  221. "VARIABLE VALUE SOURCE REQUIRED DEFAULT\n" +
  222. "API_KEY 123456 environment yes \n" +
  223. "DEBUG true compose file no true\n" +
  224. "TEST_VAR test-value environment yes \n"
  225. // Normalize spaces and newlines for comparison
  226. normalizeSpaces := func(s string) string {
  227. // Replace multiple spaces with a single space
  228. s = strings.Join(strings.Fields(strings.TrimSpace(s)), " ")
  229. return s
  230. }
  231. actualOutput := buf.String()
  232. // Compare normalized strings
  233. require.Equal(t,
  234. normalizeSpaces(expected),
  235. normalizeSpaces(actualOutput),
  236. "\nExpected:\n%s\nGot:\n%s", expected, actualOutput)
  237. }
  238. func TestConfirmRemoteIncludes(t *testing.T) {
  239. ctrl := gomock.NewController(t)
  240. defer ctrl.Finish()
  241. cli := mocks.NewMockCli(ctrl)
  242. tests := []struct {
  243. name string
  244. opts buildOptions
  245. assumeYes bool
  246. userInput string
  247. wantErr bool
  248. errMessage string
  249. wantPrompt bool
  250. wantOutput string
  251. }{
  252. {
  253. name: "no remote includes",
  254. opts: buildOptions{
  255. ProjectOptions: &ProjectOptions{
  256. ConfigPaths: []string{
  257. "docker-compose.yaml",
  258. "./local/path/compose.yaml",
  259. },
  260. },
  261. },
  262. assumeYes: false,
  263. wantErr: false,
  264. wantPrompt: false,
  265. },
  266. {
  267. name: "assume yes with remote includes",
  268. opts: buildOptions{
  269. ProjectOptions: &ProjectOptions{
  270. ConfigPaths: []string{
  271. "oci://registry.example.com/stack:latest",
  272. "git://github.com/user/repo.git",
  273. },
  274. },
  275. },
  276. assumeYes: true,
  277. wantErr: false,
  278. wantPrompt: false,
  279. },
  280. {
  281. name: "user confirms remote includes",
  282. opts: buildOptions{
  283. ProjectOptions: &ProjectOptions{
  284. ConfigPaths: []string{
  285. "oci://registry.example.com/stack:latest",
  286. "git://github.com/user/repo.git",
  287. },
  288. },
  289. },
  290. assumeYes: false,
  291. userInput: "y\n",
  292. wantErr: false,
  293. wantPrompt: true,
  294. wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" +
  295. " - oci://registry.example.com/stack:latest\n" +
  296. " - git://github.com/user/repo.git\n" +
  297. "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" +
  298. "Do you want to continue? [y/N]: ",
  299. },
  300. {
  301. name: "user rejects remote includes",
  302. opts: buildOptions{
  303. ProjectOptions: &ProjectOptions{
  304. ConfigPaths: []string{
  305. "oci://registry.example.com/stack:latest",
  306. },
  307. },
  308. },
  309. assumeYes: false,
  310. userInput: "n\n",
  311. wantErr: true,
  312. errMessage: "operation cancelled by user",
  313. wantPrompt: true,
  314. wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" +
  315. " - oci://registry.example.com/stack:latest\n" +
  316. "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" +
  317. "Do you want to continue? [y/N]: ",
  318. },
  319. }
  320. buf := new(bytes.Buffer)
  321. for _, tt := range tests {
  322. t.Run(tt.name, func(t *testing.T) {
  323. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  324. if tt.wantPrompt {
  325. inbuf := io.NopCloser(bytes.NewBufferString(tt.userInput))
  326. cli.EXPECT().In().Return(streams.NewIn(inbuf)).AnyTimes()
  327. }
  328. err := confirmRemoteIncludes(cli, tt.opts, tt.assumeYes)
  329. if tt.wantErr {
  330. require.Error(t, err)
  331. require.Equal(t, tt.errMessage, err.Error())
  332. } else {
  333. require.NoError(t, err)
  334. }
  335. if tt.wantOutput != "" {
  336. require.Equal(t, tt.wantOutput, buf.String())
  337. }
  338. buf.Reset()
  339. })
  340. }
  341. }