github.com/ZuluSpl0it/Sia@v1.3.7/modules/transactionpool/subscribe_test.go (about) 1 package transactionpool 2 3 import ( 4 "testing" 5 6 "github.com/NebulousLabs/Sia/modules" 7 "github.com/NebulousLabs/Sia/types" 8 ) 9 10 // mockSubscriber receives transactions from the transaction pool it is 11 // subscribed to, retaining them in the order they were received. 12 type mockSubscriber struct { 13 txnMap map[modules.TransactionSetID][]types.Transaction 14 txns []types.Transaction 15 } 16 17 // ReceiveUpdatedUnconfirmedTransactions receives transactinos from the 18 // transaction pool and stores them in the order they were received. 19 // This method allows *mockSubscriber to satisfy the 20 // modules.TransactionPoolSubscriber interface. 21 func (ms *mockSubscriber) ReceiveUpdatedUnconfirmedTransactions(diff *modules.TransactionPoolDiff) { 22 for _, revert := range diff.RevertedTransactions { 23 delete(ms.txnMap, revert) 24 } 25 for _, uts := range diff.AppliedTransactions { 26 ms.txnMap[uts.ID] = uts.Transactions 27 } 28 ms.txns = nil 29 for _, txnSet := range ms.txnMap { 30 ms.txns = append(ms.txns, txnSet...) 31 } 32 } 33 34 // TestSubscription checks that calling Unsubscribe on a mockSubscriber 35 // shortens the list of subscribers to the transaction pool by 1 (doesn't 36 // actually check that the mockSubscriber was the one unsubscribed). 37 func TestSubscription(t *testing.T) { 38 if testing.Short() { 39 t.Skip() 40 } 41 42 tpt, err := createTpoolTester(t.Name()) 43 if err != nil { 44 t.Fatal(err) 45 } 46 defer tpt.Close() 47 48 // Check the transaction pool is empty when initialized. 49 if len(tpt.tpool.transactionSets) != 0 { 50 t.Fatal("transaction pool is not empty") 51 } 52 53 // Create a mock subscriber and subscribe it to the transaction pool. 54 ms := mockSubscriber{ 55 txnMap: make(map[modules.TransactionSetID][]types.Transaction), 56 } 57 tpt.tpool.TransactionPoolSubscribe(&ms) 58 if len(ms.txns) != 0 { 59 t.Fatalf("mock subscriber has received %v transactions; shouldn't have received any yet", len(ms.txns)) 60 } 61 62 // Create a valid transaction set and check that the mock subscriber's 63 // transaction list is updated. 64 _, err = tpt.wallet.SendSiacoins(types.NewCurrency64(100), types.UnlockHash{}) 65 if err != nil { 66 t.Fatal(err) 67 } 68 if len(tpt.tpool.transactionSets) != 1 { 69 t.Error("sending coins didn't increase the transaction sets by 1") 70 } 71 numTxns := 0 72 for _, txnSet := range tpt.tpool.transactionSets { 73 numTxns += len(txnSet) 74 } 75 if len(ms.txns) != numTxns { 76 t.Errorf("mock subscriber should've received %v transactions; received %v instead", numTxns, len(ms.txns)) 77 } 78 79 numSubscribers := len(tpt.tpool.subscribers) 80 tpt.tpool.Unsubscribe(&ms) 81 if len(tpt.tpool.subscribers) != numSubscribers-1 { 82 t.Error("transaction pool failed to unsubscribe mock subscriber") 83 } 84 }