rand_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package stdlib_test
  2. import (
  3. "math/rand"
  4. "testing"
  5. "github.com/d5/tengo/v2"
  6. "github.com/d5/tengo/v2/require"
  7. )
  8. func TestRand(t *testing.T) {
  9. var seed int64 = 1234
  10. r := rand.New(rand.NewSource(seed))
  11. module(t, "rand").call("seed", seed).expect(tengo.UndefinedValue)
  12. module(t, "rand").call("int").expect(r.Int63())
  13. module(t, "rand").call("float").expect(r.Float64())
  14. module(t, "rand").call("intn", 111).expect(r.Int63n(111))
  15. module(t, "rand").call("exp_float").expect(r.ExpFloat64())
  16. module(t, "rand").call("norm_float").expect(r.NormFloat64())
  17. module(t, "rand").call("perm", 10).expect(r.Perm(10))
  18. buf1 := make([]byte, 10)
  19. buf2 := &tengo.Bytes{Value: make([]byte, 10)}
  20. n, _ := r.Read(buf1)
  21. module(t, "rand").call("read", buf2).expect(n)
  22. require.Equal(t, buf1, buf2.Value)
  23. seed = 9191
  24. r = rand.New(rand.NewSource(seed))
  25. randObj := module(t, "rand").call("rand", seed)
  26. randObj.call("seed", seed).expect(tengo.UndefinedValue)
  27. randObj.call("int").expect(r.Int63())
  28. randObj.call("float").expect(r.Float64())
  29. randObj.call("intn", 111).expect(r.Int63n(111))
  30. randObj.call("exp_float").expect(r.ExpFloat64())
  31. randObj.call("norm_float").expect(r.NormFloat64())
  32. randObj.call("perm", 10).expect(r.Perm(10))
  33. buf1 = make([]byte, 12)
  34. buf2 = &tengo.Bytes{Value: make([]byte, 12)}
  35. n, _ = r.Read(buf1)
  36. randObj.call("read", buf2).expect(n)
  37. require.Equal(t, buf1, buf2.Value)
  38. }