github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/linewriter/linewriter_test.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package linewriter
    16  
    17  import (
    18  	"bytes"
    19  	"testing"
    20  )
    21  
    22  func TestWriter(t *testing.T) {
    23  	testCases := []struct {
    24  		input []string
    25  		want  []string
    26  	}{
    27  		{
    28  			input: []string{"1\n", "2\n"},
    29  			want:  []string{"1", "2"},
    30  		},
    31  		{
    32  			input: []string{"1\n", "\n", "2\n"},
    33  			want:  []string{"1", "", "2"},
    34  		},
    35  		{
    36  			input: []string{"1\n2\n", "3\n"},
    37  			want:  []string{"1", "2", "3"},
    38  		},
    39  		{
    40  			input: []string{"1", "2\n"},
    41  			want:  []string{"12"},
    42  		},
    43  		{
    44  			// Data with no newline yet is omitted.
    45  			input: []string{"1\n", "2\n", "3"},
    46  			want:  []string{"1", "2"},
    47  		},
    48  	}
    49  
    50  	for _, c := range testCases {
    51  		var lines [][]byte
    52  
    53  		w := NewWriter(func(p []byte) {
    54  			// We must not retain p, so we must make a copy.
    55  			b := make([]byte, len(p))
    56  			copy(b, p)
    57  
    58  			lines = append(lines, b)
    59  		})
    60  
    61  		for _, in := range c.input {
    62  			n, err := w.Write([]byte(in))
    63  			if err != nil {
    64  				t.Errorf("Write(%q) err got %v want nil (case %+v)", in, err, c)
    65  			}
    66  			if n != len(in) {
    67  				t.Errorf("Write(%q) b got %d want %d (case %+v)", in, n, len(in), c)
    68  			}
    69  		}
    70  
    71  		if len(lines) != len(c.want) {
    72  			t.Errorf("len(lines) got %d want %d (case %+v)", len(lines), len(c.want), c)
    73  		}
    74  
    75  		for i := range lines {
    76  			if !bytes.Equal(lines[i], []byte(c.want[i])) {
    77  				t.Errorf("item %d got %q want %q (case %+v)", i, lines[i], c.want[i], c)
    78  			}
    79  		}
    80  	}
    81  }