github.com/leanovate/gopter@v0.2.9/gen/weighted_test.go (about)

     1  package gen_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/leanovate/gopter/gen"
     7  )
     8  
     9  func TestWeighted(t *testing.T) {
    10  	weighted := gen.Weighted([]gen.WeightedGen{
    11  		{Weight: 1, Gen: gen.Const("A")},
    12  		{Weight: 2, Gen: gen.Const("B")},
    13  		{Weight: 7, Gen: gen.Const("C")},
    14  	})
    15  	results := make(map[string]int)
    16  	for i := int64(0); i < int64(1000); i++ {
    17  		result, ok := weighted.Sample()
    18  		if !ok {
    19  			t.FailNow()
    20  		}
    21  		results[result.(string)]++
    22  	}
    23  	expectedResults := map[string]int{
    24  		"A": 100,
    25  		"B": 200,
    26  		"C": 700,
    27  	}
    28  	delta := 50
    29  	for _, value := range []string{"A", "B", "C"} {
    30  		result := results[value]
    31  		expected := expectedResults[value]
    32  		if result < expected-delta || result > expected+delta {
    33  			t.Errorf(
    34  				"Result %d for %v falls outside acceptable range %d, %d",
    35  				result,
    36  				value,
    37  				expected-delta,
    38  				expected+delta)
    39  		}
    40  	}
    41  }