func (s *RelationListSuite) TestRelationListHelp(c *gc.C) { template := ` usage: relation-list [options] purpose: list relation units options: --format (= smart) specify output format (json|smart|yaml) -o, --output (= "") specify an output file -r (= %s) specify a relation by id %s`[1:] for relid, t := range map[int]struct { usage, doc string }{ -1: {"", "\n-r must be specified when not in a relation hook\n"}, 0: {"peer0:0", ""}, } { c.Logf("test relid %d", relid) hctx := s.GetHookContext(c, relid, "") com, err := jujuc.NewCommand(hctx, "relation-list") c.Assert(err, gc.IsNil) ctx := testing.Context(c) code := cmd.Main(com, ctx, []string{"--help"}) c.Assert(code, gc.Equals, 0) expect := fmt.Sprintf(template, t.usage, t.doc) c.Assert(bufferString(ctx.Stdout), gc.Equals, expect) c.Assert(bufferString(ctx.Stderr), gc.Equals, "") } }
func (*NewAPIConnSuite) TestNewConn(c *gc.C) { cfg, err := config.New(config.NoDefaults, dummy.SampleConfig()) c.Assert(err, gc.IsNil) ctx := coretesting.Context(c) env, err := environs.Prepare(cfg, ctx, configstore.NewMem()) c.Assert(err, gc.IsNil) envtesting.UploadFakeTools(c, env.Storage()) err = bootstrap.Bootstrap(ctx, env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) cfg = env.Config() cfg, err = cfg.Apply(map[string]interface{}{ "secret": "fnord", }) c.Assert(err, gc.IsNil) err = env.SetConfig(cfg) c.Assert(err, gc.IsNil) conn, err := juju.NewAPIConn(env, api.DefaultDialOpts()) c.Assert(err, gc.IsNil) c.Assert(conn.Environ, gc.Equals, env) c.Assert(conn.State, gc.NotNil) // the secrets will not be updated, as they already exist attrs, err := conn.State.Client().EnvironmentGet() c.Assert(attrs["secret"], gc.Equals, "pork") c.Assert(conn.Close(), gc.IsNil) }
func (t *localServerSuite) TestAddresses(c *gc.C) { env := t.Prepare(c) envtesting.UploadFakeTools(c, env.Storage()) err := bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, gc.IsNil) addrs, err := inst.Addresses() c.Assert(err, gc.IsNil) // Expected values use Address type but really contain a regexp for // the value rather than a valid ip or hostname. expected := []instance.Address{{ Value: "*.testing.invalid", Type: instance.HostName, NetworkScope: instance.NetworkPublic, }, { Value: "*.internal.invalid", Type: instance.HostName, NetworkScope: instance.NetworkCloudLocal, }, { Value: "8.0.0.*", Type: instance.Ipv4Address, NetworkScope: instance.NetworkPublic, }, { Value: "127.0.0.*", Type: instance.Ipv4Address, NetworkScope: instance.NetworkCloudLocal, }} c.Assert(addrs, gc.HasLen, len(expected)) for i, addr := range addrs { c.Check(addr.Value, gc.Matches, expected[i].Value) c.Check(addr.Type, gc.Equals, expected[i].Type) c.Check(addr.NetworkScope, gc.Equals, expected[i].NetworkScope) } }
func (*CmdSuite) TestSetCommandInit(c *gc.C) { // missing args _, err := initSetCommand() c.Assert(err, gc.ErrorMatches, "no service name specified") // missing service name _, err = initSetCommand("name=cow") c.Assert(err, gc.ErrorMatches, "no service name specified") // test --config path expected := []byte("this: is some test data") ctx := coretesting.Context(c) path := ctx.AbsPath("testconfig.yaml") file, err := os.Create(path) c.Assert(err, gc.IsNil) _, err = file.Write(expected) c.Assert(err, gc.IsNil) file.Close() com, err := initSetCommand("--config", "testconfig.yaml", "service") c.Assert(err, gc.IsNil) c.Assert(com.SettingsYAML.Path, gc.Equals, "testconfig.yaml") actual, err := com.SettingsYAML.Read(ctx) c.Assert(err, gc.IsNil) c.Assert(actual, gc.DeepEquals, expected) // --config path, but no service com, err = initSetCommand("--config", "testconfig") c.Assert(err, gc.ErrorMatches, "no service name specified") // --config and options specified com, err = initSetCommand("service", "--config", "testconfig", "bees=") c.Assert(err, gc.ErrorMatches, "cannot specify --config when using key=value arguments") }
func (s *ConfigSuite) TestFirewallMode(c *gc.C) { for i, test := range firewallModeTests { c.Logf("test %d: %s", i, test.configFirewallMode) attrs := dummy.SampleConfig() if test.configFirewallMode != "" { attrs = attrs.Merge(testing.Attrs{ "firewall-mode": test.configFirewallMode, }) } cfg, err := config.New(config.NoDefaults, attrs) if err != nil { c.Assert(err, gc.ErrorMatches, test.errorMsg) continue } ctx := testing.Context(c) env, err := environs.Prepare(cfg, ctx, configstore.NewMem()) if test.errorMsg != "" { c.Assert(err, gc.ErrorMatches, test.errorMsg) continue } c.Assert(err, gc.IsNil) defer env.Destroy() firewallMode := env.Config().FirewallMode() c.Assert(firewallMode, gc.Equals, test.firewallMode) s.TearDownTest(c) } }
func (s *LiveTests) assertStartInstanceDefaultSecurityGroup(c *gc.C, useDefault bool) { attrs := s.TestConfig.Merge(coretesting.Attrs{ "name": "sample-" + randomName(), "control-bucket": "juju-test-" + randomName(), "use-default-secgroup": useDefault, }) cfg, err := config.New(config.NoDefaults, attrs) c.Assert(err, gc.IsNil) // Set up a test environment. env, err := environs.New(cfg) c.Assert(err, gc.IsNil) c.Assert(env, gc.NotNil) defer env.Destroy() // Bootstrap and start an instance. err = bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) inst, _ := jujutesting.AssertStartInstance(c, env, "100") // Check whether the instance has the default security group assigned. novaClient := openstack.GetNovaClient(env) groups, err := novaClient.GetServerSecurityGroups(string(inst.Id())) c.Assert(err, gc.IsNil) defaultGroupFound := false for _, group := range groups { if group.Name == "default" { defaultGroupFound = true break } } c.Assert(defaultGroupFound, gc.Equals, useDefault) }
func (s *DebugHooksSuite) TestDebugHooksCommand(c *gc.C) { machines := s.makeMachines(3, c, true) dummy := s.AddTestingCharm(c, "dummy") srv := s.AddTestingService(c, "mysql", dummy) s.addUnit(srv, machines[0], c) srv = s.AddTestingService(c, "mongodb", dummy) s.addUnit(srv, machines[1], c) s.addUnit(srv, machines[2], c) for i, t := range debugHooksTests { c.Logf("test %d: %s\n\t%s\n", i, t.info, t.args) ctx := coretesting.Context(c) debugHooksCmd := &DebugHooksCommand{} debugHooksCmd.proxy = true err := debugHooksCmd.Init(t.args) if err == nil { err = debugHooksCmd.Run(ctx) } if t.error != "" { c.Assert(err, gc.ErrorMatches, t.error) } else { c.Assert(err, gc.IsNil) } } }
func (s *RelationListSuite) TestRelationList(c *gc.C) { for i, t := range relationListTests { c.Logf("test %d: %s", i, t.summary) hctx := s.GetHookContext(c, t.relid, "") setMembers(hctx.rels[0], t.members0) setMembers(hctx.rels[1], t.members1) com, err := jujuc.NewCommand(hctx, "relation-list") c.Assert(err, gc.IsNil) ctx := testing.Context(c) code := cmd.Main(com, ctx, t.args) c.Logf(bufferString(ctx.Stderr)) c.Assert(code, gc.Equals, t.code) if code == 0 { c.Assert(bufferString(ctx.Stderr), gc.Equals, "") expect := t.out if expect != "" { expect = expect + "\n" } c.Assert(bufferString(ctx.Stdout), gc.Equals, expect) } else { c.Assert(bufferString(ctx.Stdout), gc.Equals, "") expect := fmt.Sprintf(`(.|\n)*error: %s\n`, t.out) c.Assert(bufferString(ctx.Stderr), gc.Matches, expect) } } }
func (t *ProviderSuite) assertGetImageMetadataSources(c *gc.C, stream, officialSourcePath string) { // Make an env configured with the stream. envAttrs := localConfigAttrs if stream != "" { envAttrs = envAttrs.Merge(coretesting.Attrs{ "image-stream": stream, }) } cfg, err := config.New(config.NoDefaults, envAttrs) c.Assert(err, gc.IsNil) env, err := environs.Prepare(cfg, coretesting.Context(c), configstore.NewMem()) c.Assert(err, gc.IsNil) c.Assert(env, gc.NotNil) sources, err := imagemetadata.GetMetadataSources(env) c.Assert(err, gc.IsNil) c.Assert(len(sources), gc.Equals, 2) var urls = make([]string, len(sources)) for i, source := range sources { url, err := source.URL("") c.Assert(err, gc.IsNil) urls[i] = url } // The control bucket URL contains the bucket name. c.Check(strings.Contains(urls[0], ec2.ControlBucketName(env)+"/images"), jc.IsTrue) c.Assert(urls[1], gc.Equals, fmt.Sprintf("http://cloud-images.ubuntu.com/%s/", officialSourcePath)) }
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) } }
func (*CmdSuite) TestDeployCommandInit(c *gc.C) { defer os.Setenv(osenv.JujuRepositoryEnvKey, os.Getenv(osenv.JujuRepositoryEnvKey)) os.Setenv(osenv.JujuRepositoryEnvKey, "/path/to/repo") for _, t := range deployTests { initExpectations(t.com) com, err := initDeployCommand(t.args...) c.Assert(err, gc.IsNil) c.Assert(com, gc.DeepEquals, t.com) } // test relative --config path ctx := coretesting.Context(c) expected := []byte("test: data") path := ctx.AbsPath("testconfig.yaml") file, err := os.Create(path) c.Assert(err, gc.IsNil) _, err = file.Write(expected) c.Assert(err, gc.IsNil) file.Close() com, err := initDeployCommand("--config", "testconfig.yaml", "charm-name") c.Assert(err, gc.IsNil) actual, err := com.Config.Read(ctx) c.Assert(err, gc.IsNil) c.Assert(expected, gc.DeepEquals, actual) // missing args _, err = initDeployCommand() c.Assert(err, gc.ErrorMatches, "no charm specified") // environment tested elsewhere }
func (s *SSHSuite) testSSHCommandHostAddressRetry(c *gc.C, proxy bool) { m := s.makeMachines(1, c, false) ctx := coretesting.Context(c) var called int next := func() bool { called++ return called < 2 } attemptStarter := &callbackAttemptStarter{next: next} s.PatchValue(&sshHostFromTargetAttemptStrategy, attemptStarter) // Ensure that the ssh command waits for a public address, or the attempt // strategy's Done method returns false. args := []string{"--proxy=" + fmt.Sprint(proxy), "0"} code := cmd.Main(&SSHCommand{}, ctx, args) c.Check(code, gc.Equals, 1) c.Assert(called, gc.Equals, 2) called = 0 attemptStarter.next = func() bool { called++ if called > 1 { s.setAddresses(m[0], c) } return true } code = cmd.Main(&SSHCommand{}, ctx, args) c.Check(code, gc.Equals, 0) c.Assert(called, gc.Equals, 2) }
// Prepare prepares an instance of the testing environment. func (t *Tests) Prepare(c *gc.C) environs.Environ { cfg, err := config.New(config.NoDefaults, t.TestConfig) c.Assert(err, gc.IsNil) e, err := environs.Prepare(cfg, coretesting.Context(c), t.ConfigStore) c.Assert(err, gc.IsNil, gc.Commentf("preparing environ %#v", t.TestConfig)) c.Assert(e, gc.NotNil) return e }
func (s *SuperCommandSuite) TestDescription(c *gc.C) { jc := cmd.NewSuperCommand(cmd.SuperCommandParams{Name: "jujutest", Purpose: "blow up the death star"}) jc.Register(&TestCommand{Name: "blah"}) ctx := testing.Context(c) code := cmd.Main(jc, ctx, []string{"blah", "--description"}) c.Assert(code, gc.Equals, 0) c.Assert(bufferString(ctx.Stdout), gc.Equals, "blow up the death star\n") }
func (s *providerSuite) TestPrepareUseSSHStorage(c *gc.C) { minimal := manual.MinimalConfigValues() minimal["use-sshstorage"] = false testConfig, err := config.New(config.UseDefaults, minimal) c.Assert(err, gc.IsNil) _, err = manual.ProviderInstance.Prepare(coretesting.Context(c), testConfig) c.Assert(err, gc.ErrorMatches, "use-sshstorage must not be specified") s.PatchValue(manual.NewSSHStorage, func(sshHost, storageDir, storageTmpdir string) (storage.Storage, error) { return nil, fmt.Errorf("newSSHStorage failed") }) minimal["use-sshstorage"] = true testConfig, err = config.New(config.UseDefaults, minimal) c.Assert(err, gc.IsNil) _, err = manual.ProviderInstance.Prepare(coretesting.Context(c), testConfig) c.Assert(err, gc.ErrorMatches, "initialising SSH storage failed: newSSHStorage failed") }
func (s *StorageSuite) SetUpTest(c *gc.C) { s.BaseSuite.SetUpTest(c) cfg, err := config.New(config.NoDefaults, dummy.SampleConfig()) c.Assert(err, gc.IsNil) s.env, err = environs.Prepare(cfg, testing.Context(c), configstore.NewMem()) c.Assert(err, gc.IsNil) s.dataDir = c.MkDir() }
func (suite *environSuite) TestBootstrapFailsIfNoNodes(c *gc.C) { suite.setupFakeTools(c) env := suite.makeEnviron() err := bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) // Since there are no nodes, the attempt to allocate one returns a // 409: Conflict. c.Check(err, gc.ErrorMatches, ".*409.*") }
func (s *ConfigGetSuite) TestAllPlusKey(c *gc.C) { hctx := s.GetHookContext(c, -1, "") com, err := jujuc.NewCommand(hctx, "config-get") c.Assert(err, gc.IsNil) ctx := testing.Context(c) code := cmd.Main(com, ctx, []string{"--all", "--format", "json", "monsters"}) c.Assert(code, gc.Equals, 2) c.Assert(bufferString(ctx.Stderr), gc.Equals, "error: cannot use argument --all together with key \"monsters\"\n") }
func (s *SuperCommandSuite) TestHelpWithPrefix(c *gc.C) { jc := cmd.NewSuperCommand(cmd.SuperCommandParams{Name: "jujutest", UsagePrefix: "juju"}) jc.Register(&TestCommand{Name: "blah"}) ctx := testing.Context(c) code := cmd.Main(jc, ctx, []string{"blah", "--help"}) c.Assert(code, gc.Equals, 0) stripped := strings.Replace(bufferString(ctx.Stdout), "\n", "", -1) c.Assert(stripped, gc.Matches, ".*usage: juju jujutest blah.*blah-doc.*") }
func (*configSuite) TestAvailabilitySetsEnabledImmutable(c *gc.C) { cfg, err := config.New(config.UseDefaults, makeAzureConfigMap(c)) c.Assert(err, gc.IsNil) env, err := azureEnvironProvider{}.Prepare(testing.Context(c), cfg) c.Assert(err, gc.IsNil) cfg, err = env.Config().Apply(map[string]interface{}{"availability-sets-enabled": false}) c.Assert(err, gc.IsNil) err = env.SetConfig(cfg) c.Assert(err, gc.ErrorMatches, "cannot change availability-sets-enabled") }
func (suite *environSuite) TestBootstrapSucceeds(c *gc.C) { suite.setupFakeTools(c) env := suite.makeEnviron() suite.testMAASObject.TestServer.NewNode(`{"system_id": "thenode", "hostname": "host"}`) lshwXML, err := suite.generateHWTemplate(map[string]string{"aa:bb:cc:dd:ee:f0": "eth0"}) c.Assert(err, gc.IsNil) suite.testMAASObject.TestServer.AddNodeDetails("thenode", lshwXML) err = bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) }
func (s *verifyStorageSuite) TestVerifyStorageFails(c *gc.C) { ctx := testing.Context(c) environ, err := environs.PrepareFromName("test", ctx, configstore.NewMem()) c.Assert(err, gc.IsNil) stor := environ.Storage() someError := errors.Unauthorizedf("you shall not pass") dummy.Poison(stor, environs.VerificationFilename, someError) err = environs.VerifyStorage(stor) c.Assert(err, gc.Equals, environs.VerifyStorageError) }
func (s *UnitGetSuite) TestOutputFormat(c *gc.C) { for _, t := range unitGetTests { com := s.createCommand(c) ctx := testing.Context(c) code := cmd.Main(com, ctx, t.args) c.Assert(code, gc.Equals, 0) c.Assert(bufferString(ctx.Stderr), gc.Equals, "") c.Assert(bufferString(ctx.Stdout), gc.Matches, t.out) } }
func (t *localServerSuite) TestInstanceStatus(c *gc.C) { env := t.Prepare(c) envtesting.UploadFakeTools(c, env.Storage()) err := bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) t.srv.ec2srv.SetInitialInstanceState(ec2test.Terminated) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, gc.IsNil) c.Assert(inst.Status(), gc.Equals, "terminated") }
func (t *localServerSuite) TestStartInstanceHardwareCharacteristics(c *gc.C) { env := t.Prepare(c) envtesting.UploadFakeTools(c, env.Storage()) err := bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{}) c.Assert(err, gc.IsNil) _, hc := testing.AssertStartInstance(c, env, "1") c.Check(*hc.Arch, gc.Equals, "amd64") c.Check(*hc.Mem, gc.Equals, uint64(1740)) c.Check(*hc.CpuCores, gc.Equals, uint64(1)) c.Assert(*hc.CpuPower, gc.Equals, uint64(100)) }
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 *UnitGetSuite) TestOutputPath(c *gc.C) { com := s.createCommand(c) ctx := testing.Context(c) code := cmd.Main(com, ctx, []string{"--output", "some-file", "private-address"}) c.Assert(code, gc.Equals, 0) c.Assert(bufferString(ctx.Stderr), gc.Equals, "") c.Assert(bufferString(ctx.Stdout), gc.Equals, "") content, err := ioutil.ReadFile(filepath.Join(ctx.Dir, "some-file")) c.Assert(err, gc.IsNil) c.Assert(string(content), gc.Equals, "192.168.0.99\n") }
func (s *providerSuite) TestPrepare(c *gc.C) { minimal := manual.MinimalConfigValues() minimal["use-sshstorage"] = true delete(minimal, "storage-auth-key") testConfig, err := config.New(config.UseDefaults, minimal) c.Assert(err, gc.IsNil) env, err := manual.ProviderInstance.Prepare(coretesting.Context(c), testConfig) c.Assert(err, gc.IsNil) cfg := env.Config() key, _ := cfg.UnknownAttrs()["storage-auth-key"].(string) c.Assert(key, jc.Satisfies, utils.IsValidUUIDString) }
// PrepareOnce ensures that the environment is // available and prepared. It sets t.Env appropriately. func (t *LiveTests) PrepareOnce(c *gc.C) { if t.prepared { return } cfg, err := config.New(config.NoDefaults, t.TestConfig) c.Assert(err, gc.IsNil) e, err := environs.Prepare(cfg, coretesting.Context(c), t.ConfigStore) c.Assert(err, gc.IsNil, gc.Commentf("preparing environ %#v", t.TestConfig)) c.Assert(e, gc.NotNil) t.Env = e t.prepared = true }
func (s *mainSuite) TestRunAsRootCallsFuncIfRoot(c *gc.C) { s.PatchValue(local.CheckIfRoot, func() bool { return true }) called := false call := func(*cmd.Context) error { called = true return nil } args := []string{"ignored..."} err := local.RunAsRoot("juju-magic", args, coretesting.Context(c), call) c.Assert(err, gc.IsNil) c.Assert(called, jc.IsTrue) }