RandomTest.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Test \Magento\Framework\Math\Random
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Math\Test\Unit;
  9. class RandomTest extends \PHPUnit\Framework\TestCase
  10. {
  11. /**
  12. * @param int $length
  13. * @param string $chars
  14. *
  15. * @dataProvider getRandomStringDataProvider
  16. */
  17. public function testGetRandomString($length, $chars = null)
  18. {
  19. $mathRandom = new \Magento\Framework\Math\Random();
  20. $string = $mathRandom->getRandomString($length, $chars);
  21. $this->assertEquals($length, strlen($string));
  22. if ($chars !== null) {
  23. $this->_assertContainsOnlyChars($string, $chars);
  24. }
  25. }
  26. /**
  27. * @return array
  28. */
  29. public function getRandomStringDataProvider()
  30. {
  31. return [
  32. [0],
  33. [10],
  34. [10, \Magento\Framework\Math\Random::CHARS_LOWERS],
  35. [10, \Magento\Framework\Math\Random::CHARS_UPPERS],
  36. [10, \Magento\Framework\Math\Random::CHARS_DIGITS],
  37. [
  38. 20,
  39. \Magento\Framework\Math\Random::CHARS_LOWERS .
  40. \Magento\Framework\Math\Random::CHARS_UPPERS .
  41. \Magento\Framework\Math\Random::CHARS_DIGITS
  42. ]
  43. ];
  44. }
  45. public function testGetUniqueHash()
  46. {
  47. $mathRandom = new \Magento\Framework\Math\Random();
  48. $hashOne = $mathRandom->getUniqueHash();
  49. $hashTwo = $mathRandom->getUniqueHash();
  50. $this->assertTrue(is_string($hashOne));
  51. $this->assertTrue(is_string($hashTwo));
  52. $this->assertNotEquals($hashOne, $hashTwo);
  53. }
  54. /**
  55. * @param string $string
  56. * @param string $chars
  57. */
  58. protected function _assertContainsOnlyChars($string, $chars)
  59. {
  60. if (preg_match('/[^' . $chars . ']+/', $string, $matches)) {
  61. $this->fail(sprintf('Unexpected char "%s" found', $matches[0]));
  62. }
  63. }
  64. /**
  65. * @param $min
  66. * @param $max
  67. *
  68. * @dataProvider testGetRandomNumberProvider
  69. */
  70. public function testGetRandomNumber($min, $max)
  71. {
  72. $number = \Magento\Framework\Math\Random::getRandomNumber($min, $max);
  73. $this->assertLessThanOrEqual($max, $number);
  74. $this->assertGreaterThanOrEqual($min, $number);
  75. }
  76. /**
  77. * @return array
  78. */
  79. public function testGetRandomNumberProvider()
  80. {
  81. return [
  82. [0, 100],
  83. [0, 1],
  84. [0, 0],
  85. [-1, 0],
  86. [-100, 0],
  87. [-1, 1],
  88. [-100, 100]
  89. ];
  90. }
  91. }