watch_test.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. moby "github.com/docker/docker/api/types"
  27. "github.com/jonboulle/clockwork"
  28. "github.com/stretchr/testify/require"
  29. "go.uber.org/mock/gomock"
  30. "gotest.tools/v3/assert"
  31. )
  32. func TestDebounceBatching(t *testing.T) {
  33. ch := make(chan fileEvent)
  34. clock := clockwork.NewFakeClock()
  35. ctx, stop := context.WithCancel(context.Background())
  36. t.Cleanup(stop)
  37. eventBatchCh := batchDebounceEvents(ctx, clock, quietPeriod, ch)
  38. for i := 0; i < 100; i++ {
  39. var action types.WatchAction = "a"
  40. if i%2 == 0 {
  41. action = "b"
  42. }
  43. ch <- fileEvent{Action: action}
  44. }
  45. // we sent 100 events + the debouncer
  46. clock.BlockUntil(101)
  47. clock.Advance(quietPeriod)
  48. select {
  49. case batch := <-eventBatchCh:
  50. require.ElementsMatch(t, batch, []fileEvent{
  51. {Action: "a"},
  52. {Action: "b"},
  53. })
  54. case <-time.After(50 * time.Millisecond):
  55. t.Fatal("timed out waiting for events")
  56. }
  57. clock.BlockUntil(1)
  58. clock.Advance(quietPeriod)
  59. // there should only be a single batch
  60. select {
  61. case batch := <-eventBatchCh:
  62. t.Fatalf("unexpected events: %v", batch)
  63. case <-time.After(50 * time.Millisecond):
  64. // channel is empty
  65. }
  66. }
  67. type testWatcher struct {
  68. events chan watch.FileEvent
  69. errors chan error
  70. }
  71. func (t testWatcher) Start() error {
  72. return nil
  73. }
  74. func (t testWatcher) Close() error {
  75. return nil
  76. }
  77. func (t testWatcher) Events() chan watch.FileEvent {
  78. return t.events
  79. }
  80. func (t testWatcher) Errors() chan error {
  81. return t.errors
  82. }
  83. type stdLogger struct{}
  84. func (s stdLogger) Log(containerName, message string) {
  85. fmt.Printf("%s: %s\n", containerName, message)
  86. }
  87. func (s stdLogger) Err(containerName, message string) {
  88. fmt.Fprintf(os.Stderr, "%s: %s\n", containerName, message)
  89. }
  90. func (s stdLogger) Status(container, msg string) {
  91. fmt.Printf("%s: %s\n", container, msg)
  92. }
  93. func (s stdLogger) Register(container string) {
  94. }
  95. func TestWatch_Sync(t *testing.T) {
  96. mockCtrl := gomock.NewController(t)
  97. cli := mocks.NewMockCli(mockCtrl)
  98. cli.EXPECT().Err().Return(streams.NewOut(os.Stderr)).AnyTimes()
  99. cli.EXPECT().BuildKitEnabled().Return(true, nil)
  100. apiClient := mocks.NewMockAPIClient(mockCtrl)
  101. apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).Return([]moby.Container{
  102. testContainer("test", "123", false),
  103. }, nil).AnyTimes()
  104. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  105. ctx, cancelFunc := context.WithCancel(context.Background())
  106. t.Cleanup(cancelFunc)
  107. proj := types.Project{
  108. Services: types.Services{
  109. "test": {
  110. Name: "test",
  111. },
  112. },
  113. }
  114. watcher := testWatcher{
  115. events: make(chan watch.FileEvent),
  116. errors: make(chan error),
  117. }
  118. syncer := newFakeSyncer()
  119. clock := clockwork.NewFakeClock()
  120. go func() {
  121. service := composeService{
  122. dockerCli: cli,
  123. clock: clock,
  124. }
  125. err := service.watchEvents(ctx, &proj, "test", api.WatchOptions{
  126. Build: &api.BuildOptions{},
  127. LogTo: stdLogger{},
  128. }, watcher, syncer, []types.Trigger{
  129. {
  130. Path: "/sync",
  131. Action: "sync",
  132. Target: "/work",
  133. Ignore: []string{"ignore"},
  134. },
  135. {
  136. Path: "/rebuild",
  137. Action: "rebuild",
  138. },
  139. })
  140. assert.NilError(t, err)
  141. }()
  142. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  143. watcher.Events() <- watch.NewFileEvent("/sync/changed/sub")
  144. clock.BlockUntil(3)
  145. clock.Advance(quietPeriod)
  146. select {
  147. case actual := <-syncer.synced:
  148. require.ElementsMatch(t, []sync.PathMapping{
  149. {HostPath: "/sync/changed", ContainerPath: "/work/changed"},
  150. {HostPath: "/sync/changed/sub", ContainerPath: "/work/changed/sub"},
  151. }, actual)
  152. case <-time.After(100 * time.Millisecond):
  153. t.Error("timeout")
  154. }
  155. watcher.Events() <- watch.NewFileEvent("/sync/ignore")
  156. watcher.Events() <- watch.NewFileEvent("/sync/ignore/sub")
  157. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  158. clock.BlockUntil(4)
  159. clock.Advance(quietPeriod)
  160. select {
  161. case actual := <-syncer.synced:
  162. require.ElementsMatch(t, []sync.PathMapping{
  163. {HostPath: "/sync/changed", ContainerPath: "/work/changed"},
  164. }, actual)
  165. case <-time.After(100 * time.Millisecond):
  166. t.Error("timed out waiting for events")
  167. }
  168. watcher.Events() <- watch.NewFileEvent("/rebuild")
  169. watcher.Events() <- watch.NewFileEvent("/sync/changed")
  170. clock.BlockUntil(4)
  171. clock.Advance(quietPeriod)
  172. select {
  173. case batch := <-syncer.synced:
  174. t.Fatalf("received unexpected events: %v", batch)
  175. case <-time.After(100 * time.Millisecond):
  176. // expected
  177. }
  178. // TODO: there's not a great way to assert that the rebuild attempt happened
  179. }
  180. type fakeSyncer struct {
  181. synced chan []sync.PathMapping
  182. }
  183. func newFakeSyncer() *fakeSyncer {
  184. return &fakeSyncer{
  185. synced: make(chan []sync.PathMapping),
  186. }
  187. }
  188. func (f *fakeSyncer) Sync(_ context.Context, _ types.ServiceConfig, paths []sync.PathMapping) error {
  189. f.synced <- paths
  190. return nil
  191. }