[Math] test arithmetic errors

This commit is contained in:
azjezz 2020-09-11 01:42:29 +01:00
parent b9e1c282d6
commit 85fc380f8a
4 changed files with 31 additions and 8 deletions

View File

@ -6,6 +6,6 @@ namespace Psl\Math\Exception;
use Psl\Exception\InvalidArgumentException;
final class ArithmeticException extends InvalidArgumentException implements ExceptionInterface
class ArithmeticException extends InvalidArgumentException implements ExceptionInterface
{
}

View File

@ -4,8 +4,6 @@ declare(strict_types=1);
namespace Psl\Math\Exception;
use Psl\Exception\InvalidArgumentException;
final class DivisionByZeroException extends InvalidArgumentException implements ExceptionInterface
final class DivisionByZeroException extends ArithmeticException
{
}

View File

@ -6,6 +6,7 @@ namespace Psl\Math;
use ArithmeticError;
use DivisionByZeroError;
use Psl\Str;
use function intdiv;
@ -25,16 +26,24 @@ use function intdiv;
*
* @psalm-pure
*
* @throws Exception\ArithmeticException If the numerator is Math\INT64_MAX and the denominator is -1.
* @throws Exception\ArithmeticException If the numerator is Math\INT64_MIN and the denominator is -1.
* @throws Exception\DivisionByZeroException If the denominator is 0.
*/
function div(int $numerator, int $denominator): int
{
try {
return intdiv($numerator, $denominator);
} catch (ArithmeticError $error) {
throw new Exception\ArithmeticException($error->getMessage(), $error->getCode(), $error);
} catch (DivisionByZeroError $error) {
throw new Exception\DivisionByZeroException($error->getMessage(), $error->getCode(), $error);
throw new Exception\DivisionByZeroException(
Str\format('%s.', $error->getMessage()),
$error->getCode(),
$error
);
} catch (ArithmeticError $error) {
throw new Exception\ArithmeticException(
'Division of Math\INT64_MIN by -1 is not an integer.',
$error->getCode(),
$error
);
}
}

View File

@ -17,6 +17,22 @@ class DivTest extends TestCase
self::assertSame($expected, Math\div($numerator, $denominator));
}
public function testDivByZero(): void
{
$this->expectException(Math\Exception\DivisionByZeroException::class);
$this->expectExceptionMessage('Division by zero.');
Math\div(10, 0);
}
public function testDivInt64MinByMinusOne(): void
{
$this->expectException(Math\Exception\ArithmeticException::class);
$this->expectExceptionMessage('Division of Math\INT64_MIN by -1 is not an integer.');
Math\div(Math\INT64_MIN, -1);
}
public function provideData(): array
{
return[