From f2a08f7b6c7bf9e26a1e8958e034958a53e6752e Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Thu, 4 Dec 2014 19:22:20 +0100 Subject: [PATCH 1/2] Some tests for crypt_random_string(). --- tests/Unit/Crypt/RandomTest.php | 52 +++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 tests/Unit/Crypt/RandomTest.php diff --git a/tests/Unit/Crypt/RandomTest.php b/tests/Unit/Crypt/RandomTest.php new file mode 100644 index 00000000..9be9940f --- /dev/null +++ b/tests/Unit/Crypt/RandomTest.php @@ -0,0 +1,52 @@ + + * @copyright MMXIV Andreas Fischer + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +class Unit_Crypt_RandomTest extends PhpseclibTestCase +{ + public function stringLengthData() + { + return array_map(array($this, 'wrap'), array( + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 20, 23, 29, 31, 37, + 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 111, 128, 1000, + 1024, 10000, 12345, 100000, 123456 + )); + } + + /** @dataProvider stringLengthData */ + public function testStringLength($length) + { + $this->assertSame( + $length, + strlen(crypt_random_string($length)), + 'Failed asserting that a string of expected length was generated.' + ); + } + + /** + * Takes a set of random values of length 128 bits and asserts all taken + * values are unique. + */ + public function testStringUniqueness() + { + $values = array(); + for ($i = 0; $i < 10000; ++$i) { + $rand = crypt_random_string(16); + $this->assertSame(16, strlen($rand)); + $this->assertFalse( + isset($values[$rand]), + 'Failed asserting that generated value does not exist in set.' + ); + $values[$rand] = true; + } + } + + protected function wrap($x) + { + // array() is not a function, but $this->wrap() is. + return array($x); + } +} From d6c210984ca8ce32eb3bef517a8a7e9e00c33f8c Mon Sep 17 00:00:00 2001 From: Andreas Fischer Date: Fri, 5 Dec 2014 00:18:45 +0100 Subject: [PATCH 2/2] Use assertArrayNotHasKey(). --- tests/Unit/Crypt/RandomTest.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/Unit/Crypt/RandomTest.php b/tests/Unit/Crypt/RandomTest.php index 9be9940f..f72640fe 100644 --- a/tests/Unit/Crypt/RandomTest.php +++ b/tests/Unit/Crypt/RandomTest.php @@ -36,8 +36,9 @@ class Unit_Crypt_RandomTest extends PhpseclibTestCase for ($i = 0; $i < 10000; ++$i) { $rand = crypt_random_string(16); $this->assertSame(16, strlen($rand)); - $this->assertFalse( - isset($values[$rand]), + $this->assertArrayNotHasKey( + $rand, + $values, 'Failed asserting that generated value does not exist in set.' ); $values[$rand] = true;