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