watch_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. Copyright 2020 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. "cmp"
  16. "context"
  17. "fmt"
  18. "os"
  19. "slices"
  20. "testing"
  21. "time"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/docker/cli/cli/streams"
  24. "github.com/jonboulle/clockwork"
  25. "github.com/moby/moby/api/types/container"
  26. "github.com/moby/moby/api/types/image"
  27. "github.com/moby/moby/client"
  28. "go.uber.org/mock/gomock"
  29. "gotest.tools/v3/assert"
  30. "github.com/docker/compose/v5/internal/sync"
  31. "github.com/docker/compose/v5/pkg/api"
  32. "github.com/docker/compose/v5/pkg/mocks"
  33. "github.com/docker/compose/v5/pkg/watch"
  34. )
  35. type testWatcher struct {
  36. events chan watch.FileEvent
  37. errors chan error
  38. }
  39. func (t testWatcher) Start() error {
  40. return nil
  41. }
  42. func (t testWatcher) Close() error {
  43. return nil
  44. }
  45. func (t testWatcher) Events() chan watch.FileEvent {
  46. return t.events
  47. }
  48. func (t testWatcher) Errors() chan error {
  49. return t.errors
  50. }
  51. type stdLogger struct{}
  52. func (s stdLogger) Log(containerName, message string) {
  53. fmt.Printf("%s: %s\n", containerName, message)
  54. }
  55. func (s stdLogger) Err(containerName, message string) {
  56. fmt.Fprintf(os.Stderr, "%s: %s\n", containerName, message)
  57. }
  58. func (s stdLogger) Status(containerName, msg string) {
  59. fmt.Printf("%s: %s\n", containerName, msg)
  60. }
  61. func TestWatch_Sync(t *testing.T) {
  62. mockCtrl := gomock.NewController(t)
  63. cli := mocks.NewMockCli(mockCtrl)
  64. cli.EXPECT().Err().Return(streams.NewOut(os.Stderr)).AnyTimes()
  65. apiClient := mocks.NewMockAPIClient(mockCtrl)
  66. apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).Return(client.ContainerListResult{
  67. Items: []container.Summary{
  68. testContainer("test", "123", false),
  69. },
  70. }, nil).AnyTimes()
  71. // we expect the image to be pruned
  72. apiClient.EXPECT().ImageList(gomock.Any(), client.ImageListOptions{
  73. Filters: make(client.Filters).
  74. Add("dangling", "true").
  75. Add("label", api.ProjectLabel+"=myProjectName"),
  76. }).Return(client.ImageListResult{
  77. Items: []image.Summary{
  78. {ID: "123"},
  79. {ID: "456"},
  80. },
  81. }, nil).Times(1)
  82. apiClient.EXPECT().ImageRemove(gomock.Any(), "123", client.ImageRemoveOptions{}).Times(1)
  83. apiClient.EXPECT().ImageRemove(gomock.Any(), "456", client.ImageRemoveOptions{}).Times(1)
  84. //
  85. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  86. ctx, cancelFunc := context.WithCancel(t.Context())
  87. t.Cleanup(cancelFunc)
  88. proj := types.Project{
  89. Name: "myProjectName",
  90. Services: types.Services{
  91. "test": {
  92. Name: "test",
  93. },
  94. },
  95. }
  96. watcher := testWatcher{
  97. events: make(chan watch.FileEvent),
  98. errors: make(chan error),
  99. }
  100. syncer := newFakeSyncer()
  101. clock := clockwork.NewFakeClock()
  102. go func() {
  103. service := composeService{
  104. dockerCli: cli,
  105. clock: clock,
  106. }
  107. rules, err := getWatchRules(&types.DevelopConfig{
  108. Watch: []types.Trigger{
  109. {
  110. Path: "/sync",
  111. Action: "sync",
  112. Target: "/work",
  113. Ignore: []string{"ignore"},
  114. },
  115. {
  116. Path: "/rebuild",
  117. Action: "rebuild",
  118. },
  119. },
  120. }, types.ServiceConfig{Name: "test"})
  121. assert.NilError(t, err)
  122. err = service.watchEvents(ctx, &proj, api.WatchOptions{
  123. Build: &api.BuildOptions{},
  124. LogTo: stdLogger{},
  125. Prune: true,
  126. }, watcher, syncer, rules)
  127. assert.NilError(t, err)
  128. }()
  129. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  130. watcher.Events() <- watch.NewFileEvent("/sync/changed/sub")
  131. err := clock.BlockUntilContext(ctx, 3)
  132. assert.NilError(t, err)
  133. clock.Advance(watch.QuietPeriod)
  134. select {
  135. case actual := <-syncer.synced:
  136. expected := []*sync.PathMapping{
  137. {HostPath: "/sync/changed", ContainerPath: "/work/changed"},
  138. {HostPath: "/sync/changed/sub", ContainerPath: "/work/changed/sub"},
  139. }
  140. slices.SortFunc(actual, func(a, b *sync.PathMapping) int {
  141. return cmp.Compare(a.HostPath, b.HostPath)
  142. })
  143. assert.DeepEqual(t, expected, actual)
  144. case <-time.After(100 * time.Millisecond):
  145. t.Error("timeout")
  146. }
  147. watcher.Events() <- watch.NewFileEvent("/rebuild")
  148. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  149. err = clock.BlockUntilContext(ctx, 4)
  150. assert.NilError(t, err)
  151. clock.Advance(watch.QuietPeriod)
  152. select {
  153. case batch := <-syncer.synced:
  154. t.Fatalf("received unexpected events: %v", batch)
  155. case <-time.After(100 * time.Millisecond):
  156. // expected
  157. }
  158. // TODO: there's not a great way to assert that the rebuild attempt happened
  159. }
  160. type fakeSyncer struct {
  161. synced chan []*sync.PathMapping
  162. }
  163. func newFakeSyncer() *fakeSyncer {
  164. return &fakeSyncer{
  165. synced: make(chan []*sync.PathMapping),
  166. }
  167. }
  168. func (f *fakeSyncer) Sync(ctx context.Context, service string, paths []*sync.PathMapping) error {
  169. f.synced <- paths
  170. return nil
  171. }