Getting seeds and using random numbers in ExUnit test cases

I have a test case that should use a random integer, so I have:

test "test with random integer" do IO.inspect :random.uniform(10) assert true end 

This always prints 4 when I run it, although I can see different samples in the output to the console:

 Randomized with seed 197796 ... Randomized with seed 124069 

I know that I should use :random.seed/1 or :random.seed/3 . I want to use the same seed that will be printed at the end of the test output. That way, if my test fails, I can play it using

 mix test --seed 124069 

I cannot do this if I use :random.seed(:erlang.now) , for example.

How can I get the seed that ExUnit uses to randomize its test cases inside a test case?

+6
source share
2 answers

The problem is that only manual settings are available on call

 ExUnit.configuration 

So, I set the seed manually in my test_helpers.exs :

 ExUnit.configure seed: elem(:os.timestamp, 2) 

Seed is set in the same way by ExUnit, unless I specify manually: https://github.com/elixir-lang/elixir/blob/master/lib/ex_unit/lib/ex_unit/runner.ex#L54

Now in my test I can do:

 s = ExUnit.configuration |> Keyword.get(:seed) :random.seed(s, s, s) #random enough for me IO.inspect :random.uniform(5) 

Every time I run tests, I get a good random value, but if I use

 mix test --seed <seed> 

I get the same value every time.

+5
source

At the time of receiving this answer, a random initial number is available inside your tests by phone:

 ExUnit.configuration()[:seed] 

This is very good for any tests that are dynamic and have random numbers, but must be repeatable for debugging, which was the purpose of the question. For example, if you want a number from 0 to 9, you can use:

  seedable_random_number_under_10 = rem(ExUnit.configuration()[:seed], 10) 
0
source

Source: https://habr.com/ru/post/1247035/


All Articles