1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ctpolicy
15
16 import (
17 "testing"
18 )
19
20 func TestWeightedRandomSampleDef(t *testing.T) {
21 tests := []struct {
22 name string
23 weights map[string]float32
24 wantItem string
25 wantErr bool
26 }{
27 {
28 name: "OneNegativeWeight",
29 weights: map[string]float32{"a": 0.5, "b": -0.5, "c": 3.0},
30 wantItem: "",
31 wantErr: true,
32 },
33 {
34 name: "AllZeroWeights",
35 weights: map[string]float32{"a": 0.0, "b": 0.0, "c": 0.0},
36 wantItem: "",
37 wantErr: true,
38 },
39 {
40 name: "OneNonZeroWeights",
41 weights: map[string]float32{"a": 0.0, "b": 4.0, "c": 0.0},
42 wantItem: "b",
43 wantErr: false,
44 },
45 }
46
47 for _, tc := range tests {
48 t.Run(tc.name, func(t *testing.T) {
49 gotItem, err := weightedRandomSample(tc.weights)
50 if gotErr := err != nil; gotErr != tc.wantErr {
51 t.Fatalf("weightedRandomSample(%v) = (_, error: %v), want err? %t", tc.weights, err, tc.wantErr)
52 }
53 if gotItem != tc.wantItem {
54 t.Errorf("weightedRandomSample(%v) = (%q, _) want %q", tc.weights, gotItem, tc.wantItem)
55 }
56 })
57 }
58 }
59
60 func TestWeightedRandomSampleInDef(t *testing.T) {
61 tests := []struct {
62 name string
63 weights map[string]float32
64 wantOneOf []string
65 wantErr bool
66 }{
67 {
68 name: "TwoWeights",
69 weights: map[string]float32{"a": 0.5, "b": 0.0, "c": 3.0},
70 wantOneOf: []string{"a", "c"},
71 wantErr: false,
72 },
73 }
74
75 for _, tc := range tests {
76 t.Run(tc.name, func(t *testing.T) {
77 gotItem, err := weightedRandomSample(tc.weights)
78 if gotErr := err != nil; gotErr != tc.wantErr {
79 t.Fatalf("weightedRandomSample(%v) = (_, error: %v), want err? %t", tc.weights, err, tc.wantErr)
80 }
81 for _, i := range tc.wantOneOf {
82 if i == gotItem {
83 return
84 }
85 }
86 t.Errorf("weightedRandomSample(%v) = (%q, _) want any item of %v", tc.weights, gotItem, tc.wantOneOf)
87 })
88 }
89 }
90
View as plain text