Make mock listen on random port if 0 is specified
This commit is contained in:
parent
93c1ae6221
commit
702072f177
@ -2,7 +2,11 @@ package mock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/micro/go-micro/transport"
|
||||
)
|
||||
@ -126,15 +130,25 @@ func (m *mockTransport) Listen(addr string, opts ...transport.ListenOption) (tra
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
|
||||
if _, ok := m.listeners[addr]; ok {
|
||||
return nil, errors.New("already listening on " + addr)
|
||||
}
|
||||
|
||||
var options transport.ListenOptions
|
||||
for _, o := range opts {
|
||||
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{
|
||||
opts: options,
|
||||
addr: addr,
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user