watch_test.go 5.5 KB

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