github.com/paketo-buildpacks/packit@v1.3.2-0.20211206231111-86b75c657449/internal/file_writer_test.go (about)

     1  package internal_test
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  	"testing/iotest"
    10  
    11  	"github.com/paketo-buildpacks/packit/internal"
    12  	"github.com/sclevine/spec"
    13  
    14  	. "github.com/onsi/gomega"
    15  )
    16  
    17  func testFileWriter(t *testing.T, context spec.G, it spec.S) {
    18  	var (
    19  		Expect = NewWithT(t).Expect
    20  
    21  		tmpDir     string
    22  		path       string
    23  		fileWriter internal.FileWriter
    24  	)
    25  
    26  	it.Before(func() {
    27  		var err error
    28  		tmpDir, err = os.MkdirTemp("", "file-writer")
    29  		Expect(err).NotTo(HaveOccurred())
    30  
    31  		path = filepath.Join(tmpDir, "file.ext")
    32  	})
    33  
    34  	it("writes the contents of a reader out to a file path", func() {
    35  		err := fileWriter.Write(path, strings.NewReader("some-file-contents"))
    36  		Expect(err).NotTo(HaveOccurred())
    37  
    38  		contents, err := os.ReadFile(path)
    39  		Expect(err).NotTo(HaveOccurred())
    40  		Expect(string(contents)).To(Equal("some-file-contents"))
    41  	})
    42  
    43  	context("failure cases", func() {
    44  		context("when the file path cannot be created", func() {
    45  			it.Before(func() {
    46  				Expect(os.WriteFile(path, nil, 0000)).To(Succeed())
    47  			})
    48  
    49  			it("returns an error", func() {
    50  				err := fileWriter.Write(path, strings.NewReader("some-file-contents"))
    51  				Expect(err).To(MatchError(ContainSubstring("permission denied")))
    52  			})
    53  		})
    54  
    55  		context("when the reader throws an error", func() {
    56  			it("returns an error", func() {
    57  				err := fileWriter.Write(path, iotest.ErrReader(errors.New("failed to read")))
    58  				Expect(err).To(MatchError("failed to read"))
    59  			})
    60  		})
    61  	})
    62  }