github.com/puellanivis/breton@v0.2.16/lib/mpeg/ts/pes/reader_test.go (about)

     1  package pes
     2  
     3  import (
     4  	"bytes"
     5  	"reflect"
     6  	"testing"
     7  )
     8  
     9  func TestUnmarshal(t *testing.T) {
    10  	expected := [][]byte{
    11  		[]byte("Hello World"),
    12  		[]byte("foo bar"),
    13  	}
    14  
    15  	b := []byte{
    16  		0, 0, 1,
    17  		0x42,
    18  		0, byte(3 + len(expected[0])),
    19  		0x80, 0x00, 0x00,
    20  	}
    21  	b = append(b, expected[0]...)
    22  
    23  	b = append(b, []byte{
    24  		0, 0, 1,
    25  		0x42,
    26  		0, byte(3 + len(expected[1])),
    27  		0x80, 0x00, 0x00,
    28  	}...)
    29  	b = append(b, expected[1]...)
    30  
    31  	var all []byte
    32  	for i := range expected {
    33  		all = append(all, expected[i]...)
    34  	}
    35  
    36  	rd := &Reader{
    37  		src: bytes.NewReader(b),
    38  	}
    39  
    40  	for i := range expected {
    41  		output := make([]byte, len(all))
    42  		n, err := rd.Read(output)
    43  		if err != nil {
    44  			t.Fatal(err)
    45  		}
    46  
    47  		if n != len(expected[i]) {
    48  			t.Errorf("expected to read %d bytes, but read %d bytes", len(expected[i]), n)
    49  		}
    50  
    51  		output = output[:n]
    52  
    53  		if !reflect.DeepEqual(output, expected[i]) {
    54  			t.Errorf("expected to read %v, but read %v", expected[i], output)
    55  		}
    56  	}
    57  
    58  	rd = &Reader{
    59  		src: bytes.NewReader(b),
    60  	}
    61  
    62  	// test reading with a super small buffer.
    63  	output := make([]byte, 3)
    64  	for i := 0; i < len(all); i += 3 {
    65  		expectedLen := 3
    66  		if i+3 > len(all) {
    67  			expectedLen = len(all) - i
    68  		}
    69  
    70  		n, err := rd.Read(output)
    71  		if err != nil {
    72  			t.Fatal(err)
    73  		}
    74  
    75  		if n != expectedLen {
    76  			t.Errorf("expected to read %d bytes, but read %d bytes", expectedLen, n)
    77  		}
    78  
    79  		output := output[:n]
    80  		expected := all[i : i+expectedLen]
    81  
    82  		if !reflect.DeepEqual(output, expected) {
    83  			t.Errorf("expected to read %v, but read %v", expected, output)
    84  		}
    85  	}
    86  }