git » libfiu » commit 059ca8b

Allow users to set the PRNG seed via the environment

author Alberto Bertogli
2018-05-21 11:30:45 UTC
committer Alberto Bertogli
2018-05-21 11:30:45 UTC
parent 780aa563571b8d974ec740d019a91b5057cdf18e

Allow users to set the PRNG seed via the environment

To simplify the set of PRNG seeds, this patch makes fiu_init() get the
seed from the FIU_PRNG_SEED environment variable, if present.

This makes it easier for automated tests to control the seed without
needing to instrument the code.

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