Example #1
0
// Main registers subcommands for the juju-metadata executable, and hands over control
// to the cmd package. This function is not redundant with main, because it
// provides an entry point for testing with arbitrary command line arguments.
func Main(args []string) {
	ctx, err := cmd.DefaultContext()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(2)
	}
	if err := juju.InitJujuHome(); err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(2)
	}
	metadatacmd := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name:        "metadata",
		UsagePrefix: "juju",
		Doc:         metadataDoc,
		Purpose:     "tools for generating and validating image and tools metadata",
		Log:         &cmd.Log{}})

	metadatacmd.Register(envcmd.Wrap(&ValidateImageMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ImageMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ToolsMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ValidateToolsMetadataCommand{}))
	metadatacmd.Register(&SignMetadataCommand{})

	os.Exit(cmd.Main(metadatacmd, ctx, args[1:]))
}
Example #2
0
func (s *RemoveUserSuite) TestRemoveUser(c *gc.C) {
	_, err := testing.RunCommand(c, envcmd.Wrap(&UserAddCommand{}), "foobar")
	c.Assert(err, gc.IsNil)

	_, err = testing.RunCommand(c, envcmd.Wrap(&RemoveUserCommand{}), "foobar")
	c.Assert(err, gc.IsNil)
}
Example #3
0
func (s *BootstrapSuite) TestAutoUploadAfterFailedSync(c *gc.C) {
	s.PatchValue(&version.Current.Series, config.LatestLtsSeries())
	otherSeries := "quantal"

	env := s.setupAutoUploadTest(c, "1.7.3", otherSeries)
	// Run command and check for that upload has been run for tools matching the current juju version.
	opc, errc := runCommand(nullContext(c), envcmd.Wrap(new(BootstrapCommand)))
	c.Assert(<-errc, gc.IsNil)
	c.Assert((<-opc).(dummy.OpPutFile).Env, gc.Equals, "peckham")
	list, err := envtools.FindTools(env, version.Current.Major, version.Current.Minor, coretools.Filter{}, false)
	c.Assert(err, gc.IsNil)
	c.Logf("found: " + list.String())
	urls := list.URLs()

	// We expect:
	//     supported LTS series precise, trusty,
	//     the specified series (quantal),
	//     and the environment's default series (raring).
	expectedVers := []version.Binary{
		version.MustParseBinary(fmt.Sprintf("1.7.3.1-%s-%s", "quantal", version.Current.Arch)),
		version.MustParseBinary(fmt.Sprintf("1.7.3.1-%s-%s", "raring", version.Current.Arch)),
		version.MustParseBinary(fmt.Sprintf("1.7.3.1-%s-%s", "precise", version.Current.Arch)),
		version.MustParseBinary(fmt.Sprintf("1.7.3.1-%s-%s", "trusty", version.Current.Arch)),
	}
	c.Assert(urls, gc.HasLen, len(expectedVers))
	for _, vers := range expectedVers {
		c.Logf("seeking: " + vers.String())
		_, found := urls[vers]
		c.Check(found, gc.Equals, true)
	}
}
Example #4
0
func (s *BootstrapSuite) TestBootstrapTwice(c *gc.C) {
	env := resetJujuHome(c)
	defaultSeriesVersion := version.Current
	defaultSeriesVersion.Series = config.PreferredSeries(env.Config())
	// Force a dev version by having an odd minor version number.
	// This is because we have not uploaded any tools and auto
	// upload is only enabled for dev versions.
	defaultSeriesVersion.Minor = 11
	s.PatchValue(&version.Current, defaultSeriesVersion)

	_, err := coretesting.RunCommand(c, envcmd.Wrap(&BootstrapCommand{}))
	c.Assert(err, gc.IsNil)

	_, err = coretesting.RunCommand(c, envcmd.Wrap(&BootstrapCommand{}))
	c.Assert(err, gc.ErrorMatches, "environment is already bootstrapped")
}
Example #5
0
func (s *BootstrapSuite) runAllowRetriesTest(c *gc.C, test bootstrapRetryTest) {
	toolsVersions := envtesting.VAll
	if test.version != "" {
		useVersion := strings.Replace(test.version, "%LTS%", config.LatestLtsSeries(), 1)
		testVersion := version.MustParseBinary(useVersion)
		s.PatchValue(&version.Current, testVersion)
		if test.addVersionToSource {
			toolsVersions = append([]version.Binary{}, toolsVersions...)
			toolsVersions = append(toolsVersions, testVersion)
		}
	}
	resetJujuHome(c)
	sourceDir := createToolsSource(c, toolsVersions)
	s.PatchValue(&envtools.DefaultBaseURL, sourceDir)

	var findToolsRetryValues []bool
	mockFindTools := func(cloudInst environs.ConfigGetter, majorVersion, minorVersion int,
		filter coretools.Filter, allowRetry bool) (list coretools.List, err error) {
		findToolsRetryValues = append(findToolsRetryValues, allowRetry)
		return nil, errors.NotFoundf("tools")
	}

	restore := envtools.TestingPatchBootstrapFindTools(mockFindTools)
	defer restore()

	_, errc := runCommand(nullContext(c), envcmd.Wrap(new(BootstrapCommand)), test.args...)
	err := <-errc
	c.Check(findToolsRetryValues, gc.DeepEquals, test.expectedAllowRetry)
	stripped := strings.Replace(err.Error(), "\n", "", -1)
	c.Check(stripped, gc.Matches, test.err)
}
Example #6
0
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, envcmd.Wrap(&RunCommand{}),
		"--format=json", "--machine=0", "--unit=unit/0", "hostname",
	)
	c.Assert(err, gc.IsNil)

	c.Check(testing.Stdout(context), gc.Equals, string(jsonFormatted)+"\n")
}
Example #7
0
func (*RunSuite) TestTimeoutArgParsing(c *gc.C) {
	for i, test := range []struct {
		message  string
		args     []string
		errMatch string
		timeout  time.Duration
	}{{
		message: "default time",
		args:    []string{"--all", "sudo reboot"},
		timeout: 5 * time.Minute,
	}, {
		message:  "invalid time",
		args:     []string{"--timeout=foo", "--all", "sudo reboot"},
		errMatch: `invalid value "foo" for flag --timeout: time: invalid duration foo`,
	}, {
		message: "two hours",
		args:    []string{"--timeout=2h", "--all", "sudo reboot"},
		timeout: 2 * time.Hour,
	}, {
		message: "3 minutes 30 seconds",
		args:    []string{"--timeout=3m30s", "--all", "sudo reboot"},
		timeout: (3 * time.Minute) + (30 * time.Second),
	}} {
		c.Log(fmt.Sprintf("%v: %s", i, test.message))
		runCmd := &RunCommand{}
		testing.TestInit(c, envcmd.Wrap(runCmd), test.args, test.errMatch)
		if test.errMatch == "" {
			c.Check(runCmd.timeout, gc.Equals, test.timeout)
		}
	}
}
Example #8
0
func (s *BootstrapSuite) TestAutoUploadOnlyForDev(c *gc.C) {
	s.setupAutoUploadTest(c, "1.8.3", "precise")
	_, errc := runCommand(nullContext(c), envcmd.Wrap(new(BootstrapCommand)))
	err := <-errc
	stripped := strings.Replace(err.Error(), "\n", "", -1)
	c.Assert(stripped, gc.Matches, noToolsAvailableMessage)
}
Example #9
0
func (s *ValidateImageMetadataSuite) TestInitErrors(c *gc.C) {
	for i, t := range validateInitImageErrorTests {
		c.Logf("test %d", i)
		err := coretesting.InitCommand(envcmd.Wrap(&ValidateImageMetadataCommand{}), t.args)
		c.Check(err, gc.ErrorMatches, t.err)
	}
}
Example #10
0
func (s *DeploySuite) TestInitErrors(c *gc.C) {
	for i, t := range initErrorTests {
		c.Logf("test %d", i)
		err := coretesting.InitCommand(envcmd.Wrap(&DeployCommand{}), t.args)
		c.Assert(err, gc.ErrorMatches, t.err)
	}
}
Example #11
0
File: plugin.go Project: jkary/core
func RunPlugin(ctx *cmd.Context, subcommand string, args []string) error {
	cmdName := JujuPluginPrefix + subcommand
	plugin := envcmd.Wrap(&PluginCommand{name: cmdName})

	// We process common flags supported by Juju commands.
	// To do this, we extract only those supported flags from the
	// argument list to avoid confusing flags.Parse().
	flags := gnuflag.NewFlagSet(cmdName, gnuflag.ContinueOnError)
	flags.SetOutput(ioutil.Discard)
	plugin.SetFlags(flags)
	jujuArgs := extractJujuArgs(args)
	err := flags.Parse(false, jujuArgs)
	if err != nil {
		return err
	}

	plugin.Init(args)
	err = plugin.Run(ctx)
	_, execError := err.(*exec.Error)
	// exec.Error results are for when the executable isn't found, in
	// those cases, drop through.
	if !execError {
		return err
	}
	return &cmd.UnrecognizedCommand{Name: subcommand}
}
Example #12
0
func (s *SSHSuite) TestSSHCommand(c *gc.C) {
	m := s.makeMachines(3, c, true)
	ch := coretesting.Charms.Dir("dummy")
	curl := charm.MustParseURL(
		fmt.Sprintf("local:quantal/%s-%d", ch.Meta().Name, ch.Revision()),
	)
	bundleURL, err := url.Parse("http://bundles.testing.invalid/dummy-1")
	c.Assert(err, gc.IsNil)
	dummy, err := s.State.AddCharm(ch, curl, bundleURL, "dummy-1-sha256")
	c.Assert(err, gc.IsNil)
	srv := s.AddTestingService(c, "mysql", dummy)
	s.addUnit(srv, m[0], c)

	srv = s.AddTestingService(c, "mongodb", dummy)
	s.addUnit(srv, m[1], c)
	s.addUnit(srv, m[2], c)

	for i, t := range sshTests {
		c.Logf("test %d: %s -> %s\n", i, t.about, t.args)
		ctx := coretesting.Context(c)
		jujucmd := cmd.NewSuperCommand(cmd.SuperCommandParams{})
		jujucmd.Register(envcmd.Wrap(&SSHCommand{}))

		code := cmd.Main(jujucmd, ctx, t.args)
		c.Check(code, gc.Equals, 0)
		c.Check(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "")
		c.Check(ctx.Stdout.(*bytes.Buffer).String(), gc.Equals, t.result)
	}
}
Example #13
0
func (s *BootstrapSuite) TestBootstrapDestroy(c *gc.C) {
	resetJujuHome(c)
	devVersion := version.Current
	// Force a dev version by having an odd minor version number.
	// This is because we have not uploaded any tools and auto
	// upload is only enabled for dev versions.
	devVersion.Minor = 11
	s.PatchValue(&version.Current, devVersion)
	opc, errc := runCommand(nullContext(c), envcmd.Wrap(new(BootstrapCommand)), "-e", "brokenenv")
	err := <-errc
	c.Assert(err, gc.ErrorMatches, "dummy.Bootstrap is broken")
	var opDestroy *dummy.OpDestroy
	for opDestroy == nil {
		select {
		case op := <-opc:
			switch op := op.(type) {
			case dummy.OpDestroy:
				opDestroy = &op
			}
		default:
			c.Error("expected call to env.Destroy")
			return
		}
	}
	c.Assert(opDestroy.Error, gc.ErrorMatches, "dummy.Destroy is broken")
}
Example #14
0
// assertSetSuccess sets configuration options and checks the expected settings.
func assertSetSuccess(c *gc.C, dir string, svc *state.Service, args []string, expect charm.Settings) {
	ctx := coretesting.ContextForDir(c, dir)
	code := cmd.Main(envcmd.Wrap(&SetCommand{}), ctx, append([]string{"dummy-service"}, args...))
	c.Check(code, gc.Equals, 0)
	settings, err := svc.ConfigSettings()
	c.Assert(err, gc.IsNil)
	c.Assert(settings, gc.DeepEquals, expect)
}
Example #15
0
func (s *BootstrapSuite) TestMissingToolsError(c *gc.C) {
	s.setupAutoUploadTest(c, "1.8.3", "precise")

	_, err := coretesting.RunCommand(c, envcmd.Wrap(&BootstrapCommand{}))
	c.Assert(err, gc.ErrorMatches, "cannot upload bootstrap tools: Juju "+
		"cannot bootstrap because no tools are available for your "+
		"environment(.|\n)*")
}
Example #16
0
func (s *ImportKeySuite) TestImportKeys(c *gc.C) {
	key1 := sshtesting.ValidKeyOne.Key + " user@host"
	s.setAuthorizedKeys(c, key1)

	context, err := coretesting.RunCommand(c, envcmd.Wrap(&ImportKeysCommand{}), "lp:validuser", "invalid-key")
	c.Assert(err, gc.IsNil)
	c.Assert(coretesting.Stderr(context), gc.Matches, `cannot import key id "invalid-key".*\n`)
	s.assertEnvironKeys(c, key1, sshtesting.ValidKeyThree.Key)
}
Example #17
0
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, envcmd.Wrap(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")
	}
}
Example #18
0
func (s *ValidateImageMetadataSuite) TestEc2LocalMetadataNoMatch(c *gc.C) {
	s.setupEc2LocalMetadata(c, "us-east-1", "")
	ctx := coretesting.Context(c)
	code := cmd.Main(
		envcmd.Wrap(&ValidateImageMetadataCommand{}), ctx, []string{
			"-p", "ec2", "-s", "raring", "-r", "us-west-1",
			"-u", "https://ec2.us-west-1.amazonaws.com", "-d", s.metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	code = cmd.Main(
		envcmd.Wrap(&ValidateImageMetadataCommand{}), ctx, []string{
			"-p", "ec2", "-s", "precise", "-r", "region",
			"-u", "https://ec2.region.amazonaws.com", "-d", s.metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	errOut := ctx.Stderr.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `.*Resolve Metadata:.*`)
}
Example #19
0
func (s *BootstrapSuite) TestMissingToolsUploadFailedError(c *gc.C) {
	s.setupAutoUploadTest(c, "1.7.3", "precise")
	s.PatchValue(&sync.Upload, uploadToolsAlwaysFails)

	ctx, err := coretesting.RunCommand(c, envcmd.Wrap(&BootstrapCommand{}))

	c.Check(coretesting.Stderr(ctx), gc.Matches,
		"uploading tools for series \\[precise .* raring\\]\n")
	c.Check(err, gc.ErrorMatches, "cannot upload bootstrap tools: an error")
}
Example #20
0
func (s *DeploySuite) TestUpgradeReportsDeprecated(c *gc.C) {
	coretesting.Charms.ClonedDirPath(s.SeriesPath, "dummy")
	ctx, err := coretesting.RunCommand(c, envcmd.Wrap(&DeployCommand{}), "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.")
}
Example #21
0
func (s *AddKeySuite) TestAddKey(c *gc.C) {
	key1 := sshtesting.ValidKeyOne.Key + " user@host"
	s.setAuthorizedKeys(c, key1)

	key2 := sshtesting.ValidKeyTwo.Key + " another@host"
	context, err := coretesting.RunCommand(c, envcmd.Wrap(&AddKeysCommand{}), key2, "invalid-key")
	c.Assert(err, gc.IsNil)
	c.Assert(coretesting.Stderr(context), gc.Matches, `cannot add key "invalid-key".*\n`)
	s.assertEnvironKeys(c, key1, key2)
}
Example #22
0
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, envcmd.Wrap(&ListKeysCommand{}), "--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")
}
Example #23
0
func (s *PublishSuite) TestFullPublishRace(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(pollDelay)

	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))

	// And tip isn't found either, meaning the charm was never published.
	testing.Server.Response(200, nil, []byte(body))

	// After the branch is pushed we fake the publishing delay.
	testing.Server.Response(200, nil, []byte(body))

	// But, surprisingly, the digest changed to something else entirely.
	body = `{"cs:~user/precise/wordpress": {"kind": "published", "digest": "surprising-digest", "revision": 42}}`
	testing.Server.Response(200, nil, []byte(body))

	_, err = testing.RunCommandInDir(c, envcmd.Wrap(cmd), []string{"cs:~user/precise/wordpress"}, s.dir)
	c.Assert(err, gc.ErrorMatches, `charm changed but not to local charm digest; publishing race\?`)

	// 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")
	}
}
Example #24
0
func (s *ImportKeySuite) TestImportKeyNonDefaultUser(c *gc.C) {
	key1 := sshtesting.ValidKeyOne.Key + " user@host"
	s.setAuthorizedKeys(c, key1)
	_, err := s.State.AddUser("fred", "password")
	c.Assert(err, gc.IsNil)

	context, err := coretesting.RunCommand(c, envcmd.Wrap(&ImportKeysCommand{}), "--user", "fred", "lp:validuser")
	c.Assert(err, gc.IsNil)
	c.Assert(coretesting.Stderr(context), gc.Equals, "")
	s.assertEnvironKeys(c, key1, sshtesting.ValidKeyThree.Key)
}
Example #25
0
func (s *DeleteKeySuite) TestDeleteKeys(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, envcmd.Wrap(&DeleteKeysCommand{}),
		sshtesting.ValidKeyTwo.Fingerprint, "invalid-key")
	c.Assert(err, gc.IsNil)
	c.Assert(coretesting.Stderr(context), gc.Matches, `cannot delete key id "invalid-key".*\n`)
	s.assertEnvironKeys(c, key1)
}
Example #26
0
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, envcmd.Wrap(&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)
	}
}
Example #27
0
func (s *ValidateImageMetadataSuite) TestOpenstackLocalMetadataNoMatch(c *gc.C) {
	s.makeLocalMetadata(c, "1234", "region-2", "raring", "some-auth-url", "")
	ctx := coretesting.Context(c)
	code := cmd.Main(
		envcmd.Wrap(&ValidateImageMetadataCommand{}), ctx, []string{
			"-p", "openstack", "-s", "precise", "-r", "region-2",
			"-u", "some-auth-url", "-d", s.metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	errOut := ctx.Stderr.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `.*Resolve Metadata:.*`)
	code = cmd.Main(
		envcmd.Wrap(&ValidateImageMetadataCommand{}), ctx, []string{
			"-p", "openstack", "-s", "raring", "-r", "region-3",
			"-u", "some-auth-url", "-d", s.metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	errOut = ctx.Stderr.(*bytes.Buffer).String()
	strippedOut = strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `.*Resolve Metadata:.*`)
}
Example #28
0
func (s *ValidateImageMetadataSuite) assertEc2LocalMetadataUsingEnvironment(c *gc.C, stream string) {
	s.setupEc2LocalMetadata(c, "us-east-1", stream)
	ctx := coretesting.Context(c)
	code := cmd.Main(
		envcmd.Wrap(&ValidateImageMetadataCommand{}), ctx, []string{"-e", "ec2", "-d", s.metadataDir, "-m", stream},
	)
	c.Assert(code, gc.Equals, 0)
	errOut := ctx.Stdout.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(
		strippedOut, gc.Matches,
		`ImageIds:.*"1234".*Region:.*us-east-1.*Resolve Metadata:.*source: local metadata directory.*`)
}
Example #29
0
func (s *DeleteKeySuite) TestDeleteKeyNonDefaultUser(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, envcmd.Wrap(&DeleteKeysCommand{}),
		"--user", "fred", sshtesting.ValidKeyTwo.Fingerprint)
	c.Assert(err, gc.IsNil)
	c.Assert(coretesting.Stderr(context), gc.Equals, "")
	s.assertEnvironKeys(c, key1)
}
Example #30
0
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, envcmd.Wrap(&ListKeysCommand{}), "--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\\)")
}