Ejemplo n.º 1
0
func (s *S) TestListNodesInTheSchedulerCmdRunWithFilters(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: `{
	"machines": [{"Id": "m-id-1", "Address": "localhost2"}],
	"nodes": [
		{"Address": "http://localhost1:8080", "Status": "disabled", "Metadata": {"meta1": "foo", "meta2": "bar"}},
		{"Address": "http://localhost2:9090", "Status": "disabled", "Metadata": {"meta1": "foo"}}
	]
}`, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/1.0/docker/node"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	cmd := listNodesInTheSchedulerCmd{}
	cmd.Flags().Parse(true, []string{"--filter", "meta1=foo", "-f", "meta2=bar"})
	err := cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	expected := `+------------------------+---------+----------+-----------+
| Address                | IaaS ID | Status   | Metadata  |
+------------------------+---------+----------+-----------+
| http://localhost1:8080 |         | disabled | meta1=foo |
|                        |         |          | meta2=bar |
+------------------------+---------+----------+-----------+
`
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 2
0
func (s *S) TestServiceDocRun(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	result := `This is a test doc for a test service.
Service test is foo bar.
`
	expected := result
	ctx := cmd.Context{
		Args:   []string{"foo"},
		Stdout: &stdout,
		Stderr: &stderr,
	}
	transport := testing.ConditionalTransport{
		Transport: testing.Transport{
			Message: result,
			Status:  http.StatusOK,
		},
		CondFunc: func(r *http.Request) bool {
			return r.Method == "GET" && r.URL.Path == "/services/foo/doc"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &transport}, nil, manager)
	err := (&ServiceDoc{}).Run(&ctx, client)
	c.Assert(err, gocheck.IsNil)
	obtained := stdout.String()
	c.Assert(obtained, gocheck.Equals, expected)
}
Ejemplo n.º 3
0
func (s *S) TestServiceBind(c *gocheck.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	ctx := cmd.Context{
		Args:   []string{"my-mysql"},
		Stdout: &stdout,
		Stderr: &stderr,
	}
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: `["DATABASE_HOST","DATABASE_USER","DATABASE_PASSWORD"]`, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			return req.Method == "PUT" && req.URL.Path == "/services/instances/my-mysql/g1"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := ServiceBind{}
	command.Flags().Parse(true, []string{"-a", "g1"})
	err := command.Run(&ctx, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(called, gocheck.Equals, true)
	expected := `Instance "my-mysql" is now bound to the app "g1".

The following environment variables are now available for use in your app:

- DATABASE_HOST
- DATABASE_USER
- DATABASE_PASSWORD

For more details, please check the documentation for the service, using service-doc command.
`
	c.Assert(stdout.String(), gocheck.Equals, expected)
}
Ejemplo n.º 4
0
func (s *S) TestListPoolsInTheSchedulerCmdRun(c *check.C) {
	var buf bytes.Buffer
	pool := provision.Pool{Name: "pool1", Teams: []string{"tsuruteam", "ateam"}}
	publicPool := provision.Pool{Name: "pool2", Public: true}
	defaultPool := provision.Pool{Name: "pool3", Default: true}
	pools := []provision.Pool{pool, publicPool, defaultPool}
	poolsJson, _ := json.Marshal(pools)
	ctx := cmd.Context{Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(poolsJson), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/pool"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	err := listPoolsInTheSchedulerCmd{}.Run(&ctx, client)
	c.Assert(err, check.IsNil)
	expected := `+-----------------+------------------+---------+
| Pools           | Teams            | Public  |
+-----------------+------------------+---------+
| pool1           | tsuruteam, ateam |         |
| pool2           |                  |    X    |
| pool3 (default) |                  |         |
+-----------------+------------------+---------+
`
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 5
0
func (s *S) TestServiceList(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	output := `[{"service": "mysql", "instances": ["mysql01", "mysql02"]}, {"service": "oracle", "instances": []}]`
	expectedPrefix := `+---------+------------------+
| Service | Instances        |`
	lineMysql := "| mysql   | mysql01, mysql02 |"
	lineOracle := "| oracle  |                  |"
	ctx := cmd.Context{
		Args:   []string{},
		Stdout: &stdout,
		Stderr: &stderr,
	}
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: output, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/services/instances"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	err := (&ServiceList{}).Run(&ctx, client)
	c.Assert(err, gocheck.IsNil)
	table := stdout.String()
	c.Assert(table, gocheck.Matches, "^"+expectedPrefix+".*")
	c.Assert(table, gocheck.Matches, "^.*"+lineMysql+".*")
	c.Assert(table, gocheck.Matches, "^.*"+lineOracle+".*")
}
Ejemplo n.º 6
0
func (s *S) TestListHealingHistoryCmdRunEmpty(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: `[]`, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/docker/healing"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	healing := &ListHealingHistoryCmd{}
	err := healing.Run(&context, client)
	c.Assert(err, check.IsNil)
	expected := `Node:
+-------+--------+---------+---------+---------+-------+
| Start | Finish | Success | Failing | Created | Error |
+-------+--------+---------+---------+---------+-------+
Container:
+-------+--------+---------+---------+---------+-------+
| Start | Finish | Success | Failing | Created | Error |
+-------+--------+---------+---------+---------+-------+
`
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 7
0
func (s *S) TestUpdatePoolToTheSchedulerCmd(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Args: []string{"poolTest"}, Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := map[string]interface{}{
				"default": interface{}(nil),
				"public":  true,
			}
			result := map[string]interface{}{}
			err = json.Unmarshal(body, &result)
			c.Assert(expected, check.DeepEquals, result)
			return req.URL.Path == "/pool/poolTest" && req.URL.Query().Get("force") == "false"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	cmd := updatePoolToSchedulerCmd{}
	cmd.Flags().Parse(true, []string{"--public", "true"})
	err := cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
}
Ejemplo n.º 8
0
func (s *S) TestAppLogWithNoSource(c *check.C) {
	var stdout, stderr bytes.Buffer
	t := time.Now()
	logs := []log{
		{Date: t, Message: "GET /", Source: "web"},
		{Date: t.Add(2 * time.Hour), Message: "POST /", Source: "web"},
	}
	result, err := json.Marshal(logs)
	c.Assert(err, check.IsNil)
	t = t.In(time.Local)
	tfmt := "2006-01-02 15:04:05 -0700"
	expected := cmd.Colorfy(t.Format(tfmt)+":", "blue", "", "") + " GET /\n"
	expected = expected + cmd.Colorfy(t.Add(2*time.Hour).Format(tfmt)+":", "blue", "", "") + " POST /\n"
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	fake := &cmdtest.FakeGuesser{Name: "hitthelights"}
	command := appLog{GuessingCommand: cmd.GuessingCommand{G: fake}}
	command.Flags().Parse(true, []string{"--lines", "12", "-f", "--no-source"})
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Query().Get("lines") == "12" && req.URL.Query().Get("follow") == "1"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, expected)
}
Ejemplo n.º 9
0
func (s *S) TestAppLogWithUnparsableData(c *check.C) {
	var stdout, stderr bytes.Buffer
	t := time.Now()
	logs := []log{
		{Date: t, Message: "creating app lost", Source: "tsuru"},
	}
	result, err := json.Marshal(logs)
	c.Assert(err, check.IsNil)
	t = t.In(time.Local)
	tfmt := "2006-01-02 15:04:05 -0700"

	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	command := appLog{}
	transport := cmdtest.Transport{
		Message: string(result) + "\nunparseable data",
		Status:  http.StatusOK,
	}
	client := cmd.NewClient(&http.Client{Transport: &transport}, nil, manager)
	command.Flags().Parse(true, []string{"--app", "appName"})
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	expected := cmd.Colorfy(t.Format(tfmt)+" [tsuru]:", "blue", "", "") + " creating app lost\n"
	expected += "Error: unparseable data"
	c.Assert(stdout.String(), check.Equals, expected)
}
Ejemplo n.º 10
0
func (s *S) TestAppLog(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	t := time.Now()
	logs := []log{
		{Date: t, Message: "creating app lost", Source: "tsuru"},
		{Date: t.Add(2 * time.Hour), Message: "app lost successfully created", Source: "app", Unit: "abcdef"},
	}
	result, err := json.Marshal(logs)
	c.Assert(err, gocheck.IsNil)
	t = t.In(time.Local)
	tfmt := "2006-01-02 15:04:05 -0700"
	expected := cmd.Colorfy(t.Format(tfmt)+" [tsuru]:", "blue", "", "") + " creating app lost\n"
	expected = expected + cmd.Colorfy(t.Add(2*time.Hour).Format(tfmt)+" [app][abcdef]:", "blue", "", "") + " app lost successfully created\n"
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	command := AppLog{}
	transport := testing.Transport{
		Message: string(result),
		Status:  http.StatusOK,
	}
	client := cmd.NewClient(&http.Client{Transport: &transport}, nil, manager)
	command.Flags().Parse(true, []string{"--app", "appName"})
	err = command.Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(stdout.String(), gocheck.Equals, expected)
}
Ejemplo n.º 11
0
func (s *S) TestPoolListRun(c *check.C) {
	var stdout, stderr bytes.Buffer
	result := `{"pools_by_team": [{"team": "test", "pools": ["pool"]}], "public_pools": [{"name": "public"}],"default_pool": [{"name": "default"}]}}`
	context := cmd.Context{
		Args:   []string{},
		Stdout: &stdout,
		Stderr: &stderr,
	}
	expected := `+------+-------+
| Team | Pools |
+------+-------+
| test | pool  |
+------+-------+

+--------------+
| Public Pools |
+--------------+
| public       |
+--------------+

+--------------+
| Default Pool |
+--------------+
| default      |
+--------------+
`
	client := cmd.NewClient(&http.Client{Transport: &cmdtest.Transport{Message: result, Status: http.StatusOK}}, nil, manager)
	command := poolList{}
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, expected)
}
Ejemplo n.º 12
0
func (s *S) TestAppLogByUnit(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	t := time.Now()
	logs := []log{
		{Date: t, Message: "creating app lost", Source: "tsuru", Unit: "api"},
		{Date: t.Add(2 * time.Hour), Message: "app lost successfully created", Source: "tsuru", Unit: "api"},
	}
	result, err := json.Marshal(logs)
	c.Assert(err, gocheck.IsNil)
	t = t.In(time.Local)
	tfmt := "2006-01-02 15:04:05 -0700"
	expected := cmd.Colorfy(t.Format(tfmt)+" [tsuru][api]:", "blue", "", "") + " creating app lost\n"
	expected = expected + cmd.Colorfy(t.Add(2*time.Hour).Format(tfmt)+" [tsuru][api]:", "blue", "", "") + " app lost successfully created\n"
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	fake := &FakeGuesser{name: "hitthelights"}
	command := AppLog{GuessingCommand: GuessingCommand{G: fake}}
	command.Flags().Parse(true, []string{"--unit", "api"})
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: string(result), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Query().Get("unit") == "api"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	err = command.Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(stdout.String(), gocheck.Equals, expected)
}
Ejemplo n.º 13
0
func (s *S) TestDockerLogUpdateRun(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	msg := tsuruIo.SimpleJsonMessage{Message: "success!!!"}
	result, _ := json.Marshal(msg)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusNoContent},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := provision.ScopedConfig{
				Envs: []provision.Entry{{Name: "a", Value: "1"}, {Name: "b", Value: "2"}, {Name: "log-driver", Value: "x"}},
			}
			var data logsSetData
			err = json.Unmarshal(body, &data)
			c.Assert(err, check.IsNil)
			sort.Sort(provision.ConfigEntryList(data.Config.Envs))
			c.Assert(data.Config, check.DeepEquals, expected)
			return req.URL.Path == "/1.0/docker/logs" && req.Method == "POST"
		},
	}
	manager := cmd.NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	cmd := dockerLogUpdate{}
	err := cmd.Flags().Parse(true, []string{"--log-driver", "x", "--log-opt", "a=1", "--log-opt", "b=2"})
	c.Assert(err, check.IsNil)
	err = cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "success!!!")
}
Ejemplo n.º 14
0
func (s *S) TestUpdateNodeToTheSchedulerCmdRun(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Args: []string{"http://localhost:1111", "x=y", "y=z"}, Stdout: &buf}
	expectedBody := map[string]string{
		"address": "http://localhost:1111",
		"x":       "y",
		"y":       "z",
	}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			body, _ := ioutil.ReadAll(req.Body)
			var parsed map[string]string
			err := json.Unmarshal(body, &parsed)
			c.Assert(err, check.IsNil)
			c.Assert(parsed, check.DeepEquals, expectedBody)
			return req.URL.Path == "/1.0/docker/node" && req.Method == "PUT" && req.URL.Query().Get("disabled") == "false"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	cmd := updateNodeToSchedulerCmd{}
	err := cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(buf.String(), check.Equals, "Node successfully updated.\n")
}
Ejemplo n.º 15
0
func (s *S) TestAutoScaleHistoryInProgressEndTimeCmdRun(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Stdout: &buf}
	msg := fmt.Sprintf(`[{
	"StartTime": "2015-10-23T08:00:00.000Z",
	"EndTime": "%s",
	"Successful": true,
	"Action": "add",
	"Reason": "",
	"MetadataValue": "poolx",
	"Error": ""
}]`, time.Time{}.Format(time.RFC3339))
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: msg, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/1.0/docker/autoscale"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	autoscale := &listAutoScaleHistoryCmd{}
	err := autoscale.Run(&context, client)
	c.Assert(err, check.IsNil)
	timeFormat, err := time.Parse(time.RFC3339, "2015-10-23T08:00:00.000Z")
	c.Assert(err, check.IsNil)
	startTime := timeFormat.Local().Format(time.Stamp)
	expected := fmt.Sprintf(`+-----------------+-------------+---------+----------+--------+--------+-------+
| Start           | Finish      | Success | Metadata | Action | Reason | Error |
+-----------------+-------------+---------+----------+--------+--------+-------+
| %s | in progress | true    | poolx    | add    |        |       |
+-----------------+-------------+---------+----------+--------+--------+-------+
`, startTime)
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 16
0
func (s *S) TestAppLogWithoutTheFlag(c *check.C) {
	var stdout, stderr bytes.Buffer
	t := time.Now()
	logs := []log{
		{Date: t, Message: "creating app lost", Source: "tsuru"},
		{Date: t.Add(2 * time.Hour), Message: "app lost successfully created", Source: "app"},
	}
	result, err := json.Marshal(logs)
	c.Assert(err, check.IsNil)
	t = t.In(time.Local)
	tfmt := "2006-01-02 15:04:05 -0700"
	expected := cmd.Colorfy(t.Format(tfmt)+" [tsuru]:", "blue", "", "") + " creating app lost\n"
	expected = expected + cmd.Colorfy(t.Add(2*time.Hour).Format(tfmt)+" [app]:", "blue", "", "") + " app lost successfully created\n"
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	fake := &cmdtest.FakeGuesser{Name: "hitthelights"}
	command := appLog{GuessingCommand: cmd.GuessingCommand{G: fake}}
	command.Flags().Parse(true, nil)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/apps/hitthelights/log" && req.Method == "GET" &&
				req.URL.Query().Get("lines") == "10"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, expected)
}
Ejemplo n.º 17
0
func (s *S) TestListHealingHistoryCmdRun(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: healingJsonData, Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/docker/healing"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	healing := &ListHealingHistoryCmd{}
	err := healing.Run(&context, client)
	c.Assert(err, check.IsNil)
	startT, _ := time.Parse(time.RFC3339, "2014-10-23T08:00:00.000Z")
	endT, _ := time.Parse(time.RFC3339, "2014-10-23T08:30:00.000Z")
	startTStr := startT.Local().Format(time.Stamp)
	endTStr := endT.Local().Format(time.Stamp)
	expected := fmt.Sprintf(`Node:
+-----------------+-----------------+---------+---------+---------+-------+
| Start           | Finish          | Success | Failing | Created | Error |
+-----------------+-----------------+---------+---------+---------+-------+
| %s | %s | true    | addr1   | addr2   |       |
+-----------------+-----------------+---------+---------+---------+-------+
Container:
+-----------------+-----------------+---------+------------+------------+-------+
| Start           | Finish          | Success | Failing    | Created    | Error |
+-----------------+-----------------+---------+------------+------------+-------+
| %s | %s | false   | 1234567890 |            | err1  |
+-----------------+-----------------+---------+------------+------------+-------+
| %s | %s | true    | 1234567890 | 9234567890 |       |
+-----------------+-----------------+---------+------------+------------+-------+
`, startTStr, endTStr, startTStr, endTStr, startTStr, endTStr)
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 18
0
func (s *S) TestAppInfo(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	result := `{"name":"app1","cname":"","ip":"myapp.tsuru.io","platform":"php","repository":"[email protected]:php.git","state":"dead", "units":[{"Ip":"10.10.10.10","Name":"app1/0","Status":"started"}, {"Ip":"9.9.9.9","Name":"app1/1","Status":"started"}, {"Ip":"","Name":"app1/2","Status":"pending"}],"teams":["tsuruteam","crane"], "owner": "myapp_owner", "deploys": 7}`
	expected := `Application: app1
Repository: [email protected]:php.git
Platform: php
Teams: tsuruteam, crane
Address: myapp.tsuru.io
Owner: myapp_owner
Deploys: 7
Units:
+--------+---------+
| Unit   | State   |
+--------+---------+
| app1/0 | started |
| app1/1 | started |
| app1/2 | pending |
+--------+---------+

`
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	client := cmd.NewClient(&http.Client{Transport: &testing.Transport{Message: result, Status: http.StatusOK}}, nil, manager)
	command := AppInfo{}
	command.Flags().Parse(true, []string{"--app", "app1"})
	err := command.Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(stdout.String(), gocheck.Equals, expected)
}
Ejemplo n.º 19
0
func (s *S) TestFailToAddMoreThanOneDefaultPool(c *check.C) {
	var buf bytes.Buffer
	stdin := bytes.NewBufferString("no")
	transportError := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Status: http.StatusPreconditionFailed, Message: "Default pool already exist."},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := map[string]interface{}{
				"name":    "test",
				"public":  false,
				"default": true,
			}
			result := map[string]interface{}{}
			err = json.Unmarshal(body, &result)
			c.Assert(expected, check.DeepEquals, result)
			return req.URL.Path == "/pool"
		},
	}
	manager := cmd.Manager{}
	context := cmd.Context{Args: []string{"test"}, Stdout: &buf, Stdin: stdin}
	client := cmd.NewClient(&http.Client{Transport: &transportError}, nil, &manager)
	command := addPoolToSchedulerCmd{}
	command.Flags().Parse(true, []string{"-d"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
	expected := "WARNING: Default pool already exist. Do you want change to test pool? (y/n) Pool add aborted.\n"
	c.Assert(buf.String(), check.Equals, expected)
}
Ejemplo n.º 20
0
func (s *S) TestSetCName(c *gocheck.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"death.evergrey.mycompany.com"},
	}
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: "Restarted", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			var m map[string]string
			err := json.NewDecoder(req.Body).Decode(&m)
			c.Assert(err, gocheck.IsNil)
			return req.URL.Path == "/apps/death/cname" &&
				req.Method == "POST" &&
				m["cname"] == "death.evergrey.mycompany.com"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := SetCName{}
	command.Flags().Parse(true, []string{"-a", "death"})
	err := command.Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(called, gocheck.Equals, true)
	c.Assert(stdout.String(), gocheck.Equals, "cname successfully defined.\n")
}
Ejemplo n.º 21
0
func (s *S) TestForceToOverwriteDefaultPoolInUpdate(c *check.C) {
	var buf bytes.Buffer
	stdin := bytes.NewBufferString("no")
	transportError := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Status: http.StatusPreconditionFailed, Message: "Default pool already exist."},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := map[string]interface{}{
				"default": true,
				"public":  interface{}(nil),
			}
			result := map[string]interface{}{}
			err = json.Unmarshal(body, &result)
			c.Assert(result, check.DeepEquals, expected)
			return req.URL.Path == "/pool/test" && req.URL.Query().Get("force") == "true"
		},
	}
	manager := cmd.Manager{}
	context := cmd.Context{Args: []string{"test"}, Stdout: &buf, Stdin: stdin}
	client := cmd.NewClient(&http.Client{Transport: &transportError}, nil, &manager)
	command := updatePoolToSchedulerCmd{}
	command.Flags().Parse(true, []string{"--default=true"})
	command.Flags().Parse(true, []string{"-f"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
}
Ejemplo n.º 22
0
func (s *S) TestSetCNameWithoutTheFlag(c *gocheck.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"corey.evergrey.mycompany.com"},
	}
	fake := &FakeGuesser{name: "corey"}
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: "Restarted", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			var m map[string]string
			err := json.NewDecoder(req.Body).Decode(&m)
			c.Assert(err, gocheck.IsNil)
			return req.URL.Path == "/apps/corey/cname" &&
				req.Method == "POST" &&
				m["cname"] == "corey.evergrey.mycompany.com"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	err := (&SetCName{GuessingCommand{G: fake}}).Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(called, gocheck.Equals, true)
	c.Assert(stdout.String(), gocheck.Equals, "cname successfully defined.\n")
}
Ejemplo n.º 23
0
func (s *S) TestAddDefaultPool(c *check.C) {
	var buf bytes.Buffer
	context := cmd.Context{Args: []string{"test"}, Stdout: &buf}
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := map[string]interface{}{
				"name":    "test",
				"public":  false,
				"default": true,
			}
			result := map[string]interface{}{}
			err = json.Unmarshal(body, &result)
			c.Assert(expected, check.DeepEquals, result)
			return req.URL.Path == "/pool"
		},
	}
	manager := cmd.Manager{}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager)
	command := addPoolToSchedulerCmd{}
	command.Flags().Parse(true, []string{"-d"})
	err := command.Run(&context, client)
	c.Assert(err, check.IsNil)
}
Ejemplo n.º 24
0
func (s *S) TestAppStopWithoutTheFlag(c *gocheck.C) {
	var (
		called         bool
		stdout, stderr bytes.Buffer
	)
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: "Stopped", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			return req.URL.Path == "/apps/motorbreath/stop" && req.Method == "POST"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	fake := &FakeGuesser{name: "motorbreath"}
	command := AppStop{GuessingCommand: GuessingCommand{G: fake}}
	command.Flags().Parse(true, nil)
	err := command.Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	c.Assert(called, gocheck.Equals, true)
	c.Assert(stdout.String(), gocheck.Equals, "Stopped")
}
Ejemplo n.º 25
0
func (s *S) TestServiceInfoRun(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	expected := `Info for "mongodb"

Instances
+-----------+-------+-------+--------+
| Instances | Apps  | key   | key2   |
+-----------+-------+-------+--------+
| mymongo   | myapp | value | value2 |
+-----------+-------+-------+--------+

Plans
+-------+--------------+
| Name  | Description  |
+-------+--------------+
| small | another plan |
+-------+--------------+
`
	args := []string{"mongodb"}
	context := cmd.Context{
		Args:   args,
		Stdout: &stdout,
		Stderr: &stderr,
	}
	client := cmd.NewClient(&http.Client{Transport: &infoTransport{}}, nil, manager)
	err := (&ServiceInfo{}).Run(&context, client)
	c.Assert(err, gocheck.IsNil)
	obtained := stdout.String()
	c.Assert(obtained, gocheck.Equals, expected)
}
Ejemplo n.º 26
0
func (s *S) TestAutoScaleSetRuleCmdRun(c *check.C) {
	var called bool
	transport := cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			called = true
			err := req.ParseForm()
			c.Assert(err, check.IsNil)
			var rule autoScaleRule
			err = form.DecodeValues(&rule, req.Form)
			c.Assert(err, check.IsNil)
			c.Assert(rule, check.DeepEquals, autoScaleRule{
				MetadataFilter:    "pool1",
				Enabled:           true,
				MaxContainerCount: 10,
				MaxMemoryRatio:    1.2342,
				ScaleDownRatio:    1.33,
				PreventRebalance:  false,
			})
			return req.Method == "POST" && req.URL.Path == "/1.0/docker/autoscale/rules"
		},
	}
	var buf bytes.Buffer
	context := cmd.Context{Stdout: &buf}
	var manager cmd.Manager
	client := cmd.NewClient(&http.Client{Transport: &transport}, nil, &manager)
	var command autoScaleSetRuleCmd
	flags := []string{"-f", "pool1", "-c", "10", "-m", "1.2342", "--enable"}
	err := command.Flags().Parse(true, flags)
	c.Assert(err, check.IsNil)
	err = command.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(called, check.Equals, true)
	c.Assert(buf.String(), check.Equals, "Rule successfully defined.\n")
}
Ejemplo n.º 27
0
func (s *S) TestServiceRemoveRun(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	ctx := cmd.Context{
		Args:   []string{"some-service-instance"},
		Stdout: &stdout,
		Stderr: &stderr,
		Stdin:  strings.NewReader("y\n"),
	}
	expected := `Are you sure you want to remove service "some-service-instance"? (y/n) `
	expected += `Service "some-service-instance" successfully removed!` + "\n"
	transport := testing.ConditionalTransport{
		Transport: testing.Transport{
			Message: "",
			Status:  http.StatusOK,
		},
		CondFunc: func(r *http.Request) bool {
			return r.URL.Path == "/services/instances/some-service-instance" &&
				r.Method == "DELETE"
		},
	}
	client := cmd.NewClient(&http.Client{Transport: &transport}, nil, manager)
	err := (&ServiceRemove{}).Run(&ctx, client)
	c.Assert(err, gocheck.IsNil)
	obtained := stdout.String()
	c.Assert(obtained, gocheck.Equals, expected)
}
Ejemplo n.º 28
0
func (s *S) TestDockerLogUpdateForPoolRun(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	msg := tsuruIo.SimpleJsonMessage{Message: "success!!!"}
	result, _ := json.Marshal(msg)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusNoContent},
		CondFunc: func(req *http.Request) bool {
			err := req.ParseForm()
			c.Assert(err, check.IsNil)
			c.Assert(req.Form, check.DeepEquals, url.Values{
				"restart":   []string{"false"},
				"pool":      []string{"p1"},
				"Driver":    []string{"x"},
				"LogOpts.a": []string{"1"},
				"LogOpts.b": []string{"2"},
			})
			return req.URL.Path == "/1.0/docker/logs" && req.Method == "POST"
		},
	}
	manager := cmd.NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	cmd := dockerLogUpdate{}
	err := cmd.Flags().Parse(true, []string{"--pool", "p1", "--log-driver", "x", "--log-opt", "a=1", "--log-opt", "b=2"})
	c.Assert(err, check.IsNil)
	err = cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "success!!!")
}
Ejemplo n.º 29
0
func (s *S) TestPlatformAddRun(c *gocheck.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"teste"},
	}

	expected := "Platform successfully added!\n"
	trans := &testing.ConditionalTransport{
		Transport: testing.Transport{Message: "", Status: http.StatusOK},
		CondFunc: func(req *http.Request) bool {
			c.Assert(req.Header.Get("Content-Type"), gocheck.Equals, "application/x-www-form-urlencoded")
			return req.URL.Path == "/platforms" && req.Method == "POST"
		},
	}

	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	command := platformAdd{}
	command.Flags().Parse(true, []string{"--dockerfile", "http://localhost/Dockerfile"})

	err := command.Run(&context, client)

	c.Assert(err, gocheck.IsNil)
	c.Assert(stdout.String(), gocheck.Equals, expected)
}
Ejemplo n.º 30
0
func (s *S) TestBsEnvSetRun(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
		Args:   []string{"A=1", "B=2"},
	}
	msg := io.SimpleJsonMessage{Message: "env-set success"}
	result, _ := json.Marshal(msg)
	trans := &cmdtest.ConditionalTransport{
		Transport: cmdtest.Transport{Message: string(result), Status: http.StatusNoContent},
		CondFunc: func(req *http.Request) bool {
			defer req.Body.Close()
			body, err := ioutil.ReadAll(req.Body)
			c.Assert(err, check.IsNil)
			expected := Config{
				Envs: []Env{{Name: "A", Value: "1"}, {Name: "B", Value: "2"}},
			}
			var conf Config
			err = json.Unmarshal(body, &conf)
			c.Assert(conf, check.DeepEquals, expected)
			return req.URL.Path == "/docker/bs/env" && req.Method == "POST"
		},
	}
	manager := cmd.NewManager("admin", "0.1", "admin-ver", &stdout, &stderr, nil, nil)
	client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager)
	cmd := EnvSetCmd{}
	err := cmd.Run(&context, client)
	c.Assert(err, check.IsNil)
	c.Assert(stdout.String(), check.Equals, "env-set success")
}