|
| 1 | +package pkg |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestNewConnectRequest(t *testing.T) { |
| 10 | + req := NewConnectRequest() |
| 11 | + if req.action != actionConnect { |
| 12 | + t.Errorf("wrong action") |
| 13 | + } |
| 14 | + if len(req.raw) != 16 { |
| 15 | + t.Errorf("wrong serialized size") |
| 16 | + } |
| 17 | + anotherReq := NewConnectRequest() |
| 18 | + if req.transactionId == anotherReq.transactionId { |
| 19 | + t.Errorf("transaction id is not unique") |
| 20 | + } |
| 21 | + if reflect.DeepEqual(req.raw, anotherReq.raw) { |
| 22 | + t.Errorf("serialization is not unique") |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func TestNewScrapeRequest(t *testing.T) { |
| 27 | + var exampleInfohashes []InfoHash = make([]InfoHash, 3) |
| 28 | + for idx, infohash := range exampleInfohashes { |
| 29 | + rand.Read(infohash[:]) |
| 30 | + exampleInfohashes[idx] = infohash |
| 31 | + } |
| 32 | + type args struct { |
| 33 | + connectionID uint64 |
| 34 | + infohashes []InfoHash |
| 35 | + } |
| 36 | + tests := []struct { |
| 37 | + name string |
| 38 | + args args |
| 39 | + want *Request |
| 40 | + }{ |
| 41 | + {"single", args{uint64(42), []InfoHash{exampleInfohashes[0]}}, &Request{transactionId: uint32(12), action: actionScrape}}, |
| 42 | + {"multi", args{uint64(12), exampleInfohashes}, &Request{transactionId: uint32(12), action: actionScrape}}, |
| 43 | + } |
| 44 | + var lastTid *uint32 = nil |
| 45 | + for _, tt := range tests { |
| 46 | + t.Run(tt.name, func(t *testing.T) { |
| 47 | + got := NewScrapeRequest(tt.args.connectionID, tt.args.infohashes...) |
| 48 | + if len(got.raw) != 16+20*len(tt.args.infohashes) { |
| 49 | + t.Errorf("wrong length. Expected %d, got %d", 16+20*len(tt.args.infohashes), len(got.raw)) |
| 50 | + } |
| 51 | + if lastTid != nil && got.transactionId == *lastTid { |
| 52 | + t.Errorf("transaction id not unique") |
| 53 | + } |
| 54 | + if got.action != tt.want.action { |
| 55 | + t.Errorf("wrong action") |
| 56 | + } |
| 57 | + lastTid = &got.transactionId |
| 58 | + for idx, infohash := range tt.args.infohashes { |
| 59 | + if reflect.DeepEqual(infohash, InfoHash{}) { |
| 60 | + t.Errorf("empty infohash at %d", idx) |
| 61 | + } |
| 62 | + if !reflect.DeepEqual(got.raw[16+20*idx:16+20*idx+20], infohash[0:20]) { |
| 63 | + t.Errorf("missing infohash %v", infohash[0:20]) |
| 64 | + } |
| 65 | + } |
| 66 | + }) |
| 67 | + } |
| 68 | +} |
0 commit comments