1package integration
2
3import (
4	"fmt"
5	"io/ioutil"
6	"net/http"
7	"net/http/httptest"
8	"net/http/httputil"
9	"os/exec"
10	"strings"
11	"testing"
12
13	"github.com/sclevine/spec"
14	"github.com/stretchr/testify/require"
15)
16
17var _ = suite("compute/firewall/create", func(t *testing.T, when spec.G, it spec.S) {
18	var (
19		expect *require.Assertions
20		server *httptest.Server
21	)
22
23	it.Before(func() {
24		expect = require.New(t)
25
26		server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
27			switch req.URL.Path {
28			case "/v2/firewalls":
29				auth := req.Header.Get("Authorization")
30				if auth != "Bearer some-magic-token" {
31					w.WriteHeader(http.StatusUnauthorized)
32					return
33				}
34
35				if req.Method != http.MethodPost {
36					w.WriteHeader(http.StatusMethodNotAllowed)
37					return
38				}
39
40				body, err := ioutil.ReadAll(req.Body)
41				expect.NoError(err)
42				expect.JSONEq(firewallCreateRequestBody, string(body))
43
44				w.Write([]byte(firewallCreateResponse))
45			default:
46				dump, err := httputil.DumpRequest(req, true)
47				if err != nil {
48					t.Fatal("failed to dump request")
49				}
50
51				t.Fatalf("received unknown request: %s", dump)
52			}
53		}))
54	})
55
56	when("the minimum required flags are provided", func() {
57		it("creates a firewall", func() {
58			aliases := []string{"create", "c"}
59
60			for _, alias := range aliases {
61				cmd := exec.Command(builtBinaryPath,
62					"-t", "some-magic-token",
63					"-u", server.URL,
64					"compute",
65					"firewall",
66					alias,
67					"--name", "test-firewall",
68					"--inbound-rules", `protocol:tcp,ports:443`,
69				)
70
71				output, err := cmd.CombinedOutput()
72				expect.NoError(err, fmt.Sprintf("received error output from command %s: %s", alias, output))
73				expect.Equal(strings.TrimSpace(firewallCreateOutput), strings.TrimSpace(string(output)))
74			}
75		})
76	})
77})
78
79const (
80	firewallCreateOutput = `
81ID                                      Name             Status       Created At              Inbound Rules              Outbound Rules    Droplet IDs    Tags    Pending Changes
82e4b9c960-d385-4950-84f3-d102162e6be5    test-firewall    succeeded    2019-10-24T20:30:26Z    protocol:tcp,ports:443,`
83
84	firewallCreateRequestBody = `{
85  "name":"test-firewall",
86  "inbound_rules":[{
87	"protocol":"tcp",
88	"ports":"443",
89	"sources":{}
90  }],
91  "outbound_rules":null,
92  "droplet_ids":[],
93  "tags":[]
94}`
95
96	firewallCreateResponse = `{
97  "firewall": {
98	"id":"e4b9c960-d385-4950-84f3-d102162e6be5",
99	"name":"test-firewall",
100	"status":"succeeded",
101	"inbound_rules":[{
102	  "protocol":"tcp",
103	  "ports":"443",
104	  "sources":{}
105	}],
106	"outbound_rules":[],
107	"created_at":"2019-10-24T20:30:26Z",
108	"droplet_ids":[],
109	"tags":[],
110	"pending_changes":[]
111  }
112}`
113)
114