ValidDataTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php declare(strict_types=1);
  2. namespace Inhere\ValidateTest\Simple;
  3. use Inhere\Validate\Exception\ValidateException;
  4. use Inhere\Validate\Simple\VData;
  5. use Inhere\ValidateTest\BaseValidateTestCase;
  6. use function get_class;
  7. /**
  8. * class ValidDataTest
  9. */
  10. class ValidDataTest extends BaseValidateTestCase
  11. {
  12. public array $testData = [
  13. 'int' => 23,
  14. 'num' => '23',
  15. 'str' => 'abc',
  16. 'str1' => ' abc ',
  17. 'flt' => '2.33',
  18. 'arr' => ['ab', 'cd'],
  19. 'ints' => ['23', 25],
  20. 'strs' => ['23', 'cd', 25],
  21. ];
  22. protected function setUp(): void
  23. {
  24. VData::load($this->testData);
  25. }
  26. protected function tearDown(): void
  27. {
  28. VData::reset();
  29. }
  30. public function testBasicOK(): void
  31. {
  32. $data = $this->testData;
  33. $this->assertSame(23, VData::getInt('int'));
  34. $this->assertSame(2.33, VData::getFloat('flt'));
  35. $this->assertSame(23.0, VData::getFloat('int'));
  36. $this->assertSame('abc', VData::getString('str'));
  37. $this->assertSame('abc', VData::getString('str1'));
  38. $this->assertSame($data['arr'], VData::getArray('arr'));
  39. $this->assertSame($data['arr'], VData::getStrings('arr'));
  40. $this->assertSame([23, 25], VData::getInts('ints'));
  41. VData::reset();
  42. $this->assertEmpty(VData::getData());
  43. }
  44. public function testCheckFail_int(): void
  45. {
  46. $this->assertNotEmpty(VData::getData());
  47. $e = $this->runAndGetException(function () {
  48. VData::getInt('str');
  49. });
  50. $this->assertSame(ValidateException::class, get_class($e));
  51. $this->assertSame("'str' must be int value", $e->getMessage());
  52. $e = $this->runAndGetException(function () {
  53. VData::getInt('str', 2);
  54. });
  55. $this->assertSame(ValidateException::class, get_class($e));
  56. $this->assertSame("'str' must be int value and must be greater or equal to 2", $e->getMessage());
  57. $e = $this->runAndGetException(function () {
  58. VData::getInt('str', null, 20);
  59. });
  60. $this->assertSame(ValidateException::class, get_class($e));
  61. $this->assertSame("'str' must be int value and must be less than or equal to 20", $e->getMessage());
  62. $e = $this->runAndGetException(function () {
  63. VData::getInt('str', 2, 20);
  64. });
  65. $this->assertSame(ValidateException::class, get_class($e));
  66. $this->assertSame("'str' must be int value and must be >= 2 and <= 20", $e->getMessage());
  67. }
  68. }