github.com/cloudfoundry-attic/garden-linux@v0.333.2-candidate/port_pool/state_test.go (about)

     1  package port_pool_test
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path"
     7  
     8  	"github.com/cloudfoundry-incubator/garden-linux/port_pool"
     9  	. "github.com/onsi/ginkgo"
    10  	. "github.com/onsi/gomega"
    11  )
    12  
    13  var _ = Describe("State", func() {
    14  	var (
    15  		tmpDir   string
    16  		filePath string
    17  	)
    18  
    19  	BeforeEach(func() {
    20  		var err error
    21  
    22  		tmpDir, err = ioutil.TempDir("", "")
    23  		Expect(err).NotTo(HaveOccurred())
    24  		filePath = path.Join(tmpDir, "port_pool.json")
    25  	})
    26  
    27  	AfterEach(func() {
    28  		Expect(os.RemoveAll(tmpDir)).To(Succeed())
    29  	})
    30  
    31  	Describe("NewState", func() {
    32  		It("should parse the provided file", func() {
    33  			Expect(ioutil.WriteFile(filePath, []byte(`{
    34  				"offset": 10
    35  			}`), 0660)).To(Succeed())
    36  
    37  			portPoolState, err := port_pool.LoadState(filePath)
    38  			Expect(err).NotTo(HaveOccurred())
    39  
    40  			Expect(portPoolState.Offset).To(BeNumerically("==", 10))
    41  		})
    42  
    43  		Context("when the file does not exist", func() {
    44  			It("should return a wrapped error", func() {
    45  				_, err := port_pool.LoadState("/path/to/not/existing/banana")
    46  				Expect(err).To(MatchError(ContainSubstring("openning state file")))
    47  			})
    48  		})
    49  
    50  		Context("when the file is invalid", func() {
    51  			It("should return a wrapped error", func() {
    52  				Expect(ioutil.WriteFile(filePath, []byte(`{
    53  				"offset": `), 0660)).To(Succeed())
    54  
    55  				_, err := port_pool.LoadState(filePath)
    56  				Expect(err).To(MatchError(ContainSubstring("parsing state file")))
    57  			})
    58  		})
    59  	})
    60  
    61  	Describe("Save", func() {
    62  		It("should write the file", func() {
    63  			Expect(ioutil.WriteFile(filePath, []byte("{}"), 0660)).To(Succeed())
    64  			state := port_pool.State{
    65  				Offset: 10,
    66  			}
    67  
    68  			Expect(port_pool.SaveState(filePath, state)).To(Succeed())
    69  
    70  			contents, err := ioutil.ReadFile(filePath)
    71  			Expect(err).NotTo(HaveOccurred())
    72  
    73  			Expect(string(contents)).To(ContainSubstring("\"offset\":10"))
    74  		})
    75  
    76  		Context("when file can not be created", func() {
    77  			It("should return a sensible error", func() {
    78  				state := port_pool.State{
    79  					Offset: 10,
    80  				}
    81  
    82  				err := port_pool.SaveState("/path/to/my/basement/", state)
    83  				Expect(err).To(MatchError(ContainSubstring("creating state file")))
    84  			})
    85  		})
    86  	})
    87  })