...

Source file src/github.com/concurrency-8/queue/queue_test.go

Documentation: github.com/concurrency-8/queue

     1  package queue
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/concurrency-8/parser"
     6  	"github.com/stretchr/testify/assert"
     7  	"math"
     8  	"math/rand"
     9  	"testing"
    10  )
    11  
    12  func getTorrentFile() parser.TorrentFile {
    13  	torrent, _ := parser.ParseFromFile("../test_torrents/ubuntu.iso.torrent")
    14  	return torrent
    15  }
    16  
    17  // TestQueue tests the queue functionality
    18  func TestQueue(t *testing.T) {
    19  	torrent := getTorrentFile()                                                 // get a torrent file
    20  	pieces := math.Floor(float64(torrent.Length / uint64(torrent.PieceLength))) // calculate number of pieces in file
    21  
    22  	// tests when making a Queue object
    23  	queue := NewQueue(torrent)
    24  	assert.Equal(t, queue.Choked, true, "Choked attribute not true by default")
    25  	assert.Equal(t, queue.Length(), 0, "Queue length not zero initially")
    26  
    27  	// testing enqueue() function
    28  	indexs := make([]uint32, 0)
    29  	rand.Seed(56)
    30  	epochs := rand.Intn(10)
    31  	totalLength := 0
    32  	for i := 0; i < epochs; i++ {
    33  		index := uint32(rand.Intn(int(pieces))) // generate index between numbe of pieces
    34  		err := queue.Enqueue(index)
    35  		assert.Equal(t, err, nil, "Error while enqueue ")
    36  		indexs = append(indexs, index)
    37  		block, err := queue.Peek()
    38  		assert.Equal(t, err, nil, "Error encountered while peeking ")
    39  		assert.Equal(t, block.Index, indexs[0], "Front element different in enqueue")
    40  		totalLength = totalLength + int(block.Nblocks)
    41  	}
    42  
    43  	assert.Equal(t, queue.Length(), totalLength, "Queue length not full after enqueue") // ensure queue is of full length
    44  
    45  	// testing dequeue() function
    46  	for i := 0; i < epochs; i++ {
    47  		block, err := queue.Peek()
    48  		assert.Equal(t, err, nil, "Error encountered while peeking")
    49  
    50  		for j := 0; j < int(block.Nblocks); j++ { // dequeue all blocks corresponding to a piece index
    51  			block, err := queue.Peek()
    52  			assert.Equal(t, err, nil, "Error encountered while peeking")
    53  			err = queue.Dequeue()
    54  			assert.Equal(t, err, nil, "Error encountered while dequeuing")
    55  			assert.Equal(t, block.Index, indexs[i], "Front element different in dequeue")
    56  		}
    57  
    58  	}
    59  
    60  	assert.Equal(t, queue.Length(), 0, "Queue length not zero finally")
    61  
    62  	fmt.Println("PASS")
    63  }
    64  

View as plain text