~dave-cheney/juju-core/102-cmd-init-context

« back to all changes in this revision

Viewing changes to cmd/filevar_test.go

  • Committer: Dave Cheney
  • Date: 2012-09-17 15:23:08 UTC
  • mfrom: (507.1.7 096-cmd-config-var)
  • Revision ID: david.cheney@canonical.com-20120917152308-vlt0nvcq4gwl6oj2
cmd: add FileVar flag and use it

PyJuJu had a nice construct that allowed a flag that was a file, or more
specifically the contents of a file to be handled nicely. As deploy ended
up implementing this, and I need it now for juju set, it made sense to 
pretty it up.

R=niemeyer
CC=
https://codereview.appspot.com/6490121

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package cmd_test
 
2
 
 
3
import (
 
4
        "io/ioutil"
 
5
        "launchpad.net/gnuflag"
 
6
        . "launchpad.net/gocheck"
 
7
        "launchpad.net/juju-core/cmd"
 
8
        "os"
 
9
        "path/filepath"
 
10
)
 
11
 
 
12
type FileVarSuite struct {
 
13
        ValidPath   string
 
14
        InvalidPath string // invalid path refers to a file which is not readable
 
15
}
 
16
 
 
17
var _ = Suite(&FileVarSuite{})
 
18
 
 
19
func (s *FileVarSuite) SetUpTest(c *C) {
 
20
        dir := c.MkDir()
 
21
        s.ValidPath = filepath.Join(dir, "valid.yaml")
 
22
        s.InvalidPath = filepath.Join(dir, "invalid.yaml")
 
23
        f, err := os.Create(s.ValidPath)
 
24
        c.Assert(err, IsNil)
 
25
        f.Close()
 
26
        f, err = os.Create(s.InvalidPath)
 
27
        c.Assert(err, IsNil)
 
28
        f.Close()
 
29
        err = os.Chmod(s.InvalidPath, 0) // make unreadable     
 
30
        c.Assert(err, IsNil)
 
31
}
 
32
 
 
33
func (s *FileVarSuite) TestValidFileVar(c *C) {
 
34
        fs, config := fs()
 
35
        err := fs.Parse(false, []string{"--config", s.ValidPath})
 
36
        c.Assert(err, IsNil)
 
37
        defer config.ReadCloser.Close()
 
38
        c.Assert(config.Path, Equals, s.ValidPath)
 
39
        c.Assert(config.ReadCloser, NotNil)
 
40
}
 
41
 
 
42
func (s *FileVarSuite) TestInvalidFileVar(c *C) {
 
43
        fs, config := fs()
 
44
        err := fs.Parse(false, []string{"--config", s.InvalidPath})
 
45
        c.Assert(err, ErrorMatches, ".*permission denied")
 
46
        c.Assert(config.Path, Equals, "")
 
47
        c.Assert(config.ReadCloser, IsNil)
 
48
}
 
49
 
 
50
func fs() (*gnuflag.FlagSet, *cmd.FileVar) {
 
51
        var config cmd.FileVar
 
52
        fs := gnuflag.NewFlagSet("", gnuflag.ContinueOnError)
 
53
        fs.SetOutput(ioutil.Discard)
 
54
        fs.Var(&config, "config", "the config")
 
55
        return fs, &config
 
56
}