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

     1  package fs_test
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"github.com/paketo-buildpacks/packit/fs"
     9  	"github.com/sclevine/spec"
    10  
    11  	. "github.com/onsi/gomega"
    12  )
    13  
    14  func testExists(t *testing.T, context spec.G, it spec.S) {
    15  	var (
    16  		Expect = NewWithT(t).Expect
    17  
    18  		dirPath  string
    19  		filePath string
    20  	)
    21  
    22  	context("Exists", func() {
    23  		it.Before(func() {
    24  			var err error
    25  			dirPath, err = os.MkdirTemp("", "dir")
    26  			Expect(err).NotTo(HaveOccurred())
    27  			filePath = filepath.Join(dirPath, "some-file")
    28  		})
    29  
    30  		it.After(func() {
    31  			Expect(os.RemoveAll(dirPath)).To(Succeed())
    32  		})
    33  
    34  		context("when the file exists", func() {
    35  			it.Before(func() {
    36  				Expect(os.WriteFile(filePath, []byte("hello file"), 0644)).To(Succeed())
    37  			})
    38  
    39  			it("returns true", func() {
    40  				Expect(fs.Exists(filePath)).To(BeTrue())
    41  			})
    42  		})
    43  
    44  		context("when the file DOES NOT exists", func() {
    45  			it.Before(func() {
    46  				Expect(os.RemoveAll(dirPath)).To(Succeed())
    47  			})
    48  
    49  			it("returns false", func() {
    50  				Expect(fs.Exists(filePath)).To(BeFalse())
    51  			})
    52  		})
    53  
    54  		context("when the file cannot be read", func() {
    55  			it.Before(func() {
    56  				Expect(os.WriteFile(filePath, nil, 0644)).To(Succeed())
    57  				Expect(os.Chmod(dirPath, 0000)).To(Succeed())
    58  			})
    59  
    60  			it.After(func() {
    61  				Expect(os.Chmod(dirPath, os.ModePerm)).To(Succeed())
    62  			})
    63  
    64  			it("returns false and an error", func() {
    65  				exists, err := fs.Exists(filePath)
    66  				Expect(err.Error()).To(ContainSubstring("permission denied"))
    67  				Expect(exists).To(BeFalse())
    68  			})
    69  		})
    70  	})
    71  }