github.com/decred/dcrlnd@v0.7.6/htlcswitch/queue_test.go (about)

     1  package htlcswitch
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/decred/dcrlnd/lnwire"
     9  )
    10  
    11  // TestWaitingQueueThreadSafety test the thread safety properties of the
    12  // waiting queue, by executing methods in separate goroutines which operates
    13  // with the same data.
    14  func TestWaitingQueueThreadSafety(t *testing.T) {
    15  	t.Parallel()
    16  
    17  	const numPkts = 1000
    18  
    19  	q := newPacketQueue(numPkts)
    20  	q.Start()
    21  	defer q.Stop()
    22  
    23  	a := make([]uint64, numPkts)
    24  	for i := 0; i < numPkts; i++ {
    25  		a[i] = uint64(i)
    26  		q.AddPkt(&htlcPacket{
    27  			incomingHTLCID: a[i],
    28  			htlc:           &lnwire.UpdateAddHTLC{},
    29  		})
    30  	}
    31  
    32  	// The reported length of the queue should be the exact number of
    33  	// packets we added above.
    34  	queueLength := q.Length()
    35  	if queueLength != numPkts {
    36  		t.Fatalf("queue has wrong length: expected %v, got %v", numPkts,
    37  			queueLength)
    38  	}
    39  
    40  	var b []uint64
    41  	for i := 0; i < numPkts; i++ {
    42  		q.SignalFreeSlot()
    43  
    44  		select {
    45  		case packet := <-q.outgoingPkts:
    46  			b = append(b, packet.incomingHTLCID)
    47  
    48  		case <-time.After(2 * time.Second):
    49  			t.Fatal("timeout")
    50  		}
    51  	}
    52  
    53  	// The length of the queue should be zero at this point.
    54  	time.Sleep(time.Millisecond * 50)
    55  	queueLength = q.Length()
    56  	if queueLength != 0 {
    57  		t.Fatalf("queue has wrong length: expected %v, got %v", 0,
    58  			queueLength)
    59  	}
    60  
    61  	if !reflect.DeepEqual(b, a) {
    62  		t.Fatal("wrong order of the objects")
    63  	}
    64  }