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

     1  package internal_test
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  
     8  	"github.com/paketo-buildpacks/packit/internal"
     9  	"github.com/sclevine/spec"
    10  
    11  	. "github.com/onsi/gomega"
    12  	. "github.com/paketo-buildpacks/packit/matchers"
    13  )
    14  
    15  func testTOMLWriter(t *testing.T, context spec.G, it spec.S) {
    16  	var (
    17  		Expect = NewWithT(t).Expect
    18  
    19  		tmpDir     string
    20  		path       string
    21  		tomlWriter internal.TOMLWriter
    22  	)
    23  	it.Before(func() {
    24  		var err error
    25  		tmpDir, err = os.MkdirTemp("", "tomlWriter")
    26  		Expect(err).NotTo(HaveOccurred())
    27  
    28  		path = filepath.Join(tmpDir, "writer.toml")
    29  	})
    30  
    31  	it("writes the contents of a given object out to a .toml file", func() {
    32  		err := tomlWriter.Write(path, map[string]string{
    33  			"some-field":  "some-value",
    34  			"other-field": "other-value",
    35  		})
    36  		Expect(err).NotTo(HaveOccurred())
    37  
    38  		tomlFileContents, err := os.ReadFile(path)
    39  		Expect(err).NotTo(HaveOccurred())
    40  		Expect(string(tomlFileContents)).To(MatchTOML(`
    41  some-field = "some-value"
    42  other-field = "other-value"`))
    43  	})
    44  
    45  	context("failure cases", func() {
    46  		context("the .toml file cannot be created", func() {
    47  			it.Before(func() {
    48  				Expect(os.RemoveAll(tmpDir)).To(Succeed())
    49  			})
    50  
    51  			it("returns an error", func() {
    52  				err := tomlWriter.Write(path, map[string]string{
    53  					"some-field":  "some-value",
    54  					"other-field": "other-value",
    55  				})
    56  				Expect(err).To(MatchError(ContainSubstring("no such file or directory")))
    57  			})
    58  		})
    59  
    60  		context("the TOML data is invalid", func() {
    61  
    62  			it("returns an error", func() {
    63  				err := tomlWriter.Write(path, 0)
    64  				Expect(err).To(MatchError(ContainSubstring("Only a struct or map can be marshaled to TOML")))
    65  			})
    66  		})
    67  	})
    68  }