[PATCH nft 2/3] tests/shell: add "random-source.sh" helper for random-source for sort/shuf

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Commands `sort` and `shuf` have a "--random-source" argument. That's
useful for generating stable, reproducible "random" output.

However, we want to do this based on a fixed seed, while the
"--random-source" expects a stream of randomness. Add a helper script
for that.

Also, use the stable randomness for shuf in the test
"tests/shell/testcases/sets/automerge_0".

See-also: https://www.gnu.org/software/coreutils/manual/html_node/Random-sources.html#Random-sources

Signed-off-by: Thomas Haller <thaller@xxxxxxxxxx>
---
 tests/shell/helpers/random-source.sh   | 40 ++++++++++++++++++++++++++
 tests/shell/testcases/sets/automerge_0 |  2 +-
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100755 tests/shell/helpers/random-source.sh

diff --git a/tests/shell/helpers/random-source.sh b/tests/shell/helpers/random-source.sh
new file mode 100755
index 000000000000..91a8248bea1f
--- /dev/null
+++ b/tests/shell/helpers/random-source.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+# Commands like `sort` and `shuf` have a "--random-source" argument, for
+# generating a stable, reproducible output. However, they require an input
+# that provides sufficiently many bytes (depending on the input).
+#
+# This script generates a stream that can be used like
+#
+#     shuf --random-source=<($0 "$seed")
+
+seed=""
+for a; do
+	seed="$seed${#a}:$a\n"
+done
+
+if command -v openssl &>/dev/null ; then
+	# We have openssl. Use it.
+	# https://www.gnu.org/software/coreutils/manual/html_node/Random-sources.html#Random-sources
+	#
+	# Note that we don't care that different installations/architectures generate the
+	# same output.
+	openssl enc -aes-256-ctr -pass "pass:$seed" -nosalt </dev/zero 2>/dev/null
+else
+	# Hack something. It's much slower.
+	idx=0
+	while : ; do
+		idx="$((idx++))"
+		seed="$(sha256sum <<<"$idx.$seed")"
+		echo ">>>$seed" >> a
+		seed="${seed%% *}"
+		LANG=C awk -v s="$seed" 'BEGIN{
+			for (i=1; i <= length(s); i+=2) {
+				xchar = substr(s, i, 2);
+				decnum = strtonum("0x"xchar);
+				printf("%c", decnum);
+			}
+		}' || break
+	done
+fi
+exit 0
diff --git a/tests/shell/testcases/sets/automerge_0 b/tests/shell/testcases/sets/automerge_0
index 170c38651de0..1dbac0b7cdbd 100755
--- a/tests/shell/testcases/sets/automerge_0
+++ b/tests/shell/testcases/sets/automerge_0
@@ -44,7 +44,7 @@ do
 done
 
 tmpfile3=$(mktemp)
-shuf $tmpfile2 > $tmpfile3
+shuf "$tmpfile2" --random-source=<("$NFT_TEST_BASEDIR/helpers/random-source.sh" "automerge-shuf-tmpfile2" "$NFT_TEST_RANDOM_SEED") > "$tmpfile3"
 i=0
 cat $tmpfile3 | while read line && [ $i -lt 10 ]
 do
-- 
2.41.0




[Index of Archives]     [Netfitler Users]     [Berkeley Packet Filter]     [LARTC]     [Bugtraq]     [Yosemite Forum]

  Powered by Linux