github.com/argoproj/argo-cd/v3@v3.2.1/util/cmp/stream_test.go (about) 1 package cmp_test 2 3 import ( 4 "context" 5 "errors" 6 "io" 7 "os" 8 "path/filepath" 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 15 pluginclient "github.com/argoproj/argo-cd/v3/cmpserver/apiclient" 16 "github.com/argoproj/argo-cd/v3/test" 17 "github.com/argoproj/argo-cd/v3/util/cmp" 18 "github.com/argoproj/argo-cd/v3/util/io/files" 19 ) 20 21 type streamMock struct { 22 messages chan *pluginclient.AppStreamRequest 23 done chan bool 24 } 25 26 func (m *streamMock) Recv() (*pluginclient.AppStreamRequest, error) { 27 select { 28 case message := <-m.messages: 29 return message, nil 30 case <-m.done: 31 return nil, io.EOF 32 case <-time.After(500 * time.Millisecond): 33 return nil, errors.New("timeout receiving message mock") 34 } 35 } 36 37 func (m *streamMock) Send(message *pluginclient.AppStreamRequest) error { 38 m.messages <- message 39 return nil 40 } 41 42 func newStreamMock() *streamMock { 43 messagesCh := make(chan *pluginclient.AppStreamRequest) 44 doneCh := make(chan bool) 45 return &streamMock{ 46 messages: messagesCh, 47 done: doneCh, 48 } 49 } 50 51 func TestReceiveApplicationStream(t *testing.T) { 52 t.Run("will receive the application stream successfully", func(t *testing.T) { 53 // given 54 streamMock := newStreamMock() 55 appDir := filepath.Join(getTestDataDir(t), "app") 56 workdir, err := files.CreateTempDir("") 57 require.NoError(t, err) 58 defer func() { 59 close(streamMock.messages) 60 os.RemoveAll(workdir) 61 }() 62 go streamMock.sendFile(t.Context(), t, appDir, streamMock, []string{"env1", "env2"}, []string{"DUMMY.md", "dum*"}) 63 64 // when 65 env, err := cmp.ReceiveRepoStream(t.Context(), streamMock, workdir, false) 66 67 // then 68 require.NoError(t, err) 69 assert.NotEmpty(t, workdir) 70 files, err := os.ReadDir(workdir) 71 require.NoError(t, err) 72 require.Len(t, files, 2) 73 names := []string{} 74 for _, f := range files { 75 names = append(names, f.Name()) 76 } 77 assert.Contains(t, names, "README.md") 78 assert.Contains(t, names, "applicationset") 79 assert.NotContains(t, names, "DUMMY.md") 80 assert.NotContains(t, names, "dummy") 81 assert.NotNil(t, env) 82 }) 83 } 84 85 func (m *streamMock) sendFile(ctx context.Context, t *testing.T, basedir string, sender cmp.StreamSender, env []string, excludedGlobs []string) { 86 t.Helper() 87 defer func() { 88 m.done <- true 89 }() 90 err := cmp.SendRepoStream(ctx, basedir, basedir, sender, env, excludedGlobs) 91 require.NoError(t, err) 92 } 93 94 // getTestDataDir will return the full path of the testdata dir 95 // under the running test folder. 96 func getTestDataDir(t *testing.T) string { 97 t.Helper() 98 return filepath.Join(test.GetTestDir(t), "testdata") 99 }