Ejemplo n.º 1
0
func (*jenvSuite) TestSuccess(c *gc.C) {
	// Create a jenv file.
	contents := makeJenvContents("who", "Secret!", "env-UUID", testing.CACert, "1.2.3.4:17070")
	f := openJenvFile(c, contents)
	defer f.Close()

	// Import the newly created jenv file.
	jenvCmd := &environment.JenvCommand{}
	ctx, err := testing.RunCommand(c, jenvCmd, f.Name())
	c.Assert(err, jc.ErrorIsNil)

	// The jenv file has been properly imported.
	assertJenvContents(c, contents, "testing")

	// The default environment is now the newly imported one, and the output
	// reflects the change.
	c.Assert(envcmd.ReadCurrentEnvironment(), gc.Equals, "testing")
	c.Assert(testing.Stdout(ctx), gc.Equals, "erewhemos -> testing\n")

	// Trying to import the jenv with the same name a second time raises an
	// error.
	jenvCmd = &environment.JenvCommand{}
	ctx, err = testing.RunCommand(c, jenvCmd, f.Name())
	c.Assert(err, gc.ErrorMatches, `an environment named "testing" already exists: you can provide a second parameter to rename the environment`)

	// Overriding the environment name solves the problem.
	jenvCmd = &environment.JenvCommand{}
	ctx, err = testing.RunCommand(c, jenvCmd, f.Name(), "another")
	c.Assert(err, jc.ErrorIsNil)
	assertJenvContents(c, contents, "another")
	c.Assert(envcmd.ReadCurrentEnvironment(), gc.Equals, "another")
	c.Assert(testing.Stdout(ctx), gc.Equals, "testing -> another\n")
}
Ejemplo n.º 2
0
func (s *HelpStorageSuite) assertHelp(c *gc.C, expectedNames []string) {
	ctx, err := testing.RunCommand(c, s.command, "--help")
	c.Assert(err, jc.ErrorIsNil)

	expected := "(?sm).*^purpose: " + s.command.Purpose + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^" + s.command.Doc + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)

	s.checkHelpCommands(c, ctx, expectedNames)
}
Ejemplo n.º 3
0
func (s *downloadSuite) TestHelp(c *gc.C) {
	ctx, err := testing.RunCommand(c, s.command, "download", "--help")
	c.Assert(err, jc.ErrorIsNil)

	info := s.subcommand.Info()
	expected := `(?sm)usage: juju backups download \[options] ` + info.Args + `$.*`
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^purpose: " + info.Purpose + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^" + info.Doc + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
}
Ejemplo n.º 4
0
func (s *uploadSuite) TestHelp(c *gc.C) {
	ctx, err := testing.RunCommand(c, s.command, "upload", "--help")
	c.Assert(err, jc.ErrorIsNil)

	info := s.subcommand.Info()
	expected := "(?sm)usage: juju backups upload [options] " + info.Args + "$.*"
	expected = strings.Replace(expected, "[", `\[`, -1)
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^purpose: " + info.Purpose + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^" + info.Doc + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
}
Ejemplo n.º 5
0
func (s *backupsSuite) TestHelp(c *gc.C) {
	ctx, err := testing.RunCommand(c, s.command, "--help")
	c.Assert(err, jc.ErrorIsNil)

	expected := "(?s)usage: juju backups \\[options\\] <command> .+"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^purpose: " + s.command.Purpose + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)
	expected = "(?sm).*^" + s.command.Doc + "$.*"
	c.Check(testing.Stdout(ctx), gc.Matches, expected)

	s.checkHelpCommands(c)
}
Ejemplo n.º 6
0
func (s *cmdRegistrationSuite) TestAddUserAndRegister(c *gc.C) {
	// First, add user "bob", and record the "juju register" command
	// that is printed out.
	context := s.run(c, nil, "add-user", "bob", "Bob Dobbs")
	c.Check(testing.Stderr(context), gc.Equals, "")
	stdout := testing.Stdout(context)
	c.Check(stdout, gc.Matches, `
User "Bob Dobbs \(bob\)" added
Please send this command to bob:
    juju register .*

"Bob Dobbs \(bob\)" has not been granted access to any models(.|\n)*
`[1:])
	jujuRegisterCommand := strings.Fields(strings.TrimSpace(
		strings.SplitN(stdout[strings.Index(stdout, "juju register"):], "\n", 2)[0],
	))
	c.Logf("%q", jujuRegisterCommand)

	// Now run the "juju register" command. We need to pass the
	// controller name and password to set.
	stdin := strings.NewReader("bob-controller\nhunter2\nhunter2\n")
	args := jujuRegisterCommand[1:] // drop the "juju"
	context = s.run(c, stdin, args...)
	c.Check(testing.Stdout(context), gc.Equals, "")
	c.Check(testing.Stderr(context), gc.Equals, `
Please set a name for this controller: 
Enter password: 
Confirm password: 

Welcome, bob. You are now logged into "bob-controller".

There are no models available. You can create models with
"juju create-model", or you can ask an administrator or owner
of a model to grant access to that model with "juju grant".

`[1:])

	// Make sure that the saved server details are sufficient to connect
	// to the api server.
	accountDetails, err := s.ControllerStore.AccountByName("bob-controller", "bob@local")
	c.Assert(err, jc.ErrorIsNil)
	api, err := juju.NewAPIConnection(juju.NewAPIConnectionParams{
		Store:           s.ControllerStore,
		ControllerName:  "bob-controller",
		AccountDetails:  accountDetails,
		BootstrapConfig: noBootstrapConfig,
		DialOpts:        api.DefaultDialOpts(),
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(api.Close(), jc.ErrorIsNil)
}
Ejemplo n.º 7
0
func (s *DestroySuite) TestDestroyCommandConfirmation(c *gc.C) {
	var stdin, stdout bytes.Buffer
	ctx, err := cmd.DefaultContext()
	c.Assert(err, jc.ErrorIsNil)
	ctx.Stdout = &stdout
	ctx.Stdin = &stdin

	// Ensure confirmation is requested if "-y" is not specified.
	stdin.WriteString("n")
	_, errc := cmdtesting.RunCommand(ctx, s.NewDestroyCommand(), "test2")
	select {
	case err := <-errc:
		c.Check(err, gc.ErrorMatches, "environment destruction: aborted")
	case <-time.After(testing.LongWait):
		c.Fatalf("command took too long")
	}
	c.Check(testing.Stdout(ctx), gc.Matches, "WARNING!.*test2(.|\n)*")
	checkEnvironmentExistsInStore(c, "test1", s.store)

	// EOF on stdin: equivalent to answering no.
	stdin.Reset()
	stdout.Reset()
	_, errc = cmdtesting.RunCommand(ctx, s.NewDestroyCommand(), "test2")
	select {
	case err := <-errc:
		c.Check(err, gc.ErrorMatches, "environment destruction: aborted")
	case <-time.After(testing.LongWait):
		c.Fatalf("command took too long")
	}
	c.Check(testing.Stdout(ctx), gc.Matches, "WARNING!.*test2(.|\n)*")
	checkEnvironmentExistsInStore(c, "test1", s.store)

	for _, answer := range []string{"y", "Y", "yes", "YES"} {
		stdin.Reset()
		stdout.Reset()
		stdin.WriteString(answer)
		_, errc = cmdtesting.RunCommand(ctx, s.NewDestroyCommand(), "test2")
		select {
		case err := <-errc:
			c.Check(err, jc.ErrorIsNil)
		case <-time.After(testing.LongWait):
			c.Fatalf("command took too long")
		}
		checkEnvironmentRemovedFromStore(c, "test2", s.store)

		// Add the test2 environment back into the store for the next test
		s.resetEnvironment(c)
	}
}
Ejemplo n.º 8
0
func (s *BaseActionSuite) checkHelp(c *gc.C, subcmd cmd.Command) {
	ctx, err := coretesting.RunCommand(c, s.command, subcmd.Info().Name, "--help")
	c.Assert(err, gc.IsNil)

	expected := "(?sm).*^usage: juju action " +
		regexp.QuoteMeta(subcmd.Info().Name) +
		` \[options\] ` + regexp.QuoteMeta(subcmd.Info().Args) + ".+"
	c.Check(coretesting.Stdout(ctx), gc.Matches, expected)

	expected = "(?sm).*^purpose: " + regexp.QuoteMeta(subcmd.Info().Purpose) + "$.*"
	c.Check(coretesting.Stdout(ctx), gc.Matches, expected)

	expected = "(?sm).*^" + regexp.QuoteMeta(subcmd.Info().Doc) + "$.*"
	c.Check(coretesting.Stdout(ctx), gc.Matches, expected)
}
Ejemplo n.º 9
0
func (*UserInfoCommandSuite) TestUserInfoFormatJson(c *gc.C) {
	context, err := testing.RunCommand(c, newUserInfoCommand(), "--format", "json")
	c.Assert(err, gc.IsNil)
	c.Assert(testing.Stdout(context), gc.Equals, `
{"user-name":"admin","display-name":"","date-created":"1981-02-27 16:10:05 +0000 UTC","last-connection":"2014-01-01 00:00:00 +0000 UTC"}
`[1:])
}
Ejemplo n.º 10
0
func (s *cmdLoginSuite) TestLoginCommand(c *gc.C) {
	s.createTestUser(c)

	// logout "admin" first; we'll need to give it
	// a non-random password before we can do so.
	s.changeUserPassword(c, "admin", "hunter2")
	s.run(c, nil, "logout")

	// TODO(axw) 2016-09-08 #1621375
	// "juju logout" should clear the cookies for the controller.
	os.Remove(filepath.Join(utils.Home(), ".go-cookies"))

	context := s.run(c, strings.NewReader("hunter2\nhunter2\n"), "login", "test")
	c.Assert(testing.Stdout(context), gc.Equals, "")
	c.Assert(testing.Stderr(context), gc.Equals, `
please enter password for test@local on kontroll: 
You are now logged in to "kontroll" as "test@local".
`[1:])

	// We should have a macaroon, but no password, in the client store.
	store := jujuclient.NewFileClientStore()
	accountDetails, err := store.AccountDetails("kontroll")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(accountDetails.Password, gc.Equals, "")

	// We should be able to login with the macaroon.
	s.run(c, nil, "status")
}
Ejemplo n.º 11
0
func (s *UserInfoCommandSuite) TestUserInfoFormatJsonWithUsername(c *gc.C) {
	context, err := testing.RunCommand(c, s.NewShowUserCommand(), "foobar", "--format", "json")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(context), gc.Equals, `
{"user-name":"foobar","display-name":"Foo Bar","access":"login","date-created":"1981-02-27","last-connection":"2014-01-01"}
`[1:])
}
Ejemplo n.º 12
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, jc.ErrorIsNil)

	context, err := testing.RunCommand(c, newRunCommand(),
		"--format=json", "--machine=0", "--unit=unit/0", "hostname",
	)
	c.Assert(err, jc.ErrorIsNil)

	c.Check(testing.Stdout(context), gc.Equals, string(jsonFormatted)+"\n")
}
Ejemplo n.º 13
0
func (s *cmdJujuSuite) TestServiceGet(c *gc.C) {
	expected := `charm: dummy
service: dummy-service
settings:
  outlook:
    default: true
    description: No default outlook.
    type: string
  skill-level:
    default: true
    description: A number indicating skill.
    type: int
  title:
    default: true
    description: A descriptive title used for the service.
    type: string
    value: My Title
  username:
    default: true
    description: The name of the initial account (given admin permissions).
    type: string
    value: admin001
`
	ch := s.AddTestingCharm(c, "dummy")
	s.AddTestingService(c, "dummy-service", ch)

	context, err := testing.RunCommand(c, service.NewGetCommand(), "dummy-service")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(context), gc.Equals, expected)
}
Ejemplo n.º 14
0
func (s *cmdControllerSuite) TestAddModel(c *gc.C) {
	// The JujuConnSuite doesn't set up an ssh key in the fake home dir,
	// so fake one on the command line.  The dummy provider also expects
	// a config value for 'controller'.
	context := s.run(c, "add-model", "new-model", "authorized-keys=fake-key", "controller=false")
	c.Check(testing.Stdout(context), gc.Equals, "")
	c.Check(testing.Stderr(context), gc.Equals, "added model \"new-model\"\n")

	// Make sure that the saved server details are sufficient to connect
	// to the api server.
	accountDetails, err := s.ControllerStore.AccountByName("kontroll", "admin@local")
	c.Assert(err, jc.ErrorIsNil)
	modelDetails, err := s.ControllerStore.ModelByName("kontroll", "admin@local", "new-model")
	c.Assert(err, jc.ErrorIsNil)
	api, err := juju.NewAPIConnection(juju.NewAPIConnectionParams{
		Store:           s.ControllerStore,
		ControllerName:  "kontroll",
		AccountDetails:  accountDetails,
		ModelUUID:       modelDetails.ModelUUID,
		BootstrapConfig: noBootstrapConfig,
		DialOpts:        api.DefaultDialOpts(),
	})
	c.Assert(err, jc.ErrorIsNil)
	api.Close()
}
Ejemplo n.º 15
0
func (s *ShowSuite) assertValidShow(c *gc.C, args []string, expected string) {
	context, err := runShow(c, args)
	c.Assert(err, jc.ErrorIsNil)

	obtained := testing.Stdout(context)
	c.Assert(obtained, gc.Matches, expected)
}
Ejemplo n.º 16
0
func (s *filesystemListSuite) assertUserFacingOutput(c *gc.C, context *cmd.Context, expectedOut, expectedErr string) {
	obtainedOut := testing.Stdout(context)
	c.Assert(obtainedOut, gc.Equals, expectedOut)

	obtainedErr := testing.Stderr(context)
	c.Assert(obtainedErr, gc.Equals, expectedErr)
}
Ejemplo n.º 17
0
func (s *SwitchSimpleSuite) TestNoArgsCurrentController(c *gc.C) {
	s.addController(c, "a-controller")
	s.currentController = "a-controller"
	ctx, err := s.run(c)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(coretesting.Stdout(ctx), gc.Equals, "a-controller\n")
}
Ejemplo n.º 18
0
func (s *poolListSuite) assertValidList(c *gc.C, args []string, expected string) {
	context, err := s.runPoolList(c, args)
	c.Assert(err, jc.ErrorIsNil)

	obtained := testing.Stdout(context)
	c.Assert(obtained, gc.Equals, expected)
}
Ejemplo n.º 19
0
func (s *APIInfoSuite) TestOutputNoServerUUID(c *gc.C) {
	s.PatchValue(&endpoint, func(c envcmd.EnvCommandBase, refresh bool) (configstore.APIEndpoint, error) {
		return configstore.APIEndpoint{
			Addresses:   []string{"localhost:12345", "10.0.3.1:12345"},
			CACert:      "this is the cacert",
			EnvironUUID: "deadbeef-dead-beef-dead-deaddeaddead",
		}, nil
	})
	s.PatchValue(&creds, func(c envcmd.EnvCommandBase) (configstore.APICredentials, error) {
		return configstore.APICredentials{
			User:     "******",
			Password: "******",
		}, nil
	})

	expected := "" +
		"user: tester\n" +
		"environ-uuid: deadbeef-dead-beef-dead-deaddeaddead\n" +
		"state-servers:\n" +
		"- localhost:12345\n" +
		"- 10.0.3.1:12345\n" +
		"ca-cert: this is the cacert\n"
	command := newAPIInfoCommand()
	ctx, err := testing.RunCommand(c, command)
	c.Check(err, jc.ErrorIsNil)
	c.Check(testing.Stdout(ctx), gc.Equals, expected)
}
Ejemplo n.º 20
0
func (s *LogoutCommandSuite) TestLogoutCount(c *gc.C) {
	// Create multiple controllers. We'll log out of each one
	// to observe the messages printed out by "logout".
	s.setPassword(c, "testing", "")
	controllers := []string{"testing", "testing2", "testing3"}
	details := s.store.Accounts["testing"]
	for _, controller := range controllers {
		s.store.Controllers[controller] = s.store.Controllers["testing"]
		err := s.store.UpdateAccount(controller, details)
		c.Assert(err, jc.ErrorIsNil)
	}

	expected := []string{
		"Logged out. You are still logged into 2 controllers.\n",
		"Logged out. You are still logged into 1 controller.\n",
		"Logged out. You are no longer logged into any controllers.\n",
	}

	for i, controller := range controllers {
		ctx, err := s.run(c, "-c", controller)
		c.Assert(err, jc.ErrorIsNil)
		c.Assert(coretesting.Stdout(ctx), gc.Equals, "")
		c.Assert(coretesting.Stderr(ctx), gc.Equals, expected[i])
	}
}
Ejemplo n.º 21
0
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, jc.ErrorIsNil)
	var body string
	body = `{"cs:precise/wordpress": {"errors": ["entry not found"]}}`
	gitjujutesting.Server.Response(200, nil, []byte(body))
	body = `{"cs:precise/wordpress": {"kind": "published", "digest": %q, "revision": 42}}`
	gitjujutesting.Server.Response(200, nil, []byte(fmt.Sprintf(body, digest)))

	ctx, err := s.runPublish(c, "cs:precise/wordpress")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(ctx), gc.Equals, "cs:precise/wordpress-42\n")

	req := gitjujutesting.Server.WaitRequest()
	c.Assert(req.URL.Path, gc.Equals, "/charm-event")
	c.Assert(req.Form.Get("charms"), gc.Equals, "cs:precise/wordpress@"+digest)

	req = gitjujutesting.Server.WaitRequest()
	c.Assert(req.URL.Path, gc.Equals, "/charm-event")
	c.Assert(req.Form.Get("charms"), gc.Equals, "cs:precise/wordpress")
}
Ejemplo n.º 22
0
func (*listImagesCommandSuite) TestListImagesFormatJson(c *gc.C) {
	context, err := runListCommand(c, "--format", "json", "--kind", "lxc", "--series", "trusty", "--arch", "amd64")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(context), gc.Equals, "Cached images:\n["+
		`{"kind":"lxc","series":"trusty","arch":"amd64","source-url":"http://image","created":"Thu, 01 Jan 2015 00:00:00 UTC"}`+
		"]\n")
}
Ejemplo n.º 23
0
func (s *GetSuite) TestSingleValueJSON(c *gc.C) {
	context, err := s.run(c, "--format=json", "name")
	c.Assert(err, jc.ErrorIsNil)

	output := strings.TrimSpace(testing.Stdout(context))
	c.Assert(output, gc.Equals, `"test-env"`)
}
Ejemplo n.º 24
0
func (s *cmdEnvironmentSuite) TestGet(c *gc.C) {
	err := s.State.UpdateEnvironConfig(map[string]interface{}{"special": "known"}, nil, nil)
	c.Assert(err, jc.ErrorIsNil)

	context := s.run(c, "get-environment", "special")
	c.Assert(testing.Stdout(context), gc.Equals, "known\n")
}
Ejemplo n.º 25
0
func (s *MachineShowCommandSuite) TestShowJsonMachine(c *gc.C) {
	context, err := testing.RunCommand(c, newMachineShowCommand(), "--format", "json", "0", "1")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(context), gc.Equals, ""+
		"{\"model\":\"dummyenv\",\"machines\":{\"0\":{\"agent-state\":\"started\",\"dns-name\":\"10.0.0.1\",\"instance-id\":\"juju-dummy-machine-0\",\"series\":\"trusty\",\"hardware\":\"availability-zone=us-east-1\"},\"1\":{\"agent-state\":\"pending\",\"dns-name\":\"10.0.0.2\",\"instance-id\":\"juju-dummy-machine-1\",\"series\":\"trusty\"}}}\n")

}
Ejemplo n.º 26
0
func (s *cmdModelSuite) TestModelConfigGet(c *gc.C) {
	err := s.State.UpdateModelConfig(map[string]interface{}{"special": "known"}, nil, nil)
	c.Assert(err, jc.ErrorIsNil)

	context := s.run(c, "model-config", "special")
	c.Assert(testing.Stdout(context), gc.Equals, "known\n")
}
Ejemplo n.º 27
0
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, jc.ErrorIsNil)

	context, err := testing.RunCommand(c, newRunCommand(), "--format=json", "--all", "hostname")
	c.Assert(err, jc.ErrorIsNil)

	c.Check(testing.Stdout(context), gc.Equals, string(jsonFormatted)+"\n")
}
Ejemplo n.º 28
0
func (s *GetSuite) TestSingleValue(c *gc.C) {
	context, err := s.run(c, "name")
	c.Assert(err, jc.ErrorIsNil)

	output := strings.TrimSpace(testing.Stdout(context))
	c.Assert(output, gc.Equals, "test-model")
}
Ejemplo n.º 29
0
func (s *EnableHASuite) TestEnableHADisallowsSeries(c *gc.C) {
	// We don't allow --series as an argument. This test ensures it is not
	// inadvertantly added back.
	ctx, err := s.runEnableHA(c, "-n", "0", "--series", "xenian")
	c.Assert(err, gc.ErrorMatches, "flag provided but not defined: --series")
	c.Assert(coretesting.Stdout(ctx), gc.Equals, "")
}
Ejemplo n.º 30
0
func (s *UserInfoCommandSuite) TestUserInfoFormatJson(c *gc.C) {
	context, err := testing.RunCommand(c, s.NewShowUserCommand(), "--format", "json")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(testing.Stdout(context), gc.Equals, `
{"user-name":"current-user","access":"addmodel","date-created":"1981-02-27","last-connection":"2014-01-01"}
`[1:])
}