@@ -18,11 +18,13 @@ package portforward
18
18
19
19
import (
20
20
"net"
21
+ "net/http"
21
22
"os"
22
23
"reflect"
23
24
"sort"
24
25
"strings"
25
26
"testing"
27
+ "time"
26
28
27
29
"k8s.io/apimachinery/pkg/util/httpstream"
28
30
)
@@ -39,6 +41,37 @@ func (d *fakeDialer) Dial(protocols ...string) (httpstream.Connection, string, e
39
41
return d .conn , d .negotiatedProtocol , d .err
40
42
}
41
43
44
+ type fakeConnection struct {
45
+ closed bool
46
+ closeChan chan bool
47
+ }
48
+
49
+ func newFakeConnection () httpstream.Connection {
50
+ return & fakeConnection {
51
+ closeChan : make (chan bool ),
52
+ }
53
+ }
54
+
55
+ func (c * fakeConnection ) CreateStream (headers http.Header ) (httpstream.Stream , error ) {
56
+ return nil , nil
57
+ }
58
+
59
+ func (c * fakeConnection ) Close () error {
60
+ if ! c .closed {
61
+ c .closed = true
62
+ close (c .closeChan )
63
+ }
64
+ return nil
65
+ }
66
+
67
+ func (c * fakeConnection ) CloseChan () <- chan bool {
68
+ return c .closeChan
69
+ }
70
+
71
+ func (c * fakeConnection ) SetIdleTimeout (timeout time.Duration ) {
72
+ // no-op
73
+ }
74
+
42
75
func TestParsePortsAndNew (t * testing.T ) {
43
76
tests := []struct {
44
77
input []string
@@ -310,3 +343,46 @@ func TestGetListener(t *testing.T) {
310
343
311
344
}
312
345
}
346
+
347
+ func TestGetPortsReturnsDynamicallyAssignedLocalPort (t * testing.T ) {
348
+ dialer := & fakeDialer {
349
+ conn : newFakeConnection (),
350
+ }
351
+
352
+ stopChan := make (chan struct {})
353
+ readyChan := make (chan struct {})
354
+ errChan := make (chan error )
355
+
356
+ defer func () {
357
+ close (stopChan )
358
+
359
+ forwardErr := <- errChan
360
+ if forwardErr != nil {
361
+ t .Fatalf ("ForwardPorts returned error: %s" , forwardErr )
362
+ }
363
+ }()
364
+
365
+ pf , err := New (dialer , []string {":5000" }, stopChan , readyChan , os .Stdout , os .Stderr )
366
+
367
+ if err != nil {
368
+ t .Fatalf ("error while calling New: %s" , err )
369
+ }
370
+
371
+ go func () {
372
+ errChan <- pf .ForwardPorts ()
373
+ close (errChan )
374
+ }()
375
+
376
+ <- pf .Ready
377
+
378
+ ports , err := pf .GetPorts ()
379
+
380
+ if len (ports ) != 1 {
381
+ t .Fatalf ("expected 1 port, got %d" , len (ports ))
382
+ }
383
+
384
+ port := ports [0 ]
385
+ if port .Local == 0 {
386
+ t .Fatalf ("local port is 0, expected != 0" )
387
+ }
388
+ }
0 commit comments