Make mock listen on random port if 0 is specified

This commit is contained in:
Asim 2016-06-01 15:22:27 +01:00
parent 93c1ae6221
commit 702072f177
2 changed files with 47 additions and 4 deletions

View File

@ -2,7 +2,11 @@ package mock
import ( import (
"errors" "errors"
"fmt"
"math/rand"
"strings"
"sync" "sync"
"time"
"github.com/micro/go-micro/transport" "github.com/micro/go-micro/transport"
) )
@ -126,15 +130,25 @@ func (m *mockTransport) Listen(addr string, opts ...transport.ListenOption) (tra
m.Lock() m.Lock()
defer m.Unlock() defer m.Unlock()
if _, ok := m.listeners[addr]; ok {
return nil, errors.New("already listening on " + addr)
}
var options transport.ListenOptions var options transport.ListenOptions
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
} }
parts := strings.Split(addr, ":")
// if zero port then randomly assign one
if len(parts) > 1 && parts[len(parts)-1] == "0" {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
i := r.Intn(10000)
// set addr with port
addr = fmt.Sprintf("%s:%d", parts[:len(parts)-1], 10000+i)
}
if _, ok := m.listeners[addr]; ok {
return nil, errors.New("already listening on " + addr)
}
listener := &mockListener{ listener := &mockListener{
opts: options, opts: options,
addr: addr, addr: addr,

View File

@ -58,3 +58,32 @@ func TestTransport(t *testing.T) {
} }
} }
func TestListener(t *testing.T) {
tr := NewTransport()
// bind / listen on random port
l, err := tr.Listen(":0")
if err != nil {
t.Fatalf("Unexpected error listening %v", err)
}
defer l.Close()
// try again
l2, err := tr.Listen(":0")
if err != nil {
t.Fatalf("Unexpected error listening %v", err)
}
defer l2.Close()
// now make sure it still fails
l3, err := tr.Listen(":8080")
if err != nil {
t.Fatalf("Unexpected error listening %v", err)
}
defer l3.Close()
if _, err := tr.Listen(":8080"); err == nil {
t.Fatal("Expected error binding to :8080 got nil")
}
}