github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/dynamicbanscore_test.go (about)

     1  // Copyright (c) 2016 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package main
     7  
     8  import (
     9  	"math"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  // TestDynamicBanScoreDecay tests the exponential decay implemented in
    15  // dynamicBanScore.
    16  func TestDynamicBanScoreDecay(t *testing.T) {
    17  	var bs dynamicBanScore
    18  	base := time.Now()
    19  
    20  	r := bs.increase(100, 50, base)
    21  	if r != 150 {
    22  		t.Errorf("Unexpected result %d after ban score increase.", r)
    23  	}
    24  
    25  	r = bs.int(base.Add(time.Minute))
    26  	if r != 125 {
    27  		t.Errorf("Halflife check failed - %d instead of 125", r)
    28  	}
    29  
    30  	r = bs.int(base.Add(7 * time.Minute))
    31  	if r != 100 {
    32  		t.Errorf("Decay after 7m - %d instead of 100", r)
    33  	}
    34  }
    35  
    36  // TestDynamicBanScoreLifetime tests that dynamicBanScore properly yields zero
    37  // once the maximum age is reached.
    38  func TestDynamicBanScoreLifetime(t *testing.T) {
    39  	var bs dynamicBanScore
    40  	base := time.Now()
    41  
    42  	r := bs.increase(0, math.MaxUint32, base)
    43  	r = bs.int(base.Add(Lifetime * time.Second))
    44  	if r != 3 { // 3, not 4 due to precision loss and truncating 3.999...
    45  		t.Errorf("Pre max age check with MaxUint32 failed - %d", r)
    46  	}
    47  	r = bs.int(base.Add((Lifetime + 1) * time.Second))
    48  	if r != 0 {
    49  		t.Errorf("Zero after max age check failed - %d instead of 0", r)
    50  	}
    51  }
    52  
    53  // TestDynamicBanScore tests exported functions of dynamicBanScore. Exponential
    54  // decay or other time based behavior is tested by other functions.
    55  func TestDynamicBanScoreReset(t *testing.T) {
    56  	var bs dynamicBanScore
    57  	if bs.Int() != 0 {
    58  		t.Errorf("Initial state is not zero.")
    59  	}
    60  	bs.Increase(100, 0)
    61  	r := bs.Int()
    62  	if r != 100 {
    63  		t.Errorf("Unexpected result %d after ban score increase.", r)
    64  	}
    65  	bs.Reset()
    66  	if bs.Int() != 0 {
    67  		t.Errorf("Failed to reset ban score.")
    68  	}
    69  }