author | Alberto Bertogli
<albertito@blitiri.com.ar> 2018-05-21 11:30:45 UTC |
committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2018-05-21 11:30:45 UTC |
parent | 780aa563571b8d974ec740d019a91b5057cdf18e |
libfiu/fiu.c | +7 | -0 |
tests/test-set_prng_seed-env.py | +17 | -0 |
diff --git a/libfiu/fiu.c b/libfiu/fiu.c index e49bfc2..df81669 100644 --- a/libfiu/fiu.c +++ b/libfiu/fiu.c @@ -231,6 +231,8 @@ static void atfork_child(void) * time without clashes. */ int fiu_init(unsigned int flags) { + char *static_seed_from_env; + /* Used to avoid re-initialization, protected by enabled_fails_lock */ static int initialized = 0; @@ -252,6 +254,11 @@ int fiu_init(unsigned int flags) return -1; } + static_seed_from_env = getenv("FIU_PRNG_SEED"); + if (static_seed_from_env != NULL) { + fiu_set_prng_seed(atoi(static_seed_from_env)); + } + prng_seed(); initialized = 1; diff --git a/tests/test-set_prng_seed-env.py b/tests/test-set_prng_seed-env.py new file mode 100644 index 0000000..78d4412 --- /dev/null +++ b/tests/test-set_prng_seed-env.py @@ -0,0 +1,17 @@ +""" +Test that we get reproducible results when setting PRNG seed via the +environment. +""" + +# Set the environment variable _before_ initializing the library. +import os +os.environ["FIU_PRNG_SEED"] = "1234" + +import fiu + +fiu.enable_random('p1', probability = 0.5) +result = { True: 0, False: 0 } +for i in range(1000): + result[fiu.fail('p1')] += 1 + +assert result == {False: 516, True: 484}, result