github.com/waldiirawan/apm-agent-go/v2@v2.2.2/internal/iochan/reader_test.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package iochan
    19  
    20  import (
    21  	"errors"
    22  	"io"
    23  	"io/ioutil"
    24  	"strings"
    25  	"sync"
    26  	"testing"
    27  
    28  	"github.com/stretchr/testify/assert"
    29  )
    30  
    31  func TestRead(t *testing.T) {
    32  	target := 9999
    33  	r := NewReader()
    34  	var wg sync.WaitGroup
    35  	wg.Add(1)
    36  	go func() {
    37  		defer wg.Done()
    38  		var bytes int
    39  		for req := range r.C {
    40  			for i := range req.Buf {
    41  				req.Buf[i] = '*'
    42  			}
    43  			n := len(req.Buf)
    44  			var err error
    45  			if bytes+n >= target {
    46  				if bytes+n > target {
    47  					n = target - bytes
    48  				}
    49  				err = io.EOF
    50  			}
    51  			bytes += n
    52  			req.Respond(n, err)
    53  		}
    54  	}()
    55  
    56  	data, err := ioutil.ReadAll(r)
    57  	assert.NoError(t, err)
    58  	r.CloseWrite() // unblocks the goroutine
    59  	assert.Equal(t, strings.Repeat("*", target), string(data))
    60  	wg.Wait()
    61  }
    62  
    63  func TestCloseRead(t *testing.T) {
    64  	r := NewReader()
    65  	r.CloseRead(io.EOF)
    66  	r.CloseRead(errors.New("ignored"))
    67  	n, err := r.Read(make([]byte, 1024))
    68  	assert.Equal(t, 0, n)
    69  	assert.Equal(t, io.EOF, err)
    70  }
    71  
    72  func TestCloseReadBlocked(t *testing.T) {
    73  	r := NewReader()
    74  
    75  	var wg sync.WaitGroup
    76  	wg.Add(1)
    77  	go func() {
    78  		defer wg.Done()
    79  		<-r.C // wait for ar request, but don't respond
    80  		r.CloseRead(io.EOF)
    81  	}()
    82  
    83  	n, err := r.Read(make([]byte, 1024))
    84  	assert.Equal(t, 0, n)
    85  	assert.Equal(t, io.EOF, err)
    86  	wg.Wait()
    87  }