github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/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 "strings" 10 11 "github.com/juju/cmd" 12 "github.com/juju/testing" 13 jc "github.com/juju/testing/checkers" 14 gc "gopkg.in/check.v1" 15 16 "github.com/juju/juju/cmd/plugins/local" 17 coretesting "github.com/juju/juju/testing" 18 ) 19 20 type mainSuite struct { 21 coretesting.BaseSuite 22 } 23 24 var _ = gc.Suite(&mainSuite{}) 25 26 func (*mainSuite) TestRegisteredCommands(c *gc.C) { 27 expectedSubcommands := []string{ 28 "help", 29 "version", 30 // TODO: add some as they get registered 31 } 32 plugin := local.JujuLocalPlugin() 33 ctx, err := coretesting.RunCommand(c, plugin, "help", "commands") 34 c.Assert(err, jc.ErrorIsNil) 35 36 lines := strings.Split(coretesting.Stdout(ctx), "\n") 37 var names []string 38 for _, line := range lines { 39 f := strings.Fields(line) 40 if len(f) == 0 { 41 continue 42 } 43 names = append(names, f[0]) 44 } 45 // The names should be output in alphabetical order, so don't sort. 46 c.Assert(names, gc.DeepEquals, expectedSubcommands) 47 } 48 49 func (s *mainSuite) TestRunAsRootCallsFuncIfRoot(c *gc.C) { 50 s.PatchValue(local.CheckIfRoot, func() bool { return true }) 51 called := false 52 call := func(*cmd.Context) error { 53 called = true 54 return nil 55 } 56 args := []string{"ignored..."} 57 err := local.RunAsRoot("juju-magic", args, coretesting.Context(c), call) 58 c.Assert(err, jc.ErrorIsNil) 59 c.Assert(called, jc.IsTrue) 60 } 61 62 func (s *mainSuite) TestRunAsRootCallsSudoIfNotRoot(c *gc.C) { 63 s.PatchValue(local.CheckIfRoot, func() bool { return false }) 64 testing.PatchExecutableAsEchoArgs(c, s, "sudo") 65 // the command needs to be in the path... 66 testing.PatchExecutableAsEchoArgs(c, s, "juju-magic") 67 magicPath, err := exec.LookPath("juju-magic") 68 c.Assert(err, jc.ErrorIsNil) 69 callIgnored := func(*cmd.Context) error { 70 panic("unreachable") 71 } 72 args := []string{"passed"} 73 context := coretesting.Context(c) 74 err = local.RunAsRoot("juju-magic", args, context, callIgnored) 75 c.Assert(err, jc.ErrorIsNil) 76 expected := fmt.Sprintf("sudo \"--preserve-env\" %q \"passed\"\n", magicPath) 77 c.Assert(coretesting.Stdout(context), gc.Equals, expected) 78 }