github.com/anacrolix/torrent@v1.61.0/requesting_test.go (about) 1 package torrent 2 3 import ( 4 "testing" 5 6 "github.com/bradfitz/iter" 7 qt "github.com/go-quicktest/qt" 8 9 pp "github.com/anacrolix/torrent/peer_protocol" 10 ) 11 12 func keysAsSlice(m map[Request]struct{}) (sl []Request) { 13 for k := range m { 14 sl = append(sl, k) 15 } 16 return 17 } 18 19 func makeTypicalRequests() map[Request]struct{} { 20 m := make(map[Request]struct{}) 21 for p := pp.Integer(0); p < 4; p++ { 22 for c := pp.Integer(0); c < 16; c++ { 23 m[Request{p, ChunkSpec{c * defaultChunkSize, defaultChunkSize}}] = struct{}{} 24 } 25 } 26 return m 27 } 28 29 func TestLogExampleRequestMapOrdering(t *testing.T) { 30 for k := range makeTypicalRequests() { 31 t.Log(k) 32 } 33 } 34 35 func TestRequestMapOrderingPersistent(t *testing.T) { 36 m := makeTypicalRequests() 37 // Shows that map order is persistent across separate range statements. 38 qt.Assert(t, qt.ContentEquals(keysAsSlice(m), keysAsSlice(m))) 39 } 40 41 func TestRequestMapOrderAcrossInstances(t *testing.T) { 42 // This shows that different map instances with the same contents can have the same range order. 43 qt.Assert(t, qt.ContentEquals(keysAsSlice(makeTypicalRequests()), keysAsSlice(makeTypicalRequests()))) 44 } 45 46 // Added for testing repeating loop iteration after shuffling in Peer.applyRequestState. 47 func TestForLoopRepeatItem(t *testing.T) { 48 t.Run("ExplicitLoopVar", func(t *testing.T) { 49 once := false 50 var seen []int 51 for i := 0; i < 4; i++ { 52 seen = append(seen, i) 53 if !once && i == 2 { 54 once = true 55 i-- 56 // Will i++ still run? 57 continue 58 } 59 } 60 // We can mutate i and it's observed by the loop. No special treatment of the loop var. 61 qt.Assert(t, qt.DeepEquals(seen, []int{0, 1, 2, 2, 3})) 62 }) 63 t.Run("Range", func(t *testing.T) { 64 once := false 65 var seen []int 66 for i := range iter.N(4) { 67 seen = append(seen, i) 68 if !once && i == 2 { 69 once = true 70 // Can we actually modify the next value of i produced by the range? 71 i-- 72 continue 73 } 74 } 75 // Range ignores any mutation to i. 76 qt.Assert(t, qt.DeepEquals(seen, []int{0, 1, 2, 3})) 77 }) 78 }