go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/chunkstream/chunk_test.go (about)

     1  // Copyright 2015 The LUCI 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 chunkstream
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  	"testing"
    21  
    22  	. "github.com/smartystreets/goconvey/convey"
    23  )
    24  
    25  type testChunk struct {
    26  	data     []byte
    27  	released bool
    28  }
    29  
    30  var _ Chunk = (*testChunk)(nil)
    31  
    32  func tc(d ...byte) *testChunk {
    33  	return &testChunk{
    34  		data: d,
    35  	}
    36  }
    37  
    38  func (c *testChunk) String() string {
    39  	pieces := make([]string, len(c.data))
    40  	for i, d := range c.data {
    41  		pieces[i] = fmt.Sprintf("0x%02x", d)
    42  	}
    43  	return fmt.Sprintf("{%s}", strings.Join(pieces, ", "))
    44  }
    45  
    46  func (c *testChunk) Bytes() []byte {
    47  	return c.data
    48  }
    49  
    50  func (c *testChunk) Len() int {
    51  	return len(c.data)
    52  }
    53  
    54  func (c *testChunk) Release() {
    55  	if c.released {
    56  		panic("double-free")
    57  	}
    58  	c.released = true
    59  }
    60  
    61  func TestChunkNode(t *testing.T) {
    62  	Convey(`A chunkNode wrapping a testing Chunk implementation`, t, func() {
    63  		c := tc(0, 1, 2)
    64  		n := newChunkNode(c)
    65  
    66  		Convey(`Should call Chunk methods.`, func() {
    67  			So(n.Bytes(), ShouldResemble, []byte{0, 1, 2})
    68  		})
    69  
    70  		Convey(`When released, releases the wrapped Chunk.`, func() {
    71  			n.release()
    72  			So(c.released, ShouldBeTrue)
    73  
    74  			Convey(`If released again, panics.`, func() {
    75  				So(func() { n.release() }, ShouldPanic)
    76  			})
    77  		})
    78  	})
    79  }