github.com/kat-co/cmd@v0.0.0-20140616103059-5da365f9d57e/filevar_test.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package cmd_test
     5  
     6  import (
     7  	"io/ioutil"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	gitjujutesting "github.com/juju/testing"
    12  	"github.com/juju/utils"
    13  	"launchpad.net/gnuflag"
    14  	gc "launchpad.net/gocheck"
    15  
    16  	"github.com/juju/cmd"
    17  	"github.com/juju/cmd/cmdtesting"
    18  )
    19  
    20  type FileVarSuite struct {
    21  	gitjujutesting.FakeHomeSuite
    22  	ctx         *cmd.Context
    23  	ValidPath   string
    24  	InvalidPath string // invalid path refers to a file which is not readable
    25  }
    26  
    27  var _ = gc.Suite(&FileVarSuite{})
    28  
    29  func (s *FileVarSuite) SetUpTest(c *gc.C) {
    30  	s.FakeHomeSuite.SetUpTest(c)
    31  	s.ctx = cmdtesting.Context(c)
    32  	s.ValidPath = s.ctx.AbsPath("valid.yaml")
    33  	s.InvalidPath = s.ctx.AbsPath("invalid.yaml")
    34  	f, err := os.Create(s.ValidPath)
    35  	c.Assert(err, gc.IsNil)
    36  	f.Close()
    37  	f, err = os.Create(s.InvalidPath)
    38  	c.Assert(err, gc.IsNil)
    39  	f.Close()
    40  	err = os.Chmod(s.InvalidPath, 0) // make unreadable
    41  	c.Assert(err, gc.IsNil)
    42  }
    43  
    44  func (s *FileVarSuite) TestTildeFileVar(c *gc.C) {
    45  	path := filepath.Join(utils.Home(), "config.yaml")
    46  	err := ioutil.WriteFile(path, []byte("abc"), 0644)
    47  	c.Assert(err, gc.IsNil)
    48  
    49  	var config cmd.FileVar
    50  	config.Set("~/config.yaml")
    51  	file, err := config.Read(s.ctx)
    52  	c.Assert(err, gc.IsNil)
    53  	c.Assert(string(file), gc.Equals, "abc")
    54  }
    55  
    56  func (s *FileVarSuite) TestValidFileVar(c *gc.C) {
    57  	fs, config := fs()
    58  	err := fs.Parse(false, []string{"--config", s.ValidPath})
    59  	c.Assert(err, gc.IsNil)
    60  	c.Assert(config.Path, gc.Equals, s.ValidPath)
    61  	_, err = config.Read(s.ctx)
    62  	c.Assert(err, gc.IsNil)
    63  }
    64  
    65  func (s *FileVarSuite) TestInvalidFileVar(c *gc.C) {
    66  	fs, config := fs()
    67  	err := fs.Parse(false, []string{"--config", s.InvalidPath})
    68  	c.Assert(config.Path, gc.Equals, s.InvalidPath)
    69  	_, err = config.Read(s.ctx)
    70  	c.Assert(err, gc.ErrorMatches, "*permission denied")
    71  }
    72  
    73  func fs() (*gnuflag.FlagSet, *cmd.FileVar) {
    74  	var config cmd.FileVar
    75  	fs := cmdtesting.NewFlagSet()
    76  	fs.Var(&config, "config", "the config")
    77  	return fs, &config
    78  }