BaseTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. namespace Faker\Test\Provider;
  3. use Faker\Provider\Base as BaseProvider;
  4. use PHPUnit\Framework\TestCase;
  5. use Traversable;
  6. class BaseTest extends TestCase
  7. {
  8. public function testRandomDigitReturnsInteger()
  9. {
  10. $this->assertInternalType('integer', BaseProvider::randomDigit());
  11. }
  12. public function testRandomDigitReturnsDigit()
  13. {
  14. $this->assertGreaterThanOrEqual(0, BaseProvider::randomDigit());
  15. $this->assertLessThan(10, BaseProvider::randomDigit());
  16. }
  17. public function testRandomDigitNotNullReturnsNotNullDigit()
  18. {
  19. $this->assertGreaterThan(0, BaseProvider::randomDigitNotNull());
  20. $this->assertLessThan(10, BaseProvider::randomDigitNotNull());
  21. }
  22. public function testRandomDigitNotReturnsValidDigit()
  23. {
  24. for ($i = 0; $i <= 9; $i++) {
  25. $this->assertGreaterThanOrEqual(0, BaseProvider::randomDigitNot($i));
  26. $this->assertLessThan(10, BaseProvider::randomDigitNot($i));
  27. $this->assertNotSame(BaseProvider::randomDigitNot($i), $i);
  28. }
  29. }
  30. /**
  31. * @expectedException \InvalidArgumentException
  32. */
  33. public function testRandomNumberThrowsExceptionWhenCalledWithAMax()
  34. {
  35. BaseProvider::randomNumber(5, 200);
  36. }
  37. /**
  38. * @expectedException \InvalidArgumentException
  39. */
  40. public function testRandomNumberThrowsExceptionWhenCalledWithATooHighNumberOfDigits()
  41. {
  42. BaseProvider::randomNumber(10);
  43. }
  44. public function testRandomNumberReturnsInteger()
  45. {
  46. $this->assertInternalType('integer', BaseProvider::randomNumber());
  47. $this->assertInternalType('integer', BaseProvider::randomNumber(5, false));
  48. }
  49. public function testRandomNumberReturnsDigit()
  50. {
  51. $this->assertGreaterThanOrEqual(0, BaseProvider::randomNumber(3));
  52. $this->assertLessThan(1000, BaseProvider::randomNumber(3));
  53. }
  54. public function testRandomNumberAcceptsStrictParamToEnforceNumberSize()
  55. {
  56. $this->assertEquals(5, strlen((string) BaseProvider::randomNumber(5, true)));
  57. }
  58. public function testNumberBetween()
  59. {
  60. $min = 5;
  61. $max = 6;
  62. $this->assertGreaterThanOrEqual($min, BaseProvider::numberBetween($min, $max));
  63. $this->assertGreaterThanOrEqual(BaseProvider::numberBetween($min, $max), $max);
  64. }
  65. public function testNumberBetweenAcceptsZeroAsMax()
  66. {
  67. $this->assertEquals(0, BaseProvider::numberBetween(0, 0));
  68. }
  69. public function testRandomFloat()
  70. {
  71. $min = 4;
  72. $max = 10;
  73. $nbMaxDecimals = 8;
  74. $result = BaseProvider::randomFloat($nbMaxDecimals, $min, $max);
  75. $parts = explode('.', $result);
  76. $this->assertInternalType('float', $result);
  77. $this->assertGreaterThanOrEqual($min, $result);
  78. $this->assertLessThanOrEqual($max, $result);
  79. $this->assertLessThanOrEqual($nbMaxDecimals, strlen($parts[1]));
  80. }
  81. public function testRandomLetterReturnsString()
  82. {
  83. $this->assertInternalType('string', BaseProvider::randomLetter());
  84. }
  85. public function testRandomLetterReturnsSingleLetter()
  86. {
  87. $this->assertEquals(1, strlen(BaseProvider::randomLetter()));
  88. }
  89. public function testRandomLetterReturnsLowercaseLetter()
  90. {
  91. $lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
  92. $this->assertNotFalse(strpos($lowercaseLetters, BaseProvider::randomLetter()));
  93. }
  94. public function testRandomAsciiReturnsString()
  95. {
  96. $this->assertInternalType('string', BaseProvider::randomAscii());
  97. }
  98. public function testRandomAsciiReturnsSingleCharacter()
  99. {
  100. $this->assertEquals(1, strlen(BaseProvider::randomAscii()));
  101. }
  102. public function testRandomAsciiReturnsAsciiCharacter()
  103. {
  104. $lowercaseLetters = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
  105. $this->assertNotFalse(strpos($lowercaseLetters, BaseProvider::randomAscii()));
  106. }
  107. public function testRandomElementReturnsNullWhenArrayEmpty()
  108. {
  109. $this->assertNull(BaseProvider::randomElement(array()));
  110. }
  111. public function testRandomElementReturnsNullWhenCollectionEmpty()
  112. {
  113. $this->assertNull(BaseProvider::randomElement(new Collection(array())));
  114. }
  115. public function testRandomElementReturnsElementFromArray()
  116. {
  117. $elements = array('23', 'e', 32, '#');
  118. $this->assertContains(BaseProvider::randomElement($elements), $elements);
  119. }
  120. public function testRandomElementReturnsElementFromAssociativeArray()
  121. {
  122. $elements = array('tata' => '23', 'toto' => 'e', 'tutu' => 32, 'titi' => '#');
  123. $this->assertContains(BaseProvider::randomElement($elements), $elements);
  124. }
  125. public function testRandomElementReturnsElementFromCollection()
  126. {
  127. $collection = new Collection(array('one', 'two', 'three'));
  128. $this->assertContains(BaseProvider::randomElement($collection), $collection);
  129. }
  130. public function testShuffleReturnsStringWhenPassedAStringArgument()
  131. {
  132. $this->assertInternalType('string', BaseProvider::shuffle('foo'));
  133. }
  134. public function testShuffleReturnsArrayWhenPassedAnArrayArgument()
  135. {
  136. $this->assertInternalType('array', BaseProvider::shuffle(array(1, 2, 3)));
  137. }
  138. /**
  139. * @expectedException \InvalidArgumentException
  140. */
  141. public function testShuffleThrowsExceptionWhenPassedAnInvalidArgument()
  142. {
  143. BaseProvider::shuffle(false);
  144. }
  145. public function testShuffleArraySupportsEmptyArrays()
  146. {
  147. $this->assertEquals(array(), BaseProvider::shuffleArray(array()));
  148. }
  149. public function testShuffleArrayReturnsAnArrayOfTheSameSize()
  150. {
  151. $array = array(1, 2, 3, 4, 5);
  152. $this->assertSameSize($array, BaseProvider::shuffleArray($array));
  153. }
  154. public function testShuffleArrayReturnsAnArrayWithSameElements()
  155. {
  156. $array = array(2, 4, 6, 8, 10);
  157. $shuffleArray = BaseProvider::shuffleArray($array);
  158. $this->assertContains(2, $shuffleArray);
  159. $this->assertContains(4, $shuffleArray);
  160. $this->assertContains(6, $shuffleArray);
  161. $this->assertContains(8, $shuffleArray);
  162. $this->assertContains(10, $shuffleArray);
  163. }
  164. public function testShuffleArrayReturnsADifferentArrayThanTheOriginal()
  165. {
  166. $arr = array(1, 2, 3, 4, 5);
  167. $shuffledArray = BaseProvider::shuffleArray($arr);
  168. $this->assertNotEquals($arr, $shuffledArray);
  169. }
  170. public function testShuffleArrayLeavesTheOriginalArrayUntouched()
  171. {
  172. $arr = array(1, 2, 3, 4, 5);
  173. BaseProvider::shuffleArray($arr);
  174. $this->assertEquals($arr, array(1, 2, 3, 4, 5));
  175. }
  176. public function testShuffleStringSupportsEmptyStrings()
  177. {
  178. $this->assertEquals('', BaseProvider::shuffleString(''));
  179. }
  180. public function testShuffleStringReturnsAnStringOfTheSameSize()
  181. {
  182. $string = 'abcdef';
  183. $this->assertEquals(strlen($string), strlen(BaseProvider::shuffleString($string)));
  184. }
  185. public function testShuffleStringReturnsAnStringWithSameElements()
  186. {
  187. $string = 'acegi';
  188. $shuffleString = BaseProvider::shuffleString($string);
  189. $this->assertContains('a', $shuffleString);
  190. $this->assertContains('c', $shuffleString);
  191. $this->assertContains('e', $shuffleString);
  192. $this->assertContains('g', $shuffleString);
  193. $this->assertContains('i', $shuffleString);
  194. }
  195. public function testShuffleStringReturnsADifferentStringThanTheOriginal()
  196. {
  197. $string = 'abcdef';
  198. $shuffledString = BaseProvider::shuffleString($string);
  199. $this->assertNotEquals($string, $shuffledString);
  200. }
  201. public function testShuffleStringLeavesTheOriginalStringUntouched()
  202. {
  203. $string = 'abcdef';
  204. BaseProvider::shuffleString($string);
  205. $this->assertEquals($string, 'abcdef');
  206. }
  207. public function testNumerifyReturnsSameStringWhenItContainsNoHashSign()
  208. {
  209. $this->assertEquals('fooBar?', BaseProvider::numerify('fooBar?'));
  210. }
  211. public function testNumerifyReturnsStringWithHashSignsReplacedByDigits()
  212. {
  213. $this->assertRegExp('/foo\dBa\dr/', BaseProvider::numerify('foo#Ba#r'));
  214. }
  215. public function testNumerifyReturnsStringWithPercentageSignsReplacedByDigits()
  216. {
  217. $this->assertRegExp('/foo\dBa\dr/', BaseProvider::numerify('foo%Ba%r'));
  218. }
  219. public function testNumerifyReturnsStringWithPercentageSignsReplacedByNotNullDigits()
  220. {
  221. $this->assertNotEquals('0', BaseProvider::numerify('%'));
  222. }
  223. public function testNumerifyCanGenerateALargeNumberOfDigits()
  224. {
  225. $largePattern = str_repeat('#', 20); // definitely larger than PHP_INT_MAX on all systems
  226. $this->assertEquals(20, strlen(BaseProvider::numerify($largePattern)));
  227. }
  228. public function testLexifyReturnsSameStringWhenItContainsNoQuestionMark()
  229. {
  230. $this->assertEquals('fooBar#', BaseProvider::lexify('fooBar#'));
  231. }
  232. public function testLexifyReturnsStringWithQuestionMarksReplacedByLetters()
  233. {
  234. $this->assertRegExp('/foo[a-z]Ba[a-z]r/', BaseProvider::lexify('foo?Ba?r'));
  235. }
  236. public function testBothifyCombinesNumerifyAndLexify()
  237. {
  238. $this->assertRegExp('/foo[a-z]Ba\dr/', BaseProvider::bothify('foo?Ba#r'));
  239. }
  240. public function testBothifyAsterisk()
  241. {
  242. $this->assertRegExp('/foo([a-z]|\d)Ba([a-z]|\d)r/', BaseProvider::bothify('foo*Ba*r'));
  243. }
  244. public function testBothifyUtf()
  245. {
  246. $utf = 'œ∑´®†¥¨ˆøπ“‘和製╯°□°╯︵ ┻━┻🐵 🙈 ﺚﻣ ﻦﻔﺳ ﺲﻘﻄﺗ ﻮﺑﺎﻠﺘﺣﺪﻳﺩ،, ﺝﺰﻳﺮﺘﻳ ﺏﺎﺴﺘﺧﺩﺎﻣ ﺄﻧ ﺪﻧﻭ. ﺇﺫ ﻪﻧﺍ؟ ﺎﻠﺴﺗﺍﺭ ﻮﺘ';
  247. $this->assertRegExp('/'.$utf.'foo\dB[a-z]a([a-z]|\d)r/u', BaseProvider::bothify($utf.'foo#B?a*r'));
  248. }
  249. public function testAsciifyReturnsSameStringWhenItContainsNoStarSign()
  250. {
  251. $this->assertEquals('fooBar?', BaseProvider::asciify('fooBar?'));
  252. }
  253. public function testAsciifyReturnsStringWithStarSignsReplacedByAsciiChars()
  254. {
  255. $this->assertRegExp('/foo.Ba.r/', BaseProvider::asciify('foo*Ba*r'));
  256. }
  257. public function regexifyBasicDataProvider()
  258. {
  259. return array(
  260. array('azeQSDF1234', 'azeQSDF1234', 'does not change non regex chars'),
  261. array('foo(bar){1}', 'foobar', 'replaces regex characters'),
  262. array('', '', 'supports empty string'),
  263. array('/^foo(bar){1}$/', 'foobar', 'ignores regex delimiters')
  264. );
  265. }
  266. /**
  267. * @dataProvider regexifyBasicDataProvider
  268. */
  269. public function testRegexifyBasicFeatures($input, $output, $message)
  270. {
  271. $this->assertEquals($output, BaseProvider::regexify($input), $message);
  272. }
  273. public function regexifyDataProvider()
  274. {
  275. return array(
  276. array('\d', 'numbers'),
  277. array('\w', 'letters'),
  278. array('(a|b)', 'alternation'),
  279. array('[aeiou]', 'basic character class'),
  280. array('[a-z]', 'character class range'),
  281. array('[a-z1-9]', 'multiple character class range'),
  282. array('a*b+c?', 'single character quantifiers'),
  283. array('a{2}', 'brackets quantifiers'),
  284. array('a{2,3}', 'min-max brackets quantifiers'),
  285. array('[aeiou]{2,3}', 'brackets quantifiers on basic character class'),
  286. array('[a-z]{2,3}', 'brackets quantifiers on character class range'),
  287. array('(a|b){2,3}', 'brackets quantifiers on alternation'),
  288. array('\.\*\?\+', 'escaped characters'),
  289. array('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}', 'complex regex')
  290. );
  291. }
  292. /**
  293. * @dataProvider regexifyDataProvider
  294. */
  295. public function testRegexifySupportedRegexSyntax($pattern, $message)
  296. {
  297. $this->assertRegExp('/' . $pattern . '/', BaseProvider::regexify($pattern), 'Regexify supports ' . $message);
  298. }
  299. public function testOptionalReturnsProviderValueWhenCalledWithWeight1()
  300. {
  301. $faker = new \Faker\Generator();
  302. $faker->addProvider(new \Faker\Provider\Base($faker));
  303. $this->assertNotNull($faker->optional(100)->randomDigit);
  304. }
  305. public function testOptionalReturnsNullWhenCalledWithWeight0()
  306. {
  307. $faker = new \Faker\Generator();
  308. $faker->addProvider(new \Faker\Provider\Base($faker));
  309. $this->assertNull($faker->optional(0)->randomDigit);
  310. }
  311. public function testOptionalAllowsChainingPropertyAccess()
  312. {
  313. $faker = new \Faker\Generator();
  314. $faker->addProvider(new \Faker\Provider\Base($faker));
  315. $faker->addProvider(new \ArrayObject(array(1))); // hack because method_exists forbids stubs
  316. $this->assertEquals(1, $faker->optional(100)->count);
  317. $this->assertNull($faker->optional(0)->count);
  318. }
  319. public function testOptionalAllowsChainingMethodCall()
  320. {
  321. $faker = new \Faker\Generator();
  322. $faker->addProvider(new \Faker\Provider\Base($faker));
  323. $faker->addProvider(new \ArrayObject(array(1))); // hack because method_exists forbids stubs
  324. $this->assertEquals(1, $faker->optional(100)->count());
  325. $this->assertNull($faker->optional(0)->count());
  326. }
  327. public function testOptionalAllowsChainingProviderCallRandomlyReturnNull()
  328. {
  329. $faker = new \Faker\Generator();
  330. $faker->addProvider(new \Faker\Provider\Base($faker));
  331. $values = array();
  332. for ($i=0; $i < 10; $i++) {
  333. $values[]= $faker->optional()->randomDigit;
  334. }
  335. $this->assertContains(null, $values);
  336. $values = array();
  337. for ($i=0; $i < 10; $i++) {
  338. $values[]= $faker->optional(50)->randomDigit;
  339. }
  340. $this->assertContains(null, $values);
  341. }
  342. /**
  343. * @link https://github.com/fzaninotto/Faker/issues/265
  344. */
  345. public function testOptionalPercentageAndWeight()
  346. {
  347. $faker = new \Faker\Generator();
  348. $faker->addProvider(new \Faker\Provider\Base($faker));
  349. $faker->addProvider(new \Faker\Provider\Miscellaneous($faker));
  350. $valuesOld = array();
  351. $valuesNew = array();
  352. for ($i = 0; $i < 10000; ++$i) {
  353. $valuesOld[] = $faker->optional(0.5)->boolean(100);
  354. $valuesNew[] = $faker->optional(50)->boolean(100);
  355. }
  356. $this->assertEquals(
  357. round(array_sum($valuesOld) / 10000, 2),
  358. round(array_sum($valuesNew) / 10000, 2)
  359. );
  360. }
  361. public function testUniqueAllowsChainingPropertyAccess()
  362. {
  363. $faker = new \Faker\Generator();
  364. $faker->addProvider(new \Faker\Provider\Base($faker));
  365. $faker->addProvider(new \ArrayObject(array(1))); // hack because method_exists forbids stubs
  366. $this->assertEquals(1, $faker->unique()->count);
  367. }
  368. public function testUniqueAllowsChainingMethodCall()
  369. {
  370. $faker = new \Faker\Generator();
  371. $faker->addProvider(new \Faker\Provider\Base($faker));
  372. $faker->addProvider(new \ArrayObject(array(1))); // hack because method_exists forbids stubs
  373. $this->assertEquals(1, $faker->unique()->count());
  374. }
  375. public function testUniqueReturnsOnlyUniqueValues()
  376. {
  377. $faker = new \Faker\Generator();
  378. $faker->addProvider(new \Faker\Provider\Base($faker));
  379. $values = array();
  380. for ($i=0; $i < 10; $i++) {
  381. $values[]= $faker->unique()->randomDigit;
  382. }
  383. sort($values);
  384. $this->assertEquals(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), $values);
  385. }
  386. /**
  387. * @expectedException OverflowException
  388. */
  389. public function testUniqueThrowsExceptionWhenNoUniqueValueCanBeGenerated()
  390. {
  391. $faker = new \Faker\Generator();
  392. $faker->addProvider(new \Faker\Provider\Base($faker));
  393. for ($i=0; $i < 11; $i++) {
  394. $faker->unique()->randomDigit;
  395. }
  396. }
  397. public function testUniqueCanResetUniquesWhenPassedTrueAsArgument()
  398. {
  399. $faker = new \Faker\Generator();
  400. $faker->addProvider(new \Faker\Provider\Base($faker));
  401. $values = array();
  402. for ($i=0; $i < 10; $i++) {
  403. $values[]= $faker->unique()->randomDigit;
  404. }
  405. $values[]= $faker->unique(true)->randomDigit;
  406. for ($i=0; $i < 9; $i++) {
  407. $values[]= $faker->unique()->randomDigit;
  408. }
  409. sort($values);
  410. $this->assertEquals(array(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9), $values);
  411. }
  412. public function testValidAllowsChainingPropertyAccess()
  413. {
  414. $faker = new \Faker\Generator();
  415. $faker->addProvider(new \Faker\Provider\Base($faker));
  416. $this->assertLessThan(10, $faker->valid()->randomDigit);
  417. }
  418. public function testValidAllowsChainingMethodCall()
  419. {
  420. $faker = new \Faker\Generator();
  421. $faker->addProvider(new \Faker\Provider\Base($faker));
  422. $this->assertLessThan(10, $faker->valid()->numberBetween(5, 9));
  423. }
  424. public function testValidReturnsOnlyValidValues()
  425. {
  426. $faker = new \Faker\Generator();
  427. $faker->addProvider(new \Faker\Provider\Base($faker));
  428. $values = array();
  429. $evenValidator = function($digit) {
  430. return $digit % 2 === 0;
  431. };
  432. for ($i=0; $i < 50; $i++) {
  433. $values[$faker->valid($evenValidator)->randomDigit] = true;
  434. }
  435. $uniqueValues = array_keys($values);
  436. sort($uniqueValues);
  437. $this->assertEquals(array(0, 2, 4, 6, 8), $uniqueValues);
  438. }
  439. /**
  440. * @expectedException OverflowException
  441. */
  442. public function testValidThrowsExceptionWhenNoValidValueCanBeGenerated()
  443. {
  444. $faker = new \Faker\Generator();
  445. $faker->addProvider(new \Faker\Provider\Base($faker));
  446. $evenValidator = function($digit) {
  447. return $digit % 2 === 0;
  448. };
  449. for ($i=0; $i < 11; $i++) {
  450. $faker->valid($evenValidator)->randomElement(array(1, 3, 5, 7, 9));
  451. }
  452. }
  453. /**
  454. * @expectedException InvalidArgumentException
  455. */
  456. public function testValidThrowsExceptionWhenParameterIsNotCollable()
  457. {
  458. $faker = new \Faker\Generator();
  459. $faker->addProvider(new \Faker\Provider\Base($faker));
  460. $faker->valid(12)->randomElement(array(1, 3, 5, 7, 9));
  461. }
  462. /**
  463. * @expectedException LengthException
  464. * @expectedExceptionMessage Cannot get 2 elements, only 1 in array
  465. */
  466. public function testRandomElementsThrowsWhenRequestingTooManyKeys()
  467. {
  468. BaseProvider::randomElements(array('foo'), 2);
  469. }
  470. public function testRandomElements()
  471. {
  472. $this->assertCount(1, BaseProvider::randomElements(), 'Should work without any input');
  473. $empty = BaseProvider::randomElements(array(), 0);
  474. $this->assertInternalType('array', $empty);
  475. $this->assertCount(0, $empty);
  476. $shuffled = BaseProvider::randomElements(array('foo', 'bar', 'baz'), 3);
  477. $this->assertContains('foo', $shuffled);
  478. $this->assertContains('bar', $shuffled);
  479. $this->assertContains('baz', $shuffled);
  480. $allowDuplicates = BaseProvider::randomElements(array('foo', 'bar'), 3, true);
  481. $this->assertCount(3, $allowDuplicates);
  482. $this->assertContainsOnly('string', $allowDuplicates);
  483. }
  484. }
  485. class Collection extends \ArrayObject
  486. {
  487. }