Skip to content

Commit

Permalink
uacp.Dial use context for dial
Browse files Browse the repository at this point in the history
Use `net.Dialer{}.DialContext` instead of `net.DialTCP`. This allows the dial to be canceled by the caller, or by the use of context with a timeout.
  • Loading branch information
mmikalsen committed Mar 9, 2020
1 parent 4bc2cdf commit 32fee33
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 29 deletions.
3 changes: 2 additions & 1 deletion uacp/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ func Dial(ctx context.Context, endpoint string) (*Conn, error) {
if err != nil {
return nil, err
}
c, err := net.DialTCP(network, nil, raddr)
var dialer net.Dialer
c, err := dialer.DialContext(ctx, network, raddr.String())
if err != nil {
return nil, err
}
Expand Down
70 changes: 42 additions & 28 deletions uacp/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,60 @@ package uacp

import (
"context"
"net"
"testing"
"time"

"github.com/pascaldekloe/goe/verify"
)

func TestConn(t *testing.T) {
ep := "opc.tcp://127.0.0.1:4840/foo/bar"
ln, err := Listen(ep, nil)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
t.Run("server exists ", func(t *testing.T) {
ep := "opc.tcp://127.0.0.1:4840/foo/bar"
ln, err := Listen(ep, nil)
if err != nil {
t.Fatal(err)
}
defer ln.Close()

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

done := make(chan struct{})
acceptErr := make(chan error, 1)
go func() {
c, err := ln.Accept(ctx)
if err != nil {
acceptErr <- err
return
done := make(chan struct{})
acceptErr := make(chan error, 1)
go func() {
c, err := ln.Accept(ctx)
if err != nil {
acceptErr <- err
return
}
defer c.Close()
close(done)
}()

if _, err = Dial(ctx, ep); err != nil {
t.Error(err)
}
defer c.Close()
close(done)
}()

if _, err = Dial(ctx, ep); err != nil {
t.Error(err)
}
select {
case <-done:
case err := <-acceptErr:
t.Fatalf("accept fail: %v", err)
case <-time.After(time.Second):
t.Fatal("timed out")
}
})

select {
case <-done:
case err := <-acceptErr:
t.Fatalf("accept fail: %v", err)
case <-time.After(time.Second):
t.Fatal("timed out")
}
t.Run("Address resolves, but does not implement a opcua-server", func(t *testing.T) {
ep := "opc.tcp://example.com:56789"

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := Dial(ctx, ep)
if !err.(*net.OpError).Timeout() {
t.Error(err)
}
})
}

func TestClientWrite(t *testing.T) {
Expand Down

0 comments on commit 32fee33

Please sign in to comment.