package embed import ( "net" "net/url" "os" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { os.Exit(m.Run()) } func TestAssign(t *testing.T) { localIP, err := getLocalIP() require.NoError(t, err) testCases := map[string]struct { input *url.URL expectedHost string expectedPort string expectError bool }{ "Success": { input: &url.URL{ Host: net.JoinHostPort(localIP.String(), "31654"), }, expectedHost: localIP.String(), expectedPort: "31654", expectError: false, }, "Success_NoPort": { input: &url.URL{ Host: localIP.String(), }, expectedHost: localIP.String(), expectedPort: "", expectError: false, }, "Success_NoHost": { input: &url.URL{ Host: ":31655", }, expectedHost: "127.0.0.1", expectedPort: "31655", expectError: false, }, "Failure_InvalidHost": { input: &url.URL{ Host: "invalid-made-up-host:8085", }, expectError: true, }, "Failure_InvalidPort": { input: &url.URL{ Host: "127.0.0.1:invalid", }, expectError: true, }, "Failure_PortTooHigh": { input: &url.URL{ Host: "127.0.0.1:70000", }, expectError: true, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { a := assignedAddress{} err := a.assign(tc.input) if tc.expectError { require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, tc.expectedHost, a.host) switch tc.expectedPort { case "": port, err := strconv.Atoi(a.port) require.NoError(t, err) assert.GreaterOrEqual(t, 65535, port) assert.LessOrEqual(t, 1, port) default: assert.Equal(t, tc.expectedPort, a.port) } }) } } func getLocalIP() (net.IP, error) { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { return nil, err } defer conn.Close() localAddress := conn.LocalAddr().(*net.UDPAddr) return localAddress.IP, nil } func TestURL(t *testing.T) { testCases := map[string]struct { input assignedAddress expected url.URL }{ "Success_IP": { input: assignedAddress{ host: "166.55.44.33", port: "5432", }, expected: url.URL{ Scheme: "http", Host: net.JoinHostPort("166.55.44.33", "5432"), }, }, "Success_Hostname": { input: assignedAddress{ host: "my-hostname", port: "2345", }, expected: url.URL{ Scheme: "http", Host: net.JoinHostPort("my-hostname", "2345"), }, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { assert.Equal(t, tc.expected, tc.input.url()) }) } }