您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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