github.com/uber/kraken@v0.1.4/lib/torrent/scheduler/conn/fixtures.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package conn 15 16 import ( 17 "net" 18 "time" 19 20 "github.com/andres-erbsen/clock" 21 "github.com/uber-go/tally" 22 "go.uber.org/zap" 23 24 "github.com/uber/kraken/core" 25 "github.com/uber/kraken/lib/torrent/networkevent" 26 "github.com/uber/kraken/lib/torrent/storage" 27 "github.com/uber/kraken/utils/testutil" 28 ) 29 30 type noopEvents struct{} 31 32 func (e noopEvents) ConnClosed(*Conn) {} 33 34 // noopDeadline wraps a Conn which does not support deadlines (e.g. net.Pipe) 35 // and makes it accept deadlines. 36 type noopDeadline struct { 37 net.Conn 38 } 39 40 func (n noopDeadline) SetDeadline(t time.Time) error { return nil } 41 func (n noopDeadline) SetReadDeadline(t time.Time) error { return nil } 42 func (n noopDeadline) SetWriteDeadline(t time.Time) error { return nil } 43 44 // PipeFixture returns Conns for both sides of a live connection for testing. 45 func PipeFixture( 46 config Config, info *storage.TorrentInfo) (local *Conn, remote *Conn, cleanupFunc func()) { 47 48 var cleanup testutil.Cleanup 49 defer cleanup.Recover() 50 51 nc1, nc2 := net.Pipe() 52 cleanup.Add(func() { nc1.Close() }) 53 cleanup.Add(func() { nc2.Close() }) 54 55 var err error 56 57 local, err = HandshakerFixture(config).newConn( 58 noopDeadline{nc1}, core.PeerIDFixture(), info, false) 59 if err != nil { 60 panic(err) 61 } 62 local.Start() 63 64 remote, err = HandshakerFixture(config).newConn( 65 noopDeadline{nc2}, core.PeerIDFixture(), info, true) 66 if err != nil { 67 panic(err) 68 } 69 remote.Start() 70 71 return local, remote, cleanup.Run 72 } 73 74 // Fixture returns a single local Conn for testing. 75 func Fixture() (*Conn, func()) { 76 info := storage.TorrentInfoFixture(1, 1) 77 local, _, cleanup := PipeFixture(Config{}, info) 78 return local, cleanup 79 } 80 81 // HandshakerFixture returns a Handshaker for testing. 82 func HandshakerFixture(config Config) *Handshaker { 83 h, err := NewHandshaker( 84 config, 85 tally.NewTestScope("", nil), 86 clock.New(), 87 networkevent.NewTestProducer(), 88 core.PeerIDFixture(), 89 noopEvents{}, 90 zap.NewNop().Sugar()) 91 if err != nil { 92 panic(err) 93 } 94 return h 95 } 96 97 // ConfigFixture returns a Config for testing. 98 func ConfigFixture() Config { 99 return Config{}.applyDefaults() 100 }