respect-validation/tests/unit/Rules/SortedTest.php
Henrique Moody d1f108dc87
Make proper use of exceptions in rules
This commit will ensure that all rules that cannot be created because of
invalid arguments in the constructor will throw the
InvalidRuleConstructorException. It will also make ComponentException
extend LogicException, which makes it easier to determine that the
client has improperly used the library.

I also introduced some tests for two exceptions with logic in their
constructor.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-25 22:09:02 +01:00

66 lines
2.6 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Exceptions\InvalidRuleConstructorException;
use Respect\Validation\Test\RuleTestCase;
use stdClass;
#[Group('rules')]
#[CoversClass(Sorted::class)]
final class SortedTest extends RuleTestCase
{
#[Test]
public function itShouldNotAcceptWrongSortingDirection(): void
{
$this->expectException(InvalidRuleConstructorException::class);
$this->expectExceptionMessage('Direction should be either "ASC" or "DESC"');
new Sorted('something');
}
/** @return iterable<array{Sorted, mixed}> */
public static function providerForValidInput(): iterable
{
return [
'empty' => [new Sorted('ASC'), []],
'one item' => [new Sorted('ASC'), [1]],
'one character' => [new Sorted('ASC'), 'z'],
'ASC array-sequence' => [new Sorted('ASC'), [1, 3, 5]],
'ASC sequence in associative array' => [new Sorted('ASC'), ['foo' => 1, 'bar' => 3, 'baz' => 5]],
'ASC string-sequence' => [new Sorted('ASC'), 'ABCD'],
'DESC array-sequence ' => [new Sorted('DESC'), [10, 9, 8]],
'DESC string-sequence ' => [new Sorted('DESC'), 'zyx'],
];
}
/** @return iterable<array{Sorted, mixed}> */
public static function providerForInvalidInput(): iterable
{
return [
'duplicate' => [new Sorted('ASC'), [1, 1, 1]],
'wrong ASC array-sequence' => [new Sorted('ASC'), [1, 3, 2]],
'wrong ASC string-sequence' => [new Sorted('ASC'), 'xzy'],
'wrong DESC array-sequence' => [new Sorted('DESC'), [1, 3, 2]],
'wrong DESC string-sequence' => [new Sorted('DESC'), 'jml'],
'DESC array-sequence with ASC validation' => [new Sorted('ASC'), [3, 2, 1]],
'DESC string-sequence with ASC validation' => [new Sorted('ASC'), '321'],
'ASC array-sequence with DESC validation' => [new Sorted('DESC'), [1, 2, 3]],
'ASC string-sequence with DESC validation' => [new Sorted('DESC'), 'abc'],
'unsupported value (integer)' => [new Sorted('DESC'), 1 ],
'unsupported value (float)' => [new Sorted('DESC'), 1.2 ],
'unsupported value (bool)' => [new Sorted('DESC'), true ],
'unsupported value (object)' => [new Sorted('DESC'), new stdClass() ],
];
}
}