Skip to main content

Posts

Showing posts from September, 2017

About me

Hi,

I'm currently working as a software developer in the logistics industry in San Francisco. 
My aim is to impact billions of people's live for the better and make the world a better place.

Cheers,
Vignesh



Go lang: Return True specified Pct% of time

When writing test for state machines, I came across a need for a helper that would all call flow into a path some percentage% of times.

Eg:
func TestSelfDrivingCar_BasicRun(t *testing.T) {
car := NewMockCar(t)
car.Start()
if (/* 50% probability that this will happen */) {
car.SimulateLidarFailure()
} else if /* 25% probability that this will happen */ {
car.SimulateVisionFailure()
} else {
/* 25% probability that this will happen*/
car.SimulateGearBoxFailure()
}
car.VerifySafeTrajectory()
}

You can write a small Go helper like this:
package testutils

import (
"math/rand"
"time"
)

// Odds returns True to pct% number of Check() calls
type Odds interface {
Check() bool
}

// odds returns `true` pct% of times
type odds struct {
randgen *rand.Rand
pct int
}

// NewOdds returns a odds instance with the given percent vaule
func NewOdds(pct int) Odds {
src := rand.NewSource(time.Now().UnixNano())
return &odds{
randg…