1
// Copyright 2014 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
10
jc "github.com/juju/testing/checkers"
11
gc "gopkg.in/check.v1"
13
"github.com/juju/juju/network"
14
"github.com/juju/juju/testing"
15
"github.com/juju/juju/worker/uniter/runner/jujuc"
18
type OpenedPortsSuite struct {
22
var _ = gc.Suite(&OpenedPortsSuite{})
24
func (s *OpenedPortsSuite) TestRunAllFormats(c *gc.C) {
25
expectedPorts := []network.PortRange{
31
network.SortPortRanges(expectedPorts)
32
portsAsStrings := make([]string, len(expectedPorts))
33
for i, portRange := range expectedPorts {
34
portsAsStrings[i] = portRange.String()
36
defaultOutput := strings.Join(portsAsStrings, "\n") + "\n"
37
jsonOutput := `["` + strings.Join(portsAsStrings, `","`) + `"]` + "\n"
38
yamlOutput := "- " + strings.Join(portsAsStrings, "\n- ") + "\n"
40
formatToOutput := map[string]string{
42
"smart": defaultOutput,
46
for format, expectedOutput := range formatToOutput {
47
hctx := s.getContextAndOpenPorts(c)
51
stdout, stderr = s.runCommand(c, hctx)
53
stdout, stderr = s.runCommand(c, hctx, "--format", format)
55
c.Check(stdout, gc.Equals, expectedOutput)
56
c.Check(stderr, gc.Equals, "")
57
hctx.info.CheckPorts(c, expectedPorts)
61
func (s *OpenedPortsSuite) TestBadArgs(c *gc.C) {
62
hctx := s.GetHookContext(c, -1, "")
63
com, err := jujuc.NewCommand(hctx, cmdString("opened-ports"))
64
c.Assert(err, jc.ErrorIsNil)
65
err = testing.InitCommand(com, []string{"foo"})
66
c.Assert(err, gc.ErrorMatches, `unrecognized args: \["foo"\]`)
69
func (s *OpenedPortsSuite) TestHelp(c *gc.C) {
70
hctx := s.GetHookContext(c, -1, "")
71
openedPorts, err := jujuc.NewCommand(hctx, cmdString("opened-ports"))
72
c.Assert(err, jc.ErrorIsNil)
73
flags := testing.NewFlagSet()
74
c.Assert(string(openedPorts.Info().Help(flags)), gc.Equals, `
78
lists all ports or ranges opened by the unit
81
Each list entry has format <port>/<protocol> (e.g. "80/tcp") or
82
<from>-<to>/<protocol> (e.g. "8080-8088/udp").
86
func (s *OpenedPortsSuite) getContextAndOpenPorts(c *gc.C) *Context {
87
hctx := s.GetHookContext(c, -1, "")
88
hctx.OpenPorts("tcp", 80, 80)
89
hctx.OpenPorts("tcp", 10, 20)
90
hctx.OpenPorts("udp", 63, 63)
91
hctx.OpenPorts("udp", 53, 55)
95
func (s *OpenedPortsSuite) runCommand(c *gc.C, hctx *Context, args ...string) (stdout, stderr string) {
96
com, err := jujuc.NewCommand(hctx, cmdString("opened-ports"))
97
c.Assert(err, jc.ErrorIsNil)
98
ctx := testing.Context(c)
99
code := cmd.Main(com, ctx, args)
100
c.Assert(code, gc.Equals, 0)
101
return bufferString(ctx.Stdout), bufferString(ctx.Stderr)