github.com/blend/go-sdk@v1.20220411.3/fileutil/file_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package fileutil
     9  
    10  import (
    11  	"crypto/rand"
    12  	"testing"
    13  
    14  	"github.com/blend/go-sdk/assert"
    15  )
    16  
    17  func TestFileReadByLines(t *testing.T) {
    18  	assert := assert.New(t)
    19  
    20  	f, err := NewTemp([]byte("this is a test\nof the emergency broadcast system\n"))
    21  	assert.Nil(err)
    22  	defer f.Close()
    23  
    24  	var called, lineCorrect, readFirstLine bool
    25  	err = ReadLines(f.Name(), func(line string) error {
    26  		called = true
    27  		if !readFirstLine {
    28  			lineCorrect = line == "this is a test"
    29  			readFirstLine = true
    30  		}
    31  		return nil
    32  	})
    33  
    34  	assert.Nil(err)
    35  	assert.True(called, "We should have called the handler for `README.md`")
    36  	assert.True(lineCorrect, "The first line should have matched the input")
    37  }
    38  
    39  func TestFileReadByChunks(t *testing.T) {
    40  	assert := assert.New(t)
    41  
    42  	buffer := make([]byte, 64)
    43  	_, err := rand.Read(buffer)
    44  	assert.Nil(err)
    45  
    46  	f, err := NewTemp(buffer)
    47  	assert.Nil(err)
    48  	defer f.Close()
    49  
    50  	var called, lengthCorrect bool
    51  	err = ReadChunks(f.Name(), 32, func(chunk []byte) error {
    52  		called = true
    53  		lengthCorrect = len(chunk) == 32
    54  		return nil
    55  	})
    56  
    57  	assert.Nil(err)
    58  	assert.True(called, "We should have called the handler for `README.md`")
    59  	assert.True(lengthCorrect, "We should have been passed 32 bytes")
    60  }