github.com/Pankov404/juju@v0.0.0-20150703034450-be266991dceb/cmd/plugins/local/main_test.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package local_test 5 6 import ( 7 "fmt" 8 "os/exec" 9 "runtime" 10 "strings" 11 12 "github.com/juju/cmd" 13 "github.com/juju/testing" 14 jc "github.com/juju/testing/checkers" 15 gc "gopkg.in/check.v1" 16 17 "github.com/juju/juju/cmd/plugins/local" 18 coretesting "github.com/juju/juju/testing" 19 ) 20 21 type mainSuite struct { 22 coretesting.BaseSuite 23 } 24 25 var _ = gc.Suite(&mainSuite{}) 26 27 func (*mainSuite) TestRegisteredCommands(c *gc.C) { 28 expectedSubcommands := []string{ 29 "help", 30 "version", 31 // TODO: add some as they get registered 32 } 33 plugin := local.JujuLocalPlugin() 34 ctx, err := coretesting.RunCommand(c, plugin, "help", "commands") 35 c.Assert(err, jc.ErrorIsNil) 36 37 lines := strings.Split(coretesting.Stdout(ctx), "\n") 38 var names []string 39 for _, line := range lines { 40 f := strings.Fields(line) 41 if len(f) == 0 { 42 continue 43 } 44 names = append(names, f[0]) 45 } 46 // The names should be output in alphabetical order, so don't sort. 47 c.Assert(names, gc.DeepEquals, expectedSubcommands) 48 } 49 50 func (s *mainSuite) TestRunAsRootCallsFuncIfRoot(c *gc.C) { 51 s.PatchValue(local.CheckIfRoot, func() bool { return true }) 52 called := false 53 call := func(*cmd.Context) error { 54 called = true 55 return nil 56 } 57 args := []string{"ignored..."} 58 err := local.RunAsRoot("juju-magic", args, coretesting.Context(c), call) 59 c.Assert(err, jc.ErrorIsNil) 60 c.Assert(called, jc.IsTrue) 61 } 62 63 func (s *mainSuite) TestRunAsRootCallsSudoIfNotRoot(c *gc.C) { 64 if runtime.GOOS == "windows" { 65 c.Skip("No root on windows") 66 } 67 s.PatchValue(local.CheckIfRoot, func() bool { return false }) 68 testing.PatchExecutableAsEchoArgs(c, s, "sudo") 69 // the command needs to be in the path... 70 testing.PatchExecutableAsEchoArgs(c, s, "juju-magic") 71 magicPath, err := exec.LookPath("juju-magic") 72 c.Assert(err, jc.ErrorIsNil) 73 callIgnored := func(*cmd.Context) error { 74 panic("unreachable") 75 } 76 args := []string{"passed"} 77 context := coretesting.Context(c) 78 err = local.RunAsRoot("juju-magic", args, context, callIgnored) 79 c.Assert(err, jc.ErrorIsNil) 80 expected := fmt.Sprintf("sudo \"--preserve-env\" \"%s\" \"passed\"", magicPath) 81 c.Assert(strings.TrimRight(coretesting.Stdout(context), "\r\n"), gc.Equals, expected) 82 }