github.com/ManabuSeki/goa-v1@v1.4.3/design/random.go (about)

     1  package design
     2  
     3  import (
     4  	"crypto/md5"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"math/rand"
     8  	"time"
     9  
    10  	"github.com/gofrs/uuid"
    11  	"github.com/manveru/faker"
    12  )
    13  
    14  // RandomGenerator generates consistent random values of different types given a seed.
    15  // The random values are consistent in that given the same seed the same random values get
    16  // generated.
    17  type RandomGenerator struct {
    18  	Seed  string
    19  	faker *faker.Faker
    20  	rand  *rand.Rand
    21  }
    22  
    23  // NewRandomGenerator returns a random value generator seeded from the given string value.
    24  func NewRandomGenerator(seed string) *RandomGenerator {
    25  	hasher := md5.New()
    26  	hasher.Write([]byte(seed))
    27  	sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil)))
    28  	source := rand.NewSource(sint)
    29  	ran := rand.New(source)
    30  	faker := &faker.Faker{
    31  		Language: "end",
    32  		Dict:     faker.Dict["en"],
    33  		Rand:     ran,
    34  	}
    35  	return &RandomGenerator{
    36  		Seed:  seed,
    37  		faker: faker,
    38  		rand:  ran,
    39  	}
    40  }
    41  
    42  // Int produces a random integer.
    43  func (r *RandomGenerator) Int() int {
    44  	return r.rand.Int()
    45  }
    46  
    47  // String produces a random string.
    48  func (r *RandomGenerator) String() string {
    49  	return r.faker.Sentence(2, false)
    50  
    51  }
    52  
    53  // DateTime produces a random date.
    54  func (r *RandomGenerator) DateTime() time.Time {
    55  	// Use a constant max value to make sure the same pseudo random
    56  	// values get generated for a given API.
    57  	max := time.Date(2016, time.July, 11, 23, 0, 0, 0, time.UTC).Unix()
    58  	unix := r.rand.Int63n(max)
    59  	return time.Unix(unix, 0).UTC()
    60  }
    61  
    62  // UUID produces a random UUID.
    63  func (r *RandomGenerator) UUID() uuid.UUID {
    64  	return uuid.Must(uuid.NewV4())
    65  }
    66  
    67  // Bool produces a random boolean.
    68  func (r *RandomGenerator) Bool() bool {
    69  	return r.rand.Int()%2 == 0
    70  }
    71  
    72  // Float64 produces a random float64 value.
    73  func (r *RandomGenerator) Float64() float64 {
    74  	return r.rand.Float64()
    75  }
    76  
    77  // File produces a random file.
    78  func (r *RandomGenerator) File() string {
    79  	return fmt.Sprintf("%sjpg", r.faker.Sentence(1, false))
    80  }