github.com/swaros/contxt/module/runner@v0.0.0-20240305083542-3dbd4436ac40/randcolor_test.go (about) 1 package runner_test 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/swaros/contxt/module/runner" 8 ) 9 10 func TestColorPick(t *testing.T) { 11 randColor := runner.NewRandColorStore() 12 13 // create a couple of colors with different target names 14 // and lets check if we hit some twice 15 colors := []runner.RandColor{} 16 for i := 0; i < randColor.GetMaxVariants(); i++ { 17 targetName := "test" + fmt.Sprintf("_%v", i) 18 colorPicked := randColor.GetOrSetIndexColor(targetName) 19 // just using this test for also testing the IsUnused() method 20 if !randColor.IsInusage(colorPicked) { 21 t.Error("whoops. this color :", colorPicked, "for target:", targetName, " MUST be detected as used") 22 } 23 for inx, color := range colors { 24 if colorPicked == color { 25 t.Error("color picked twice:", colorPicked, "for target:", targetName, "already picked for index:", inx) 26 } 27 } 28 29 colors = append(colors, colorPicked) 30 } 31 } 32 33 func TestColorPickRand(t *testing.T) { 34 randColor := runner.NewRandColorStore() 35 36 successCount := 0 37 failCount := 0 38 39 // create a couple of colors with different target names 40 // and lets check if we hit some twice 41 colors := []runner.RandColor{} 42 for i := 0; i < randColor.GetMaxVariants(); i++ { 43 targetName := "test" + fmt.Sprintf("_%v", i) 44 colorPicked, wasUnused := randColor.GetOrSetRandomColor(targetName) 45 46 // lets check if we get the same color again for the same task 47 colorPicked2, wasUnused2 := randColor.GetOrSetRandomColor(targetName) 48 if colorPicked != colorPicked2 { 49 t.Error("color picked twice:", colorPicked, "for target:", targetName, "already picked for index:", i) 50 } 51 if !wasUnused2 { 52 t.Error("wasUnused could not be false if we requesting an existing color:", targetName) 53 } 54 55 if wasUnused { 56 successCount++ 57 for inx, color := range colors { 58 if colorPicked == color { 59 t.Error( 60 "color picked twice:", 61 colorPicked, "for target:", 62 targetName, "already picked for index:", 63 inx, 64 ) 65 } 66 } 67 } else { 68 failCount++ 69 } 70 71 colors = append(colors, colorPicked) 72 } 73 // we accept a 10% fail rate 74 // there is always a chance that we hit a color twice 75 if failCount > successCount/10 { 76 t.Error("fail rate to high:", failCount, "of", randColor.GetMaxVariants()) 77 } 78 } 79 80 func TestColorPickRandom(t *testing.T) { 81 // just test if we ever get an error 82 // if we try to pick a color 2000 times. 83 // an error would be an go error, because we would hit an index out of range. 84 for i := 0; i < 2000; i++ { 85 runner.PickRandColor() 86 } 87 } 88 89 func TestLastInstance(t *testing.T) { 90 randColor := runner.NewRandColorStore() 91 if randColor != runner.LastRandColorInstance() { 92 t.Error("last instance is not the same as the new instance") 93 } 94 }