options_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. "go.uber.org/mock/gomock"
  25. "gotest.tools/v3/assert"
  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. assert.NilError(t, applyPlatforms(project, true))
  51. assert.DeepEqual(t, types.StringList{"alice/32"}, project.Services["test"].Build.Platforms)
  52. })
  53. t.Run("MultiPlatform", func(t *testing.T) {
  54. project := makeProject()
  55. assert.NilError(t, applyPlatforms(project, false))
  56. assert.DeepEqual(t, types.StringList{"linux/amd64", "linux/arm64", "alice/32"}, project.Services["test"].Build.Platforms)
  57. })
  58. }
  59. func TestApplyPlatforms_DockerDefaultPlatform(t *testing.T) {
  60. makeProject := func() *types.Project {
  61. return &types.Project{
  62. Environment: map[string]string{
  63. "DOCKER_DEFAULT_PLATFORM": "linux/amd64",
  64. },
  65. Services: types.Services{
  66. "test": {
  67. Name: "test",
  68. Image: "foo",
  69. Build: &types.BuildConfig{
  70. Context: ".",
  71. Platforms: []string{
  72. "linux/amd64",
  73. "linux/arm64",
  74. },
  75. },
  76. },
  77. },
  78. }
  79. }
  80. t.Run("SinglePlatform", func(t *testing.T) {
  81. project := makeProject()
  82. assert.NilError(t, applyPlatforms(project, true))
  83. assert.DeepEqual(t, types.StringList{"linux/amd64"}, project.Services["test"].Build.Platforms)
  84. })
  85. t.Run("MultiPlatform", func(t *testing.T) {
  86. project := makeProject()
  87. assert.NilError(t, applyPlatforms(project, false))
  88. assert.DeepEqual(t, types.StringList{"linux/amd64", "linux/arm64"}, project.Services["test"].Build.Platforms)
  89. })
  90. }
  91. func TestApplyPlatforms_UnsupportedPlatform(t *testing.T) {
  92. makeProject := func() *types.Project {
  93. return &types.Project{
  94. Environment: map[string]string{
  95. "DOCKER_DEFAULT_PLATFORM": "commodore/64",
  96. },
  97. Services: types.Services{
  98. "test": {
  99. Name: "test",
  100. Image: "foo",
  101. Build: &types.BuildConfig{
  102. Context: ".",
  103. Platforms: []string{
  104. "linux/amd64",
  105. "linux/arm64",
  106. },
  107. },
  108. },
  109. },
  110. }
  111. }
  112. t.Run("SinglePlatform", func(t *testing.T) {
  113. project := makeProject()
  114. assert.Error(t, applyPlatforms(project, true),
  115. `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`)
  116. })
  117. t.Run("MultiPlatform", func(t *testing.T) {
  118. project := makeProject()
  119. assert.Error(t, applyPlatforms(project, false),
  120. `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`)
  121. })
  122. }
  123. func TestIsRemoteConfig(t *testing.T) {
  124. ctrl := gomock.NewController(t)
  125. defer ctrl.Finish()
  126. cli := mocks.NewMockCli(ctrl)
  127. tests := []struct {
  128. name string
  129. configPaths []string
  130. want bool
  131. }{
  132. {
  133. name: "empty config paths",
  134. configPaths: []string{},
  135. want: false,
  136. },
  137. {
  138. name: "local file",
  139. configPaths: []string{"docker-compose.yaml"},
  140. want: false,
  141. },
  142. {
  143. name: "OCI reference",
  144. configPaths: []string{"oci://registry.example.com/stack:latest"},
  145. want: true,
  146. },
  147. {
  148. name: "GIT reference",
  149. configPaths: []string{"git://github.com/user/repo.git"},
  150. want: true,
  151. },
  152. }
  153. for _, tt := range tests {
  154. t.Run(tt.name, func(t *testing.T) {
  155. opts := buildOptions{
  156. ProjectOptions: &ProjectOptions{
  157. ConfigPaths: tt.configPaths,
  158. },
  159. }
  160. got := isRemoteConfig(cli, opts)
  161. assert.Equal(t, tt.want, got)
  162. })
  163. }
  164. }
  165. func TestDisplayLocationRemoteStack(t *testing.T) {
  166. ctrl := gomock.NewController(t)
  167. defer ctrl.Finish()
  168. cli := mocks.NewMockCli(ctrl)
  169. buf := new(bytes.Buffer)
  170. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  171. project := &types.Project{
  172. Name: "test-project",
  173. WorkingDir: "/tmp/test",
  174. }
  175. options := buildOptions{
  176. ProjectOptions: &ProjectOptions{
  177. ConfigPaths: []string{"oci://registry.example.com/stack:latest"},
  178. },
  179. }
  180. displayLocationRemoteStack(cli, project, options)
  181. output := buf.String()
  182. assert.Equal(t, output, fmt.Sprintf("Your compose stack %q is stored in %q\n", "oci://registry.example.com/stack:latest", "/tmp/test"))
  183. }
  184. func TestDisplayInterpolationVariables(t *testing.T) {
  185. ctrl := gomock.NewController(t)
  186. defer ctrl.Finish()
  187. tmpDir := t.TempDir()
  188. // Create a temporary compose file
  189. composeContent := `
  190. services:
  191. app:
  192. image: nginx
  193. environment:
  194. - TEST_VAR=${TEST_VAR:?required} # required with default
  195. - API_KEY=${API_KEY:?} # required without default
  196. - DEBUG=${DEBUG:-true} # optional with default
  197. - UNSET_VAR # optional without default
  198. `
  199. composePath := filepath.Join(tmpDir, "docker-compose.yml")
  200. assert.NilError(t, os.WriteFile(composePath, []byte(composeContent), 0o644))
  201. buf := new(bytes.Buffer)
  202. cli := mocks.NewMockCli(ctrl)
  203. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  204. // Create ProjectOptions with the temporary compose file
  205. projectOptions := &ProjectOptions{
  206. ConfigPaths: []string{composePath},
  207. }
  208. // Set up the context with necessary environment variables
  209. t.Setenv("TEST_VAR", "test-value")
  210. t.Setenv("API_KEY", "123456")
  211. // Extract variables from the model
  212. info, noVariables, err := extractInterpolationVariablesFromModel(t.Context(), cli, projectOptions, []string{})
  213. assert.NilError(t, err)
  214. assert.Assert(t, noVariables == false)
  215. // Display the variables
  216. displayInterpolationVariables(cli.Out(), info)
  217. // Expected output format with proper spacing
  218. expected := "\nFound the following variables in configuration:\n" +
  219. "VARIABLE VALUE SOURCE REQUIRED DEFAULT\n" +
  220. "API_KEY 123456 environment yes \n" +
  221. "DEBUG true compose file no true\n" +
  222. "TEST_VAR test-value environment yes \n"
  223. // Normalize spaces and newlines for comparison
  224. normalizeSpaces := func(s string) string {
  225. // Replace multiple spaces with a single space
  226. s = strings.Join(strings.Fields(strings.TrimSpace(s)), " ")
  227. return s
  228. }
  229. actualOutput := buf.String()
  230. // Compare normalized strings
  231. assert.Equal(t,
  232. normalizeSpaces(expected),
  233. normalizeSpaces(actualOutput),
  234. "\nExpected:\n%s\nGot:\n%s", expected, actualOutput)
  235. }
  236. func TestConfirmRemoteIncludes(t *testing.T) {
  237. ctrl := gomock.NewController(t)
  238. defer ctrl.Finish()
  239. cli := mocks.NewMockCli(ctrl)
  240. tests := []struct {
  241. name string
  242. opts buildOptions
  243. assumeYes bool
  244. userInput string
  245. wantErr bool
  246. errMessage string
  247. wantPrompt bool
  248. wantOutput string
  249. }{
  250. {
  251. name: "no remote includes",
  252. opts: buildOptions{
  253. ProjectOptions: &ProjectOptions{
  254. ConfigPaths: []string{
  255. "docker-compose.yaml",
  256. "./local/path/compose.yaml",
  257. },
  258. },
  259. },
  260. assumeYes: false,
  261. wantErr: false,
  262. wantPrompt: false,
  263. },
  264. {
  265. name: "assume yes with remote includes",
  266. opts: buildOptions{
  267. ProjectOptions: &ProjectOptions{
  268. ConfigPaths: []string{
  269. "oci://registry.example.com/stack:latest",
  270. "git://github.com/user/repo.git",
  271. },
  272. },
  273. },
  274. assumeYes: true,
  275. wantErr: false,
  276. wantPrompt: false,
  277. },
  278. {
  279. name: "user confirms remote includes",
  280. opts: buildOptions{
  281. ProjectOptions: &ProjectOptions{
  282. ConfigPaths: []string{
  283. "oci://registry.example.com/stack:latest",
  284. "git://github.com/user/repo.git",
  285. },
  286. },
  287. },
  288. assumeYes: false,
  289. userInput: "y\n",
  290. wantErr: false,
  291. wantPrompt: true,
  292. wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" +
  293. " - oci://registry.example.com/stack:latest\n" +
  294. " - git://github.com/user/repo.git\n" +
  295. "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" +
  296. "Do you want to continue? [y/N]: ",
  297. },
  298. {
  299. name: "user rejects remote includes",
  300. opts: buildOptions{
  301. ProjectOptions: &ProjectOptions{
  302. ConfigPaths: []string{
  303. "oci://registry.example.com/stack:latest",
  304. },
  305. },
  306. },
  307. assumeYes: false,
  308. userInput: "n\n",
  309. wantErr: true,
  310. errMessage: "operation cancelled by user",
  311. wantPrompt: true,
  312. wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" +
  313. " - oci://registry.example.com/stack:latest\n" +
  314. "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" +
  315. "Do you want to continue? [y/N]: ",
  316. },
  317. }
  318. buf := new(bytes.Buffer)
  319. for _, tt := range tests {
  320. t.Run(tt.name, func(t *testing.T) {
  321. cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes()
  322. if tt.wantPrompt {
  323. inbuf := io.NopCloser(bytes.NewBufferString(tt.userInput))
  324. cli.EXPECT().In().Return(streams.NewIn(inbuf)).AnyTimes()
  325. }
  326. err := confirmRemoteIncludes(cli, tt.opts, tt.assumeYes)
  327. if tt.wantErr {
  328. assert.Error(t, err, tt.errMessage)
  329. } else {
  330. assert.NilError(t, err)
  331. }
  332. if tt.wantOutput != "" {
  333. assert.Equal(t, tt.wantOutput, buf.String())
  334. }
  335. buf.Reset()
  336. })
  337. }
  338. }