示例#1
0
func (s *cmdMetricsCommandSuite) TestUnits(c *gc.C) {
	meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered"})
	meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Charm: meteredCharm})
	unit := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
	unit2 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
	newTime1 := time.Now().Round(time.Second)
	newTime2 := newTime1.Add(time.Second)
	metricA := state.Metric{"pings", "5", newTime1}
	metricB := state.Metric{"pings", "10.5", newTime2}
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit, Metrics: []state.Metric{metricA}})
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit2, Metrics: []state.Metric{metricA, metricB}})
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered/1")
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(cmdtesting.Stdout(ctx), gc.Equals,
		formatTabular(metric{
			Unit:      unit2.Name(),
			Timestamp: newTime2,
			Metric:    "pings",
			Value:     "10.5",
		}),
	)
	ctx, err = coretesting.RunCommand(c, metricsdebug.New(), "metered/0")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals,
		formatTabular(metric{
			Unit:      unit.Name(),
			Timestamp: newTime1,
			Metric:    "pings",
			Value:     "5",
		}),
	)
}
func (s *listAgreementsSuite) TestGetUsersAgreementsWithTermOwner(c *gc.C) {
	ctx, err := cmdtesting.RunCommand(c, listagreements.NewListAgreementsCommand())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, `[]
`)
	c.Assert(s.client.called, jc.IsTrue)

	s.client.setError("well, this is embarassing")
	ctx, err = cmdtesting.RunCommand(c, listagreements.NewListAgreementsCommand())
	c.Assert(err, gc.ErrorMatches, "failed to list user agreements: well, this is embarassing")
	c.Assert(s.client.called, jc.IsTrue)

	agreements := []terms.AgreementResponse{{
		User:      "******",
		Owner:     "owner",
		Term:      "test-term",
		Revision:  1,
		CreatedOn: time.Date(2015, 12, 25, 0, 0, 0, 0, time.UTC),
	}}
	s.client.setAgreements(agreements)

	ctx, err = cmdtesting.RunCommand(c, listagreements.NewListAgreementsCommand())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(ctx, gc.NotNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, expectedListAgreementsJSONOutputWithOwner)
	c.Assert(s.client.called, jc.IsTrue)

	ctx, err = cmdtesting.RunCommand(c, listagreements.NewListAgreementsCommand(), "--format", "yaml")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(ctx, gc.NotNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "- user: test-user\n  owner: owner\n  term: test-term\n  revision: 1\n  createdon: 2015-12-25T00:00:00Z\n")
	c.Assert(s.client.called, jc.IsTrue)
}
示例#3
0
文件: metrics_test.go 项目: bac/juju
func (s *metricsSuite) TestYAMLFormat(c *gc.C) {
	s.client.metrics = []params.MetricResult{{
		Unit:  "unit-metered-0",
		Key:   "pings",
		Value: "5.0",
		Time:  time.Date(2016, 8, 22, 12, 02, 03, 0, time.UTC),
	}, {
		Unit:  "unit-metered-0",
		Key:   "pongs",
		Value: "15.0",
		Time:  time.Date(2016, 8, 22, 12, 02, 04, 0, time.UTC),
	}}
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered", "--format", "yaml")
	c.Assert(err, jc.ErrorIsNil)
	s.client.CheckCall(c, 0, "GetMetrics", []string{"application-metered"})
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, `- unit: unit-metered-0
  timestamp: 2016-08-22T12:02:03Z
  metric: pings
  value: "5.0"
- unit: unit-metered-0
  timestamp: 2016-08-22T12:02:04Z
  metric: pongs
  value: "15.0"
`)
}
示例#4
0
文件: allocate_test.go 项目: bac/juju
func (s *allocateSuite) TestAllocate(c *gc.C) {
	s.mockAPI.resp = "allocation updated"
	ctx, err := s.run(c, "name:100", "db")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "allocation updated\n")
	s.mockAPI.CheckCall(c, 0, "CreateAllocation", "name", "100", "model-uuid", []string{"db"})
}
示例#5
0
文件: help_test.go 项目: juju/cmd
func (s *HelpCommandSuite) TestRegisterSuperAliasHelp(c *gc.C) {
	jc := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujutest",
	})
	sub := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name:        "bar",
		UsagePrefix: "jujutest",
		Purpose:     "bar functions",
	})
	jc.Register(sub)
	sub.Register(&simple{name: "foo"})

	jc.RegisterSuperAlias("bar-foo", "bar", "foo", nil)

	for _, test := range []struct {
		args []string
	}{
		{
			args: []string{"bar", "foo", "--help"},
		}, {
			args: []string{"bar", "help", "foo"},
		}, {
			args: []string{"help", "bar-foo"},
		}, {
			args: []string{"bar-foo", "--help"},
		},
	} {
		c.Logf("args: %v", test.args)
		ctx := cmdtesting.Context(c)
		code := cmd.Main(jc, ctx, test.args)
		c.Check(code, gc.Equals, 0)
		help := "Usage: jujutest bar foo\n\nSummary:\nto be simple\n"
		c.Check(cmdtesting.Stdout(ctx), gc.Equals, help)
	}
}
示例#6
0
func (s *updateAllocationSuite) TestUpdateAllocation(c *gc.C) {
	s.mockAPI.resp = "name budget set to 5"
	ctx, err := s.run(c, "name", "5")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "name budget set to 5\n")
	s.mockAPI.CheckCall(c, 0, "UpdateAllocation", "model-uuid", "name", "5")
}
示例#7
0
func (s *listBudgetsSuite) TestListBudgetsOutputNoBudgets(c *gc.C) {
	s.mockAPI.result = &budget.ListBudgetsResponse{
		Budgets: budget.BudgetSummaries{},
		Total: budget.BudgetTotals{
			Limit:       "0",
			Allocated:   "0",
			Available:   "0",
			Unallocated: "0",
			Consumed:    "0",
		},
		Credit: "0",
	}
	expected := "" +
		"BUDGET       \tMONTHLY\tALLOCATED\tAVAILABLE\tSPENT\n" +
		"TOTAL        \t      0\t        0\t        0\t    0\n" +
		"             \t       \t         \t         \t     \n" +
		"Credit limit:\t      0\t         \t         \t     \n"

	listBudgets := listbudgets.NewListBudgetsCommand()

	ctx, err := cmdtesting.RunCommand(c, listBudgets)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, expected)
	s.mockAPI.CheckCallNames(c, "ListBudgets")
}
示例#8
0
func (s *DebugMetricsCommandSuite) TestUnitJsonOutput(c *gc.C) {
	meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered"})
	meteredService := s.Factory.MakeService(c, &factory.ServiceParams{Charm: meteredCharm})
	unit := s.Factory.MakeUnit(c, &factory.UnitParams{Service: meteredService, SetCharmURL: true})
	newTime := time.Now().Round(time.Second)
	metricA := state.Metric{"pings", "5", newTime}
	metricB := state.Metric{"pings", "10.5", newTime}
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit, Metrics: []state.Metric{metricA}})
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit, Metrics: []state.Metric{metricA, metricB}})
	outputTime := newTime.Format(time.RFC3339)
	expectedOutput := fmt.Sprintf(`[
    {
        "time": "%v",
        "key": "pings",
        "value": "5"
    },
    {
        "time": "%v",
        "key": "pings",
        "value": "5"
    },
    {
        "time": "%v",
        "key": "pings",
        "value": "10.5"
    }
]`, outputTime, outputTime, outputTime)
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered/0", "--json")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, expectedOutput)
}
示例#9
0
func (s *DebugMetricsCommandSuite) TestNoMetrics(c *gc.C) {
	meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered"})
	meteredService := s.Factory.MakeService(c, &factory.ServiceParams{Charm: meteredCharm})
	s.Factory.MakeUnit(c, &factory.UnitParams{Service: meteredService, SetCharmURL: true})
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered", "-n", "2")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "")
}
示例#10
0
func (s *allocateSuite) TestAllocate(c *gc.C) {
	s.mockAPI.resp = "allocation updated"
	alloc := allocate.NewAllocateCommand()
	ctx, err := cmdtesting.RunCommand(c, alloc, "name:100", "db")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "allocation updated")
	s.mockAPI.CheckCall(c, 0, "CreateAllocation", "name", "100", "env-uuid", []string{"db"})
}
示例#11
0
func (s *listBudgetsSuite) TestListBudgetsNoOutput(c *gc.C) {
	listBudgets := listbudgets.NewListBudgetsCommand()

	ctx, err := cmdtesting.RunCommand(c, listBudgets)
	c.Assert(err, gc.ErrorMatches, `no budget information available`)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, ``)
	s.mockAPI.CheckCallNames(c, "ListBudgets")
}
示例#12
0
func (s *updateAllocationSuite) TestUpdateAllocation(c *gc.C) {
	s.mockAPI.resp = "name budget set to 5"
	set := updateallocation.NewUpdateAllocationCommand()
	ctx, err := cmdtesting.RunCommand(c, set, "name", "5")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "name budget set to 5")
	s.mockAPI.CheckCall(c, 0, "UpdateAllocation", "env-uuid", "name", "5")
}
示例#13
0
func (s *setBudgetSuite) TestSetBudget(c *gc.C) {
	s.mockAPI.resp = "name budget set to 5"
	set := setbudget.NewSetBudgetCommand()
	ctx, err := cmdtesting.RunCommand(c, set, "name", "5")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "name budget set to 5\n")
	s.mockAPI.CheckCall(c, 0, "SetBudget", "name", "5")
}
示例#14
0
func (s *createBudgetSuite) TestCreateBudget(c *gc.C) {
	s.mockAPI.resp = "name budget set to 5"
	createCmd := createbudget.NewCreateBudgetCommand()
	ctx, err := cmdtesting.RunCommand(c, createCmd, "name", "5")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, "name budget set to 5")
	s.mockAPI.CheckCall(c, 0, "CreateBudget", "name", "5")
}
示例#15
0
func (s *listBudgetsSuite) TestListBudgetsOutput(c *gc.C) {
	s.mockAPI.result = &budget.ListBudgetsResponse{
		Budgets: budget.BudgetSummaries{
			budget.BudgetSummary{
				Owner:       "bob",
				Budget:      "personal",
				Limit:       "50",
				Allocated:   "30",
				Unallocated: "20",
				Available:   "45",
				Consumed:    "5",
			},
			budget.BudgetSummary{
				Owner:       "bob",
				Budget:      "work",
				Limit:       "200",
				Allocated:   "100",
				Unallocated: "100",
				Available:   "150",
				Consumed:    "50",
			},
			budget.BudgetSummary{
				Owner:       "bob",
				Budget:      "team",
				Limit:       "50",
				Allocated:   "10",
				Unallocated: "40",
				Available:   "40",
				Consumed:    "10",
			},
		},
		Total: budget.BudgetTotals{
			Limit:       "300",
			Allocated:   "140",
			Available:   "235",
			Unallocated: "160",
			Consumed:    "65",
		},
		Credit: "400",
	}
	// Expected command output. Make sure budgets are sorted alphabetically.
	expected := "" +
		"BUDGET       \tMONTHLY\tALLOCATED\tAVAILABLE\tSPENT\n" +
		"personal     \t     50\t       30\t       45\t    5\n" +
		"team         \t     50\t       10\t       40\t   10\n" +
		"work         \t    200\t      100\t      150\t   50\n" +
		"TOTAL        \t    300\t      140\t      235\t   65\n" +
		"             \t       \t         \t         \t     \n" +
		"Credit limit:\t    400\t         \t         \t     \n"

	listBudgets := listbudgets.NewListBudgetsCommand()

	ctx, err := cmdtesting.RunCommand(c, listBudgets)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), jc.DeepEquals, expected)
	s.mockAPI.CheckCallNames(c, "ListBudgets")
}
示例#16
0
func (s *LogSuite) TestShowLogSetsLogLevel(c *gc.C) {
	l := &cmd.Log{ShowLog: true}
	ctx := cmdtesting.Context(c)
	err := l.Start(ctx)
	c.Assert(err, gc.IsNil)

	c.Assert(loggo.GetLogger("").LogLevel(), gc.Equals, loggo.INFO)
	c.Assert(cmdtesting.Stderr(ctx), gc.Equals, "")
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "")
}
示例#17
0
func (s *SuperCommandSuite) TestRegisterDeprecated(c *gc.C) {
	jc := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujutest",
	})

	// Test that calling with a nil command will not panic
	jc.RegisterDeprecated(nil, nil)

	jc.RegisterDeprecated(&simpleAlias{simple{name: "test-non-dep"}}, nil)
	jc.RegisterDeprecated(&simpleAlias{simple{name: "test-dep"}}, deprecate{replacement: "test-dep-new"})
	jc.RegisterDeprecated(&simpleAlias{simple{name: "test-ob"}}, deprecate{obsolete: true})

	badCall := func() {
		jc.RegisterDeprecated(&simpleAlias{simple{name: "test-dep"}}, deprecate{replacement: "test-dep-new"})
	}
	c.Assert(badCall, gc.PanicMatches, `command already registered: "test-dep"`)

	for _, test := range []struct {
		args   []string
		stdout string
		stderr string
		code   int
	}{
		{
			args:   []string{"test-non-dep", "arg"},
			stdout: "test-non-dep arg\n",
		}, {
			args:   []string{"test-non-dep-alias", "arg"},
			stdout: "test-non-dep arg\n",
		}, {
			args:   []string{"test-dep", "arg"},
			stdout: "test-dep arg\n",
			stderr: "WARNING: \"test-dep\" is deprecated, please use \"test-dep-new\"\n",
		}, {
			args:   []string{"test-dep-alias", "arg"},
			stdout: "test-dep arg\n",
			stderr: "WARNING: \"test-dep-alias\" is deprecated, please use \"test-dep-new\"\n",
		}, {
			args:   []string{"test-ob", "arg"},
			stderr: "error: unrecognized command: jujutest test-ob\n",
			code:   2,
		}, {
			args:   []string{"test-ob-alias", "arg"},
			stderr: "error: unrecognized command: jujutest test-ob-alias\n",
			code:   2,
		},
	} {

		ctx := cmdtesting.Context(c)
		code := cmd.Main(jc, ctx, test.args)
		c.Check(code, gc.Equals, test.code)
		c.Check(cmdtesting.Stderr(ctx), gc.Equals, test.stderr)
		c.Check(cmdtesting.Stdout(ctx), gc.Equals, test.stdout)
	}
}
示例#18
0
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 := cmdtesting.Context(c)
	code := cmd.Main(NewSuperWithCallback(callback), ctx, []string{"foo"})
	c.Assert(code, gc.Equals, 1)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "")
	c.Assert(cmdtesting.Stderr(ctx), gc.Equals, "ERROR command not found \"foo\"\n")
}
示例#19
0
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 := cmdtesting.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(cmdtesting.Stderr(ctx), gc.Matches, `^.*WARNING a warning\n.*ERROR an error\n.*`)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "")
}
示例#20
0
func (s *LogSuite) TestLoggingToFileAndStderr(c *gc.C) {
	l := &cmd.Log{Path: "foo.log", Config: "<root>=INFO", ShowLog: true}
	ctx := cmdtesting.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(cmdtesting.Stderr(ctx), gc.Matches, `^.* INFO .* hello\n`)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "")
}
示例#21
0
func (s *agreeSuite) TestAgreementNothingToSign(c *gc.C) {
	jujutesting.PatchValue(agree.UserAnswer, func() (string, error) {
		return "y", nil
	})

	s.client.user = "******"
	s.client.setUnsignedTerms([]terms.GetTermsResponse{})

	ctx, err := cmdtesting.RunCommand(c, agree.NewAgreeCommand(), "test-term/1")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, `Already agreed
`)
}
示例#22
0
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 := cmdtesting.Context(c)
	code := cmd.Main(NewSuperWithCallback(callback), ctx, []string{"foo", "bar", "baz", "--debug"})
	c.Assert(code, gc.Equals, 0)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, "this is std out")
	c.Assert(cmdtesting.Stderr(ctx), gc.Equals, "this is std err")
}
示例#23
0
func (s *SuperCommandSuite) TestRegisterAlias(c *gc.C) {
	jc := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujutest",
	})
	jc.Register(&simple{name: "test"})
	jc.RegisterAlias("foo", "test", nil)
	jc.RegisterAlias("bar", "test", deprecate{replacement: "test"})
	jc.RegisterAlias("baz", "test", deprecate{obsolete: true})

	c.Assert(
		func() { jc.RegisterAlias("omg", "unknown", nil) },
		gc.PanicMatches, `"unknown" not found when registering alias`)

	info := jc.Info()
	// NOTE: deprecated `bar` not shown in commands.
	c.Assert(info.Doc, gc.Equals, `commands:
    foo  - alias for 'test'
    help - show help on a command or other topic
    test - to be simple`)

	for _, test := range []struct {
		name   string
		stdout string
		stderr string
		code   int
	}{
		{
			name:   "test",
			stdout: "test arg\n",
		}, {
			name:   "foo",
			stdout: "test arg\n",
		}, {
			name:   "bar",
			stdout: "test arg\n",
			stderr: "WARNING: \"bar\" is deprecated, please use \"test\"\n",
		}, {
			name:   "baz",
			stderr: "error: unrecognized command: jujutest baz\n",
			code:   2,
		},
	} {
		ctx := cmdtesting.Context(c)
		code := cmd.Main(jc, ctx, []string{test.name, "arg"})
		c.Check(code, gc.Equals, test.code)
		c.Check(cmdtesting.Stdout(ctx), gc.Equals, test.stdout)
		c.Check(cmdtesting.Stderr(ctx), gc.Equals, test.stderr)
	}
}
示例#24
0
文件: metrics_test.go 项目: bac/juju
func (s *metricsSuite) TestDefaultTabulatFormat(c *gc.C) {
	s.client.metrics = []params.MetricResult{{
		Unit:  "unit-metered-0",
		Key:   "pings",
		Value: "5.0",
		Time:  time.Date(2016, 8, 22, 12, 02, 03, 0, time.UTC),
	}, {
		Unit:  "unit-metered-0",
		Key:   "pongs",
		Value: "15.0",
		Time:  time.Date(2016, 8, 22, 12, 02, 04, 0, time.UTC),
	}}
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered/0")
	c.Assert(err, jc.ErrorIsNil)
	s.client.CheckCall(c, 0, "GetMetrics", []string{"unit-metered-0"})
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, `UNIT          	           TIMESTAMP	METRIC	VALUE
unit-metered-0	2016-08-22T12:02:03Z	 pings	  5.0
unit-metered-0	2016-08-22T12:02:04Z	 pongs	 15.0
`)
}
示例#25
0
func (s *DebugMetricsCommandSuite) TestUnits(c *gc.C) {
	meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered"})
	meteredService := s.Factory.MakeService(c, &factory.ServiceParams{Charm: meteredCharm})
	unit := s.Factory.MakeUnit(c, &factory.UnitParams{Service: meteredService, SetCharmURL: true})
	unit2 := s.Factory.MakeUnit(c, &factory.UnitParams{Service: meteredService, SetCharmURL: true})
	newTime := time.Now().Round(time.Second)
	metricA := state.Metric{"pings", "5", newTime}
	metricB := state.Metric{"pings", "10.5", newTime}
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit, Metrics: []state.Metric{metricA}})
	s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit2, Metrics: []state.Metric{metricA, metricB}})
	outputTime := newTime.Format(time.RFC3339)
	expectedOutput := bytes.Buffer{}
	tw := tabwriter.NewWriter(&expectedOutput, 0, 1, 1, ' ', 0)
	fmt.Fprintf(tw, "TIME\tMETRIC\tVALUE\n")
	fmt.Fprintf(tw, "%v\tpings\t5\n", outputTime)
	fmt.Fprintf(tw, "%v\tpings\t10.5\n", outputTime)
	tw.Flush()
	ctx, err := coretesting.RunCommand(c, metricsdebug.New(), "metered/1")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(cmdtesting.Stdout(ctx), gc.Equals, expectedOutput.String())
}
示例#26
0
func (s *SuperCommandSuite) TestRegisterSuperAlias(c *gc.C) {
	jc := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujutest",
	})
	jc.Register(&simple{name: "test"})
	sub := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name:        "bar",
		UsagePrefix: "jujutest",
		Purpose:     "bar functions",
	})
	jc.Register(sub)
	sub.Register(&simple{name: "foo"})

	c.Assert(
		func() { jc.RegisterSuperAlias("bar-foo", "unknown", "foo", nil) },
		gc.PanicMatches, `"unknown" not found when registering alias`)
	c.Assert(
		func() { jc.RegisterSuperAlias("bar-foo", "test", "foo", nil) },
		gc.PanicMatches, `"test" is not a SuperCommand`)
	c.Assert(
		func() { jc.RegisterSuperAlias("bar-foo", "bar", "unknown", nil) },
		gc.PanicMatches, `"unknown" not found as a command in "bar"`)

	jc.RegisterSuperAlias("bar-foo", "bar", "foo", nil)
	jc.RegisterSuperAlias("bar-dep", "bar", "foo", deprecate{replacement: "bar foo"})
	jc.RegisterSuperAlias("bar-ob", "bar", "foo", deprecate{obsolete: true})

	info := jc.Info()
	// NOTE: deprecated `bar` not shown in commands.
	c.Assert(info.Doc, gc.Equals, `commands:
    bar     - bar functions
    bar-foo - alias for 'bar foo'
    help    - show help on a command or other topic
    test    - to be simple`)

	for _, test := range []struct {
		args   []string
		stdout string
		stderr string
		code   int
	}{
		{
			args:   []string{"bar", "foo", "arg"},
			stdout: "foo arg\n",
		}, {
			args:   []string{"bar-foo", "arg"},
			stdout: "foo arg\n",
		}, {
			args:   []string{"bar-dep", "arg"},
			stdout: "foo arg\n",
			stderr: "WARNING: \"bar-dep\" is deprecated, please use \"bar foo\"\n",
		}, {
			args:   []string{"bar-ob", "arg"},
			stderr: "error: unrecognized command: jujutest bar-ob\n",
			code:   2,
		},
	} {
		ctx := cmdtesting.Context(c)
		code := cmd.Main(jc, ctx, test.args)
		c.Check(code, gc.Equals, test.code)
		c.Check(cmdtesting.Stdout(ctx), gc.Equals, test.stdout)
		c.Check(cmdtesting.Stderr(ctx), gc.Equals, test.stderr)
	}
}
示例#27
0
func (s *showBudgetSuite) TestShowBudgetCommand(c *gc.C) {
	tests := []struct {
		about      string
		args       []string
		err        string
		budget     string
		apierr     string
		resolveerr string
		output     string
	}{{
		about: "missing argument",
		err:   `missing arguments`,
	}, {
		about: "unknown arguments",
		args:  []string{"my-special-budget", "extra", "arguments"},
		err:   `unrecognized args: \["extra" "arguments"\]`,
	}, {
		about:  "api error",
		args:   []string{"personal"},
		apierr: "well, this is embarrassing",
		err:    "failed to retrieve the budget: well, this is embarrassing",
	}, {
		about:  "all ok",
		args:   []string{"personal"},
		budget: "personal",
		output: "" +
			"MODEL      \tSERVICES \tSPENT\tALLOCATED\tBY       \tUSAGE\n" +
			"model.joe  \tmysql    \t  200\t     1200\tuser.joe \t  42%\n" +
			"           \twordpress\t  300\t         \t         \n" +
			"model.jess \tlandscape\t  600\t     1000\tuser.jess\t  60%\n" +
			"uuid3      \tmysql    \t   10\t      100\tuser.bob \t  10%\n" +
			"           \t         \t     \t         \t         \n" +
			"TOTAL      \t         \t 1110\t     2300\t         \t  48%\n" +
			"BUDGET     \t         \t     \t     4000\t         \n" +
			"UNALLOCATED\t         \t     \t     1700\t         \n",
	}, {
		about:      "all ok",
		args:       []string{"personal"},
		budget:     "personal",
		resolveerr: "test error",
		output: "" +
			"MODEL      \tSERVICES \tSPENT\tALLOCATED\tBY       \tUSAGE\n" +
			"uuid1      \tmysql    \t  200\t     1200\tuser.joe \t  42%\n" +
			"           \twordpress\t  300\t         \t         \n" +
			"uuid2      \tlandscape\t  600\t     1000\tuser.jess\t  60%\n" +
			"uuid3      \tmysql    \t   10\t      100\tuser.bob \t  10%\n" +
			"           \t         \t     \t         \t         \n" +
			"TOTAL      \t         \t 1110\t     2300\t         \t  48%\n" +
			"BUDGET     \t         \t     \t     4000\t         \n" +
			"UNALLOCATED\t         \t     \t     1700\t         \n",
	},
	}

	for i, test := range tests {
		c.Logf("running test %d: %v", i, test.about)
		s.mockAPI.ResetCalls()

		errs := []error{}
		if test.apierr != "" {
			errs = append(errs, errors.New(test.apierr))
		} else {
			errs = append(errs, nil)
		}
		if test.resolveerr != "" {
			errs = append(errs, errors.New(test.resolveerr))
		} else {
			errs = append(errs, nil)
		}
		s.mockAPI.SetErrors(errs...)

		showBudget := showbudget.NewShowBudgetCommand()

		ctx, err := cmdtesting.RunCommand(c, showBudget, test.args...)
		if test.err == "" {
			c.Assert(err, jc.ErrorIsNil)
			s.stub.CheckCalls(c, []testing.StubCall{
				{"GetBudget", []interface{}{test.budget}},
				{"ModelInfo", []interface{}{[]names.ModelTag{names.NewModelTag("uuid1"), names.NewModelTag("uuid2"), names.NewModelTag("uuid3")}}},
			})
			output := cmdtesting.Stdout(ctx)
			c.Assert(output, gc.Equals, test.output)
		} else {
			c.Assert(err, gc.ErrorMatches, test.err)
		}
	}
}
示例#28
0
func (s *agreeSuite) TestAgreement(c *gc.C) {
	var answer string
	jujutesting.PatchValue(agree.UserAnswer, func() (string, error) {
		return answer, nil
	})

	s.client.user = "******"
	s.client.setUnsignedTerms([]terms.GetTermsResponse{{
		Name:     "test-term",
		Revision: 1,
		Content:  testTerms,
	}})
	tests := []struct {
		about    string
		args     []string
		err      string
		stdout   string
		answer   string
		apiCalls []jujutesting.StubCall
	}{{
		about:    "everything works",
		args:     []string{"test-term/1", "--yes"},
		stdout:   "Agreed to revision 1 of test-term for Juju users\n",
		apiCalls: []jujutesting.StubCall{{FuncName: "SaveAgreement", Args: []interface{}{&terms.SaveAgreements{Agreements: []terms.SaveAgreement{{TermName: "test-term", TermRevision: 1}}}}}},
	}, {
		about:    "everything works with owner term",
		args:     []string{"owner/test-term/1", "--yes"},
		stdout:   "Agreed to revision 1 of test-term for Juju users\n",
		apiCalls: []jujutesting.StubCall{{FuncName: "SaveAgreement", Args: []interface{}{&terms.SaveAgreements{Agreements: []terms.SaveAgreement{{TermOwner: "owner", TermName: "test-term", TermRevision: 1}}}}}},
	}, {
		about: "cannot parse revision number",
		args:  []string{"test-term/abc"},
		err:   "invalid term format: strconv.ParseInt: parsing \"abc\": invalid syntax",
	}, {
		about: "missing arguments",
		args:  []string{},
		err:   "missing arguments",
	}, {
		about:  "everything works - user accepts",
		args:   []string{"test-term/1"},
		answer: "y",
		stdout: `
=== test-term/1: 0001-01-01 00:00:00 +0000 UTC ===
Test Terms
========
Do you agree to the displayed terms? (Y/n): Agreed to revision 1 of test-term for Juju users
`,
		apiCalls: []jujutesting.StubCall{{
			FuncName: "GetUnunsignedTerms", Args: []interface{}{
				&terms.CheckAgreementsRequest{Terms: []string{"test-term/1"}},
			},
		}, {
			FuncName: "SaveAgreement", Args: []interface{}{
				&terms.SaveAgreements{Agreements: []terms.SaveAgreement{{TermName: "test-term", TermRevision: 1}}},
			},
		}},
	}, {
		about:  "everything works - user refuses",
		args:   []string{"test-term/1"},
		answer: "n",
		stdout: `
=== test-term/1: 0001-01-01 00:00:00 +0000 UTC ===
Test Terms
========
Do you agree to the displayed terms? (Y/n): You didn't agree to the presented terms.
`,
		apiCalls: []jujutesting.StubCall{{
			FuncName: "GetUnunsignedTerms", Args: []interface{}{
				&terms.CheckAgreementsRequest{Terms: []string{"test-term/1"}},
			},
		}},
	}, {
		about: "must not accept 0 revision",
		args:  []string{"test-term/0", "--yes"},
		err:   `must specify a valid term revision "test-term/0"`,
	}, {
		about:  "user accepts, multiple terms",
		args:   []string{"test-term/1", "test-term/2"},
		answer: "y",
		stdout: `
=== test-term/1: 0001-01-01 00:00:00 +0000 UTC ===
Test Terms
========
Do you agree to the displayed terms? (Y/n): Agreed to revision 1 of test-term for Juju users
`,
		apiCalls: []jujutesting.StubCall{
			{
				FuncName: "GetUnunsignedTerms", Args: []interface{}{
					&terms.CheckAgreementsRequest{Terms: []string{"test-term/1", "test-term/2"}},
				},
			}, {
				FuncName: "SaveAgreement", Args: []interface{}{
					&terms.SaveAgreements{Agreements: []terms.SaveAgreement{
						{TermName: "test-term", TermRevision: 1},
					}},
				},
			}},
	}, {
		about: "valid then unknown arguments",
		args:  []string{"test-term/1", "unknown", "arguments"},
		err:   `must specify a valid term revision "unknown"`,
	}, {
		about: "user accepts all the terms",
		args:  []string{"test-term/1", "test-term/2", "--yes"},
		stdout: `Agreed to revision 1 of test-term for Juju users
Agreed to revision 2 of test-term for Juju users
`,
		apiCalls: []jujutesting.StubCall{
			{FuncName: "SaveAgreement", Args: []interface{}{&terms.SaveAgreements{
				Agreements: []terms.SaveAgreement{
					{TermName: "test-term", TermRevision: 1},
					{TermName: "test-term", TermRevision: 2},
				}}}}},
	},
	}
	for i, test := range tests {
		s.client.ResetCalls()
		c.Logf("running test %d: %s", i, test.about)
		if test.answer != "" {
			answer = test.answer
		}
		ctx, err := cmdtesting.RunCommand(c, agree.NewAgreeCommand(), test.args...)
		if test.err != "" {
			c.Assert(err, gc.ErrorMatches, test.err)
		} else {
			c.Assert(err, jc.ErrorIsNil)
		}
		if ctx != nil {
			c.Assert(cmdtesting.Stdout(ctx), gc.Equals, test.stdout)
		}
		if len(test.apiCalls) > 0 {
			s.client.CheckCalls(c, test.apiCalls)
		}
	}
}
示例#29
0
文件: help_test.go 项目: juju/cmd
func (s *HelpCommandSuite) assertStdOutMatches(c *gc.C, ctx *cmd.Context, match string) {
	stripped := strings.Replace(cmdtesting.Stdout(ctx), "\n", "", -1)
	c.Assert(stripped, gc.Matches, match)
}