|
| 1 | +package portforward |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | + "github.com/stretchr/testify/require" |
| 9 | +) |
| 10 | + |
| 11 | +// ParseManualPort accepts 1..65535 verbatim and rejects everything else |
| 12 | +// with an error so callers can log + fall through to UPnP discovery |
| 13 | +// rather than register a non-listening port with lantern-cloud. |
| 14 | +func TestParseManualPort(t *testing.T) { |
| 15 | + tests := []struct { |
| 16 | + name string |
| 17 | + input string |
| 18 | + want uint16 |
| 19 | + wantErr bool |
| 20 | + }{ |
| 21 | + {"valid mid-range", "5698", 5698, false}, |
| 22 | + {"valid low boundary", "1", 1, false}, |
| 23 | + {"valid high boundary", "65535", 65535, false}, |
| 24 | + {"empty", "", 0, true}, |
| 25 | + {"non-numeric", "abc", 0, true}, |
| 26 | + {"zero", "0", 0, true}, |
| 27 | + {"negative", "-5", 0, true}, |
| 28 | + {"above uint16", "65536", 0, true}, |
| 29 | + {"way above uint16", "99999", 0, true}, |
| 30 | + } |
| 31 | + for _, tc := range tests { |
| 32 | + t.Run(tc.name, func(t *testing.T) { |
| 33 | + got, err := ParseManualPort(tc.input) |
| 34 | + if tc.wantErr { |
| 35 | + assert.Error(t, err) |
| 36 | + assert.Equal(t, uint16(0), got) |
| 37 | + return |
| 38 | + } |
| 39 | + require.NoError(t, err) |
| 40 | + assert.Equal(t, tc.want, got) |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// ManualForwarder satisfies the portForwarder contract: MapPort returns |
| 46 | +// a Mapping with external==internal port and the "manual" method tag, |
| 47 | +// UnmapPort and StartRenewal are no-ops, ExternalIP returns "" so the |
| 48 | +// server substitutes the IP it observed on the register call. |
| 49 | +func TestManualForwarder(t *testing.T) { |
| 50 | + f := NewManualForwarder(5698) |
| 51 | + |
| 52 | + m, err := f.MapPort(context.Background(), 30001, "ignored") |
| 53 | + require.NoError(t, err) |
| 54 | + assert.Equal(t, uint16(5698), m.ExternalPort) |
| 55 | + assert.Equal(t, uint16(5698), m.InternalPort, "external==internal — user mapped them themselves") |
| 56 | + assert.Equal(t, "manual", m.Method) |
| 57 | + |
| 58 | + require.NoError(t, f.UnmapPort(context.Background()), "UnmapPort is a no-op for manual forwarders") |
| 59 | + |
| 60 | + // StartRenewal must not panic or block. |
| 61 | + f.StartRenewal(context.Background()) |
| 62 | + |
| 63 | + ip, err := f.ExternalIP(context.Background()) |
| 64 | + require.NoError(t, err) |
| 65 | + assert.Empty(t, ip, "empty IP signals server to use observed source address") |
| 66 | +} |
0 commit comments