From f59311ed1bcf5dbbcc4ee81f3ceb81d882f48a70 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Mon, 30 Sep 2024 13:00:54 +1000 Subject: [PATCH] Start moving to github.com/go-quicktest/qt --- bencode/both_test.go | 8 +- bencode/bytes_test.go | 12 +- bencode/decode_test.go | 46 +++--- bencode/fuzz_test.go | 21 ++- client-nowasm_test.go | 30 ++-- client_test.go | 127 ++++++++--------- fs/torrentfs_test.go | 19 +-- go.mod | 3 +- go.sum | 4 + internal/alloclim/alloclim_test.go | 47 +++---- internal/nestedmaps/nestedmaps_test.go | 35 ++--- internal/qtnew/qtnew.go | 9 ++ iplist/cidr_test.go | 7 +- iplist/iplist_test.go | 3 +- iplist/packed_test.go | 5 +- issue-949_test.go | 11 +- issue211_test.go | 6 +- issue97_test.go | 8 +- ltep_test.go | 31 +++-- metainfo/magnet-v2_test.go | 35 ++--- metainfo/magnet_test.go | 18 +-- metainfo/metainfo_test.go | 38 ++--- metainfo/nodes_test.go | 12 +- mse/mse_test.go | 19 +-- network_test.go | 10 +- ordered-bitmap.go | 3 +- peer_protocol/decoder_test.go | 9 +- peer_protocol/fuzz_test.go | 11 +- peer_protocol/pex_test.go | 15 +- peer_protocol/reserved_test.go | 7 +- .../ut-holepunch/ut-holepunch_test.go | 13 +- peerconn_test.go | 131 +++++++++--------- pexconn_test.go | 3 +- reader_test.go | 5 +- request-strategy-impls_test.go | 20 +-- requesting_test.go | 2 +- reuse_test.go | 25 ++-- roaring.go | 4 +- segments/segments_test.go | 4 +- storage/bolt-piece-completion_test.go | 14 +- storage/file-misc_test.go | 11 +- storage/file_test.go | 6 +- storage/issue95_test.go | 6 +- storage/issue96_test.go | 5 +- storage/mmap_test.go | 13 +- storage/safe-path_test.go | 11 +- storage/sqlite-piece-completion.go | 2 +- storage/sqlite/sqlite-storage_test.go | 9 +- storage/test/bench-piece-mark-complete.go | 18 +-- test/issue377_test.go | 12 +- test/leecher-storage.go | 15 +- test/sqlite_test.go | 15 +- test/transfer_test.go | 16 +-- .../add-webseed-after-priorities/herp_test.go | 12 +- tests/issue-952/issue-952_test.go | 17 +-- tests/webseed-partial-seed/herp_test.go | 7 +- torrent_test.go | 32 +++-- tracker/http/http_test.go | 18 +-- tracker/udp/server/server.go | 2 +- tracker/udp/timeout_test.go | 9 +- tracker/udp/udp_test.go | 21 +-- tracker/udp_test.go | 14 +- ut-holepunching_test.go | 48 +++---- util/dirwatch/dirwatch_test.go | 4 +- webseed/request_test.go | 18 +-- webtorrent/fuzz_test.go | 7 +- webtorrent/transport_test.go | 7 +- worse-conns_test.go | 31 +++-- 68 files changed, 628 insertions(+), 588 deletions(-) create mode 100644 internal/qtnew/qtnew.go diff --git a/bencode/both_test.go b/bencode/both_test.go index fdcb90d9f8..39aa026273 100644 --- a/bencode/both_test.go +++ b/bencode/both_test.go @@ -5,13 +5,13 @@ import ( "os" "testing" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func loadFile(name string, t *testing.T) []byte { data, err := os.ReadFile(name) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) return data } @@ -20,10 +20,10 @@ func testFileInterface(t *testing.T, filename string) { var iface interface{} err := Unmarshal(data1, &iface) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) data2, err := Marshal(iface) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, data1, data2) } diff --git a/bencode/bytes_test.go b/bencode/bytes_test.go index 08b4f98ba0..f203dfa544 100644 --- a/bencode/bytes_test.go +++ b/bencode/bytes_test.go @@ -3,7 +3,7 @@ package bencode import ( "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" ) func TestBytesMarshalNil(t *testing.T) { @@ -18,8 +18,7 @@ type structWithBytes struct { func TestMarshalNilStructBytes(t *testing.T) { _, err := Marshal(structWithBytes{B: Bytes("i42e")}) - c := qt.New(t) - c.Assert(err, qt.IsNotNil) + qt.Assert(t, qt.IsNotNil(err)) } type structWithOmitEmptyBytes struct { @@ -28,12 +27,11 @@ type structWithOmitEmptyBytes struct { } func TestMarshalNilStructBytesOmitEmpty(t *testing.T) { - c := qt.New(t) b, err := Marshal(structWithOmitEmptyBytes{B: Bytes("i42e")}) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) t.Logf("%q", b) var s structWithBytes err = Unmarshal(b, &s) - c.Assert(err, qt.IsNil) - c.Check(s.B, qt.DeepEquals, Bytes("i42e")) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.DeepEquals(s.B, Bytes("i42e"))) } diff --git a/bencode/decode_test.go b/bencode/decode_test.go index 16fa448773..f8546059e3 100644 --- a/bencode/decode_test.go +++ b/bencode/decode_test.go @@ -10,7 +10,8 @@ import ( "strings" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -68,10 +69,10 @@ func TestDecoderConsecutive(t *testing.T) { d := NewDecoder(bytes.NewReader([]byte("i1ei2e"))) var i int err := d.Decode(&i) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, 1, i) err = d.Decode(&i) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, 2, i) err = d.Decode(&i) require.Equal(t, io.EOF, err) @@ -86,19 +87,19 @@ func TestDecoderConsecutiveDicts(t *testing.T) { var m map[string]interface{} - require.NoError(t, d.Decode(&m)) + qt.Assert(t, qt.IsNil(d.Decode(&m))) assert.Len(t, m, 1) assert.Equal(t, "derp", m["herp"]) assert.Equal(t, "d3:wat1:ke17:oh baby a triple!", bb.String()) assert.EqualValues(t, 14, d.Offset) - require.NoError(t, d.Decode(&m)) + qt.Assert(t, qt.IsNil(d.Decode(&m))) assert.Equal(t, "k", m["wat"]) assert.Equal(t, "17:oh baby a triple!", bb.String()) assert.EqualValues(t, 24, d.Offset) var s string - require.NoError(t, d.Decode(&s)) + qt.Assert(t, qt.IsNil(d.Decode(&s))) assert.Equal(t, "oh baby a triple!", s) assert.EqualValues(t, 44, d.Offset) } @@ -150,7 +151,7 @@ func TestIgnoreUnmarshalTypeError(t *testing.T) { }{} require.Error(t, Unmarshal([]byte("d6:Normal5:helloe"), &s)) assert.NoError(t, Unmarshal([]byte("d6:Ignore5:helloe"), &s)) - qt.Assert(t, Unmarshal([]byte("d6:Ignorei42ee"), &s), qt.IsNil) + qt.Assert(t, qt.IsNil(Unmarshal([]byte("d6:Ignorei42ee"), &s))) assert.EqualValues(t, 42, s.Ignore) } @@ -162,8 +163,8 @@ func TestDecodeCustomSlice(t *testing.T) { // We do a longer slice then a shorter slice to see if the buffers are // shared. d := NewDecoder(bytes.NewBufferString("3:\x01\x10\xff2:\x04\x0f")) - require.NoError(t, d.Decode(&fs3)) - require.NoError(t, d.Decode(&fs2)) + qt.Assert(t, qt.IsNil(d.Decode(&fs3))) + qt.Assert(t, qt.IsNil(d.Decode(&fs2))) assert.EqualValues(t, []flag{1, 16, 255}, fs3) assert.EqualValues(t, []flag{4, 15}, fs2) } @@ -183,19 +184,19 @@ func TestUnmarshalByteArray(t *testing.T) { func TestDecodeDictIntoUnsupported(t *testing.T) { // Any type that a dict shouldn't be unmarshallable into. var i int - c := qt.New(t) + c := qtnew.New(t) err := Unmarshal([]byte("d1:a1:be"), &i) t.Log(err) - c.Check(err, qt.IsNotNil) + qt.Check(c, qt.IsNotNil(err)) } func TestUnmarshalDictKeyNotString(t *testing.T) { // Any type that a dict shouldn't be unmarshallable into. var i int - c := qt.New(t) + c := qtnew.New(t) err := Unmarshal([]byte("di42e3:yese"), &i) t.Log(err) - c.Check(err, qt.Not(qt.IsNil)) + qt.Check(c, qt.Not(qt.IsNil(err))) } type arbitraryReader struct{} @@ -220,14 +221,13 @@ func decodeHugeString(t *testing.T, strLen int64, header, tail string, v interfa // Ensure that bencode strings in various places obey the Decoder.MaxStrLen field. func TestDecodeMaxStrLen(t *testing.T) { t.Parallel() - c := qt.New(t) test := func(header, tail string, v interface{}, maxStrLen MaxStrLen) { strLen := maxStrLen if strLen == 0 { strLen = DefaultDecodeMaxStrLen } - c.Assert(decodeHugeString(t, strLen, header, tail, v, maxStrLen), qt.IsNil) - c.Assert(decodeHugeString(t, strLen+1, header, tail, v, maxStrLen), qt.IsNotNil) + qt.Assert(t, qt.IsNil(decodeHugeString(t, strLen, header, tail, v, maxStrLen))) + qt.Assert(t, qt.IsNotNil(decodeHugeString(t, strLen+1, header, tail, v, maxStrLen))) } test("d%d:", "i0ee", new(interface{}), 0) test("%d:", "", new(interface{}), DefaultDecodeMaxStrLen) @@ -242,14 +242,14 @@ func TestDecodeStringIntoBoolPtr(t *testing.T) { var m struct { Private *bool `bencode:"private,omitempty"` } - c := qt.New(t) + c := qtnew.New(t) check := func(msg string, expectNil, expectTrue bool) { m.Private = nil - c.Check(Unmarshal([]byte(msg), &m), qt.IsNil, qt.Commentf("%q", msg)) + qt.Check(qt, qt.IsNil(Unmarshal([]byte(msg), &m), qt.Commentf("%q", msg))(c)) if expectNil { - c.Check(m.Private, qt.IsNil) + qt.Check(c, qt.IsNil(m.Private)) } else { - if c.Check(m.Private, qt.IsNotNil, qt.Commentf("%q", msg)) { + if qt.Check(qt, qt.IsNotNil(m.Private, qt.Commentf("%q", msg))(c)) { c.Check(*m.Private, qt.Equals, expectTrue, qt.Commentf("%q", msg)) } } @@ -270,7 +270,7 @@ func TestDecodeStringIntoBoolPtr(t *testing.T) { // To set expectations about how our Decoder should work. func TestJsonDecoderBehaviour(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) test := func(input string, items int, finalErr error) { d := json.NewDecoder(strings.NewReader(input)) actualItems := 0 @@ -283,8 +283,8 @@ func TestJsonDecoderBehaviour(t *testing.T) { } actualItems++ } - c.Check(firstErr, qt.Equals, finalErr) - c.Check(actualItems, qt.Equals, items) + qt.Check(qt, qt.Equals(firstErr, finalErr)(c)) + qt.Check(qt, qt.Equals(actualItems, items)(c)) } test("", 0, io.EOF) test("{}", 1, io.EOF) diff --git a/bencode/fuzz_test.go b/bencode/fuzz_test.go index d0dce71f3d..1dd7443fe5 100644 --- a/bencode/fuzz_test.go +++ b/bencode/fuzz_test.go @@ -7,31 +7,28 @@ import ( "math/big" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" "github.com/google/go-cmp/cmp" ) -var bencodeInterfaceChecker = qt.CmpEquals(cmp.Comparer(func(a, b *big.Int) bool { - return a.Cmp(b) == 0 -})) - func Fuzz(f *testing.F) { for _, ret := range random_encode_tests { f.Add([]byte(ret.expected)) } f.Fuzz(func(t *testing.T, b []byte) { - c := qt.New(t) + c := qtnew.New(t) var d interface{} err := Unmarshal(b, &d) if err != nil { t.Skip() } b0, err := Marshal(d) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) var d0 interface{} err = Unmarshal(b0, &d0) - c.Assert(err, qt.IsNil) - c.Assert(d0, bencodeInterfaceChecker, d) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.CmpEquals(d0, d, cmp.Comparer(func(a, b *big.Int) bool { return a.Cmp(b) == 0 }))) }) } @@ -40,14 +37,14 @@ func FuzzInterfaceRoundTrip(f *testing.F) { f.Add([]byte(ret.expected)) } f.Fuzz(func(t *testing.T, b []byte) { - c := qt.New(t) + c := qtnew.New(t) var d interface{} err := Unmarshal(b, &d) if err != nil { c.Skip(err) } b0, err := Marshal(d) - c.Assert(err, qt.IsNil) - c.Check(b0, qt.DeepEquals, b) + qt.Assert(t, qt.IsNil(err)) + qt.Check(qt, qt.DeepEquals(b0, b)(c)) }) } diff --git a/client-nowasm_test.go b/client-nowasm_test.go index 08ed80ced4..0bcbd02283 100644 --- a/client-nowasm_test.go +++ b/client-nowasm_test.go @@ -7,27 +7,27 @@ import ( "os" "testing" - qt "github.com/frankban/quicktest" - "github.com/stretchr/testify/require" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" "github.com/anacrolix/torrent/storage" ) func TestBoltPieceCompletionClosedWhenClientClosed(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) cfg := TestingConfig(t) pc, err := storage.NewBoltPieceCompletion(cfg.DataDir) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) ci := storage.NewFileWithCompletion(cfg.DataDir, pc) defer ci.Close() cfg.DefaultStorage = ci cl, err := NewClient(cfg) - c.Assert(err, qt.IsNil, qt.Commentf("%#v", err)) + qt.Assert(t, qt.IsNil(err, qt.Commentf("%#v", err))) cl.Close() // And again, https://github.com/anacrolix/torrent/issues/158 cl, err = NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) cl.Close() } @@ -51,22 +51,22 @@ func TestIssue335(t *testing.T) { cfg.Debug = true cfg.DataDir = dir comp, err := storage.NewBoltPieceCompletion(dir) - c := qt.New(t) - c.Assert(err, qt.IsNil) + c := qtnew.New(t) + qt.Assert(t, qt.IsNil(err)) defer logErr(comp.Close, "closing bolt piece completion") mmapStorage := storage.NewMMapWithCompletion(dir, comp) defer logErr(mmapStorage.Close, "closing mmap storage") cfg.DefaultStorage = mmapStorage cl, err := NewClient(cfg) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() tor, new, err := cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) - c.Assert(err, qt.IsNil) - c.Assert(new, qt.IsTrue) - c.Assert(cl.WaitAll(), qt.IsTrue) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsTrue(new)) + qt.Assert(t, qt.IsTrue(cl.WaitAll())) tor.Drop() _, new, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) - c.Assert(err, qt.IsNil) - c.Assert(new, qt.IsTrue) - c.Assert(cl.WaitAll(), qt.IsTrue) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsTrue(new)) + qt.Assert(t, qt.IsTrue(cl.WaitAll())) } diff --git a/client_test.go b/client_test.go index 49bd8102b0..1a0e81207d 100644 --- a/client_test.go +++ b/client_test.go @@ -20,11 +20,12 @@ import ( "github.com/anacrolix/missinggo/v2" "github.com/anacrolix/missinggo/v2/filecache" "github.com/frankban/quicktest" - qt "github.com/frankban/quicktest" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/bencode" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" "github.com/anacrolix/torrent/iplist" "github.com/anacrolix/torrent/metainfo" @@ -33,7 +34,7 @@ import ( func TestClientDefault(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Empty(t, cl.Close()) } @@ -43,18 +44,18 @@ func TestClientNilConfig(t *testing.T) { defer os.Chdir(origDir) os.Chdir(t.TempDir()) cl, err := NewClient(nil) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Empty(t, cl.Close()) } func TestAddDropTorrent(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() dir, mi := testutil.GreetingTestTorrent() defer os.RemoveAll(dir) tt, new, err := cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, new) tt.SetMaxEstablishedConns(0) tt.SetMaxEstablishedConns(1) @@ -94,7 +95,7 @@ func TestTorrentInitialState(t *testing.T) { tor.cl.lock() err := tor.setInfoBytesLocked(mi.InfoBytes) tor.cl.unlock() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Len(t, tor.pieces, 3) tor.pendAllChunkSpecs(0) tor.cl.lock() @@ -131,7 +132,7 @@ func TestReducedDialTimeout(t *testing.T) { func TestAddDropManyTorrents(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() for i := range 1000 { var spec TorrentSpec @@ -154,7 +155,7 @@ func fileCachePieceResourceStorage(fc *filecache.Cache) storage.ClientImpl { func TestMergingTrackersByAddingSpecs(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() spec := TorrentSpec{} rand.Read(spec.InfoHash[:]) @@ -175,7 +176,7 @@ func TestCompletedPieceWrongSize(t *testing.T) { cfg := TestingConfig(t) cfg.DefaultStorage = badStorage{} cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() info := metainfo.Info{ PieceLength: 15, @@ -185,17 +186,17 @@ func TestCompletedPieceWrongSize(t *testing.T) { }, } b, err := bencode.Marshal(info) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) tt, new, err := cl.AddTorrentSpec(&TorrentSpec{ InfoBytes: b, InfoHash: metainfo.HashBytes(b), }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer tt.Drop() assert.True(t, new) r := tt.NewReader() defer r.Close() - qt.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), qt.IsNil) + qt.Check(qt, iotest.TestReader(r, []byte(testutil.GreetingFileContents))(t, qt.IsNil)(qt)) } func BenchmarkAddLargeTorrent(b *testing.B) { @@ -203,7 +204,7 @@ func BenchmarkAddLargeTorrent(b *testing.B) { cfg.DisableTCP = true cfg.DisableUTP = true cl, err := NewClient(cfg) - require.NoError(b, err) + qt.Assert(b, qt.IsNil(err)) defer cl.Close() b.ReportAllocs() for i := 0; i < b.N; i += 1 { @@ -244,12 +245,12 @@ func TestResponsive(t *testing.T) { reader.SetResponsive() b := make([]byte, 2) _, err = reader.Seek(3, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) _, err = io.ReadFull(reader, b) assert.Nil(t, err) assert.EqualValues(t, "lo", string(b)) _, err = reader.Seek(11, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) n, err := io.ReadFull(reader, b) assert.Nil(t, err) assert.EqualValues(t, 2, n) @@ -288,12 +289,12 @@ func TestResponsiveTcpOnly(t *testing.T) { reader.SetResponsive() b := make([]byte, 2) _, err = reader.Seek(3, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) _, err = io.ReadFull(reader, b) assert.Nil(t, err) assert.EqualValues(t, "lo", string(b)) _, err = reader.Seek(11, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) n, err := io.ReadFull(reader, b) assert.Nil(t, err) assert.EqualValues(t, 2, n) @@ -329,12 +330,12 @@ func TestTorrentDroppedDuringResponsiveRead(t *testing.T) { reader.SetResponsive() b := make([]byte, 2) _, err = reader.Seek(3, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) _, err = io.ReadFull(reader, b) assert.Nil(t, err) assert.EqualValues(t, "lo", string(b)) _, err = reader.Seek(11, io.SeekStart) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) leecherTorrent.Drop() n, err := reader.Read(b) assert.EqualError(t, err, "torrent closed") @@ -342,14 +343,14 @@ func TestTorrentDroppedDuringResponsiveRead(t *testing.T) { } func TestDhtInheritBlocklist(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) ipl := iplist.New(nil) require.NotNil(t, ipl) cfg := TestingConfig(t) cfg.IPBlocklist = ipl cfg.NoDHT = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() numServers := 0 cl.eachDhtServer(func(s DhtServer) { @@ -357,25 +358,25 @@ func TestDhtInheritBlocklist(t *testing.T) { assert.Equal(t, ipl, s.(AnacrolixDhtServerWrapper).Server.IPBlocklist()) numServers++ }) - c.Assert(numServers, qt.Not(qt.Equals), 0) + qt.Assert(t, qt.Not(qt.Equals)(numServers, 0)) } // Check that stuff is merged in subsequent AddTorrentSpec for the same // infohash. func TestAddTorrentSpecMerging(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() dir, mi := testutil.GreetingTestTorrent() defer os.RemoveAll(dir) tt, new, err := cl.AddTorrentSpec(&TorrentSpec{ InfoHash: mi.HashInfoBytes(), }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.True(t, new) require.Nil(t, tt.Info()) _, new, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.False(t, new) require.NotNil(t, tt.Info()) } @@ -407,22 +408,22 @@ func writeTorrentData(ts *storage.Torrent, info metainfo.Info, b []byte) { func testAddTorrentPriorPieceCompletion(t *testing.T, alreadyCompleted bool, csf func(*filecache.Cache) storage.ClientImpl) { fileCacheDir := t.TempDir() fileCache, err := filecache.NewCache(fileCacheDir) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) greetingDataTempDir, greetingMetainfo := testutil.GreetingTestTorrent() defer os.RemoveAll(greetingDataTempDir) filePieceStore := csf(fileCache) info, err := greetingMetainfo.UnmarshalInfo() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) ih := greetingMetainfo.HashInfoBytes() greetingData, err := storage.NewClient(filePieceStore).OpenTorrent(context.Background(), &info, ih) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) writeTorrentData(greetingData, info, []byte(testutil.GreetingFileContents)) // require.Equal(t, len(testutil.GreetingFileContents), written) // require.NoError(t, err) for i := 0; i < info.NumPieces(); i++ { p := info.Piece(i) if alreadyCompleted { - require.NoError(t, greetingData.Piece(p).MarkComplete()) + qt.Assert(t, qt.IsNil(greetingData.Piece(p).MarkComplete())) } } cfg := TestingConfig(t) @@ -431,17 +432,17 @@ func testAddTorrentPriorPieceCompletion(t *testing.T, alreadyCompleted bool, csf cfg.DisableUTP = true cfg.DefaultStorage = filePieceStore cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() tt, err := cl.AddTorrent(greetingMetainfo) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) psrs := tt.PieceStateRuns() assert.Len(t, psrs, 1) assert.EqualValues(t, 3, psrs[0].Length) assert.Equal(t, alreadyCompleted, psrs[0].Complete) if alreadyCompleted { r := tt.NewReader() - quicktest.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), quicktest.IsNil) + qt.Check(qt, iotest.TestReader(r, []byte(testutil.GreetingFileContents))(t, quicktest.IsNil)(quicktest)) } } @@ -462,7 +463,7 @@ func TestAddMetainfoWithNodes(t *testing.T) { // DHT code doesn't support mixing secure and insecure nodes if security is enabled (yet). // cfg.DHTConfig.NoSecurity = true cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() sum := func() (ret int64) { cl.eachDhtServer(func(s DhtServer) { @@ -472,7 +473,7 @@ func TestAddMetainfoWithNodes(t *testing.T) { } assert.EqualValues(t, 0, sum()) tt, err := cl.AddTorrentFromFile("metainfo/testdata/issue_65a.torrent") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) // Nodes are not added or exposed in Torrent's metainfo. We just randomly // check if the announce-list is here instead. TODO: Add nodes. assert.Len(t, tt.metainfo.AnnounceList, 5) @@ -495,21 +496,21 @@ func testDownloadCancel(t *testing.T, ps testDownloadCancelParams) { cfg.Seed = true cfg.DataDir = greetingTempDir seeder, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seeder.Close() defer testutil.ExportStatusWriter(seeder, "s", t)() seederTorrent, _, _ := seeder.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) seederTorrent.VerifyData() leecherDataDir := t.TempDir() fc, err := filecache.NewCache(leecherDataDir) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) if ps.SetLeecherStorageCapacity { fc.SetCapacity(ps.LeecherStorageCapacity) } cfg.DefaultStorage = storage.NewResourcePieces(fc.AsResourceProvider()) cfg.DataDir = leecherDataDir leecher, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecher.Close() defer testutil.ExportStatusWriter(leecher, "l", t)() leecherGreeting, new, err := leecher.AddTorrentSpec(func() (ret *TorrentSpec) { @@ -517,7 +518,7 @@ func testDownloadCancel(t *testing.T, ps testDownloadCancelParams) { ret.ChunkSize = 2 return }()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, new) psc := leecherGreeting.SubscribePieceStateChanges() defer psc.Close() @@ -560,7 +561,7 @@ func TestPeerInvalidHave(t *testing.T) { cfg := TestingConfig(t) cfg.DropMutuallyCompletePeers = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() info := metainfo.Info{ PieceLength: 1, @@ -568,13 +569,13 @@ func TestPeerInvalidHave(t *testing.T) { Files: []metainfo.FileInfo{{Length: 1}}, } infoBytes, err := bencode.Marshal(info) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) tt, _new, err := cl.AddTorrentSpec(&TorrentSpec{ InfoBytes: infoBytes, InfoHash: metainfo.HashBytes(infoBytes), Storage: badStorage{}, }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, _new) defer tt.Drop() cn := &PeerConn{Peer: Peer{ @@ -590,27 +591,27 @@ func TestPeerInvalidHave(t *testing.T) { } func TestPieceCompletedInStorageButNotClient(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) greetingTempDir, greetingMetainfo := testutil.GreetingTestTorrent() defer os.RemoveAll(greetingTempDir) cfg := TestingConfig(t) cfg.DataDir = greetingTempDir seeder, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seeder.Close() _, new, err := seeder.AddTorrentSpec(&TorrentSpec{ InfoBytes: greetingMetainfo.InfoBytes, InfoHash: greetingMetainfo.HashInfoBytes(), }) - c.Check(err, qt.IsNil) - c.Check(new, qt.IsTrue) + qt.Check(c, qt.IsNil(err)) + qt.Check(c, qt.IsTrue(new)) } // Check that when the listen port is 0, all the protocols listened on have // the same port, and it isn't zero. func TestClientDynamicListenPortAllProtocols(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() port := cl.LocalPort() assert.NotEqual(t, 0, port) @@ -625,7 +626,7 @@ func TestClientDynamicListenTCPOnly(t *testing.T) { cfg.DisableUTP = true cfg.DisableTCP = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() assert.NotEqual(t, 0, cl.LocalPort()) } @@ -635,7 +636,7 @@ func TestClientDynamicListenUTPOnly(t *testing.T) { cfg.DisableTCP = true cfg.DisableUTP = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() assert.NotEqual(t, 0, cl.LocalPort()) } @@ -657,7 +658,7 @@ func TestSetMaxEstablishedConn(t *testing.T) { cfg.DropDuplicatePeerIds = true for i := 0; i < 3; i += 1 { cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() tt, _ := cl.AddTorrentInfoHash(ih) tt.SetMaxEstablishedConns(2) @@ -698,19 +699,19 @@ func TestSetMaxEstablishedConn(t *testing.T) { func makeMagnet(t *testing.T, cl *Client, dir, name string) string { os.MkdirAll(dir, 0o770) file, err := os.Create(filepath.Join(dir, name)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) file.Write([]byte(name)) file.Close() mi := metainfo.MetaInfo{} mi.SetDefaults() info := metainfo.Info{PieceLength: 256 * 1024} err = info.BuildFromFilePath(filepath.Join(dir, name)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) mi.InfoBytes, err = bencode.Marshal(info) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) magnet := mi.Magnet(nil, &info).String() tr, err := cl.AddTorrent(&mi) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.True(t, tr.Seeding()) tr.VerifyData() return magnet @@ -739,7 +740,7 @@ func testSeederLeecherPair(t *testing.T, seeder, leecher func(*ClientConfig)) { os.Mkdir(cfg.DataDir, 0o755) seeder(cfg) server, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer server.Close() defer testutil.ExportStatusWriter(server, "s", t)() magnet1 := makeMagnet(t, server, cfg.DataDir, "test1") @@ -753,11 +754,11 @@ func testSeederLeecherPair(t *testing.T, seeder, leecher func(*ClientConfig)) { cfg.DataDir = filepath.Join(cfg.DataDir, "client") leecher(cfg) client, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer client.Close() defer testutil.ExportStatusWriter(client, "c", t)() tr, err := client.AddMagnet(magnet1) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) tr.AddClientPeer(server) <-tr.GotInfo() tr.DownloadAll() @@ -815,7 +816,7 @@ func TestClientHasDhtServersWhenUtpDisabled(t *testing.T) { cc.DisableUTP = true cc.NoDHT = false cl, err := NewClient(cc) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() assert.NotEmpty(t, cl.DhtServers()) } @@ -826,7 +827,7 @@ func TestClientDisabledImplicitNetworksButDhtEnabled(t *testing.T) { cfg.DisableUTP = true cfg.NoDHT = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() assert.Empty(t, cl.listeners) assert.NotEmpty(t, cl.DhtServers()) @@ -894,7 +895,7 @@ func TestBadPeerIpPort(t *testing.T) { cfg.DisableUTP = true cfg.NoDHT = false cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() tc.setup(cl) @@ -907,11 +908,11 @@ func TestBadPeerIpPort(t *testing.T) { func TestClientConfigSetHandlerNotIgnored(t *testing.T) { cfg := TestingConfig(t) cfg.Logger.SetHandlers(log.DiscardHandler) - c := qt.New(t) + c := qtnew.New(t) cl, err := NewClient(cfg) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() - c.Assert(cl.logger.Handlers, qt.HasLen, 1) + qt.Assert(t, qt.HasLen(cl.logger.Handlers, 1)) h := cl.logger.Handlers[0].(log.StreamHandler) - c.Check(h.W, qt.Equals, io.Discard) + qt.Check(qt, qt.Equals(h.W, io.Discard)(c)) } diff --git a/fs/torrentfs_test.go b/fs/torrentfs_test.go index 1bf9004e61..8a89504f21 100644 --- a/fs/torrentfs_test.go +++ b/fs/torrentfs_test.go @@ -16,6 +16,7 @@ import ( "github.com/anacrolix/fuse" fusefs "github.com/anacrolix/fuse/fs" "github.com/anacrolix/missinggo/v2" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -77,7 +78,7 @@ func newGreetingLayout(t *testing.T) (tl testLayout, err error) { // operations blocked inside the filesystem code. func TestUnmountWedged(t *testing.T) { layout, err := newGreetingLayout(t) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer func() { err := layout.Destroy() if err != nil { @@ -91,10 +92,10 @@ func TestUnmountWedged(t *testing.T) { cfg.DisableTCP = true cfg.DisableUTP = true client, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer client.Close() tt, err := client.AddTorrent(layout.Metainfo) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) fs := New(client) fuseConn, err := fuse.Mount(layout.MountDir) if err != nil { @@ -159,7 +160,7 @@ func TestUnmountWedged(t *testing.T) { func TestDownloadOnDemand(t *testing.T) { layout, err := newGreetingLayout(t) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer layout.Destroy() cfg := torrent.NewDefaultClientConfig() cfg.DataDir = layout.Completed @@ -169,13 +170,13 @@ func TestDownloadOnDemand(t *testing.T) { cfg.ListenPort = 0 cfg.ListenHost = torrent.LoopbackListenHost seeder, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seeder.Close() defer testutil.ExportStatusWriter(seeder, "s", t)() // Just to mix things up, the seeder starts with the data, but the leecher // starts with the metainfo. seederTorrent, err := seeder.AddMagnet(fmt.Sprintf("magnet:?xt=urn:btih:%s", layout.Metainfo.HashInfoBytes().HexString())) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) go func() { // Wait until we get the metainfo, then check for the data. <-seederTorrent.GotInfo() @@ -189,11 +190,11 @@ func TestDownloadOnDemand(t *testing.T) { cfg.ListenHost = torrent.LoopbackListenHost cfg.ListenPort = 0 leecher, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) testutil.ExportStatusWriter(leecher, "l", t)() defer leecher.Close() leecherTorrent, err := leecher.AddTorrent(layout.Metainfo) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) leecherTorrent.AddClientPeer(seeder) fs := New(leecher) defer fs.Destroy() @@ -204,7 +205,7 @@ func TestDownloadOnDemand(t *testing.T) { size := attr.Size data := make([]byte, size) h, err := node.(fusefs.NodeOpener).Open(context.TODO(), nil, nil) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) // torrent.Reader.Read no longer tries to fill the entire read buffer, so this is a ReadFull for // fusefs. diff --git a/go.mod b/go.mod index 733c6670f0..7ac4732728 100644 --- a/go.mod +++ b/go.mod @@ -73,6 +73,7 @@ require ( github.com/go-logr/logr v1.2.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect + github.com/go-quicktest/qt v1.101.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.3.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.12.0 // indirect @@ -110,7 +111,7 @@ require ( github.com/prometheus/common v0.35.0 // indirect github.com/prometheus/procfs v0.7.3 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417 // indirect github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 // indirect github.com/sethvargo/go-envconfig v0.8.2 // indirect diff --git a/go.sum b/go.sum index 0a98832a4e..70afddc28e 100644 --- a/go.sum +++ b/go.sum @@ -230,6 +230,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= +github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -498,6 +500,8 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417 h1:Lt9DzQALzHoDwMBGJ6v8ObDPR0dzr2a6sXTB1Fq7IHs= github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA= github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 h1:GHRpF1pTW19a8tTFrMLUcfWwyC0pnifVo2ClaLq+hP8= diff --git a/internal/alloclim/alloclim_test.go b/internal/alloclim/alloclim_test.go index 5952804eb9..e17a30ca9d 100644 --- a/internal/alloclim/alloclim_test.go +++ b/internal/alloclim/alloclim_test.go @@ -6,72 +6,69 @@ import ( "time" _ "github.com/anacrolix/envpprof" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func TestReserveOverMax(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) l := &Limiter{Max: 10} r := l.Reserve(20) - c.Assert(r.Wait(context.Background()), qt.IsNotNil) + qt.Assert(t, qt.IsNotNil(r.Wait(context.Background()))) } func TestImmediateAllow(t *testing.T) { - c := qt.New(t) l := &Limiter{Max: 10} r := l.Reserve(10) - c.Assert(r.Wait(context.Background()), qt.IsNil) + qt.Assert(t, qt.IsNil(r.Wait(context.Background()))) } func TestSimpleSequence(t *testing.T) { - c := qt.New(t) l := &Limiter{Max: 10} rs := make([]*Reservation, 0) rs = append(rs, l.Reserve(6)) rs = append(rs, l.Reserve(5)) rs = append(rs, l.Reserve(5)) - c.Assert(rs[0].Wait(context.Background()), qt.IsNil) + qt.Assert(t, qt.IsNil(rs[0].Wait(context.Background()))) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Nanosecond)) - c.Assert(rs[1].Wait(ctx), qt.Equals, context.DeadlineExceeded) + qt.Assert(t, qt.Equals(rs[1].Wait(ctx), context.DeadlineExceeded)) go cancel() ctx, cancel = context.WithCancel(context.Background()) go cancel() - c.Assert(rs[2].Wait(ctx), qt.Equals, context.Canceled) + qt.Assert(t, qt.Equals(rs[2].Wait(ctx), context.Canceled)) go rs[0].Release() ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(time.Second)) - c.Assert(rs[1].Wait(ctx), qt.IsNil) + qt.Assert(t, qt.IsNil(rs[1].Wait(ctx))) go rs[1].Release() - c.Assert(rs[2].Wait(ctx), qt.IsNil) + qt.Assert(t, qt.IsNil(rs[2].Wait(ctx))) go rs[2].Release() go cancel() rs[2].Release() rs[1].Release() - c.Assert(l.Value(), qt.Equals, l.Max) + qt.Assert(t, qt.Equals(l.Value(), l.Max)) } func TestSequenceWithCancel(t *testing.T) { - c := qt.New(t) l := &Limiter{Max: 10} rs := make([]*Reservation, 0) rs = append(rs, l.Reserve(6)) rs = append(rs, l.Reserve(6)) rs = append(rs, l.Reserve(4)) rs = append(rs, l.Reserve(4)) - c.Assert(rs[0].Cancel(), qt.IsFalse) - c.Assert(func() { rs[1].Release() }, qt.PanicMatches, "not resolved") - c.Assert(rs[1].Cancel(), qt.IsTrue) - c.Assert(rs[2].Wait(context.Background()), qt.IsNil) + qt.Assert(t, qt.IsFalse(rs[0].Cancel())) + qt.Assert(t, qt.PanicMatches(func() { rs[1].Release() }, "not resolved")) + qt.Assert(t, qt.IsTrue(rs[1].Cancel())) + qt.Assert(t, qt.IsNil(rs[2].Wait(context.Background()))) rs[0].Release() - c.Assert(rs[3].Wait(context.Background()), qt.IsNil) - c.Assert(l.Value(), qt.Equals, int64(2)) + qt.Assert(t, qt.IsNil(rs[3].Wait(context.Background()))) + qt.Assert(t, qt.Equals(l.Value(), int64(2))) rs[1].Release() rs[2].Release() rs[3].Release() - c.Assert(l.Value(), qt.Equals, l.Max) + qt.Assert(t, qt.Equals(l.Value(), l.Max)) } func TestCancelWhileWaiting(t *testing.T) { - c := qt.New(t) l := &Limiter{Max: 10} rs := make([]*Reservation, 0) rs = append(rs, l.Reserve(6)) @@ -80,14 +77,14 @@ func TestCancelWhileWaiting(t *testing.T) { rs = append(rs, l.Reserve(4)) go rs[1].Cancel() err := rs[1].Wait(context.Background()) - c.Assert(err, qt.IsNotNil) + qt.Assert(t, qt.IsNotNil(err)) err = rs[2].Wait(context.Background()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) ctx, cancel := context.WithCancel(context.Background()) go cancel() err = rs[3].Wait(ctx) - c.Assert(err, qt.Equals, context.Canceled) + qt.Assert(t, qt.Equals(err, context.Canceled)) rs[0].Drop() err = rs[3].Wait(ctx) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) } diff --git a/internal/nestedmaps/nestedmaps_test.go b/internal/nestedmaps/nestedmaps_test.go index 97916afbbf..df45b3f7ef 100644 --- a/internal/nestedmaps/nestedmaps_test.go +++ b/internal/nestedmaps/nestedmaps_test.go @@ -4,38 +4,39 @@ import ( "testing" g "github.com/anacrolix/generics" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func TestNestedMaps(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) var nest map[string]map[*int]map[byte][]int64 intKey := g.PtrTo(420) var root = Begin(&nest) var first = Next(root, "answer") var second = Next(first, intKey) var last = Next(second, 69) - c.Assert(root.Exists(), qt.IsFalse) - c.Assert(first.Exists(), qt.IsFalse) - c.Assert(second.Exists(), qt.IsFalse) - c.Assert(last.Exists(), qt.IsFalse) + qt.Assert(t, qt.IsFalse(root.Exists())) + qt.Assert(t, qt.IsFalse(first.Exists())) + qt.Assert(t, qt.IsFalse(second.Exists())) + qt.Assert(t, qt.IsFalse(last.Exists())) last.Set([]int64{4, 8, 15, 16, 23, 42}) - c.Assert(root.Exists(), qt.IsTrue) - c.Assert(first.Exists(), qt.IsTrue) - c.Assert(second.Exists(), qt.IsTrue) - c.Assert(last.Exists(), qt.IsTrue) - c.Assert(Next(second, 70).Exists(), qt.IsFalse) + qt.Assert(t, qt.IsTrue(root.Exists())) + qt.Assert(t, qt.IsTrue(first.Exists())) + qt.Assert(t, qt.IsTrue(second.Exists())) + qt.Assert(t, qt.IsTrue(last.Exists())) + qt.Assert(t, qt.IsFalse(Next(second, 70).Exists())) secondIntKey := g.PtrTo(1337) secondPath := Next(Next(Next(Begin(&nest), "answer"), secondIntKey), 42) secondPath.Set(nil) - c.Assert(secondPath.Exists(), qt.IsTrue) + qt.Assert(t, qt.IsTrue(secondPath.Exists())) last.Delete() - c.Assert(last.Exists(), qt.IsFalse) - c.Assert(second.Exists(), qt.IsFalse) - c.Assert(root.Exists(), qt.IsTrue) - c.Assert(first.Exists(), qt.IsTrue) + qt.Assert(t, qt.IsFalse(last.Exists())) + qt.Assert(t, qt.IsFalse(second.Exists())) + qt.Assert(t, qt.IsTrue(root.Exists())) + qt.Assert(t, qt.IsTrue(first.Exists())) // See if we get panics deleting an already deleted item. last.Delete() secondPath.Delete() - c.Assert(root.Exists(), qt.IsFalse) + qt.Assert(t, qt.IsFalse(root.Exists())) } diff --git a/internal/qtnew/qtnew.go b/internal/qtnew/qtnew.go new file mode 100644 index 0000000000..ada3f563df --- /dev/null +++ b/internal/qtnew/qtnew.go @@ -0,0 +1,9 @@ +package qtnew + +import ( + "testing" +) + +func New(t *testing.T) *testing.T { + return t +} diff --git a/iplist/cidr_test.go b/iplist/cidr_test.go index ad904f52d2..08150203b6 100644 --- a/iplist/cidr_test.go +++ b/iplist/cidr_test.go @@ -5,18 +5,19 @@ import ( "net" "testing" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestIPNetLast(t *testing.T) { _, in, err := net.ParseCIDR("138.255.252.0/22") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, []byte{138, 255, 252, 0}, in.IP) assert.EqualValues(t, []byte{255, 255, 252, 0}, in.Mask) assert.EqualValues(t, []byte{138, 255, 255, 255}, IPNetLast(in)) _, in, err = net.ParseCIDR("2400:cb00::/31") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, []byte{0x24, 0, 0xcb, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, in.IP) assert.EqualValues(t, []byte{255, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, in.Mask) assert.EqualValues(t, []byte{0x24, 0, 0xcb, 1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, IPNetLast(in)) @@ -32,7 +33,7 @@ func TestParseCIDRList(t *testing.T) { 2a06:98c0::/29 `) rs, err := ParseCIDRListReader(r) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Len(t, rs, 7) assert.EqualValues(t, Range{ First: net.IP{0x28, 3, 0xf8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, diff --git a/iplist/iplist_test.go b/iplist/iplist_test.go index 4e36e0aef1..39b27a143a 100644 --- a/iplist/iplist_test.go +++ b/iplist/iplist_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -115,7 +116,7 @@ func testLookuperSimple(t *testing.T, iplist Ranger) { func TestSimple(t *testing.T) { ranges, err := sampleRanges(t) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Len(t, ranges, 5) iplist := New(ranges) testLookuperSimple(t, iplist) diff --git a/iplist/packed_test.go b/iplist/packed_test.go index abc9e29612..460fa94a73 100644 --- a/iplist/packed_test.go +++ b/iplist/packed_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" ) @@ -19,10 +20,10 @@ import ( func TestWritePacked(t *testing.T) { l, err := NewFromReader(strings.NewReader(sample)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) var buf bytes.Buffer err = l.WritePacked(&buf) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.Equal(t, "\x05\x00\x00\x00\x00\x00\x00\x00"+ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x01\x02\x04\x00"+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x01\x02\x04\xff"+"\x00\x00\x00\x00\x00\x00\x00\x00"+"\x01\x00\x00\x00"+ diff --git a/issue-949_test.go b/issue-949_test.go index 89b459294c..fbf68ea7e5 100644 --- a/issue-949_test.go +++ b/issue-949_test.go @@ -3,8 +3,9 @@ package torrent import ( "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" ) @@ -19,11 +20,11 @@ func TestIssue949LastPieceZeroPadding(t *testing.T) { panic(err) } lastPiece := info.Piece(info.NumPieces() - 1) - c := qt.New(t) - c.Assert(info.FilesArePieceAligned(), qt.IsTrue) + c := qtnew.New(t) + qt.Assert(t, qt.IsTrue(info.FilesArePieceAligned())) // Check the v1 piece length includes the trailing padding file. - c.Check(lastPiece.V1Length(), qt.Equals, info.PieceLength) + qt.Check(qt, qt.Equals(lastPiece.V1Length(), info.PieceLength)(c)) // The v2 piece should only include the file data, which fits inside the piece length for this // file. - c.Check(lastPiece.Length(), qt.Equals, int64(3677645)) + qt.Check(qt, qt.Equals(lastPiece.Length(), int64(3677645))(c)) } diff --git a/issue211_test.go b/issue211_test.go index a76be07a8a..adf80af09a 100644 --- a/issue211_test.go +++ b/issue211_test.go @@ -7,8 +7,8 @@ import ( "io" "testing" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/time/rate" "github.com/anacrolix/torrent/internal/testutil" @@ -21,7 +21,7 @@ func TestDropTorrentWithMmapStorageWhileHashing(t *testing.T) { // over the network as the test runs. cfg.DownloadRateLimiter = rate.NewLimiter(0, 0) cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() td, mi := testutil.GreetingTestTorrent() @@ -32,7 +32,7 @@ func TestDropTorrentWithMmapStorageWhileHashing(t *testing.T) { InfoHash: mi.HashInfoBytes(), InfoBytes: mi.InfoBytes, }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, new) r := tt.NewReader() diff --git a/issue97_test.go b/issue97_test.go index 9e14f047c0..cf5a16c38f 100644 --- a/issue97_test.go +++ b/issue97_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/anacrolix/log" - "github.com/stretchr/testify/require" + qt "github.com/go-quicktest/qt" "github.com/anacrolix/torrent/internal/testutil" "github.com/anacrolix/torrent/storage" @@ -23,8 +23,8 @@ func TestHashPieceAfterStorageClosed(t *testing.T) { tt.infoHash.Value[0] = 1 mi := testutil.GreetingMetaInfo() info, err := mi.UnmarshalInfo() - require.NoError(t, err) - require.NoError(t, tt.setInfo(&info)) - require.NoError(t, tt.storage.Close()) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsNil(tt.setInfo(&info))) + qt.Assert(t, qt.IsNil(tt.storage.Close())) tt.hashPiece(0) } diff --git a/ltep_test.go b/ltep_test.go index 37300f09cf..5fb7f219cd 100644 --- a/ltep_test.go +++ b/ltep_test.go @@ -6,9 +6,10 @@ import ( "testing" "github.com/anacrolix/sync" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" . "github.com/anacrolix/torrent" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" pp "github.com/anacrolix/torrent/peer_protocol" ) @@ -38,7 +39,7 @@ func countHandler( return } name, builtin, err := event.PeerConn.LocalLtepProtocolMap.LookupId(event.ExtensionNumber) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) // Not a user protocol. if builtin { return @@ -46,20 +47,20 @@ func countHandler( switch name { case answerToName: u64, err := strconv.ParseUint(string(event.Payload), 10, 0) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) i := uint(u64) c.Logf("%v got %d", handlerName, i) if i == doneValue { wg.Done() return } - c.Assert(i%2, qt.Equals, expectedMod2) + qt.Assert(t, qt.Equals(i%2, expectedMod2)) go func() { - c.Assert( + qt.Assert(t, qt.IsNil( event.PeerConn.WriteExtendedMessage( replyToName, - []byte(strconv.FormatUint(uint64(i+1), 10))), - qt.IsNil) + []byte(strconv.FormatUint(uint64(i+1), 10))))) + }() default: c.Fatalf("got unexpected extension name %q", name) @@ -68,7 +69,7 @@ func countHandler( } func TestUserLtep(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) var wg sync.WaitGroup makeCfg := func() *ClientConfig { @@ -85,9 +86,9 @@ func TestUserLtep(t *testing.T) { // separate goroutine. go func() { // Check sending an extended message for a protocol the peer doesn't support is an error. - c.Check(pc.WriteExtendedMessage("pm_me_floats", []byte("3.142")), qt.IsNotNil) + qt.Check(c, qt.IsNotNil(pc.WriteExtendedMessage("pm_me_floats", []byte("3.142")))) // Kick things off by sending a 1. - c.Check(pc.WriteExtendedMessage(testRepliesToOddsExtensionName, []byte("1")), qt.IsNil) + qt.Check(c, qt.IsNil(pc.WriteExtendedMessage(testRepliesToOddsExtensionName, []byte("1")))) }() } evensCfg.Callbacks.PeerConnReadExtensionMessage = append( @@ -95,23 +96,23 @@ func TestUserLtep(t *testing.T) { countHandler(c, &wg, "evens", 0, testRepliesToEvensExtensionName, testRepliesToOddsExtensionName, 100)) evensCfg.Callbacks.PeerConnAdded = append(evensCfg.Callbacks.PeerConnAdded, func(conn *PeerConn) { conn.LocalLtepProtocolMap.AddUserProtocol(testRepliesToEvensExtensionName) - c.Assert(conn.LocalLtepProtocolMap.Index[conn.LocalLtepProtocolMap.NumBuiltin:], qt.HasLen, 1) + qt.Assert(t, qt.HasLen(conn.LocalLtepProtocolMap.Index[conn.LocalLtepProtocolMap.NumBuiltin:], 1)) }) oddsCfg := makeCfg() oddsCfg.Callbacks.PeerConnAdded = append(oddsCfg.Callbacks.PeerConnAdded, func(conn *PeerConn) { conn.LocalLtepProtocolMap.AddUserProtocol(testRepliesToOddsExtensionName) - c.Assert(conn.LocalLtepProtocolMap.Index[conn.LocalLtepProtocolMap.NumBuiltin:], qt.HasLen, 1) + qt.Assert(t, qt.HasLen(conn.LocalLtepProtocolMap.Index[conn.LocalLtepProtocolMap.NumBuiltin:], 1)) }) oddsCfg.Callbacks.PeerConnReadExtensionMessage = append( oddsCfg.Callbacks.PeerConnReadExtensionMessage, countHandler(c, &wg, "odds", 1, testRepliesToOddsExtensionName, testRepliesToEvensExtensionName, 100)) cl1, err := NewClient(oddsCfg) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer cl1.Close() cl2, err := NewClient(evensCfg) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer cl2.Close() addOpts := AddTorrentOpts{} rand.Read(addOpts.InfoHash[:]) @@ -123,7 +124,7 @@ func TestUserLtep(t *testing.T) { wg.Add(1) added := t1.AddClientPeer(cl2) // Ensure some addresses for the other client were added. - c.Assert(added, qt.Not(qt.Equals), 0) + qt.Assert(t, qt.Not(qt.Equals)(added, 0)) wg.Wait() _ = t2 } diff --git a/metainfo/magnet-v2_test.go b/metainfo/magnet-v2_test.go index 620d385c66..bc75bb9ab9 100644 --- a/metainfo/magnet-v2_test.go +++ b/metainfo/magnet-v2_test.go @@ -3,36 +3,37 @@ package metainfo import ( "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func TestParseMagnetV2(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) const v2Only = "magnet:?xt=urn:btmh:1220caf1e1c30e81cb361b9ee167c4aa64228a7fa4fa9f6105232b28ad099f3a302e&dn=bittorrent-v2-test" m2, err := ParseMagnetV2Uri(v2Only) - c.Assert(err, qt.IsNil) - c.Check(m2.InfoHash.Ok, qt.IsFalse) - c.Check(m2.V2InfoHash.Ok, qt.IsTrue) - c.Check(m2.V2InfoHash.Value.HexString(), qt.Equals, "caf1e1c30e81cb361b9ee167c4aa64228a7fa4fa9f6105232b28ad099f3a302e") - c.Check(m2.Params, qt.HasLen, 0) + qt.Assert(t, qt.IsNil(err)) + qt.Check(c, qt.IsFalse(m2.InfoHash.Ok)) + qt.Check(c, qt.IsTrue(m2.V2InfoHash.Ok)) + qt.Check(qt, qt.Equals(m2.V2InfoHash.Value.HexString(), "caf1e1c30e81cb361b9ee167c4aa64228a7fa4fa9f6105232b28ad099f3a302e")(c)) + qt.Check(qt, qt.HasLen(m2.Params, 0)(c)) _, err = ParseMagnetUri(v2Only) - c.Check(err, qt.IsNotNil) + qt.Check(c, qt.IsNotNil(err)) const hybrid = "magnet:?xt=urn:btih:631a31dd0a46257d5078c0dee4e66e26f73e42ac&xt=urn:btmh:1220d8dd32ac93357c368556af3ac1d95c9d76bd0dff6fa9833ecdac3d53134efabb&dn=bittorrent-v1-v2-hybrid-test" m2, err = ParseMagnetV2Uri(hybrid) - c.Assert(err, qt.IsNil) - c.Check(m2.InfoHash.Ok, qt.IsTrue) - c.Check(m2.InfoHash.Value.HexString(), qt.Equals, "631a31dd0a46257d5078c0dee4e66e26f73e42ac") - c.Check(m2.V2InfoHash.Ok, qt.IsTrue) - c.Check(m2.V2InfoHash.Value.HexString(), qt.Equals, "d8dd32ac93357c368556af3ac1d95c9d76bd0dff6fa9833ecdac3d53134efabb") - c.Check(m2.Params, qt.HasLen, 0) + qt.Assert(t, qt.IsNil(err)) + qt.Check(c, qt.IsTrue(m2.InfoHash.Ok)) + qt.Check(qt, qt.Equals(m2.InfoHash.Value.HexString(), "631a31dd0a46257d5078c0dee4e66e26f73e42ac")(c)) + qt.Check(c, qt.IsTrue(m2.V2InfoHash.Ok)) + qt.Check(qt, qt.Equals(m2.V2InfoHash.Value.HexString(), "d8dd32ac93357c368556af3ac1d95c9d76bd0dff6fa9833ecdac3d53134efabb")(c)) + qt.Check(qt, qt.HasLen(m2.Params, 0)(c)) m, err := ParseMagnetUri(hybrid) - c.Assert(err, qt.IsNil) - c.Check(m.InfoHash.HexString(), qt.Equals, "631a31dd0a46257d5078c0dee4e66e26f73e42ac") - c.Check(m.Params["xt"], qt.HasLen, 1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(qt, qt.Equals(m.InfoHash.HexString(), "631a31dd0a46257d5078c0dee4e66e26f73e42ac")(c)) + qt.Check(qt, qt.HasLen(m.Params["xt"], 1)(c)) } diff --git a/metainfo/magnet_test.go b/metainfo/magnet_test.go index 2547509894..0a06529d38 100644 --- a/metainfo/magnet_test.go +++ b/metainfo/magnet_test.go @@ -4,10 +4,10 @@ import ( "encoding/hex" "testing" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/davecgh/go-spew/spew" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) var ( @@ -28,7 +28,7 @@ func init() { // Converting from our Magnet type to URL string. func TestMagnetString(t *testing.T) { m, err := ParseMagnetUri(exampleMagnet.String()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, exampleMagnet, m) } @@ -73,10 +73,10 @@ func TestParseMagnetURI(t *testing.T) { func TestMagnetize(t *testing.T) { mi, err := LoadFromFile("../testdata/bootstrap.dat.torrent") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) info, err := mi.UnmarshalInfo() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) m := mi.Magnet(nil, &info) assert.EqualValues(t, "bootstrap.dat", m.DisplayName) @@ -118,18 +118,18 @@ func contains(haystack []string, needle string) bool { // Check that we can parse the magnet link generated from a real-world torrent. This was added due // to a regression in copyParams. func TestParseSintelMagnet(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) mi, err := LoadFromFile("../testdata/sintel.torrent") - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) m := mi.Magnet(nil, nil) ms := m.String() t.Logf("magnet link: %q", ms) m, err = ParseMagnetUri(ms) - c.Check(err, qt.IsNil) + qt.Check(c, qt.IsNil(err)) spewCfg := spew.NewDefaultConfig() spewCfg.DisableMethods = true spewCfg.Dump(m) m2, err := ParseMagnetV2Uri(ms) spewCfg.Dump(m2) - c.Check(err, qt.IsNil) + qt.Check(c, qt.IsNil(err)) } diff --git a/metainfo/metainfo_test.go b/metainfo/metainfo_test.go index 6a97f91172..2ed644738c 100644 --- a/metainfo/metainfo_test.go +++ b/metainfo/metainfo_test.go @@ -10,18 +10,18 @@ import ( "github.com/anacrolix/missinggo/v2" "github.com/davecgh/go-spew/spew" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/bencode" + "github.com/anacrolix/torrent/internal/qtnew" ) func testFile(t *testing.T, filename string) { mi, err := LoadFromFile(filename) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) info, err := mi.UnmarshalInfo() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) if len(info.Files) == 1 { t.Logf("Single file: %s (length: %d)\n", info.BestName(), info.Files[0].Length) @@ -39,7 +39,7 @@ func testFile(t *testing.T, filename string) { } b, err := bencode.Marshal(&info) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, string(b), string(mi.InfoBytes)) } @@ -49,8 +49,8 @@ func TestFile(t *testing.T) { testFile(t, "testdata/23516C72685E8DB0C8F15553382A927F185C4F01.torrent") testFile(t, "testdata/trackerless.torrent") _, err := LoadFromFile("testdata/minimal-trailing-newline.torrent") - c := qt.New(t) - c.Check(err, qt.ErrorMatches, ".*expected EOF") + c := qtnew.New(t) + qt.Check(qt, qt.ErrorMatches(err, ".*expected EOF")(c)) } // Ensure that the correct number of pieces are generated when hashing files. @@ -89,12 +89,12 @@ func touchFile(path string) (err error) { func TestBuildFromFilePathOrder(t *testing.T) { td := t.TempDir() - require.NoError(t, touchFile(filepath.Join(td, "b"))) - require.NoError(t, touchFile(filepath.Join(td, "a"))) + qt.Assert(t, qt.IsNil(touchFile(filepath.Join(td, "b")))) + qt.Assert(t, qt.IsNil(touchFile(filepath.Join(td, "a")))) info := Info{ PieceLength: 1, } - require.NoError(t, info.BuildFromFilePath(td)) + qt.Assert(t, qt.IsNil(info.BuildFromFilePath(td))) assert.EqualValues(t, []FileInfo{{ Path: []string{"a"}, }, { @@ -122,7 +122,7 @@ func TestUnmarshal(t *testing.T) { func TestMetainfoWithListURLList(t *testing.T) { mi, err := LoadFromFile("testdata/SKODAOCTAVIA336x280_archive.torrent") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.Len(t, mi.UrlList, 3) qt.Assert(t, mi.Magnet(nil, nil).String(), qt.ContentEquals, strings.Join([]string{ @@ -137,7 +137,7 @@ func TestMetainfoWithListURLList(t *testing.T) { func TestMetainfoWithStringURLList(t *testing.T) { mi, err := LoadFromFile("testdata/flat-url-list.torrent") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.Len(t, mi.UrlList, 1) qt.Assert(t, mi.Magnet(nil, nil).String(), qt.ContentEquals, strings.Join([]string{ @@ -160,19 +160,19 @@ func TestStringCreationDate(t *testing.T) { // See https://github.com/anacrolix/torrent/issues/843. func TestUnmarshalEmptyStringNodes(t *testing.T) { var mi MetaInfo - c := qt.New(t) + c := qtnew.New(t) err := bencode.Unmarshal([]byte("d5:nodes0:e"), &mi) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) } func TestUnmarshalV2Metainfo(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) mi, err := LoadFromFile("../testdata/bittorrent-v2-test.torrent") - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) info, err := mi.UnmarshalInfo() - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) spew.Dump(info) - c.Check(info.NumPieces(), qt.Not(qt.Equals), 0) + qt.Check(qt, qt.Not(qt.Equals)(info.NumPieces(), 0)(c)) err = ValidatePieceLayers(mi.PieceLayers, &info.FileTree, info.PieceLength) - c.Check(err, qt.IsNil) + qt.Check(c, qt.IsNil(err)) } diff --git a/metainfo/nodes_test.go b/metainfo/nodes_test.go index adebbb3670..8822e2600f 100644 --- a/metainfo/nodes_test.go +++ b/metainfo/nodes_test.go @@ -4,6 +4,7 @@ import ( "bytes" "testing" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -12,7 +13,7 @@ import ( func testFileNodesMatch(t *testing.T, file string, nodes []Node) { mi, err := LoadFromFile(file) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, nodes, mi.Nodes) } @@ -65,10 +66,11 @@ func TestUnmarshalBadMetainfoNodes(t *testing.T) { func TestMetainfoEmptyInfoBytes(t *testing.T) { var buf bytes.Buffer - require.NoError(t, (&MetaInfo{ - // Include a non-empty field that comes after "info". + qt.Assert(t, qt.IsNil((&MetaInfo{ + UrlList: []string{"hello"}, - }).Write(&buf)) + }).Write(&buf))) + var mi MetaInfo - require.NoError(t, bencode.Unmarshal(buf.Bytes(), &mi)) + qt.Assert(t, qt.IsNil(bencode.Unmarshal(buf.Bytes(), &mi))) } diff --git a/mse/mse_test.go b/mse/mse_test.go index d97323f1c8..03f43865ce 100644 --- a/mse/mse_test.go +++ b/mse/mse_test.go @@ -11,6 +11,7 @@ import ( "testing" _ "github.com/anacrolix/envpprof" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -65,7 +66,7 @@ func handshakeTest(t testing.TB, ia []byte, aData, bData string, cryptoProvides go func() { defer wg.Done() a, cm, err := InitiateHandshake(a, []byte("yep"), ia, cryptoProvides) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.Equal(t, cryptoSelect(cryptoProvides), cm) go a.Write([]byte(aData)) @@ -84,7 +85,7 @@ func handshakeTest(t testing.TB, ia []byte, aData, bData string, cryptoProvides sliceIter([][]byte{[]byte("nope"), []byte("yep"), []byte("maybe")}), cryptoSelect, ) - require.NoError(t, res.error) + qt.Assert(t, qt.IsNil(res.error)) assert.EqualValues(t, "yep", res.SecretKey) b := res.ReadWriter assert.Equal(t, cryptoSelect(cryptoProvides), res.CryptoMethod) @@ -147,7 +148,7 @@ func TestReceiveRandomData(t *testing.T) { func fillRand(t testing.TB, bs ...[]byte) { for _, b := range bs { _, err := rand.Read(b) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) } } @@ -186,8 +187,8 @@ func benchmarkStream(t *testing.B, crypto CryptoMethod) { defer ac.Close() defer wg.Done() rw, _, err := InitiateHandshake(ac, []byte("cats"), ia, crypto) - require.NoError(t, err) - require.NoError(t, readAndWrite(rw, ar, a)) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsNil(readAndWrite(rw, ar, a))) }() func() { defer bc.Close() @@ -197,8 +198,8 @@ func benchmarkStream(t *testing.B, crypto CryptoMethod) { sliceIter([][]byte{[]byte("cats")}), func(CryptoMethod) CryptoMethod { return crypto }, ) - require.NoError(t, err) - require.NoError(t, readAndWrite(rw, br, b)) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsNil(readAndWrite(rw, br, b))) }() wg.Wait() t.StopTimer() @@ -231,13 +232,13 @@ func BenchmarkPipeRC4(t *testing.B) { require.Equal(t, len(key), n) var buf bytes.Buffer c, err := rc4.NewCipher(key) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) r := cipherReader{ c: c, r: &buf, } c, err = rc4.NewCipher(key) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) w := cipherWriter{ c: c, w: &buf, diff --git a/network_test.go b/network_test.go index 691d6725b8..4c0ba746cd 100644 --- a/network_test.go +++ b/network_test.go @@ -6,8 +6,8 @@ import ( "github.com/anacrolix/log" "github.com/anacrolix/missinggo/v2" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func testListenerNetwork( @@ -19,7 +19,7 @@ func testListenerNetwork( if isUnsupportedNetworkError(err) { return } - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer l.Close() assert.EqualValues(t, expectedNet, l.Addr().Network()) ip := missinggo.AddrIP(l.Addr()) @@ -38,18 +38,18 @@ func testAcceptedConnAddr( listen func() (net.Listener, error), ) { l, err := listen() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer l.Close() done := make(chan struct{}) defer close(done) go func() { c, err := dial(l.Addr().String()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) <-done c.Close() }() c, err := l.Accept() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer c.Close() assert.EqualValues(t, network, c.RemoteAddr().Network()) assert.Equal(t, valid4, missinggo.AddrIP(c.RemoteAddr()).To4() == nil) diff --git a/ordered-bitmap.go b/ordered-bitmap.go index 2163a37574..73b4466ccd 100644 --- a/ordered-bitmap.go +++ b/ordered-bitmap.go @@ -4,9 +4,8 @@ import ( "iter" g "github.com/anacrolix/generics" + typedRoaring "github.com/anacrolix/torrent/typed-roaring" list "github.com/bahlo/generic-list-go" - - "github.com/anacrolix/torrent/typed-roaring" ) type orderedBitmap[T typedRoaring.BitConstraint] struct { diff --git a/peer_protocol/decoder_test.go b/peer_protocol/decoder_test.go index 39b54c1c84..5240c28db4 100644 --- a/peer_protocol/decoder_test.go +++ b/peer_protocol/decoder_test.go @@ -7,7 +7,8 @@ import ( "sync" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -35,7 +36,7 @@ func BenchmarkDecodePieces(t *testing.B) { }, }, } - c := qt.New(t) + c := qtnew.New(t) t.ReportAllocs() t.ResetTimer() for i := 0; i < t.N; i += 1 { @@ -47,7 +48,7 @@ func BenchmarkDecodePieces(t *testing.B) { } // This is very expensive, and should be discovered in tests rather than a benchmark. if false { - c.Assert(msg, qt.DeepEquals, inputMsg) + qt.Assert(t, qt.DeepEquals(msg, inputMsg)) } // WWJD d.Pool.Put(&msg.Piece) @@ -69,7 +70,7 @@ func TestDecodeShortPieceEOF(t *testing.T) { }}, } var m Message - require.NoError(t, d.Decode(&m)) + qt.Assert(t, qt.IsNil(d.Decode(&m))) assert.Len(t, m.Piece, 1) assert.ErrorIs(t, d.Decode(&m), io.EOF) } diff --git a/peer_protocol/fuzz_test.go b/peer_protocol/fuzz_test.go index 8ffdfd7b47..43a3d55152 100644 --- a/peer_protocol/fuzz_test.go +++ b/peer_protocol/fuzz_test.go @@ -9,7 +9,8 @@ import ( "io" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func FuzzDecoder(f *testing.F) { @@ -19,7 +20,7 @@ func FuzzDecoder(f *testing.F) { f.Add([]byte("\x00\x00\x00\x01\x07")) f.Fuzz(func(t *testing.T, b []byte) { t.Logf("%q", b) - c := qt.New(t) + c := qtnew.New(t) d := Decoder{ R: bufio.NewReader(bytes.NewReader(b)), MaxLength: 0x100, @@ -33,7 +34,7 @@ func FuzzDecoder(f *testing.F) { break } if err == nil { - c.Assert(m, qt.Not(qt.Equals), Message{}) + qt.Assert(t, qt.Not(qt.Equals)(m, Message{})) ms = append(ms, m) continue } else { @@ -46,9 +47,9 @@ func FuzzDecoder(f *testing.F) { buf.Write(m.MustMarshalBinary()) } if len(b) == 0 { - c.Assert(buf.Bytes(), qt.HasLen, 0) + qt.Assert(t, qt.HasLen(buf.Bytes(), 0)) } else { - c.Assert(buf.Bytes(), qt.DeepEquals, b) + qt.Assert(t, qt.DeepEquals(buf.Bytes(), b)) } }) } diff --git a/peer_protocol/pex_test.go b/peer_protocol/pex_test.go index 5e5e96c14a..56dd6e3af1 100644 --- a/peer_protocol/pex_test.go +++ b/peer_protocol/pex_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/anacrolix/dht/v2/krpc" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/bencode" @@ -15,7 +16,7 @@ import ( func TestUnmarshalPex(t *testing.T) { var pem PexMsg err := bencode.Unmarshal([]byte("d5:added12:\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0ce"), &pem) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, 2, len(pem.Added)) require.EqualValues(t, 1286, pem.Added[0].Port) require.EqualValues(t, 0x100*0xb+0xc, pem.Added[1].Port) @@ -25,8 +26,8 @@ func TestEmptyPexMsg(t *testing.T) { pm := PexMsg{} b, err := bencode.Marshal(pm) t.Logf("%q", b) - require.NoError(t, err) - require.NoError(t, bencode.Unmarshal(b, &pm)) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.IsNil(bencode.Unmarshal(b, &pm))) } func TestMarshalPexMessage(t *testing.T) { @@ -37,13 +38,13 @@ func TestMarshalPexMessage(t *testing.T) { pm.AddedFlags = append(pm.AddedFlags, f) _, err := bencode.Marshal(pm) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) pexExtendedId := ExtensionNumber(7) msg := pm.Message(pexExtendedId) expected := []byte("\x00\x00\x00\x4c\x14\x07d5:added6:\x7f\x00\x00\x01\x55\xaa7:added.f1:\x116:added60:8:added6.f0:7:dropped0:8:dropped60:e") b, err := msg.MarshalBinary() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, b, expected) msg = Message{} @@ -53,11 +54,11 @@ func TestMarshalPexMessage(t *testing.T) { } pmOut := PexMsg{} err = dec.Decode(&msg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, Extended, msg.Type) require.EqualValues(t, pexExtendedId, msg.ExtendedID) err = bencode.Unmarshal(msg.ExtendedPayload, &pmOut) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, len(pm.Added), len(pmOut.Added)) require.EqualValues(t, pm.Added[0].IP, pmOut.Added[0].IP) require.EqualValues(t, pm.Added[0].Port, pmOut.Added[0].Port) diff --git a/peer_protocol/reserved_test.go b/peer_protocol/reserved_test.go index 53f9d86d92..95d28c08f3 100644 --- a/peer_protocol/reserved_test.go +++ b/peer_protocol/reserved_test.go @@ -3,12 +3,13 @@ package peer_protocol import ( "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func TestV2BitLocation(t *testing.T) { var bits PeerExtensionBits bits.SetBit(ExtensionBitV2Upgrade, true) - c := qt.New(t) - c.Assert(bits[7], qt.Equals, byte(0x10)) + c := qtnew.New(t) + qt.Assert(t, qt.Equals(bits[7], byte(0x10))) } diff --git a/peer_protocol/ut-holepunch/ut-holepunch_test.go b/peer_protocol/ut-holepunch/ut-holepunch_test.go index 7221e1f70f..5996986920 100644 --- a/peer_protocol/ut-holepunch/ut-holepunch_test.go +++ b/peer_protocol/ut-holepunch/ut-holepunch_test.go @@ -5,7 +5,8 @@ import ( "net/netip" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) var exampleMsgs = []Msg{ @@ -22,19 +23,19 @@ var exampleMsgs = []Msg{ } func TestUnmarshalMsg(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) for _, m := range exampleMsgs { b, err := m.MarshalBinary() - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) expectedLen := 24 if m.AddrPort.Addr().Is4() { expectedLen = 12 } - c.Check(b, qt.HasLen, expectedLen) + qt.Check(qt, qt.HasLen(b, expectedLen)(c)) var um Msg err = um.UnmarshalBinary(b) - c.Assert(err, qt.IsNil) - c.Check(um, qt.Equals, m) + qt.Assert(t, qt.IsNil(err)) + qt.Check(qt, qt.Equals(um, m)(c)) } } diff --git a/peerconn_test.go b/peerconn_test.go index 7dc28bd1ac..d2556697a6 100644 --- a/peerconn_test.go +++ b/peerconn_test.go @@ -12,10 +12,12 @@ import ( g "github.com/anacrolix/generics" "github.com/frankban/quicktest" - qt "github.com/frankban/quicktest" + "github.com/go-quicktest/qt" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" "golang.org/x/time/rate" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" pp "github.com/anacrolix/torrent/peer_protocol" "github.com/anacrolix/torrent/storage" @@ -27,11 +29,11 @@ func TestSendBitfieldThenHave(t *testing.T) { var cl Client cl.init(TestingConfig(t)) cl.initLogger() - qtc := qt.New(t) + qtc := qtnew.New(t) c := cl.newConnection(nil, newConnectionOpts{network: "io.Pipe"}) c.setTorrent(cl.newTorrentForTesting()) err := c.t.setInfo(&metainfo.Info{Pieces: make([]byte, metainfo.HashSize*3)}) - qtc.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) r, w := io.Pipe() // c.r = r c.w = w @@ -49,7 +51,7 @@ func TestSendBitfieldThenHave(t *testing.T) { // This will cause connection.writer to terminate. c.closed.Set() c.locker().Unlock() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, 15, n) // Here we see that the bitfield doesn't have piece 2 set, as that should // arrive in the following Have message. @@ -100,11 +102,12 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { ts := &torrentStorage{} t := cl.newTorrentForTesting() t.initialPieceCheckDisabled = true - require.NoError(b, t.setInfo(&metainfo.Info{ + qt.Assert(t, qt.IsNil(t.setInfo(&metainfo.Info{ Pieces: make([]byte, 20), Length: 1 << 20, PieceLength: 1 << 20, - })) + }))(b)) + t.storage = &storage.Torrent{TorrentImpl: storage.TorrentImpl{Piece: ts.Piece, Close: ts.Close}} t.onSetInfo() t._pendingPieces.Add(0) @@ -117,7 +120,7 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { network: r.RemoteAddr().Network(), connString: regularNetConnPeerConnConnString(r), }) - c.Assert(cn.bannableAddr.Ok, qt.IsTrue) + qt.Assert(t, qt.IsTrue(cn.bannableAddr.Ok)) cn.setTorrent(t) requestIndexBegin := t.pieceRequestIndexOffset(0) requestIndexEnd := t.pieceRequestIndexOffset(1) @@ -166,7 +169,7 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { ts.allChunksWritten.Add(int(numRequests)) for _, wb := range msgBufs { n, err := w.Write(wb) - require.NoError(b, err) + qt.Assert(t, qt.IsNil(err)(b)) require.EqualValues(b, len(wb), n) } // This is unlocked by a successful write to storage. So this unblocks when that is @@ -187,9 +190,9 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { break } } - c.Assert(err, qt.IsNil) - c.Assert(cn._stats.ChunksReadUseful.Int64(), quicktest.Equals, int64(b.N)*int64(numRequests)) - c.Assert(t.smartBanCache.HasBlocks(), qt.IsTrue) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, quicktest.Equals(cn._stats.ChunksReadUseful.Int64(), int64(b.N)*int64(numRequests))) + qt.Assert(t, qt.IsTrue(t.smartBanCache.HasBlocks())) } func TestConnPexPeerFlags(t *testing.T) { @@ -217,7 +220,7 @@ func TestConnPexPeerFlags(t *testing.T) { } func TestConnPexEvent(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) var ( udpAddr = &net.UDPAddr{IP: net.IPv6loopback, Port: 4848} tcpAddr = &net.TCPAddr{IP: net.IPv6loopback, Port: 4848} @@ -262,14 +265,14 @@ func TestConnPexEvent(t *testing.T) { for i, tc := range testcases { c.Run(fmt.Sprintf("%v", i), func(c *qt.C) { e, err := tc.c.pexEvent(tc.t) - c.Assert(err, qt.IsNil) - c.Check(e, qt.Equals, tc.e) + qt.Assert(t, qt.IsNil(err)) + qt.Check(qt, qt.Equals(e, tc.e)(c)) }) } } func TestHaveAllThenBitfield(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) cl := newTestingClient(t) tt := cl.newTorrentForTesting() // cl.newConnection() @@ -279,29 +282,30 @@ func TestHaveAllThenBitfield(t *testing.T) { pc.initRequestState() pc.peerImpl = &pc tt.conns[&pc] = struct{}{} - c.Assert(pc.onPeerSentHaveAll(), qt.IsNil) - c.Check(pc.t.connsWithAllPieces, qt.DeepEquals, map[*Peer]struct{}{&pc.Peer: {}}) + qt.Assert(t, qt.IsNil(pc.onPeerSentHaveAll())) + qt.Check(qt, qt.DeepEquals(pc.t.connsWithAllPieces, map[*Peer]struct{}{&pc.Peer: {}})(c)) pc.peerSentBitfield([]bool{false, false, true, false, true, true, false, false}) - c.Check(pc.peerMinPieces, qt.Equals, 6) - c.Check(pc.t.connsWithAllPieces, qt.HasLen, 0) - c.Assert(pc.t.setInfo(&metainfo.Info{ + qt.Check(qt, qt.Equals(pc.peerMinPieces, 6)(c)) + qt.Check(qt, qt.HasLen(pc.t.connsWithAllPieces, 0)(c)) + qt.Assert(t, qt.IsNil(pc.t.setInfo(&metainfo.Info{ PieceLength: 0, Pieces: make([]byte, pieceHash.Size()*7), - }), qt.IsNil) + }))) + pc.t.onSetInfo() - c.Check(tt.numPieces(), qt.Equals, 7) - c.Check(tt.pieceAvailabilityRuns(), qt.DeepEquals, []pieceAvailabilityRun{ - // The last element of the bitfield is irrelevant, as the Torrent actually only has 7 - // pieces. + qt.Check(qt, qt.Equals(tt.numPieces(), 7)(c)) + qt.Check(qt, qt.DeepEquals(tt.pieceAvailabilityRuns(), []pieceAvailabilityRun{ + {2, 0}, {1, 1}, {1, 0}, {2, 1}, {1, 0}, - }) + })(c)) + } func TestApplyRequestStateWriteBufferConstraints(t *testing.T) { - c := qt.New(t) - c.Check(interestedMsgLen, qt.Equals, 5) - c.Check(requestMsgLen, qt.Equals, 17) - c.Check(maxLocalToRemoteRequests >= 8, qt.IsTrue) + c := qtnew.New(t) + qt.Check(qt, qt.Equals(interestedMsgLen, 5)(c)) + qt.Check(qt, qt.Equals(requestMsgLen, 17)(c)) + qt.Check(c, qt.IsTrue(maxLocalToRemoteRequests >= 8)) c.Logf("max local to remote requests: %v", maxLocalToRemoteRequests) } @@ -328,42 +332,35 @@ func peerConnForPreferredNetworkDirection( func TestPreferredNetworkDirection(t *testing.T) { pc := peerConnForPreferredNetworkDirection - c := qt.New(t) + c := qtnew.New(t) // Prefer outgoing to lower peer ID - c.Check( - pc(1, 2, true, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)), - qt.IsFalse, - ) - c.Check( - pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, true, false, false)), - qt.IsTrue, - ) - c.Check( - pc(2, 1, false, false, false).hasPreferredNetworkOver(pc(2, 1, true, false, false)), - qt.IsFalse, - ) + qt.Check(c, qt.IsFalse( + pc(1, 2, true, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)))) + + qt.Check(c, qt.IsTrue( + pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, true, false, false)))) + + qt.Check(c, qt.IsFalse( + pc(2, 1, false, false, false).hasPreferredNetworkOver(pc(2, 1, true, false, false)))) // Don't prefer uTP - c.Check( - pc(1, 2, false, true, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)), - qt.IsFalse, - ) + qt.Check(c, qt.IsFalse( + pc(1, 2, false, true, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)))) + // Prefer IPv6 - c.Check( - pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, true)), - qt.IsFalse, - ) + qt.Check(c, qt.IsFalse( + pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, true)))) + // No difference - c.Check( - pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)), - qt.IsFalse, - ) + qt.Check(c, qt.IsFalse( + pc(1, 2, false, false, false).hasPreferredNetworkOver(pc(1, 2, false, false, false)))) + } func TestReceiveLargeRequest(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) cl := newTestingClient(t) pc := cl.newConnection(nil, newConnectionOpts{network: "test"}) tor := cl.newTorrentForTesting() @@ -375,26 +372,26 @@ func TestReceiveLargeRequest(t *testing.T) { pc.initMessageWriter() req := Request{} req.Length = defaultChunkSize - c.Assert(pc.fastEnabled(), qt.IsTrue) - c.Check(pc.onReadRequest(req, false), qt.IsNil) - c.Check(pc.peerRequests, qt.HasLen, 1) + qt.Assert(t, qt.IsTrue(pc.fastEnabled())) + qt.Check(c, qt.IsNil(pc.onReadRequest(req, false))) + qt.Check(qt, qt.HasLen(pc.peerRequests, 1)(c)) req.Length = 2 << 20 - c.Check(pc.onReadRequest(req, false), qt.IsNil) - c.Check(pc.peerRequests, qt.HasLen, 2) + qt.Check(c, qt.IsNil(pc.onReadRequest(req, false))) + qt.Check(qt, qt.HasLen(pc.peerRequests, 2)(c)) pc.peerRequests = nil pc.t.cl.config.UploadRateLimiter = rate.NewLimiter(1, defaultChunkSize) req.Length = defaultChunkSize - c.Check(pc.onReadRequest(req, false), qt.IsNil) - c.Check(pc.peerRequests, qt.HasLen, 1) + qt.Check(c, qt.IsNil(pc.onReadRequest(req, false))) + qt.Check(qt, qt.HasLen(pc.peerRequests, 1)(c)) req.Length = 2 << 20 - c.Check(pc.onReadRequest(req, false), qt.IsNil) - c.Check(pc.messageWriter.writeBuffer.Len(), qt.Equals, 17) + qt.Check(c, qt.IsNil(pc.onReadRequest(req, false))) + qt.Check(qt, qt.Equals(pc.messageWriter.writeBuffer.Len(), 17)(c)) } func TestChunkOverflowsPiece(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) check := func(begin, length, limit pp.Integer, expected bool) { - c.Check(chunkOverflowsPiece(ChunkSpec{begin, length}, limit), qt.Equals, expected) + qt.Check(qt, qt.Equals(chunkOverflowsPiece(ChunkSpec{begin, length}, limit), expected)(c)) } check(2, 3, 1, true) check(2, pp.IntegerMax, 1, true) diff --git a/pexconn_test.go b/pexconn_test.go index 02da7d0a1b..312335d68e 100644 --- a/pexconn_test.go +++ b/pexconn_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/anacrolix/dht/v2/krpc" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" pp "github.com/anacrolix/torrent/peer_protocol" @@ -48,7 +49,7 @@ func TestPexConnState(t *testing.T) { require.EqualValues(t, c.PeerExtensionIDs[pp.ExtensionNamePex], out.ExtendedID) x, err := pp.LoadPexMsg(out.ExtendedPayload) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) targx := pp.PexMsg{ Added: krpc.CompactIPv4NodeAddrs(nil), AddedFlags: []pp.PexPeerFlags{}, diff --git a/reader_test.go b/reader_test.go index c1017a0cb8..5a8927cca2 100644 --- a/reader_test.go +++ b/reader_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/internal/testutil" @@ -12,10 +13,10 @@ import ( func TestReaderReadContext(t *testing.T) { cl, err := NewClient(TestingConfig(t)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() tt, err := cl.AddTorrent(testutil.GreetingMetaInfo()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer tt.Drop() ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Millisecond)) defer cancel() diff --git a/request-strategy-impls_test.go b/request-strategy-impls_test.go index aab3b34ef2..c178b2ad35 100644 --- a/request-strategy-impls_test.go +++ b/request-strategy-impls_test.go @@ -9,8 +9,9 @@ import ( g "github.com/anacrolix/generics" "github.com/anacrolix/missinggo/v2/iter" "github.com/davecgh/go-spew/spew" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" request_strategy "github.com/anacrolix/torrent/request-strategy" "github.com/anacrolix/torrent/storage" @@ -22,14 +23,14 @@ func makeRequestStrategyPiece(t request_strategy.Torrent) request_strategy.Piece } func TestRequestStrategyPieceDoesntAlloc(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) akshalTorrent := &Torrent{pieces: make([]Piece, 1)} rst := requestStrategyTorrent{akshalTorrent} var before, after runtime.MemStats runtime.ReadMemStats(&before) p := makeRequestStrategyPiece(rst) runtime.ReadMemStats(&after) - c.Assert(before.HeapAlloc, qt.Equals, after.HeapAlloc) + qt.Assert(t, qt.Equals(before.HeapAlloc, after.HeapAlloc)) // We have to use p, or it gets optimized away. spew.Fdump(io.Discard, p) } @@ -81,7 +82,7 @@ func (s *storageClient) OpenTorrent( } func BenchmarkRequestStrategy(b *testing.B) { - c := qt.New(b) + c := qtnew.New(b) cl := newTestingClient(b) storageClient := storageClient{} tor, new := cl.AddTorrentOpt(AddTorrentOpts{ @@ -89,7 +90,7 @@ func BenchmarkRequestStrategy(b *testing.B) { Storage: &storageClient, }) tor.disableTriggers = true - c.Assert(new, qt.IsTrue) + qt.Assert(t, qt.IsTrue(new)) const pieceLength = 1 << 8 << 10 const numPieces = 30_000 err := tor.setInfo(&metainfo.Info{ @@ -97,13 +98,13 @@ func BenchmarkRequestStrategy(b *testing.B) { PieceLength: pieceLength, Length: pieceLength * numPieces, }) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) tor.onSetInfo() peer := cl.newConnection(nil, newConnectionOpts{ network: "test", }) peer.setTorrent(tor) - c.Assert(tor.storage, qt.IsNotNil) + qt.Assert(t, qt.IsNotNil(tor.storage)) const chunkSize = defaultChunkSize peer.onPeerHasAllPiecesNoTriggers() for i := 0; i < tor.numPieces(); i++ { @@ -129,9 +130,10 @@ func BenchmarkRequestStrategy(b *testing.B) { tor.cacheNextRequestIndexesForReuse(rs.Requests.requestIndexes) // End of part that should be timed. remainingChunks := (numPieces - completed) * (pieceLength / chunkSize) - c.Assert(rs.Requests.requestIndexes, qt.HasLen, minInt( + qt.Assert(t, qt.HasLen(rs.Requests.requestIndexes, minInt( remainingChunks, - int(cl.config.MaxUnverifiedBytes/chunkSize))) + int(cl.config.MaxUnverifiedBytes/chunkSize)))) + } } } diff --git a/requesting_test.go b/requesting_test.go index 6c791a58c0..12c0eaf195 100644 --- a/requesting_test.go +++ b/requesting_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/bradfitz/iter" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" pp "github.com/anacrolix/torrent/peer_protocol" ) diff --git a/reuse_test.go b/reuse_test.go index 5da4ab8096..1235a21854 100644 --- a/reuse_test.go +++ b/reuse_test.go @@ -8,14 +8,15 @@ import ( "testing" "github.com/anacrolix/log" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) // Show that multiple connections from the same local TCP port to the same remote port will fail. func TestTcpPortReuseIsABadIdea(t *testing.T) { remote, err := net.Listen("tcp", "localhost:0") - c := qt.New(t) - c.Assert(err, qt.IsNil) + c := qtnew.New(t) + qt.Assert(t, qt.IsNil(err)) defer remote.Close() dialer := net.Dialer{} // Show that we can't duplicate an existing connection even with various socket options. @@ -26,16 +27,16 @@ func TestTcpPortReuseIsABadIdea(t *testing.T) { } // Tie up a local port to the remote. first, err := dialer.Dial("tcp", remote.Addr().String()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer first.Close() // Show that dialling the remote with the same local port fails. dialer.LocalAddr = first.LocalAddr() _, err = dialer.Dial("tcp", remote.Addr().String()) - c.Assert(err, qt.IsNotNil) + qt.Assert(t, qt.IsNotNil(err)) // Show that not fixing the local port again allows connections to succeed. dialer.LocalAddr = nil second, err := dialer.Dial("tcp", remote.Addr().String()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) second.Close() } @@ -43,9 +44,9 @@ func TestTcpPortReuseIsABadIdea(t *testing.T) { // succeed. This is necessary for ut_holepunch to work. func TestUtpLocalPortIsReusable(t *testing.T) { const network = "udp" - c := qt.New(t) + c := qtnew.New(t) remote, err := NewUtpSocket(network, "localhost:0", nil, log.Default) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer remote.Close() var remoteAccepts int32 doneAccepting := make(chan struct{}) @@ -65,15 +66,15 @@ func TestUtpLocalPortIsReusable(t *testing.T) { } }() local, err := NewUtpSocket(network, "localhost:0", nil, log.Default) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer local.Close() first, err := local.DialContext(context.Background(), network, remote.Addr().String()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer first.Close() second, err := local.DialContext(context.Background(), network, remote.Addr().String()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer second.Close() remote.Close() <-doneAccepting - c.Assert(atomic.LoadInt32(&remoteAccepts), qt.Equals, int32(2)) + qt.Assert(t, qt.Equals(atomic.LoadInt32(&remoteAccepts), int32(2))) } diff --git a/roaring.go b/roaring.go index 8e39416cd7..f8e622b116 100644 --- a/roaring.go +++ b/roaring.go @@ -1,8 +1,6 @@ package torrent -import ( - "github.com/anacrolix/torrent/typed-roaring" -) +import typedRoaring "github.com/anacrolix/torrent/typed-roaring" // Return the number of bits set in the range. To do this we need the rank of the item before the // first, and the rank of the last item. An off-by-one minefield. Hopefully I haven't missed diff --git a/segments/segments_test.go b/segments/segments_test.go index ef165714f2..205e8e6732 100644 --- a/segments/segments_test.go +++ b/segments/segments_test.go @@ -3,7 +3,7 @@ package segments import ( "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" ) func LengthIterFromSlice(ls []Length) LengthIter { @@ -50,7 +50,7 @@ func assertLocate( expected.scanCallback(firstExpectedIndex+i, e) } nl(LengthIterFromSlice(ls))(needle, actual.scanCallback) - qt.Check(t, actual, qt.DeepEquals, expected) + qt.Check(qt, qt.DeepEquals(actual, expected)(t)) } func testLocater(t *testing.T, newLocater newLocater) { diff --git a/storage/bolt-piece-completion_test.go b/storage/bolt-piece-completion_test.go index 3a778a86a9..f105fadcff 100644 --- a/storage/bolt-piece-completion_test.go +++ b/storage/bolt-piece-completion_test.go @@ -3,8 +3,8 @@ package storage import ( "testing" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/metainfo" ) @@ -13,24 +13,24 @@ func TestBoltPieceCompletion(t *testing.T) { td := t.TempDir() pc, err := NewBoltPieceCompletion(td) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer pc.Close() pk := metainfo.PieceKey{} b, err := pc.Get(pk) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.False(t, b.Ok) - require.NoError(t, pc.Set(pk, false)) + qt.Assert(t, qt.IsNil(pc.Set(pk, false))) b, err = pc.Get(pk) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.Equal(t, Completion{Complete: false, Ok: true}, b) - require.NoError(t, pc.Set(pk, true)) + qt.Assert(t, qt.IsNil(pc.Set(pk, true))) b, err = pc.Get(pk) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.Equal(t, Completion{Complete: true, Ok: true}, b) } diff --git a/storage/file-misc_test.go b/storage/file-misc_test.go index 706fc2103b..246058f02c 100644 --- a/storage/file-misc_test.go +++ b/storage/file-misc_test.go @@ -3,10 +3,11 @@ package storage import ( "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/anacrolix/torrent/common" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/segments" ) @@ -49,9 +50,9 @@ func TestExtentCompleteRequiredLengthsV2InfoWithGaps(t *testing.T) { }, }, } - c := qt.New(t) + c := qtnew.New(t) check := func(off, n int64, expected ...requiredLength) { - c.Check(extentCompleteRequiredLengths(info, off, n), qt.DeepEquals, expected) + qt.Check(qt, qt.DeepEquals(extentCompleteRequiredLengths(info, off, n), expected)(c)) } check(0, 0) check(0, 1, requiredLength{FileIndex: 0, Length: 1}) @@ -72,9 +73,9 @@ func TestExtentCompleteRequiredLengths(t *testing.T) { {Path: []string{"b"}, Length: 3}, }, } - c := qt.New(t) + c := qtnew.New(t) check := func(off, n int64, expected ...requiredLength) { - c.Check(extentCompleteRequiredLengths(info, off, n), qt.DeepEquals, expected) + qt.Check(qt, qt.DeepEquals(extentCompleteRequiredLengths(info, off, n), expected)(c)) } assert.Empty(t, extentCompleteRequiredLengths(info, 0, 0)) assert.EqualValues(t, []requiredLength{ diff --git a/storage/file_test.go b/storage/file_test.go index 103e828877..8f9f92a26b 100644 --- a/storage/file_test.go +++ b/storage/file_test.go @@ -9,8 +9,8 @@ import ( "testing" "github.com/anacrolix/missinggo/v2" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/metainfo" ) @@ -28,9 +28,9 @@ func TestShortFile(t *testing.T) { ts, err := s.OpenTorrent(context.Background(), info, metainfo.Hash{}) assert.NoError(t, err) f, err := os.Create(filepath.Join(td, "a")) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) err = f.Truncate(1) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) f.Close() var buf bytes.Buffer p := info.Piece(0) diff --git a/storage/issue95_test.go b/storage/issue95_test.go index 2beb416164..7f63d85421 100644 --- a/storage/issue95_test.go +++ b/storage/issue95_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/anacrolix/missinggo/v2/resource" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/metainfo" ) @@ -21,10 +21,10 @@ func testIssue95(t *testing.T, ci ClientImpl) { } c := NewClient(ci) t1, err := c.OpenTorrent(context.Background(), &info, metainfo.HashBytes([]byte("a"))) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer t1.Close() t2, err := c.OpenTorrent(context.Background(), &info, metainfo.HashBytes([]byte("b"))) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer t2.Close() t2p := t2.Piece(info.Piece(0)) assert.NoError(t, t1.Close()) diff --git a/storage/issue96_test.go b/storage/issue96_test.go index 5c43574d79..00877c3006 100644 --- a/storage/issue96_test.go +++ b/storage/issue96_test.go @@ -5,6 +5,7 @@ import ( "testing" g "github.com/anacrolix/generics" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/metainfo" @@ -21,9 +22,9 @@ func testMarkedCompleteMissingOnRead(t *testing.T, csf func(string) ClientImplCl Pieces: make([]byte, 20), } ts, err := cs.OpenTorrent(context.Background(), info, metainfo.Hash{}) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) p := ts.PieceWithHash(info.Piece(0), g.None[[]byte]()) - require.NoError(t, p.MarkComplete()) + qt.Assert(t, qt.IsNil(p.MarkComplete())) // require.False(t, p.GetIsComplete()) n, err := p.ReadAt(make([]byte, 1), 0) require.Error(t, err) diff --git a/storage/mmap_test.go b/storage/mmap_test.go index c72f9a9cb2..7acaf35c9d 100644 --- a/storage/mmap_test.go +++ b/storage/mmap_test.go @@ -4,23 +4,24 @@ import ( "context" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" ) func TestMmapWindows(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) dir, mi := testutil.GreetingTestTorrent() cs := NewMMap(dir) defer func() { - c.Check(cs.Close(), qt.IsNil) + qt.Check(c, qt.IsNil(cs.Close())) }() info, err := mi.UnmarshalInfo() - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) ts, err := cs.OpenTorrent(context.Background(), &info, mi.HashInfoBytes()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer func() { - c.Check(ts.Close(), qt.IsNil) + qt.Check(c, qt.IsNil(ts.Close())) }() } diff --git a/storage/safe-path_test.go b/storage/safe-path_test.go index 13701e4b3e..bda41bc97e 100644 --- a/storage/safe-path_test.go +++ b/storage/safe-path_test.go @@ -7,8 +7,9 @@ import ( "path/filepath" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" ) @@ -49,7 +50,7 @@ func TestToSafeFilePath(t *testing.T) { // Check that safe file path handling still exists for the newer file-opt-maker variants. func TestFileOptsSafeFilePathHandling(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) for i, _case := range safeFilePathTests { c.Run(fmt.Sprintf("Case%v", i), func(c *qt.C) { info := metainfo.Info{ @@ -60,12 +61,12 @@ func TestFileOptsSafeFilePathHandling(t *testing.T) { client := NewFileOpts(NewFileClientOpts{ ClientBaseDir: t.TempDir(), }) - defer func() { c.Check(client.Close(), qt.IsNil) }() + defer func() { qt.Check(c, qt.IsNil(client.Close())) }() torImpl, err := client.OpenTorrent(context.Background(), &info, metainfo.Hash{}) if _case.expectErr { - c.Check(err, qt.Not(qt.IsNil)) + qt.Check(c, qt.Not(qt.IsNil)(err)) } else { - c.Check(torImpl.Close(), qt.IsNil) + qt.Check(c, qt.IsNil(torImpl.Close())) } }) } diff --git a/storage/sqlite-piece-completion.go b/storage/sqlite-piece-completion.go index 73407f3f23..2edd8e2d41 100644 --- a/storage/sqlite-piece-completion.go +++ b/storage/sqlite-piece-completion.go @@ -11,7 +11,7 @@ import ( "path/filepath" "sync" - "github.com/go-llsqlite/adapter" + sqlite "github.com/go-llsqlite/adapter" "github.com/go-llsqlite/adapter/sqlitex" "github.com/anacrolix/torrent/metainfo" diff --git a/storage/sqlite/sqlite-storage_test.go b/storage/sqlite/sqlite-storage_test.go index a566322d70..e0f1881209 100644 --- a/storage/sqlite/sqlite-storage_test.go +++ b/storage/sqlite/sqlite-storage_test.go @@ -12,8 +12,9 @@ import ( _ "github.com/anacrolix/envpprof" "github.com/anacrolix/squirrel" "github.com/dustin/go-humanize" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/storage" test_storage "github.com/anacrolix/torrent/storage/test" "github.com/anacrolix/torrent/test" @@ -47,7 +48,7 @@ func BenchmarkMarkComplete(b *testing.B) { runBench := func(b *testing.B, ci storage.ClientImpl) { test_storage.BenchmarkPieceMarkComplete(b, ci, pieceSize, test_storage.DefaultNumPieces, capacity) } - c := qt.New(b) + c := qtnew.New(b) b.Run("CustomDirect", func(b *testing.B) { var opts squirrel.NewCacheOpts opts.Capacity = capacity @@ -55,7 +56,7 @@ func BenchmarkMarkComplete(b *testing.B) { benchOpts := func(b *testing.B) { opts.Path = filepath.Join(b.TempDir(), "storage.db") ci, err := NewDirectStorage(opts) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer ci.Close() runBench(b, ci) } @@ -75,7 +76,7 @@ func BenchmarkMarkComplete(b *testing.B) { if errors.As(err, &ujm) { b.Skipf("setting journal mode %q: %v", opts.SetJournalMode, err) } - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer ci.Close() runBench(b, ci) } diff --git a/storage/test/bench-piece-mark-complete.go b/storage/test/bench-piece-mark-complete.go index b665bf4160..bc915162a8 100644 --- a/storage/test/bench-piece-mark-complete.go +++ b/storage/test/bench-piece-mark-complete.go @@ -7,7 +7,7 @@ import ( "sync" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/storage" @@ -28,7 +28,7 @@ func BenchmarkPieceMarkComplete( // implementation. capacity int64, ) { - c := qt.New(b) + t := b info := &metainfo.Info{ Pieces: make([]byte, numPieces*metainfo.HashSize), PieceLength: pieceSize, @@ -36,7 +36,7 @@ func BenchmarkPieceMarkComplete( Name: "TorrentName", } ti, err := ci.OpenTorrent(context.Background(), info, metainfo.Hash{}) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) tw := storage.Torrent{ti} defer tw.Close() rand.Read(info.Pieces) @@ -67,14 +67,14 @@ func BenchmarkPieceMarkComplete( pi.MarkNotComplete() } // This might not apply if users of this benchmark don't cache with the expected capacity. - c.Assert(pi.Completion(), qt.Equals, storage.Completion{Complete: false, Ok: true}) - c.Assert(pi.MarkComplete(), qt.IsNil) - c.Assert(pi.Completion(), qt.Equals, storage.Completion{Complete: true, Ok: true}) + qt.Assert(t, qt.Equals(pi.Completion(), storage.Completion{Complete: false, Ok: true})) + qt.Assert(t, qt.IsNil(pi.MarkComplete())) + qt.Assert(t, qt.Equals(pi.Completion(), storage.Completion{Complete: true, Ok: true})) n, err := pi.WriteTo(bytes.NewBuffer(readData[:0])) b.StopTimer() - c.Assert(err, qt.IsNil) - c.Assert(n, qt.Equals, int64(len(data))) - c.Assert(bytes.Equal(readData[:n], data), qt.IsTrue) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.Equals(n, int64(len(data)))) + qt.Assert(t, qt.IsTrue(bytes.Equal(readData[:n], data))) } } // Fill the cache diff --git a/test/issue377_test.go b/test/issue377_test.go index 3d1025e3d4..2c8acdddfe 100644 --- a/test/issue377_test.go +++ b/test/issue377_test.go @@ -10,8 +10,8 @@ import ( "testing/iotest" "github.com/anacrolix/log" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent" "github.com/anacrolix/torrent/internal/testutil" @@ -46,7 +46,7 @@ func testReceiveChunkStorageFailure(t *testing.T, seederFast bool) { seederClientConfig.Debug = true seederClientConfig.Extensions.SetBit(pp.ExtensionBitFast, seederFast) seederClient, err := torrent.NewClient(seederClientConfig) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seederClient.Close() defer testutil.ExportStatusWriter(seederClient, "s", t)() leecherClientConfig := torrent.TestingConfig(t) @@ -56,11 +56,11 @@ func testReceiveChunkStorageFailure(t *testing.T, seederFast bool) { leecherClientConfig.MinPeerExtensions.SetBit(pp.ExtensionBitFast, false) justOneNetwork(leecherClientConfig) leecherClient, err := torrent.NewClient(leecherClientConfig) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecherClient.Close() defer testutil.ExportStatusWriter(leecherClient, "l", t)() info, err := metainfo.UnmarshalInfo() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) leecherStorage := diskFullStorage{ pieces: make([]pieceState, info.NumPieces()), data: make([]byte, info.TotalLength()), @@ -71,10 +71,10 @@ func testReceiveChunkStorageFailure(t *testing.T, seederFast bool) { Storage: &leecherStorage, }) leecherStorage.t = leecherTorrent - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, new) seederTorrent, err := seederClient.AddTorrent(metainfo) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) // Tell the seeder to find the leecher. Is it guaranteed seeders will always try to do this? seederTorrent.AddClientPeer(leecherClient) <-leecherTorrent.GotInfo() diff --git a/test/leecher-storage.go b/test/leecher-storage.go index dfaad2bcd2..2d212b33be 100644 --- a/test/leecher-storage.go +++ b/test/leecher-storage.go @@ -9,9 +9,8 @@ import ( "testing/iotest" "github.com/anacrolix/missinggo/v2/bitmap" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/time/rate" "github.com/anacrolix/torrent" @@ -97,7 +96,7 @@ func testClientTransfer(t *testing.T, ps testClientTransferParams) { newGOMAXPROCS = ps.GOMAXPROCS } defer func() { - qt.Check(t, runtime.GOMAXPROCS(prevGOMAXPROCS), qt.ContentEquals, newGOMAXPROCS) + qt.Check(qt, qt.ContentEquals(runtime.GOMAXPROCS(prevGOMAXPROCS), newGOMAXPROCS)(t)) }() greetingTempDir, mi := testutil.GreetingTestTorrent() @@ -125,7 +124,7 @@ func testClientTransfer(t *testing.T, ps testClientTransferParams) { ps.ConfigureSeeder.Config(cfg) } seeder, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) if ps.ConfigureSeeder.Client != nil { ps.ConfigureSeeder.Client(seeder) } @@ -159,7 +158,7 @@ func testClientTransfer(t *testing.T, ps testClientTransferParams) { ps.ConfigureLeecher.Config(cfg) } leecher, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecher.Close() if ps.ConfigureLeecher.Client != nil { ps.ConfigureLeecher.Client(leecher) @@ -173,7 +172,7 @@ func testClientTransfer(t *testing.T, ps testClientTransferParams) { } return }()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.False(t, leecherTorrent.Complete().Bool()) assert.True(t, new) @@ -202,7 +201,7 @@ func testClientTransfer(t *testing.T, ps testClientTransferParams) { } assertReadAllGreeting(t, r) info, err := mi.UnmarshalInfo() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) canComplete := ps.LeecherStorageCapacity == 0 || ps.LeecherStorageCapacity >= info.TotalLength() if !canComplete { // Reading from a cache doesn't refresh older pieces until we fail to read those, so we need @@ -251,5 +250,5 @@ func assertReadAllGreeting(t *testing.T, r io.ReadSeeker) { pos, err := r.Seek(0, io.SeekStart) assert.NoError(t, err) assert.EqualValues(t, 0, pos) - qt.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), qt.IsNil) + qt.Check(t, qt.IsNil(iotest.TestReader(r, []byte(testutil.GreetingFileContents)))) } diff --git a/test/sqlite_test.go b/test/sqlite_test.go index 437499d441..a4adcaa9c2 100644 --- a/test/sqlite_test.go +++ b/test/sqlite_test.go @@ -11,27 +11,28 @@ import ( "net/http" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/anacrolix/torrent" "github.com/anacrolix/torrent/bencode" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" sqliteStorage "github.com/anacrolix/torrent/storage/sqlite" ) func TestSqliteStorageClosed(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) cfg := torrent.TestingConfig(t) storage, err := sqliteStorage.NewDirectStorage(sqliteStorage.NewDirectStorageOpts{}) defer storage.Close() cfg.DefaultStorage = storage cfg.Debug = true - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) cl, err := torrent.NewClient(cfg) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() l, err := net.Listen("tcp", "localhost:0") - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer l.Close() // We need at least once piece to trigger a call to storage to determine completion state. We // need non-zero content length to trigger piece hashing. @@ -44,7 +45,7 @@ func TestSqliteStorageClosed(t *testing.T) { } mi := metainfo.MetaInfo{} mi.InfoBytes, err = bencode.Marshal(i) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) s := http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mi.Write(w) @@ -63,6 +64,6 @@ func TestSqliteStorageClosed(t *testing.T) { InfoHash: mi.HashInfoBytes(), Sources: []string{"http://" + l.Addr().String()}, }) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) <-tor.GotInfo() } diff --git a/test/transfer_test.go b/test/transfer_test.go index 501872fd8f..6b44d2c813 100644 --- a/test/transfer_test.go +++ b/test/transfer_test.go @@ -10,7 +10,7 @@ import ( "github.com/anacrolix/log" "github.com/anacrolix/missinggo/v2/filecache" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/time/rate" @@ -142,11 +142,11 @@ func testSeedAfterDownloading(t *testing.T, disableUtp bool) { cfg.DataDir = greetingTempDir cfg.DisableUTP = disableUtp seeder, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seeder.Close() defer testutil.ExportStatusWriter(seeder, "s", t)() seederTorrent, ok, err := seeder.AddTorrentSpec(torrent.TorrentSpecFromMetaInfo(mi)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) seederTorrent.VerifyData() @@ -162,7 +162,7 @@ func testSeedAfterDownloading(t *testing.T, disableUtp bool) { //cfg.Debug = true cfg.Logger = log.Default.WithContextText("leecher") leecher, err := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecher.Close() defer testutil.ExportStatusWriter(leecher, "l", t)() @@ -174,7 +174,7 @@ func testSeedAfterDownloading(t *testing.T, disableUtp bool) { cfg.Logger = log.Default.WithContextText("leecher-leecher") cfg.Debug = true leecherLeecher, _ := torrent.NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecherLeecher.Close() defer testutil.ExportStatusWriter(leecherLeecher, "ll", t)() leecherGreeting, ok, err := leecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) { @@ -182,14 +182,14 @@ func testSeedAfterDownloading(t *testing.T, disableUtp bool) { ret.ChunkSize = 2 return }()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *torrent.TorrentSpec) { ret = torrent.TorrentSpecFromMetaInfo(mi) ret.ChunkSize = 3 return }()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) // Simultaneously DownloadAll in Leecher, and read the contents // consecutively in LeecherLeecher. This non-deterministically triggered a @@ -203,7 +203,7 @@ func testSeedAfterDownloading(t *testing.T, disableUtp bool) { go func() { defer wg.Done() defer r.Close() - qt.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), qt.IsNil) + qt.Check(qt, iotest.TestReader(r, []byte(testutil.GreetingFileContents))(t, qt.IsNil)(qt)) }() } go leecherGreeting.AddClientPeer(seeder) diff --git a/tests/add-webseed-after-priorities/herp_test.go b/tests/add-webseed-after-priorities/herp_test.go index 6c89a87bce..2b7ea517a2 100644 --- a/tests/add-webseed-after-priorities/herp_test.go +++ b/tests/add-webseed-after-priorities/herp_test.go @@ -1,13 +1,15 @@ package webseed_partial_seed import ( - "github.com/anacrolix/torrent" - "github.com/anacrolix/torrent/internal/testutil" - qt "github.com/frankban/quicktest" "path/filepath" "runtime" "testing" "time" + + "github.com/anacrolix/torrent" + "github.com/anacrolix/torrent/internal/qtnew" + "github.com/anacrolix/torrent/internal/testutil" + qt "github.com/go-quicktest/qt" ) func testSrcDir() string { @@ -50,7 +52,7 @@ func downloadAll(t *torrent.Torrent) { } func TestWebseedPartialSeed(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) seederClient := makeSeederClient(t) defer seederClient.Close() testutil.ExportStatusWriter(seederClient, "seeder", t) @@ -82,5 +84,5 @@ func TestWebseedPartialSeed(t *testing.T) { time.Sleep(time.Second) seederTorrent.AddWebSeeds([]string{"http://localhost:3003/test.img"}) allDownloaded := leecherClient.WaitAll() - c.Assert(allDownloaded, qt.IsTrue) + qt.Assert(t, qt.IsTrue(allDownloaded)) } diff --git a/tests/issue-952/issue-952_test.go b/tests/issue-952/issue-952_test.go index 8220647704..ddecded6c3 100644 --- a/tests/issue-952/issue-952_test.go +++ b/tests/issue-952/issue-952_test.go @@ -3,9 +3,10 @@ package issue_952 import ( "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/anacrolix/torrent/bencode" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/types/infohash" ) @@ -25,16 +26,16 @@ func TestUnmarshalStringToByteArray(t *testing.T) { var s scrapeResponse const hashStr = "\x05a~F\xfd{c\xd1`\xb8\xd9\x89\xceM\xb9t\x1d\\\x0b\xded" err := bencode.Unmarshal([]byte("d5:filesd20:\x05a~F\xfd{c\xd1`\xb8\xd9\x89\xceM\xb9t\x1d\\\x0b\xded9:completedi1e10:downloadedi1eeee"), &s) - c := qt.New(t) - c.Assert(err, qt.IsNil) - c.Check(s.Files, qt.HasLen, 1) + c := qtnew.New(t) + qt.Assert(t, qt.IsNil(err)) + qt.Check(qt, qt.HasLen(s.Files, 1)(c)) file, ok := s.Files[(infohash.T)([]byte(hashStr))] - c.Assert(ok, qt.IsTrue) - c.Check(file, qt.Equals, scrapeResponseFile{ - // Note that complete is misspelled in the example. I don't know why. + qt.Assert(t, qt.IsTrue(ok)) + qt.Check(qt, qt.Equals(file, scrapeResponseFile{ + Complete: 0, Downloaded: 1, Incomplete: 0, - }) + })(c)) } diff --git a/tests/webseed-partial-seed/herp_test.go b/tests/webseed-partial-seed/herp_test.go index 8eedff3685..9e82a30c77 100644 --- a/tests/webseed-partial-seed/herp_test.go +++ b/tests/webseed-partial-seed/herp_test.go @@ -6,8 +6,9 @@ import ( "testing" "github.com/anacrolix/torrent" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" ) func testSrcDir() string { @@ -50,7 +51,7 @@ func downloadAll(t *torrent.Torrent) { } func TestWebseedPartialSeed(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) seederClient := makeSeederClient(t) defer seederClient.Close() testutil.ExportStatusWriter(seederClient, "seeder", t) @@ -79,5 +80,5 @@ func TestWebseedPartialSeed(t *testing.T) { seederTorrent.DownloadAll() allDownloaded := leecherClient.WaitAll() - c.Assert(allDownloaded, qt.IsTrue) + qt.Assert(t, qt.IsTrue(allDownloaded)) } diff --git a/torrent_test.go b/torrent_test.go index bd409b6834..ddd887df20 100644 --- a/torrent_test.go +++ b/torrent_test.go @@ -14,11 +14,12 @@ import ( "github.com/anacrolix/log" "github.com/anacrolix/missinggo/v2" "github.com/anacrolix/missinggo/v2/bitmap" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/bencode" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" "github.com/anacrolix/torrent/metainfo" pp "github.com/anacrolix/torrent/peer_protocol" @@ -91,11 +92,12 @@ func BenchmarkUpdatePiecePriorities(b *testing.B) { cl := &Client{config: TestingConfig(b)} cl.initLogger() t := cl.newTorrentForTesting() - require.NoError(b, t.setInfo(&metainfo.Info{ + qt.Assert(t, qt.IsNil(t.setInfo(&metainfo.Info{ Pieces: make([]byte, metainfo.HashSize*numPieces), PieceLength: pieceLength, Length: pieceLength * numPieces, - })) + }))(b)) + t.onSetInfo() assert.EqualValues(b, 13410, t.numPieces()) for i := 0; i < 7; i += 1 { @@ -118,21 +120,21 @@ func BenchmarkUpdatePiecePriorities(b *testing.B) { // file-based on the native filesystem based. func testEmptyFilesAndZeroPieceLength(t *testing.T, cfg *ClientConfig) { cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() ib, err := bencode.Marshal(metainfo.Info{ Name: "empty", Length: 0, PieceLength: 0, }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) fp := filepath.Join(cfg.DataDir, "empty") os.Remove(fp) assert.False(t, missinggo.FilePathExists(fp)) tt, err := cl.AddTorrent(&metainfo.MetaInfo{ InfoBytes: ib, }) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer tt.Drop() tt.DownloadAll() require.True(t, cl.WaitAll()) @@ -153,7 +155,7 @@ func TestPieceHashFailed(t *testing.T) { cl := newTestingClient(t) tt := cl.newTorrent(mi.HashInfoBytes(), badStorage{}) tt.setChunkSize(2) - require.NoError(t, tt.setInfoBytesLocked(mi.InfoBytes)) + qt.Assert(t, qt.IsNil(tt.setInfoBytesLocked(mi.InfoBytes))) tt.cl.lock() tt.dirtyChunks.AddRange( uint64(tt.pieceRequestIndexOffset(1)), @@ -172,7 +174,7 @@ func TestTorrentMetainfoIncompleteMetadata(t *testing.T) { // Disable this just because we manually initiate a connection without it. cfg.MinPeerExtensions.SetBit(pp.ExtensionBitFast, false) cl, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() mi := testutil.GreetingMetaInfo() @@ -183,13 +185,13 @@ func TestTorrentMetainfoIncompleteMetadata(t *testing.T) { assert.False(t, tt.haveAllMetadataPieces()) nc, err := net.Dial("tcp", fmt.Sprintf(":%d", cl.LocalPort())) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer nc.Close() var pex PeerExtensionBits pex.SetBit(pp.ExtensionBitLtep, true) hr, err := pp.Handshake(context.Background(), nc, &ih, [20]byte{}, pex) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, hr.PeerExtensionBits.GetBit(pp.ExtensionBitLtep)) assert.EqualValues(t, cl.PeerID(), hr.PeerID) assert.EqualValues(t, ih, hr.Hash) @@ -214,7 +216,7 @@ func TestTorrentMetainfoIncompleteMetadata(t *testing.T) { return b }(), }.MustMarshalBinary()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) }() tt.metadataChanged.Wait() }() @@ -224,7 +226,7 @@ func TestTorrentMetainfoIncompleteMetadata(t *testing.T) { } func TestRelativeAvailabilityHaveNone(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) var err error cl := Client{ config: TestingConfig(t), @@ -243,13 +245,13 @@ func TestRelativeAvailabilityHaveNone(t *testing.T) { g.InitNew(&pc.callbacks) tt.conns[&pc] = struct{}{} err = pc.peerSentHave(0) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) info := testutil.Greeting.Info(5) err = tt.setInfo(&info) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) tt.onSetInfo() err = pc.peerSentHaveNone() - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) var wg sync.WaitGroup tt.close(&wg) tt.assertAllPiecesRelativeAvailabilityZero() diff --git a/tracker/http/http_test.go b/tracker/http/http_test.go index 4e5efaf572..cc31b9660a 100644 --- a/tracker/http/http_test.go +++ b/tracker/http/http_test.go @@ -4,7 +4,7 @@ import ( "net/url" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -14,14 +14,14 @@ import ( func TestUnmarshalHTTPResponsePeerDicts(t *testing.T) { var hr HttpResponse - require.NoError(t, bencode.Unmarshal( + qt.Assert(t, qt.IsNil(bencode.Unmarshal( []byte("d5:peersl"+ "d2:ip7:1.2.3.47:peer id20:thisisthe20bytepeeri4:porti9999ee"+ "d2:ip39:2001:0db8:85a3:0000:0000:8a2e:0370:73347:peer id20:thisisthe20bytepeeri4:porti9998ee"+ "e"+ "6:peers618:123412341234123456"+ "e"), - &hr)) + &hr))) require.Len(t, hr.Peers.List, 2) assert.Equal(t, []byte("thisisthe20bytepeeri"), hr.Peers.List[0].ID) @@ -37,10 +37,11 @@ func TestUnmarshalHTTPResponsePeerDicts(t *testing.T) { func TestUnmarshalHttpResponseNoPeers(t *testing.T) { var hr HttpResponse - require.NoError(t, bencode.Unmarshal( + qt.Assert(t, qt.IsNil(bencode.Unmarshal( []byte("d6:peers618:123412341234123456e"), &hr, - )) + ))) + require.Len(t, hr.Peers.List, 0) assert.Len(t, hr.Peers6, 1) } @@ -69,8 +70,9 @@ func TestSetAnnounceInfohashParamWithSpaces(t *testing.T) { AnnounceOpt{}) t.Logf("%q", someUrl) qt.Assert(t, someUrl.Query().Get("info_hash"), qt.Equals, string(ihBytes[:])) - qt.Check(t, + qt.Check(qt, qt.StringContains( someUrl.String(), - qt.Contains, - "info_hash=%2Bv%0A%A1x%93%200%C8G%DC%DF%8E%AE%BFV%0A%1B%D1l") + + "info_hash=%2Bv%0A%A1x%93%200%C8G%DC%DF%8E%AE%BFV%0A%1B%D1l")(t)) + } diff --git a/tracker/udp/server/server.go b/tracker/udp/server/server.go index 35688394cf..ae7abbf51f 100644 --- a/tracker/udp/server/server.go +++ b/tracker/udp/server/server.go @@ -90,7 +90,7 @@ func (me *Server) handleAnnounce( // Should we set a timeout of 10s or something for the entire response, so that we give up if a // retry is imminent? - ok, err := me.ConnTracker.Check(ctx, source.String(), connId) + ok, err := qt.Check(qt, source.String()(ctx, connId)(me.ConnTracker)) if err != nil { err = fmt.Errorf("checking conn id: %w", err) return err diff --git a/tracker/udp/timeout_test.go b/tracker/udp/timeout_test.go index 4bb0dc83f0..85749566e0 100644 --- a/tracker/udp/timeout_test.go +++ b/tracker/udp/timeout_test.go @@ -4,12 +4,11 @@ import ( "math" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" ) func TestTimeoutMax(t *testing.T) { - c := qt.New(t) - c.Check(timeout(8), qt.Equals, maxTimeout) - c.Check(timeout(9), qt.Equals, maxTimeout) - c.Check(timeout(math.MaxInt32), qt.Equals, maxTimeout) + qt.Check(t, qt.Equals(timeout(8), maxTimeout)) + qt.Check(t, qt.Equals(timeout(9), maxTimeout)) + qt.Check(t, qt.Equals(timeout(math.MaxInt32), maxTimeout)) } diff --git a/tracker/udp/udp_test.go b/tracker/udp/udp_test.go index 378351cd81..b537382c5f 100644 --- a/tracker/udp/udp_test.go +++ b/tracker/udp/udp_test.go @@ -14,7 +14,8 @@ import ( "github.com/anacrolix/dht/v2/krpc" _ "github.com/anacrolix/envpprof" "github.com/anacrolix/missinggo/v2/iter" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/require" ) @@ -36,7 +37,7 @@ func TestMarshalAnnounceResponse(t *testing.T) { {[]byte{255, 0, 0, 3}, 4}, } b, err := peers.MarshalBinary() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) require.EqualValues(t, "\x7f\x00\x00\x01\x00\x02\xff\x00\x00\x03\x00\x04", b) @@ -47,7 +48,7 @@ func TestMarshalAnnounceResponse(t *testing.T) { func TestLongWriteUDP(t *testing.T) { t.Parallel() l, err := net.ListenUDP("udp4", nil) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer l.Close() c, err := net.DialUDP("udp", nil, l.LocalAddr().(*net.UDPAddr)) if err != nil { @@ -88,19 +89,19 @@ func TestConnClientLogDispatchUnknownTransactionId(t *testing.T) { cc, err := NewConnClient(NewConnClientOpts{ Network: network, }) - c := qt.New(t) - c.Assert(err, qt.IsNil) + c := qtnew.New(t) + qt.Assert(t, qt.IsNil(err)) defer cc.Close() pc, err := net.ListenPacket(network, ":0") - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer pc.Close() ccAddr := *cc.LocalAddr().(*net.UDPAddr) ipAddrs, err := net.DefaultResolver.LookupIPAddr(context.Background(), "localhost") - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) ccAddr.IP = ipAddrs[0].IP ccAddr.Zone = ipAddrs[0].Zone _, err = pc.WriteTo(make([]byte, 30), &ccAddr) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) } func TestConnectionIdMismatch(t *testing.T) { @@ -112,8 +113,8 @@ func TestConnectionIdMismatch(t *testing.T) { //Host: "tracker.opentrackr.org:1337", Network: "udp", }) - c := qt.New(t) - c.Assert(err, qt.IsNil) + c := qtnew.New(t) + qt.Assert(t, qt.IsNil(err)) defer cl.Close() ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() diff --git a/tracker/udp_test.go b/tracker/udp_test.go index 232aeb1973..079f125579 100644 --- a/tracker/udp_test.go +++ b/tracker/udp_test.go @@ -15,8 +15,8 @@ import ( "github.com/anacrolix/dht/v2/krpc" _ "github.com/anacrolix/envpprof" + "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/tracker/udp" ) @@ -43,10 +43,10 @@ func TestAnnounceLocalhost(t *testing.T) { } var err error srv.pc, err = net.ListenPacket("udp", "localhost:0") - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer srv.pc.Close() go func() { - require.NoError(t, srv.serveOne()) + qt.Assert(t, qt.IsNil(srv.serveOne())) }() req := AnnounceRequest{ NumWant: -1, @@ -55,13 +55,13 @@ func TestAnnounceLocalhost(t *testing.T) { rand.Read(req.PeerId[:]) copy(req.InfoHash[:], []uint8{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1}) go func() { - require.NoError(t, srv.serveOne()) + qt.Assert(t, qt.IsNil(srv.serveOne())) }() ar, err := Announce{ TrackerUrl: fmt.Sprintf("udp://%s/announce", srv.pc.LocalAddr().String()), Request: req, }.Do() - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.EqualValues(t, 1, ar.Seeders) assert.EqualValues(t, 2, len(ar.Peers)) } @@ -93,7 +93,7 @@ func TestUDPTracker(t *testing.T) { if errors.As(err, &ne) { t.Skip(err) } - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) t.Logf("%+v", ar) } @@ -190,5 +190,5 @@ func TestURLPathOption(t *testing.T) { }) udp.Write(w, udp.AnnounceResponseHeader{}) conn.WriteTo(w.Bytes(), addr) - require.NoError(t, <-announceErr) + qt.Assert(t, qt.IsNil(<-announceErr)) } diff --git a/ut-holepunching_test.go b/ut-holepunching_test.go index ef7cda6ba7..862286128e 100644 --- a/ut-holepunching_test.go +++ b/ut-holepunching_test.go @@ -15,18 +15,18 @@ import ( "github.com/anacrolix/log" "github.com/anacrolix/missinggo/v2/iter" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/time/rate" + "github.com/anacrolix/torrent/internal/qtnew" "github.com/anacrolix/torrent/internal/testutil" ) // Check that after completing leeching, a leecher transitions to a seeding // correctly. Connected in a chain like so: Seeder <-> Leecher <-> LeecherLeecher. func TestHolepunchConnect(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) greetingTempDir, mi := testutil.GreetingTestTorrent() defer os.RemoveAll(greetingTempDir) @@ -45,11 +45,11 @@ func TestHolepunchConnect(t *testing.T) { cfg.DialRateLimiter = rate.NewLimiter(0, 1) cfg.Logger = cfg.Logger.WithContextText("seeder") seeder, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer seeder.Close() defer testutil.ExportStatusWriter(seeder, "s", t)() seederTorrent, ok, err := seeder.AddTorrentSpec(TorrentSpecFromMetaInfo(mi)) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) seederTorrent.VerifyData() @@ -63,7 +63,7 @@ func TestHolepunchConnect(t *testing.T) { //cfg.DisablePEX = true cfg.Debug = true leecher, err := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecher.Close() defer testutil.ExportStatusWriter(leecher, "l", t)() @@ -76,7 +76,7 @@ func TestHolepunchConnect(t *testing.T) { cfg.Logger = cfg.Logger.WithContextText("leecher-leecher") //cfg.DisableUTP = true leecherLeecher, _ := NewClient(cfg) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer leecherLeecher.Close() defer testutil.ExportStatusWriter(leecherLeecher, "ll", t)() leecherGreeting, ok, err := leecher.AddTorrentSpec(func() (ret *TorrentSpec) { @@ -85,14 +85,14 @@ func TestHolepunchConnect(t *testing.T) { return }()) _ = leecherGreeting - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *TorrentSpec) { ret = TorrentSpecFromMetaInfo(mi) ret.ChunkSize = 3 return }()) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) assert.True(t, ok) var wg sync.WaitGroup @@ -101,7 +101,7 @@ func TestHolepunchConnect(t *testing.T) { defer wg.Done() r := llg.NewReader() defer r.Close() - qt.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), qt.IsNil) + qt.Check(qt, iotest.TestReader(r, []byte(testutil.GreetingFileContents))(t, qt.IsNil)(qt)) }() go seederTorrent.AddClientPeer(leecher) waitForConns(seederTorrent) @@ -123,13 +123,13 @@ func TestHolepunchConnect(t *testing.T) { llg.cl.unlock() wg.Wait() - c.Check(seeder.dialedSuccessfullyAfterHolepunchConnect, qt.Not(qt.HasLen), 0) - c.Check(leecherLeecher.probablyOnlyConnectedDueToHolepunch, qt.Not(qt.HasLen), 0) + qt.Check(qt, qt.Not(qt.HasLen)(seeder.dialedSuccessfullyAfterHolepunchConnect, 0)(c)) + qt.Check(qt, qt.Not(qt.HasLen)(leecherLeecher.probablyOnlyConnectedDueToHolepunch, 0)(c)) llClientStats := leecherLeecher.Stats() - c.Check(llClientStats.NumPeersUndialableWithoutHolepunch, qt.Not(qt.Equals), 0) - c.Check(llClientStats.NumPeersUndialableWithoutHolepunchDialedAfterHolepunchConnect, qt.Not(qt.Equals), 0) - c.Check(llClientStats.NumPeersProbablyOnlyConnectedDueToHolepunch, qt.Not(qt.Equals), 0) + qt.Check(qt, qt.Not(qt.Equals)(llClientStats.NumPeersUndialableWithoutHolepunch, 0)(c)) + qt.Check(qt, qt.Not(qt.Equals)(llClientStats.NumPeersUndialableWithoutHolepunchDialedAfterHolepunchConnect, 0)(c)) + qt.Check(qt, qt.Not(qt.Equals)(llClientStats.NumPeersProbablyOnlyConnectedDueToHolepunch, 0)(c)) } func waitForConns(t *Torrent) { @@ -146,11 +146,11 @@ func waitForConns(t *Torrent) { // Show that dialling TCP will complete before the other side accepts. func TestDialTcpNotAccepting(t *testing.T) { l, err := net.Listen("tcp", "localhost:0") - c := qt.New(t) - c.Check(err, qt.IsNil) + c := qtnew.New(t) + qt.Check(c, qt.IsNil(err)) defer l.Close() dialedConn, err := net.Dial("tcp", l.Addr().String()) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) dialedConn.Close() } @@ -168,7 +168,7 @@ func TestTcpSimultaneousOpen(t *testing.T) { return dialer.DialContext(ctx, network, remoteAddr) } } - c := qt.New(t) + c := qtnew.New(t) // I really hate doing this in unit tests, but we would need to pick apart Dialer to get // perfectly synchronized simultaneous dials. for range iter.N(10) { @@ -311,7 +311,7 @@ const defaultMsg = "hello" // for one or both peers involved. func TestUtpSimultaneousOpen(t *testing.T) { t.Parallel() - c := qt.New(t) + c := qtnew.New(t) const network = "udp" ctx := context.Background() newUtpSocket := func(addr string) utpSocket { @@ -323,7 +323,7 @@ func TestUtpSimultaneousOpen(t *testing.T) { }, log.Default, ) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) return socket } first := newUtpSocket("localhost:0") @@ -370,14 +370,14 @@ func skipGoUtpDialIssue(t *testing.T, err error) { // same connection. func TestUtpDirectDialMsg(t *testing.T) { t.Parallel() - c := qt.New(t) + c := qtnew.New(t) const network = "udp4" ctx := context.Background() newUtpSocket := func(addr string) utpSocket { socket, err := NewUtpSocket(network, addr, func(net.Addr) bool { return false }, log.Default) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) return socket } for range iter.N(10) { @@ -393,7 +393,7 @@ func TestUtpDirectDialMsg(t *testing.T) { defer writer.Close() reader, err := second.Accept() defer reader.Close() - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) return writeAndReadMsg(reader, writer) }() if err == nil { diff --git a/util/dirwatch/dirwatch_test.go b/util/dirwatch/dirwatch_test.go index 04475994b5..68fd512423 100644 --- a/util/dirwatch/dirwatch_test.go +++ b/util/dirwatch/dirwatch_test.go @@ -3,13 +3,13 @@ package dirwatch import ( "testing" - "github.com/stretchr/testify/require" + "github.com/go-quicktest/qt" ) func TestDirwatch(t *testing.T) { tempDirName := t.TempDir() t.Logf("tempdir: %q", tempDirName) dw, err := New(tempDirName) - require.NoError(t, err) + qt.Assert(t, qt.IsNil(err)) defer dw.Close() } diff --git a/webseed/request_test.go b/webseed/request_test.go index af3071f3fd..7eef291580 100644 --- a/webseed/request_test.go +++ b/webseed/request_test.go @@ -4,11 +4,13 @@ import ( "net/url" "testing" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + + qt "github.com/go-quicktest/qt" ) func TestDefaultPathEscaper(t *testing.T) { - c := qt.New(t) + c := qtnew.New(t) test := func(unescaped string, parts ...string) { assertPartsUnescape(c, unescaped, parts...) } @@ -36,14 +38,14 @@ var defaultPathEscapeTestCases = []struct { }, } -func assertPartsUnescape(c *qt.C, unescaped string, parts ...string) { +func assertPartsUnescape(t *testing.T, unescaped string, parts ...string) { escaped := defaultPathEscaper(parts) pathUnescaped, err := url.PathUnescape(escaped) - c.Assert(err, qt.IsNil) - c.Assert(pathUnescaped, qt.Equals, unescaped) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.Equals(pathUnescaped, unescaped)) queryUnescaped, err := url.QueryUnescape(escaped) - c.Assert(err, qt.IsNil) - c.Assert(queryUnescaped, qt.Equals, unescaped) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.Equals(queryUnescaped, unescaped)) } func FuzzDefaultPathEscaper(f *testing.F) { @@ -55,6 +57,6 @@ func FuzzDefaultPathEscaper(f *testing.F) { // I think a single separator is enough to test special handling around /. Also fuzzing doesn't // let us take []string as an input. f.Fuzz(func(t *testing.T, first, second string) { - assertPartsUnescape(qt.New(t), first+"/"+second, first, second) + assertPartsUnescape(qtnew.New(t), first+"/"+second, first, second) }) } diff --git a/webtorrent/fuzz_test.go b/webtorrent/fuzz_test.go index 14638fa211..8e194d4c13 100644 --- a/webtorrent/fuzz_test.go +++ b/webtorrent/fuzz_test.go @@ -7,7 +7,7 @@ import ( "encoding/json" "testing" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" ) func FuzzJsonBinaryStrings(f *testing.F) { @@ -23,9 +23,8 @@ func FuzzJsonBinaryStrings(f *testing.F) { t.Fatal(err) } // t.Logf("%q", jsonStr) - c := qt.New(t) out, err := decodeJsonByteString(jsonStr, []byte{}) - c.Assert(err, qt.IsNil) - c.Assert(out, qt.DeepEquals, in) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.DeepEquals(out, in)) }) } diff --git a/webtorrent/transport_test.go b/webtorrent/transport_test.go index c17328e8dd..b367d360ba 100644 --- a/webtorrent/transport_test.go +++ b/webtorrent/transport_test.go @@ -4,15 +4,14 @@ import ( "testing" "github.com/anacrolix/log" - qt "github.com/frankban/quicktest" + qt "github.com/go-quicktest/qt" "github.com/pion/webrtc/v3" ) func TestClosingPeerConnectionDoesNotCloseUnopenedDataChannel(t *testing.T) { - c := qt.New(t) var tc TrackerClient pc, dc, _, err := tc.newOffer(log.Default, "", [20]byte{}) - c.Assert(err, qt.IsNil) + qt.Assert(t, qt.IsNil(err)) defer pc.Close() defer dc.Close() peerConnClosed := make(chan struct{}) @@ -30,6 +29,6 @@ func TestClosingPeerConnectionDoesNotCloseUnopenedDataChannel(t *testing.T) { t.Logf("data channel error: %v", err) }) pc.Close() - c.Check(dc.ReadyState(), qt.Equals, webrtc.DataChannelStateClosed) + qt.Check(t, qt.Equals(dc.ReadyState(), webrtc.DataChannelStateClosed)) <-peerConnClosed } diff --git a/worse-conns_test.go b/worse-conns_test.go index 3865b648a5..21f764a8a5 100644 --- a/worse-conns_test.go +++ b/worse-conns_test.go @@ -4,41 +4,46 @@ import ( "testing" "time" - qt "github.com/frankban/quicktest" + "github.com/anacrolix/torrent/internal/qtnew" + qt "github.com/go-quicktest/qt" ) func TestWorseConnLastHelpful(t *testing.T) { - c := qt.New(t) - c.Check((&worseConnInput{}).Less(&worseConnInput{LastHelpful: time.Now()}), qt.IsTrue) - c.Check((&worseConnInput{}).Less(&worseConnInput{CompletedHandshake: time.Now()}), qt.IsTrue) - c.Check((&worseConnInput{LastHelpful: time.Now()}).Less(&worseConnInput{CompletedHandshake: time.Now()}), qt.IsFalse) - c.Check((&worseConnInput{ + c := qtnew.New(t) + qt.Check(c, qt.IsTrue((&worseConnInput{}).Less(&worseConnInput{LastHelpful: time.Now()}))) + qt.Check(c, qt.IsTrue((&worseConnInput{}).Less(&worseConnInput{CompletedHandshake: time.Now()}))) + qt.Check(c, qt.IsFalse((&worseConnInput{LastHelpful: time.Now()}).Less(&worseConnInput{CompletedHandshake: time.Now()}))) + qt.Check(c, qt.IsTrue((&worseConnInput{ LastHelpful: time.Now(), }).Less(&worseConnInput{ LastHelpful: time.Now(), CompletedHandshake: time.Now(), - }), qt.IsTrue) + }))) + now := time.Now() - c.Check((&worseConnInput{ + qt.Check(c, qt.IsFalse((&worseConnInput{ LastHelpful: now, }).Less(&worseConnInput{ LastHelpful: now.Add(-time.Nanosecond), CompletedHandshake: now, - }), qt.IsFalse) + }))) + readyPeerPriority := func() (peerPriority, error) { return 42, nil } - c.Check((&worseConnInput{ + qt.Check(c, qt.IsTrue((&worseConnInput{ GetPeerPriority: readyPeerPriority, }).Less(&worseConnInput{ GetPeerPriority: readyPeerPriority, Pointer: 1, - }), qt.IsTrue) - c.Check((&worseConnInput{ + }))) + + qt.Check(c, qt.IsFalse((&worseConnInput{ GetPeerPriority: readyPeerPriority, Pointer: 2, }).Less(&worseConnInput{ GetPeerPriority: readyPeerPriority, Pointer: 1, - }), qt.IsFalse) + }))) + }