1 Star 0 Fork 0

徐大周的春天/tftp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
tftp_test.go 20.90 KB
一键复制 编辑 原始数据 按行查看 历史
Owen Mooney 提交于 2019-12-23 10:46 . Fix race in hook tests
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
package tftp
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"strconv"
"sync"
"testing"
"testing/iotest"
"time"
"github.com/stretchr/testify/mock"
)
var localhost = determineLocalhost()
func determineLocalhost() string {
l, err := net.ListenTCP("tcp", nil)
if err != nil {
panic(fmt.Sprintf("ListenTCP error: %s", err))
}
_, lport, _ := net.SplitHostPort(l.Addr().String())
defer l.Close()
lo := make(chan string)
go func() {
for {
conn, err := l.Accept()
if err != nil {
break
}
conn.Close()
}
}()
go func() {
port, _ := strconv.Atoi(lport)
for _, af := range []string{"tcp6", "tcp4"} {
conn, err := net.DialTCP(af, &net.TCPAddr{}, &net.TCPAddr{Port: port})
if err == nil {
conn.Close()
host, _, _ := net.SplitHostPort(conn.LocalAddr().String())
lo <- host
return
}
}
panic("could not determine address family")
}()
return <-lo
}
func localSystem(c *net.UDPConn) string {
_, port, _ := net.SplitHostPort(c.LocalAddr().String())
return net.JoinHostPort(localhost, port)
}
func TestPackUnpack(t *testing.T) {
v := []string{"test-filename/with-subdir"}
testOptsList := []options{
nil,
options{
"tsize": "1234",
"blksize": "22",
},
}
for _, filename := range v {
for _, mode := range []string{"octet", "netascii"} {
for _, opts := range testOptsList {
packUnpack(t, filename, mode, opts)
}
}
}
}
func packUnpack(t *testing.T, filename, mode string, opts options) {
b := make([]byte, datagramLength)
for _, op := range []uint16{opRRQ, opWRQ} {
n := packRQ(b, op, filename, mode, opts)
f, m, o, err := unpackRQ(b[:n])
if err != nil {
t.Errorf("%s pack/unpack: %v", filename, err)
}
if f != filename {
t.Errorf("filename mismatch (%s): '%x' vs '%x'",
filename, f, filename)
}
if m != mode {
t.Errorf("mode mismatch (%s): '%x' vs '%x'",
mode, m, mode)
}
if opts != nil {
for name, value := range opts {
v, ok := o[name]
if !ok {
t.Errorf("missing %s option", name)
}
if v != value {
t.Errorf("option %s mismatch: '%x' vs '%x'", name, v, value)
}
}
}
}
}
func TestZeroLength(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
testSendReceive(t, c, 0)
}
func Test900(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
for i := 600; i < 4000; i++ {
c.SetBlockSize(i)
s.SetBlockSize(4600 - i)
testSendReceive(t, c, 9000+int64(i))
}
}
func Test1000(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
for i := int64(0); i < 5000; i++ {
filename := fmt.Sprintf("length-%d-bytes-%d", i, time.Now().UnixNano())
rf, err := c.Send(filename, "octet")
if err != nil {
t.Fatalf("requesting %s write: %v", filename, err)
}
r := io.LimitReader(newRandReader(rand.NewSource(i)), i)
n, err := rf.ReadFrom(r)
if err != nil {
t.Fatalf("sending %s: %v", filename, err)
}
if n != i {
t.Errorf("%s length mismatch: %d != %d", filename, n, i)
}
}
}
func Test1810(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
c.SetBlockSize(1810)
testSendReceive(t, c, 9000+1810)
}
type fakeHook struct {
mock.Mock
}
func (f *fakeHook) OnSuccess(result TransferStats) {
f.Called(result)
return
}
func (f *fakeHook) OnFailure(result TransferStats, err error) {
f.Called(result)
return
}
func TestHookSuccess(t *testing.T) {
s, c := makeTestServer(false)
fakeHookTemp := new(fakeHook)
// Due to the way test are run there will always be some failures
fakeHookTemp.On("OnFailure", mock.AnythingOfType("TransferStats")).Return()
fakeHookTemp.On("OnSuccess", mock.AnythingOfType("TransferStats")).Return()
s.SetHook(fakeHookTemp)
c.SetBlockSize(1810)
length := int64(9000)
filename := fmt.Sprintf("length-%d-bytes-%d", length, time.Now().UnixNano())
rf, err := c.Send(filename, "octet")
if err != nil {
t.Fatalf("requesting %s write: %v", filename, err)
}
r := io.LimitReader(newRandReader(rand.NewSource(length)), length)
n, err := rf.ReadFrom(r)
if err != nil {
t.Fatalf("sending %s: %v", filename, err)
}
if n != length {
t.Errorf("%s length mismatch: %d != %d", filename, n, length)
}
s.Shutdown()
fakeHookTemp.AssertNumberOfCalls(t, "OnSuccess", 1)
}
func TestHookFailure(t *testing.T) {
s, c := makeTestServer(false)
fakeHookTemp := new(fakeHook)
fakeHookTemp.On("OnFailure", mock.AnythingOfType("TransferStats")).Return()
s.SetHook(fakeHookTemp)
filename := "test-not-exists"
mode := "octet"
_, err := c.Receive(filename, mode)
if err == nil {
t.Fatalf("file not exists: %v", err)
}
t.Logf("receiving file that does not exist: %v", err)
s.Shutdown()
fakeHookTemp.AssertExpectations(t)
}
func TestTSize(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
c.tsize = true
testSendReceive(t, c, 640)
}
func TestNearBlockLength(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
for i := 450; i < 520; i++ {
testSendReceive(t, c, int64(i))
}
}
func TestBlockWrapsAround(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
n := 65535 * 512
for i := n - 2; i < n+2; i++ {
testSendReceive(t, c, int64(i))
}
}
func TestRandomLength(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
r := rand.New(rand.NewSource(42))
for i := 0; i < 100; i++ {
testSendReceive(t, c, r.Int63n(100000))
}
}
func TestBigFile(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
testSendReceive(t, c, 3*1000*1000)
}
func TestByOneByte(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
filename := "test-by-one-byte"
mode := "octet"
const length = 80000
sender, err := c.Send(filename, mode)
if err != nil {
t.Fatalf("requesting write: %v", err)
}
r := iotest.OneByteReader(io.LimitReader(
newRandReader(rand.NewSource(42)), length))
n, err := sender.ReadFrom(r)
if err != nil {
t.Fatalf("send error: %v", err)
}
if n != length {
t.Errorf("%s read length mismatch: %d != %d", filename, n, length)
}
readTransfer, err := c.Receive(filename, mode)
if err != nil {
t.Fatalf("requesting read %s: %v", filename, err)
}
buf := &bytes.Buffer{}
n, err = readTransfer.WriteTo(buf)
if err != nil {
t.Fatalf("%s read error: %v", filename, err)
}
if n != length {
t.Errorf("%s read length mismatch: %d != %d", filename, n, length)
}
bs, _ := ioutil.ReadAll(io.LimitReader(
newRandReader(rand.NewSource(42)), length))
if !bytes.Equal(bs, buf.Bytes()) {
t.Errorf("\nsent: %x\nrcvd: %x", bs, buf)
}
}
func TestDuplicate(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
filename := "test-duplicate"
mode := "octet"
bs := []byte("lalala")
sender, err := c.Send(filename, mode)
if err != nil {
t.Fatalf("requesting write: %v", err)
}
buf := bytes.NewBuffer(bs)
_, err = sender.ReadFrom(buf)
if err != nil {
t.Fatalf("send error: %v", err)
}
sender, err = c.Send(filename, mode)
if err == nil {
t.Fatalf("file already exists")
}
t.Logf("sending file that already exists: %v", err)
}
func TestNotFound(t *testing.T) {
s, c := makeTestServer(false)
defer s.Shutdown()
filename := "test-not-exists"
mode := "octet"
_, err := c.Receive(filename, mode)
if err == nil {
t.Fatalf("file not exists: %v", err)
}
t.Logf("receiving file that does not exist: %v", err)
}
func testSendReceive(t *testing.T, client *Client, length int64) {
filename := fmt.Sprintf("length-%d-bytes", length)
mode := "octet"
writeTransfer, err := client.Send(filename, mode)
if err != nil {
t.Fatalf("requesting write %s: %v", filename, err)
}
r := io.LimitReader(newRandReader(rand.NewSource(42)), length)
n, err := writeTransfer.ReadFrom(r)
if err != nil {
t.Fatalf("%s write error: %v", filename, err)
}
if n != length {
t.Errorf("%s write length mismatch: %d != %d", filename, n, length)
}
readTransfer, err := client.Receive(filename, mode)
if err != nil {
t.Fatalf("requesting read %s: %v", filename, err)
}
if it, ok := readTransfer.(IncomingTransfer); ok {
if n, ok := it.Size(); ok {
fmt.Printf("Transfer size: %d\n", n)
if n != length {
t.Errorf("tsize mismatch: %d vs %d", n, length)
}
}
}
buf := &bytes.Buffer{}
n, err = readTransfer.WriteTo(buf)
if err != nil {
t.Fatalf("%s read error: %v", filename, err)
}
if n != length {
t.Errorf("%s read length mismatch: %d != %d", filename, n, length)
}
bs, _ := ioutil.ReadAll(io.LimitReader(
newRandReader(rand.NewSource(42)), length))
if !bytes.Equal(bs, buf.Bytes()) {
t.Errorf("\nsent: %x\nrcvd: %x", bs, buf)
}
}
func TestSendTsizeFromSeek(t *testing.T) {
// create read-only server
s := NewServer(func(filename string, rf io.ReaderFrom) error {
b := make([]byte, 100)
rr := newRandReader(rand.NewSource(42))
rr.Read(b)
// bytes.Reader implements io.Seek
r := bytes.NewReader(b)
_, err := rf.ReadFrom(r)
if err != nil {
t.Errorf("sending bytes: %v", err)
}
return nil
}, nil)
conn, err := net.ListenUDP("udp", &net.UDPAddr{})
if err != nil {
t.Fatalf("listening: %v", err)
}
go s.Serve(conn)
defer s.Shutdown()
c, _ := NewClient(localSystem(conn))
c.RequestTSize(true)
r, _ := c.Receive("f", "octet")
var size int64
if it, ok := r.(IncomingTransfer); ok {
if n, ok := it.Size(); ok {
size = n
fmt.Printf("Transfer size: %d\n", n)
}
}
if size != 100 {
t.Errorf("size expected: 100, got %d", size)
}
r.WriteTo(ioutil.Discard)
c.RequestTSize(false)
r, _ = c.Receive("f", "octet")
if it, ok := r.(IncomingTransfer); ok {
_, ok := it.Size()
if ok {
t.Errorf("unexpected size received")
}
}
r.WriteTo(ioutil.Discard)
}
type testBackend struct {
m map[string][]byte
mu sync.Mutex
}
func makeTestServer(singlePort bool) (*Server, *Client) {
b := &testBackend{}
b.m = make(map[string][]byte)
// Create server
s := NewServer(b.handleRead, b.handleWrite)
if singlePort {
s.SetBlockSize(2000)
s.gcThreshold = 100000
s.EnableSinglePort()
}
conn, err := net.ListenUDP("udp", &net.UDPAddr{})
if err != nil {
panic(err)
}
go s.Serve(conn)
// Create client for that server
c, err := NewClient(localSystem(conn))
if err != nil {
panic(err)
}
return s, c
}
func TestNoHandlers(t *testing.T) {
s := NewServer(nil, nil)
conn, err := net.ListenUDP("udp", &net.UDPAddr{})
if err != nil {
panic(err)
}
go s.Serve(conn)
c, err := NewClient(localSystem(conn))
if err != nil {
panic(err)
}
_, err = c.Send("test", "octet")
if err == nil {
t.Errorf("error expected")
}
_, err = c.Receive("test", "octet")
if err == nil {
t.Errorf("error expected")
}
}
func (b *testBackend) handleWrite(filename string, wt io.WriterTo) error {
b.mu.Lock()
defer b.mu.Unlock()
_, ok := b.m[filename]
if ok {
fmt.Fprintf(os.Stderr, "File %s already exists\n", filename)
return fmt.Errorf("file already exists")
}
if t, ok := wt.(IncomingTransfer); ok {
if n, ok := t.Size(); ok {
fmt.Printf("Transfer size: %d\n", n)
}
}
buf := &bytes.Buffer{}
_, err := wt.WriteTo(buf)
if err != nil {
fmt.Fprintf(os.Stderr, "Can't receive %s: %v\n", filename, err)
return err
}
b.m[filename] = buf.Bytes()
return nil
}
func (b *testBackend) handleRead(filename string, rf io.ReaderFrom) error {
b.mu.Lock()
defer b.mu.Unlock()
bs, ok := b.m[filename]
if !ok {
fmt.Fprintf(os.Stderr, "File %s not found\n", filename)
return fmt.Errorf("file not found")
}
if t, ok := rf.(OutgoingTransfer); ok {
t.SetSize(int64(len(bs)))
}
_, err := rf.ReadFrom(bytes.NewBuffer(bs))
if err != nil {
fmt.Fprintf(os.Stderr, "Can't send %s: %v\n", filename, err)
return err
}
return nil
}
type randReader struct {
src rand.Source
next int64
i int8
}
func newRandReader(src rand.Source) io.Reader {
r := &randReader{
src: src,
next: src.Int63(),
}
return r
}
func (r *randReader) Read(p []byte) (n int, err error) {
next, i := r.next, r.i
for n = 0; n < len(p); n++ {
if i == 7 {
next, i = r.src.Int63(), 0
}
p[n] = byte(next)
next >>= 8
i++
}
r.next, r.i = next, i
return
}
func serverTimeoutSendTest(s *Server, c *Client, t *testing.T) {
s.SetTimeout(time.Second)
s.SetRetries(2)
var serverErr error
s.readHandler = func(filename string, rf io.ReaderFrom) error {
r := io.LimitReader(newRandReader(rand.NewSource(42)), 80000)
_, serverErr = rf.ReadFrom(r)
return serverErr
}
defer s.Shutdown()
filename := "test-server-send-timeout"
mode := "octet"
readTransfer, err := c.Receive(filename, mode)
if err != nil {
t.Fatalf("requesting read %s: %v", filename, err)
}
w := &slowWriter{
n: 3,
delay: 8 * time.Second,
}
_, _ = readTransfer.WriteTo(w)
netErr, ok := serverErr.(net.Error)
if !ok {
t.Fatalf("network error expected: %T", serverErr)
}
if !netErr.Timeout() {
t.Fatalf("timout is expected: %v", serverErr)
}
}
func TestServerSendTimeout(t *testing.T) {
s, c := makeTestServer(false)
serverTimeoutSendTest(s, c, t)
}
func serverReceiveTimeoutTest(s *Server, c *Client, t *testing.T) {
s.SetTimeout(time.Second)
s.SetRetries(2)
var serverErr error
s.writeHandler = func(filename string, wt io.WriterTo) error {
buf := &bytes.Buffer{}
_, serverErr = wt.WriteTo(buf)
return serverErr
}
defer s.Shutdown()
filename := "test-server-receive-timeout"
mode := "octet"
writeTransfer, err := c.Send(filename, mode)
if err != nil {
t.Fatalf("requesting write %s: %v", filename, err)
}
r := &slowReader{
r: io.LimitReader(newRandReader(rand.NewSource(42)), 80000),
n: 3,
delay: 8 * time.Second,
}
_, _ = writeTransfer.ReadFrom(r)
netErr, ok := serverErr.(net.Error)
if !ok {
t.Fatalf("network error expected: %T", serverErr)
}
if !netErr.Timeout() {
t.Fatalf("timout is expected: %v", serverErr)
}
}
func TestServerReceiveTimeout(t *testing.T) {
s, c := makeTestServer(false)
serverReceiveTimeoutTest(s, c, t)
}
func TestClientReceiveTimeout(t *testing.T) {
s, c := makeTestServer(false)
c.SetTimeout(time.Second)
c.SetRetries(2)
s.readHandler = func(filename string, rf io.ReaderFrom) error {
r := &slowReader{
r: io.LimitReader(newRandReader(rand.NewSource(42)), 80000),
n: 3,
delay: 8 * time.Second,
}
_, err := rf.ReadFrom(r)
return err
}
defer s.Shutdown()
filename := "test-client-receive-timeout"
mode := "octet"
readTransfer, err := c.Receive(filename, mode)
if err != nil {
t.Fatalf("requesting read %s: %v", filename, err)
}
buf := &bytes.Buffer{}
_, err = readTransfer.WriteTo(buf)
netErr, ok := err.(net.Error)
if !ok {
t.Fatalf("network error expected: %T", err)
}
if !netErr.Timeout() {
t.Fatalf("timout is expected: %v", err)
}
}
func TestClientSendTimeout(t *testing.T) {
s, c := makeTestServer(false)
c.SetTimeout(time.Second)
c.SetRetries(2)
s.writeHandler = func(filename string, wt io.WriterTo) error {
w := &slowWriter{
n: 3,
delay: 8 * time.Second,
}
_, err := wt.WriteTo(w)
return err
}
defer s.Shutdown()
filename := "test-client-send-timeout"
mode := "octet"
writeTransfer, err := c.Send(filename, mode)
if err != nil {
t.Fatalf("requesting write %s: %v", filename, err)
}
r := io.LimitReader(newRandReader(rand.NewSource(42)), 80000)
_, err = writeTransfer.ReadFrom(r)
netErr, ok := err.(net.Error)
if !ok {
t.Fatalf("network error expected: %T", err)
}
if !netErr.Timeout() {
t.Fatalf("timout is expected: %v", err)
}
}
type slowReader struct {
r io.Reader
n int64
delay time.Duration
}
func (r *slowReader) Read(p []byte) (n int, err error) {
if r.n > 0 {
r.n--
return r.r.Read(p)
}
time.Sleep(r.delay)
return r.r.Read(p)
}
type slowWriter struct {
r io.Reader
n int64
delay time.Duration
}
func (r *slowWriter) Write(p []byte) (n int, err error) {
if r.n > 0 {
r.n--
return len(p), nil
}
time.Sleep(r.delay)
return len(p), nil
}
// TestRequestPacketInfo checks that request packet destination address
// obtained by server using out-of-band socket info is sane.
// It creates server and tries to do transfers using different local interfaces.
// NB: Test ignores transfer errors and validates RequestPacketInfo only
// if transfer is completed successfully. So it checks that LocalIP returns
// correct result if any result is returned, but does not check if result was
// returned at all when it should.
func TestRequestPacketInfo(t *testing.T) {
// localIP keeps value received from RequestPacketInfo.LocalIP
// call inside handler.
// If RequestPacketInfo is not supported, value is set to unspecified
// IP address.
var localIP net.IP
var localIPMu sync.Mutex
s := NewServer(
func(_ string, rf io.ReaderFrom) error {
localIPMu.Lock()
if rpi, ok := rf.(RequestPacketInfo); ok {
localIP = rpi.LocalIP()
} else {
localIP = net.IP{}
}
localIPMu.Unlock()
_, err := rf.ReadFrom(io.LimitReader(
newRandReader(rand.NewSource(42)), 42))
if err != nil {
t.Logf("sending to client: %v", err)
}
return nil
},
func(_ string, wt io.WriterTo) error {
localIPMu.Lock()
if rpi, ok := wt.(RequestPacketInfo); ok {
localIP = rpi.LocalIP()
} else {
localIP = net.IP{}
}
localIPMu.Unlock()
_, err := wt.WriteTo(ioutil.Discard)
if err != nil {
t.Logf("receiving from client: %v", err)
}
return nil
},
)
conn, err := net.ListenUDP("udp", &net.UDPAddr{})
if err != nil {
t.Fatalf("listen UDP: %v", err)
}
_, port, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
t.Fatalf("parsing server port: %v", err)
}
// Start server
go func() {
err := s.Serve(conn)
if err != nil {
t.Fatalf("serve: %v", err)
}
}()
defer s.Shutdown()
addrs, err := net.InterfaceAddrs()
if err != nil {
t.Fatalf("listing interface addresses: %v", err)
}
for _, addr := range addrs {
ip := networkIP(addr.(*net.IPNet))
if ip == nil {
continue
}
c, err := NewClient(net.JoinHostPort(ip.String(), port))
if err != nil {
t.Fatalf("new client: %v", err)
}
// Skip re-tries to skip non-routable interfaces faster
c.SetRetries(0)
ot, err := c.Send("a", "octet")
if err != nil {
t.Logf("start sending to %v: %v", ip, err)
continue
}
_, err = ot.ReadFrom(io.LimitReader(
newRandReader(rand.NewSource(42)), 42))
if err != nil {
t.Logf("sending to %v: %v", ip, err)
continue
}
// Check that read handler received IP that was used
// to create the client.
localIPMu.Lock()
if localIP != nil && !localIP.IsUnspecified() { // Skip check if no packet info
if !localIP.Equal(ip) {
t.Errorf("sent to: %v, request packet: %v", ip, localIP)
}
} else {
fmt.Printf("Skip %v\n", ip)
}
localIPMu.Unlock()
it, err := c.Receive("a", "octet")
if err != nil {
t.Logf("start receiving from %v: %v", ip, err)
continue
}
_, err = it.WriteTo(ioutil.Discard)
if err != nil {
t.Logf("receiving from %v: %v", ip, err)
continue
}
// Check that write handler received IP that was used
// to create the client.
localIPMu.Lock()
if localIP != nil && !localIP.IsUnspecified() { // Skip check if no packet info
if !localIP.Equal(ip) {
t.Errorf("sent to: %v, request packet: %v", ip, localIP)
}
} else {
fmt.Printf("Skip %v\n", ip)
}
localIPMu.Unlock()
fmt.Printf("Done %v\n", ip)
}
}
func networkIP(n *net.IPNet) net.IP {
if ip := n.IP.To4(); ip != nil {
return ip
}
if len(n.IP) == net.IPv6len {
return n.IP
}
return nil
}
// TestFileIOExceptions checks that errors returned by io.Reader or io.Writer used by
// the handler are handled correctly.
func TestReadWriteErrors(t *testing.T) {
s := NewServer(
func(_ string, rf io.ReaderFrom) error {
_, err := rf.ReadFrom(&failingReader{}) // Read operation fails immediately.
if err != errRead {
t.Errorf("want: %v, got: %v", errRead, err)
}
// return no error from handler, client still should receive error
return nil
},
func(_ string, wt io.WriterTo) error {
_, err := wt.WriteTo(&failingWriter{}) // Write operation fails immediately.
if err != errWrite {
t.Errorf("want: %v, got: %v", errWrite, err)
}
// return no error from handler, client still should receive error
return nil
},
)
conn, err := net.ListenUDP("udp", &net.UDPAddr{})
if err != nil {
t.Fatalf("listen UDP: %v", err)
}
_, port, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
t.Fatalf("parsing server port: %v", err)
}
// Start server
go func() {
err := s.Serve(conn)
if err != nil {
t.Fatalf("running serve: %v", err)
}
}()
defer s.Shutdown()
// Create client
c, err := NewClient(net.JoinHostPort(localhost, port))
if err != nil {
t.Fatalf("creating new client: %v", err)
}
ot, err := c.Send("a", "octet")
if err != nil {
t.Errorf("start sending: %v", err)
}
_, err = ot.ReadFrom(io.LimitReader(
newRandReader(rand.NewSource(42)), 42))
if err == nil {
t.Errorf("missing write error")
}
_, err = c.Receive("a", "octet")
if err == nil {
t.Errorf("missing read error")
}
}
type failingReader struct{}
var errRead = errors.New("read error")
func (r *failingReader) Read(_ []byte) (int, error) {
return 0, errRead
}
type failingWriter struct{}
var errWrite = errors.New("write error")
func (r *failingWriter) Write(_ []byte) (int, error) {
return 0, errWrite
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/xu_dazhous_spring/tftp.git
git@gitee.com:xu_dazhous_spring/tftp.git
xu_dazhous_spring
tftp
tftp
master

搜索帮助