watch_test.go 4.9 KB

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