github.com/stffabi/git-lfs@v2.3.5-0.20180214015214-8eeaa8d88902+incompatible/git/pkt_line_writer_test.go (about) 1 package git 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestPktlineWriterWritesPacketsShorterThanMaxPacketSize(t *testing.T) { 11 var buf bytes.Buffer 12 13 w := NewPktlineWriter(&buf, 0) 14 assertWriterWrite(t, w, []byte("Hello, world!"), 13) 15 assertWriterWrite(t, w, nil, 0) 16 17 pl := newPktline(&buf, nil) 18 assertPacketRead(t, pl, []byte("Hello, world!")) 19 assertPacketRead(t, pl, nil) 20 } 21 22 func TestPktlineWriterWritesPacketsEqualToMaxPacketLength(t *testing.T) { 23 big := make([]byte, MaxPacketLength) 24 for i, _ := range big { 25 big[i] = 1 26 } 27 28 // Make a copy so that we can drain the data inside of it 29 p := make([]byte, MaxPacketLength) 30 copy(p, big) 31 32 var buf bytes.Buffer 33 34 w := NewPktlineWriter(&buf, 0) 35 assertWriterWrite(t, w, p, len(big)) 36 assertWriterWrite(t, w, nil, 0) 37 38 pl := newPktline(&buf, nil) 39 assertPacketRead(t, pl, big) 40 assertPacketRead(t, pl, nil) 41 } 42 43 func TestPktlineWriterWritesMultiplePacketsLessThanMaxPacketLength(t *testing.T) { 44 var buf bytes.Buffer 45 46 w := NewPktlineWriter(&buf, 0) 47 assertWriterWrite(t, w, []byte("first\n"), len("first\n")) 48 assertWriterWrite(t, w, []byte("second"), len("second")) 49 assertWriterWrite(t, w, nil, 0) 50 51 pl := newPktline(&buf, nil) 52 assertPacketRead(t, pl, []byte("first\nsecond")) 53 assertPacketRead(t, pl, nil) 54 } 55 56 func TestPktlineWriterWritesMultiplePacketsGreaterThanMaxPacketLength(t *testing.T) { 57 var buf bytes.Buffer 58 59 b1 := make([]byte, MaxPacketLength*3/4) 60 for i, _ := range b1 { 61 b1[i] = 1 62 } 63 64 b2 := make([]byte, MaxPacketLength*3/4) 65 for i, _ := range b2 { 66 b2[i] = 2 67 } 68 69 w := NewPktlineWriter(&buf, 0) 70 assertWriterWrite(t, w, b1, len(b1)) 71 assertWriterWrite(t, w, b2, len(b2)) 72 assertWriterWrite(t, w, nil, 0) 73 74 // offs is how far into b2 we needed to buffer before writing an entire 75 // packet 76 offs := MaxPacketLength - len(b1) 77 78 pl := newPktline(&buf, nil) 79 assertPacketRead(t, pl, append(b1, b2[:offs]...)) 80 assertPacketRead(t, pl, b2[offs:]) 81 assertPacketRead(t, pl, nil) 82 } 83 84 func TestPktlineWriterAllowsFlushesOnNil(t *testing.T) { 85 assert.NoError(t, (*PktlineWriter)(nil).Flush()) 86 } 87 88 func TestPktlineWriterDoesntWrapItself(t *testing.T) { 89 itself := &PktlineWriter{} 90 nw := NewPktlineWriter(itself, 0) 91 92 assert.Equal(t, itself, nw) 93 } 94 95 func assertWriterWrite(t *testing.T, w *PktlineWriter, p []byte, plen int) { 96 var n int 97 var err error 98 99 if p == nil { 100 err = w.Flush() 101 } else { 102 n, err = w.Write(p) 103 } 104 105 assert.Nil(t, err) 106 assert.Equal(t, plen, n) 107 } 108 109 func assertPacketRead(t *testing.T, pl *pktline, expected []byte) { 110 got, err := pl.readPacket() 111 112 assert.Nil(t, err) 113 assert.Equal(t, expected, got) 114 }