github.com/jacekolszak/noteo@v0.5.0/notes/filter_test.go (about) 1 package notes_test 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 "github.com/jacekolszak/noteo/notes" 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestFilter(t *testing.T) { 14 expectedNote := ¬eMock{} 15 filteredOutNote1 := ¬eMock{} 16 filteredOutNote2 := ¬eMock{} 17 18 t.Run("should remove not matched notes", func(t *testing.T) { 19 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 20 defer cancel() 21 notesChannel := make(chan notes.Note, 3) 22 notesChannel <- filteredOutNote1 23 notesChannel <- expectedNote 24 notesChannel <- filteredOutNote2 25 // when 26 filtered, errors := notes.Filter(ctx, notesChannel, func(note notes.Note) (bool, error) { 27 if expectedNote == note { 28 return true, nil 29 } 30 return false, nil 31 }) 32 close(notesChannel) 33 // then 34 output := collectNotes(t, filtered, errors) 35 assert.Equal(t, []notes.Note{expectedNote}, output) 36 }) 37 } 38 39 func collectNotes(t *testing.T, filtered <-chan notes.Note, errors <-chan error) []notes.Note { 40 var output []notes.Note 41 for { 42 select { 43 case n, ok := <-filtered: 44 if !ok { 45 return output 46 } 47 output = append(output, n) 48 case err := <-errors: 49 require.NoError(t, err) 50 } 51 } 52 }