okami.mom/ultraviolet
git clone https://git.nkp.pet/okami.mom/ultraviolet
04a6149
main
1package uv 2 3import ( 4"bytes" 5"fmt" 6"io" 7"sync" 8"testing" 9) 10 11type blockingReader struct { 12 sync.Mutex 13read bool 14unblockCh chan bool 15startedCh chan bool 16} 17 18func (r * blockingReader )Read ([]byte ) (int ,error ) { 19defer func () { 20r .Lock () 21defer r .Unlock () 22r .read = true 23 }() 24r .startedCh <- true 25<- r .unblockCh 26return 0 ,fmt .Errorf ("this error should be ignored" ) 27} 28 29func TestFallbackReaderConcurrentCancel (t * testing.T ) { 30doneCh := make (chan bool ,1 ) 31startedCh := make (chan bool ,1 ) 32unblockCh := make (chan bool ,1 ) 33r := blockingReader { 34startedCh :startedCh , 35unblockCh :unblockCh , 36 } 37pr ,err := newFallbackReader (& r ) 38if err != nil { 39t .Errorf ("expected no error, but got %s" ,err ) 40 } 41 42go func () { 43defer func () {doneCh <- true }() 44if _ ,err := io .ReadAll (pr );err != ErrCanceled { 45t .Errorf ("expected canceled error, got %v" ,err ) 46 } 47 }() 48 49// make sure the read started before canceling the reader 50<- startedCh 51pr .Cancel () 52unblockCh <- true 53 54// wait for the read to end to ensure its assertions were made 55<- doneCh 56 57// make sure that it waited for the reader 58if ! r .read { 59t .Error ("seems like the reader was canceled before the read, this shouldn't happen" ) 60 } 61} 62 63func TestFallbackReader (t * testing.T ) { 64var r bytes.Buffer 65pr ,err := newFallbackReader (& r ) 66if err != nil { 67t .Errorf ("expected no error, but got %s" ,err ) 68 } 69 70txt := "first" 71_ ,_ = r .WriteString (txt ) 72first ,err := io .ReadAll (pr ) 73if err != nil { 74t .Errorf ("expected no error, but got %s" ,err ) 75 } 76if string (first )!= txt { 77t .Errorf ("expected output to be %q, got %q" ,txt ,string (first )) 78 } 79 80pr .Cancel () 81second ,err := io .ReadAll (pr ) 82if err != ErrCanceled { 83t .Errorf ("expected ErrCanceled, got %v" ,err ) 84 } 85if len (second )> 0 { 86t .Errorf ("expected an empty read, got %q" ,string (second )) 87 } 88}