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