func (s *RunSuite) TestAllMachines(c *gc.C) { mock := s.setupMockAPI() mock.setMachinesAlive("0", "1") response0 := mockResponse{ stdout: "megatron\n", machineId: "0", } response1 := mockResponse{ error: "command timed out", machineId: "1", } mock.setResponse("0", response0) unformatted := ConvertRunResults([]params.RunResult{ makeRunResult(response0), makeRunResult(response1), }) jsonFormatted, err := cmd.FormatJson(unformatted) c.Assert(err, gc.IsNil) context, err := testing.RunCommand(c, &RunCommand{}, []string{ "--format=json", "--all", "hostname", }) c.Assert(err, gc.IsNil) c.Check(testing.Stdout(context), gc.Equals, string(jsonFormatted)+"\n") }
func (s *RunSuite) TestRunForMachineAndUnit(c *gc.C) { mock := s.setupMockAPI() machineResponse := mockResponse{ stdout: "megatron\n", machineId: "0", } unitResponse := mockResponse{ stdout: "bumblebee", machineId: "1", unitId: "unit/0", } mock.setResponse("0", machineResponse) mock.setResponse("unit/0", unitResponse) unformatted := ConvertRunResults([]params.RunResult{ makeRunResult(machineResponse), makeRunResult(unitResponse), }) jsonFormatted, err := cmd.FormatJson(unformatted) c.Assert(err, gc.IsNil) context, err := testing.RunCommand(c, &RunCommand{}, []string{ "--format=json", "--machine=0", "--unit=unit/0", "hostname", }) c.Assert(err, gc.IsNil) c.Check(testing.Stdout(context), gc.Equals, string(jsonFormatted)+"\n") }
func (*SwitchSimpleSuite) TestShowsJujuEnv(c *gc.C) { defer testing.MakeFakeHome(c, testing.MultipleEnvConfig).Restore() os.Setenv("JUJU_ENV", "using-env") context, err := testing.RunCommand(c, &SwitchCommand{}, nil) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(context), gc.Equals, "using-env\n") }
func (*SwitchSimpleSuite) TestSettingWritesFile(c *gc.C) { defer testing.MakeFakeHome(c, testing.MultipleEnvConfig).Restore() context, err := testing.RunCommand(c, &SwitchCommand{}, []string{"erewhemos-2"}) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(context), gc.Equals, "erewhemos -> erewhemos-2\n") c.Assert(envcmd.ReadCurrentEnvironment(), gc.Equals, "erewhemos-2") }
func (s *PublishSuite) TestPreExistingPublishedEdge(c *gc.C) { addMeta(c, s.branch, "") // If it doesn't find the right digest on the first try, it asks again for // any digest at all to keep the tip in mind. There's a small chance that // on the second request the tip has changed and matches the digest we're // looking for, in which case we have the answer already. digest, err := s.branch.RevisionId() c.Assert(err, gc.IsNil) var body string body = `{"cs:precise/wordpress": {"errors": ["entry not found"]}}` testing.Server.Response(200, nil, []byte(body)) body = `{"cs:precise/wordpress": {"kind": "published", "digest": %q, "revision": 42}}` testing.Server.Response(200, nil, []byte(fmt.Sprintf(body, digest))) ctx, err := s.runPublish(c, "cs:precise/wordpress") c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "cs:precise/wordpress-42\n") req := testing.Server.WaitRequest() c.Assert(req.URL.Path, gc.Equals, "/charm-event") c.Assert(req.Form.Get("charms"), gc.Equals, "cs:precise/wordpress@"+digest) req = testing.Server.WaitRequest() c.Assert(req.URL.Path, gc.Equals, "/charm-event") c.Assert(req.Form.Get("charms"), gc.Equals, "cs:precise/wordpress") }
func (*SwitchSimpleSuite) TestListEnvironmentsOSJujuEnvSet(c *gc.C) { defer testing.MakeFakeHome(c, testing.MultipleEnvConfig).Restore() os.Setenv("JUJU_ENV", "using-env") context, err := testing.RunCommand(c, &SwitchCommand{}, []string{"--list"}) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(context), gc.Equals, expectedEnvironments) }
func (s *DebugLogSuite) TestLogOutput(c *gc.C) { s.PatchValue(&getDebugLogAPI, func(envName string) (DebugLogAPI, error) { return &fakeDebugLogAPI{log: "this is the log output"}, nil }) ctx, err := testing.RunCommand(c, &DebugLogCommand{}, nil) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "this is the log output") }
func (suite *PluginSuite) TestRunPluginWithFailing(c *gc.C) { suite.makeFailingPlugin("foo", 2) ctx := testing.Context(c) err := RunPlugin(ctx, "foo", []string{"some params"}) c.Assert(err, gc.ErrorMatches, "exit status 2") c.Assert(testing.Stdout(ctx), gc.Equals, "failing\n") c.Assert(testing.Stderr(ctx), gc.Equals, "") }
func (suite *PluginSuite) TestRunPluginExising(c *gc.C) { suite.makePlugin("foo", 0755) ctx := testing.Context(c) err := RunPlugin(ctx, "foo", []string{"some params"}) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "foo some params\n") c.Assert(testing.Stderr(ctx), gc.Equals, "") }
func (*SwitchSimpleSuite) TestCurrentEnvironmentHasPrecidence(c *gc.C) { home := testing.MakeFakeHome(c, testing.MultipleEnvConfig) defer home.Restore() home.AddFiles(c, []testing.TestFile{{".juju/current-environment", "fubar"}}) context, err := testing.RunCommand(c, &SwitchCommand{}, nil) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(context), gc.Equals, "fubar\n") }
func (s *RunTestSuite) TestNoContext(c *gc.C) { s.PatchValue(&LockDir, c.MkDir()) s.PatchValue(&AgentDir, c.MkDir()) ctx, err := testing.RunCommand(c, &RunCommand{}, []string{"--no-context", "echo done"}) c.Assert(err, jc.Satisfies, cmd.IsRcPassthroughError) c.Assert(err, gc.ErrorMatches, "subprocess encountered error code 0") c.Assert(testing.Stdout(ctx), gc.Equals, "done\n") }
func (s *PublishSuite) TestFullPublish(c *gc.C) { addMeta(c, s.branch, "") digest, err := s.branch.RevisionId() c.Assert(err, gc.IsNil) pushBranch := bzr.New(c.MkDir()) err = pushBranch.Init() c.Assert(err, gc.IsNil) cmd := &PublishCommand{} cmd.ChangePushLocation(func(location string) string { c.Assert(location, gc.Equals, "lp:~user/charms/precise/wordpress/trunk") return pushBranch.Location() }) cmd.SetPollDelay(testing.ShortWait) var body string // The local digest isn't found. body = `{"cs:~user/precise/wordpress": {"kind": "", "errors": ["entry not found"]}}` testing.Server.Response(200, nil, []byte(body)) // But the charm exists with an arbitrary non-matching digest. body = `{"cs:~user/precise/wordpress": {"kind": "published", "digest": "other-digest"}}` testing.Server.Response(200, nil, []byte(body)) // After the branch is pushed we fake the publishing delay. body = `{"cs:~user/precise/wordpress": {"kind": "published", "digest": "other-digest"}}` testing.Server.Response(200, nil, []byte(body)) // And finally report success. body = `{"cs:~user/precise/wordpress": {"kind": "published", "digest": %q, "revision": 42}}` testing.Server.Response(200, nil, []byte(fmt.Sprintf(body, digest))) ctx, err := testing.RunCommandInDir(c, cmd, []string{"cs:~user/precise/wordpress"}, s.dir) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "cs:~user/precise/wordpress-42\n") // Ensure the branch was actually pushed. pushDigest, err := pushBranch.RevisionId() c.Assert(err, gc.IsNil) c.Assert(pushDigest, gc.Equals, digest) // And that all the requests were sent with the proper data. req := testing.Server.WaitRequest() c.Assert(req.URL.Path, gc.Equals, "/charm-event") c.Assert(req.Form.Get("charms"), gc.Equals, "cs:~user/precise/wordpress@"+digest) for i := 0; i < 3; i++ { // The second request grabs tip to see the current state, and the // following requests are done after pushing to see when it changes. req = testing.Server.WaitRequest() c.Assert(req.URL.Path, gc.Equals, "/charm-event") c.Assert(req.Form.Get("charms"), gc.Equals, "cs:~user/precise/wordpress") } }
func (s *RunTestSuite) TestNoContextAsync(c *gc.C) { s.PatchValue(&LockDir, c.MkDir()) s.PatchValue(&AgentDir, c.MkDir()) channel := startRunAsync(c, []string{"--no-context", "echo done"}) ctx, err := waitForResult(channel) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "done\n") }
func (*SwitchSimpleSuite) TestJujuEnvOverCurrentEnvironment(c *gc.C) { home := testing.MakeFakeHome(c, testing.MultipleEnvConfig) defer home.Restore() home.AddFiles(c, []testing.TestFile{{".juju/current-environment", "fubar"}}) os.Setenv("JUJU_ENV", "using-env") context, err := testing.RunCommand(c, &SwitchCommand{}, nil) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(context), gc.Equals, "using-env\n") }
func (s *SetEnvironmentSuite) TestChangeAsCommandPair(c *gc.C) { _, err := testing.RunCommand(c, &SetEnvironmentCommand{}, []string{"default-series=raring"}) c.Assert(err, gc.IsNil) context, err := testing.RunCommand(c, &GetEnvironmentCommand{}, []string{"default-series"}) c.Assert(err, gc.IsNil) output := strings.TrimSpace(testing.Stdout(context)) c.Assert(output, gc.Equals, "raring") }
func (s *RunTestSuite) TestRunning(c *gc.C) { loggo.GetLogger("worker.uniter").SetLogLevel(loggo.TRACE) s.runListenerForAgent(c, "foo") ctx, err := testing.RunCommand(c, &RunCommand{}, []string{"foo", "bar"}) c.Check(cmd.IsRcPassthroughError(err), jc.IsTrue) c.Assert(err, gc.ErrorMatches, "subprocess encountered error code 42") c.Assert(testing.Stdout(ctx), gc.Equals, "bar stdout") c.Assert(testing.Stderr(ctx), gc.Equals, "bar stderr") }
func (s *RelationSetSuite) TestRunDeprecationWarning(c *gc.C) { hctx := s.GetHookContext(c, 0, "") com, _ := jujuc.NewCommand(hctx, "relation-set") // The rel= is needed to make this a valid command. ctx, err := testing.RunCommand(c, com, []string{"--format", "foo", "rel="}) c.Assert(err, gc.IsNil) c.Assert(testing.Stdout(ctx), gc.Equals, "") c.Assert(testing.Stderr(ctx), gc.Equals, "--format flag deprecated for command \"relation-set\"") }
func (s *LogSuite) TestShowLogSetsLogLevel(c *gc.C) { l := &cmd.Log{ShowLog: true} ctx := coretesting.Context(c) err := l.Start(ctx) c.Assert(err, gc.IsNil) c.Assert(loggo.GetLogger("").LogLevel(), gc.Equals, loggo.INFO) c.Assert(coretesting.Stderr(ctx), gc.Equals, "") c.Assert(coretesting.Stdout(ctx), gc.Equals, "") }
func (s *DeploySuite) TestUpgradeReportsDeprecated(c *gc.C) { coretesting.Charms.ClonedDirPath(s.SeriesPath, "dummy") ctx, err := coretesting.RunCommand(c, &DeployCommand{}, []string{"local:dummy", "-u"}) c.Assert(err, gc.IsNil) c.Assert(coretesting.Stdout(ctx), gc.Equals, "") output := strings.Split(coretesting.Stderr(ctx), "\n") c.Check(output[0], gc.Matches, `Added charm ".*" to the environment.`) c.Check(output[1], gc.Equals, "--upgrade (or -u) is deprecated and ignored; charms are always deployed with a unique revision.") }
func (s *ListKeysSuite) TestListFullKeys(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) context, err := coretesting.RunCommand(c, &ListKeysCommand{}, []string{"--full"}) c.Assert(err, gc.IsNil) output := strings.TrimSpace(coretesting.Stdout(context)) c.Assert(err, gc.IsNil) c.Assert(output, gc.Matches, "Keys for user admin:\n.*user@host\n.*another@host") }
func (s *SuperCommandSuite) TestMissingCallbackErrors(c *gc.C) { callback := func(ctx *cmd.Context, subcommand string, args []string) error { return fmt.Errorf("command not found %q", subcommand) } ctx := testing.Context(c) code := cmd.Main(NewSuperWithCallback(callback), ctx, []string{"foo"}) c.Assert(code, gc.Equals, 1) c.Assert(testing.Stdout(ctx), gc.Equals, "") c.Assert(testing.Stderr(ctx), gc.Equals, "ERROR command not found \"foo\"\n") }
func (s *RunSuite) TestSingleResponse(c *gc.C) { mock := s.setupMockAPI() mock.setMachinesAlive("0") mockResponse := mockResponse{ stdout: "stdout\n", stderr: "stderr\n", code: 42, machineId: "0", } mock.setResponse("0", mockResponse) unformatted := ConvertRunResults([]params.RunResult{ makeRunResult(mockResponse)}) yamlFormatted, err := cmd.FormatYaml(unformatted) c.Assert(err, gc.IsNil) jsonFormatted, err := cmd.FormatJson(unformatted) c.Assert(err, gc.IsNil) for i, test := range []struct { message string format string stdout string stderr string errorMatch string }{{ message: "smart (default)", stdout: "stdout\n", stderr: "stderr\n", errorMatch: "subprocess encountered error code 42", }, { message: "yaml output", format: "yaml", stdout: string(yamlFormatted) + "\n", }, { message: "json output", format: "json", stdout: string(jsonFormatted) + "\n", }} { c.Log(fmt.Sprintf("%v: %s", i, test.message)) args := []string{} if test.format != "" { args = append(args, "--format", test.format) } args = append(args, "--all", "ignored") context, err := testing.RunCommand(c, &RunCommand{}, args) if test.errorMatch != "" { c.Check(err, gc.ErrorMatches, test.errorMatch) } else { c.Check(err, gc.IsNil) } c.Check(testing.Stdout(context), gc.Equals, test.stdout) c.Check(testing.Stderr(context), gc.Equals, test.stderr) } }
func (s *LogSuite) TestLoggingToFileAndStderr(c *gc.C) { l := &cmd.Log{Path: "foo.log", Config: "<root>=INFO", ShowLog: true} ctx := coretesting.Context(c) err := l.Start(ctx) c.Assert(err, gc.IsNil) logger.Infof("hello") content, err := ioutil.ReadFile(filepath.Join(ctx.Dir, "foo.log")) c.Assert(err, gc.IsNil) c.Assert(string(content), gc.Matches, `^.* INFO .* hello\n`) c.Assert(coretesting.Stderr(ctx), gc.Matches, `^.* INFO .* hello\n`) c.Assert(coretesting.Stdout(ctx), gc.Equals, "") }
func (s *GetEnvironmentSuite) TestSingleValue(c *gc.C) { for _, t := range singleValueTests { context, err := testing.RunCommand(c, &GetEnvironmentCommand{}, []string{t.key}) if t.err != "" { c.Assert(err, gc.ErrorMatches, t.err) } else { output := strings.TrimSpace(testing.Stdout(context)) c.Assert(err, gc.IsNil) c.Assert(output, gc.Equals, t.output) } } }
func (s *LogSuite) TestErrorAndWarningLoggingToStderr(c *gc.C) { // Error and warning go to stderr even with ShowLog=false l := &cmd.Log{Config: "<root>=INFO", ShowLog: false} ctx := coretesting.Context(c) err := l.Start(ctx) c.Assert(err, gc.IsNil) logger.Warningf("a warning") logger.Errorf("an error") logger.Infof("an info") c.Assert(coretesting.Stderr(ctx), gc.Matches, `^.*WARNING a warning\n.*ERROR an error\n.*`) c.Assert(coretesting.Stdout(ctx), gc.Equals, "") }
func (s *SuperCommandSuite) TestMissingCallbackContextWiredIn(c *gc.C) { callback := func(ctx *cmd.Context, subcommand string, args []string) error { fmt.Fprintf(ctx.Stdout, "this is std out") fmt.Fprintf(ctx.Stderr, "this is std err") return nil } ctx := testing.Context(c) code := cmd.Main(NewSuperWithCallback(callback), ctx, []string{"foo", "bar", "baz", "--debug"}) c.Assert(code, gc.Equals, 0) c.Assert(testing.Stdout(ctx), gc.Equals, "this is std out") c.Assert(testing.Stderr(ctx), gc.Equals, "this is std err") }
func (s *DebugLogSuite) TestTailFallback(c *gc.C) { s.PatchValue(&runSSHCommand, func(sshCmd *SSHCommand, ctx *cmd.Context) error { fmt.Fprintf(ctx.Stdout, "%s", sshCmd.Args) return nil }) s.PatchValue(&getDebugLogAPI, func(envName string) (DebugLogAPI, error) { return &fakeDebugLogAPI{err: errors.NotSupportedf("testing")}, nil }) ctx, err := testing.RunCommand(c, &DebugLogCommand{}, []string{"-n", "100"}) c.Assert(err, gc.IsNil) c.Check(testing.Stderr(ctx), gc.Equals, "Server does not support new stream log, falling back to tail\n") c.Check(testing.Stdout(ctx), gc.Equals, "[tail -n -100 -f /var/log/juju/all-machines.log]") }
func (s *PortsSuite) TestOpenCloseDeprecation(c *gc.C) { hctx := s.GetHookContext(c, -1, "") for _, t := range portsFormatDeprectaionTests { name := t.cmd[0] com, err := jujuc.NewCommand(hctx, name) c.Assert(err, gc.IsNil) ctx := testing.Context(c) code := cmd.Main(com, ctx, t.cmd[1:]) c.Assert(code, gc.Equals, 0) c.Assert(testing.Stdout(ctx), gc.Equals, "") c.Assert(testing.Stderr(ctx), gc.Equals, "--format flag deprecated for command \""+name+"\"") } }
func (s *ImageMetadataSuite) TestImageMetadataFilesLatestLts(c *gc.C) { ctx := testing.Context(c) code := cmd.Main( &ImageMetadataCommand{}, ctx, []string{ "-d", s.dir, "-i", "1234", "-r", "region", "-a", "arch", "-u", "endpoint"}) c.Assert(code, gc.Equals, 0) out := testing.Stdout(ctx) expected := expectedMetadata{ series: config.LatestLtsSeries(), arch: "arch", } s.assertCommandOutput(c, expected, out, defaultIndexFileName, defaultImageFileName) }
func (s *ListKeysSuite) TestListKeysNonDefaultUser(c *gc.C) { key1 := sshtesting.ValidKeyOne.Key + " user@host" key2 := sshtesting.ValidKeyTwo.Key + " another@host" s.setAuthorizedKeys(c, key1, key2) _, err := s.State.AddUser("fred", "password") c.Assert(err, gc.IsNil) context, err := coretesting.RunCommand(c, &ListKeysCommand{}, []string{"--user", "fred"}) c.Assert(err, gc.IsNil) output := strings.TrimSpace(coretesting.Stdout(context)) c.Assert(err, gc.IsNil) c.Assert(output, gc.Matches, "Keys for user fred:\n.*\\(user@host\\)\n.*\\(another@host\\)") }