small pixel drawing of a pufferfish cascade

command/agent/agent_test.go

package agent

import (
	"strings"
	"testing"

	"git.j3s.sh/cascade/agent"
)

func TestParseFlagAddress(t *testing.T) {
	type c struct {
		inputAddr    string
		expectIP     string
		expectPort   int
		expectErrStr string
	}
	cases := []c{
		{
			inputAddr:  "127.0.0.1",
			expectIP:   "127.0.0.1",
			expectPort: 4443,
		},
		{
			inputAddr:  "127.0.0.1:6969",
			expectIP:   "127.0.0.1",
			expectPort: 6969,
		},
		{
			inputAddr:  "192.168.0.4:420",
			expectIP:   "192.168.0.4",
			expectPort: 420,
		},
		{
			inputAddr:  "127.0.0.3:",
			expectIP:   "127.0.0.3",
			expectPort: 4443,
		},
		// error cases
		{
			inputAddr:    "",
			expectIP:     "0.0.0.0",
			expectPort:   4443,
			expectErrStr: "Error parsing blank address",
		},
		{
			inputAddr:    ":1234",
			expectIP:     "0.0.0.0",
			expectPort:   4443,
			expectErrStr: "Error parsing blank address",
		},
		{
			inputAddr:    "127.0.0.1:abcd",
			expectIP:     "0.0.0.0",
			expectPort:   4443,
			expectErrStr: "Error parsing port",
		},
		{
			inputAddr:    "127.0.0.256:6969",
			expectIP:     "0.0.0.0",
			expectPort:   4443,
			expectErrStr: "Error parsing address",
		},
	}

	for _, tc := range cases {
		addr := agent.DefaultConfig().BindAddr
		expectErr := tc.expectErrStr != ""

		err := parseFlagAddress(tc.inputAddr, addr)
		if expectErr && err == nil {
			t.Errorf("Expected error '%s', but received none", tc.expectErrStr)
		}
		if !expectErr && err != nil {
			t.Errorf("Unexpected error: '%s'", err)
		}
		// errors we expect are unwrapped here
		if expectErr && err != nil {
			if !strings.Contains(err.Error(), tc.expectErrStr) {
				t.Errorf("Expected error '%s', got '%s'", tc.expectErrStr, err)
			}
		}
		if tc.expectIP != addr.IP.String() {
			t.Errorf("Expected IP '%s', got '%s'", tc.expectIP, addr.IP.String())
		}
		if tc.expectPort != addr.Port {
			t.Errorf("Expected port '%d', got '%d'", tc.expectPort, addr.Port)
		}
	}
}