From d0c1b68692a9eb20a5da9c29f2cd1b1a1a9da3d8 Mon Sep 17 00:00:00 2001 From: Bora Alper Date: Tue, 7 Nov 2017 21:20:40 +0000 Subject: [PATCH] Thanks to @anacrolix, we no longer need to monkey-patch the `torrent`! Also added `operations_test.go` to ensure that it works as it's advertised. --- magneticod/bittorrent/operations.go | 5 +-- magneticod/bittorrent/operations_test.go | 44 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 magneticod/bittorrent/operations_test.go diff --git a/magneticod/bittorrent/operations.go b/magneticod/bittorrent/operations.go index 73525b8..36c7be0 100644 --- a/magneticod/bittorrent/operations.go +++ b/magneticod/bittorrent/operations.go @@ -235,10 +235,11 @@ func (ms *MetadataSink) awaitMetadata(infoHash metainfo.Hash, peer Peer) { } else if rMessage[1] == 0x01 { // __on_ext_message(message[2:]) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + // Run TestDecoder() function in operations_test.go in case you have any doubts. rMessageBuf := bytes.NewBuffer(rMessage[2:]) rExtDict := new(extDict) - // TODO: We monkey-patched anacrolix/torrent! - err := bencode.NewDecoder2(rMessageBuf).Decode(rExtDict) + err := bencode.NewDecoder(rMessageBuf).Decode(rExtDict) if err != nil { zap.L().Warn("Couldn't decode extension message in the loop!", zap.Error(err)) return diff --git a/magneticod/bittorrent/operations_test.go b/magneticod/bittorrent/operations_test.go new file mode 100644 index 0000000..8c24fa6 --- /dev/null +++ b/magneticod/bittorrent/operations_test.go @@ -0,0 +1,44 @@ +package bittorrent + +import ( + "bytes" + "testing" + + "github.com/anacrolix/torrent/bencode" +) + +var operationsTest_instances = []struct{ + dump []byte + surplus []byte +}{ + // No Surplus + { + dump: []byte("d1:md11:ut_metadatai1ee13:metadata_sizei22528ee"), + surplus: []byte(""), + }, + // Surplus is an ASCII string + { + dump: []byte("d1:md11:ut_metadatai1ee13:metadata_sizei22528eeDENEME"), + surplus: []byte("DENEME"), + }, + // Surplus is a bencoded dictionary + { + dump: []byte("d1:md11:ut_metadatai1ee13:metadata_sizei22528eed3:inti1337ee"), + surplus: []byte("d3:inti1337ee"), + }, +} + +func TestDecoder(t *testing.T) { + for i, instance := range operationsTest_instances { + buf := bytes.NewBuffer(instance.dump) + err := bencode.NewDecoder(buf).Decode(&struct {}{}) + if err != nil { + t.Errorf("Couldn't decode the dump #%d! %s", i + 1, err.Error()) + } + + bufSurplus := buf.Bytes() + if !bytes.Equal(bufSurplus, instance.surplus) { + t.Errorf("Surplus #%d is not equal to what we expected! `%s`", i + 1, bufSurplus) + } + } +}