SodiumTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * The RandomLib library for securely generating random numbers and strings in PHP
  4. *
  5. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  6. * @copyright 2011 The Authors
  7. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  8. * @version Build @@version@@
  9. */
  10. namespace RandomLib\Source;
  11. use SecurityLib\Strength;
  12. class SodiumTest extends \PHPUnit_Framework_TestCase
  13. {
  14. public function setUp()
  15. {
  16. if (!extension_loaded('libsodium')) {
  17. $this->markTestSkipped('The libsodium extension is not loaded');
  18. }
  19. }
  20. public static function provideGenerate()
  21. {
  22. $data = array();
  23. for ($i = 1; $i < 100; $i += 5) {
  24. $not = str_repeat(chr(0), $i);
  25. $data[] = array($i, $not);
  26. }
  27. return $data;
  28. }
  29. public function testGetStrength()
  30. {
  31. $strength = new Strength(Strength::HIGH);
  32. $actual = Sodium::getStrength();
  33. $this->assertEquals($actual, $strength);
  34. }
  35. /**
  36. * @dataProvider provideGenerate
  37. */
  38. public function testGenerate($length, $not)
  39. {
  40. if (!extension_loaded('libsodium')) {
  41. $this->markTestSkipped('The libsodium extension is not loaded');
  42. }
  43. $rand = new Sodium();
  44. $stub = $rand->generate($length);
  45. $this->assertEquals($length, strlen($stub));
  46. $this->assertNotEquals($not, $stub);
  47. }
  48. /**
  49. * @dataProvider provideGenerate
  50. */
  51. public function testGenerateWithoutLibsodium($length, $not)
  52. {
  53. $rand = new Sodium(false);
  54. $stub = $rand->generate($length);
  55. $this->assertEquals($length, strlen($stub));
  56. $this->assertEquals($not, $stub);
  57. }
  58. public function testGenerateWithZeroLength()
  59. {
  60. if (!extension_loaded('libsodium')) {
  61. $this->markTestSkipped('The libsodium extension is not loaded');
  62. }
  63. $rand = new Sodium();
  64. $stub = $rand->generate(0);
  65. $this->assertEquals(0, strlen($stub));
  66. $this->assertEquals('', $stub);
  67. }
  68. public function testGenerateWithZeroLengthWithoutLibsodium()
  69. {
  70. $rand = new Sodium(false);
  71. $stub = $rand->generate(0);
  72. $this->assertEquals(0, strlen($stub));
  73. $this->assertEquals('', $stub);
  74. }
  75. }