diff --git a/src/functions.php b/src/functions.php index 533a41cadc8d344cbd9a2ae7b6a6db9967692aac..e66830413b5172c72f5c5f397556be17f1e64ce5 100644 --- a/src/functions.php +++ b/src/functions.php @@ -3,9 +3,7 @@ * Used to load functions. */ -// todo: TESTS: better assertion messages + throw FunctionSignatureAssertionError + catch in fn + pass it to assert -> compatible with PHP assert config // todo: covariance and contra-variance -// todo: tests for primitive types namespace Grifart\AssertFunction; diff --git a/tests/fn.assertSignature.primitives.phpt b/tests/fn.assertSignature.primitives.phpt new file mode 100644 index 0000000000000000000000000000000000000000..bdc2566f293d872b57d20990490e8d665a5af4f7 --- /dev/null +++ b/tests/fn.assertSignature.primitives.phpt @@ -0,0 +1,32 @@ +<?php declare(strict_types=1); +namespace MyTestNamespace; +require __DIR__ . '/bootstrap.php'; +require __DIR__ . '/testClasses.php'; +use function Grifart\AssertFunction\{assertSignature, nullable, params}; +use Grifart\AssertFunction\FunctionSignatureAssertionError; +use Tester\Assert; +$place = 'tests/' . basename(__FILE__) . ':' . (__LINE__ +2) . ' '; + +$fn = function(string $p1, ?int $p2): void {}; + +assertSignature($fn, params('string', '?int'), 'void'); +assertSignature($fn, params('string', nullable('int')), 'void'); +assertSignature($fn, params('string', nullable('int')), NULL); // no-return type expectations + +// parameter nullability +Assert::exception( + function () use ($fn) { + assertSignature($fn, params(nullable('string'), 'int'), NULL); // no-return type expectations + }, + FunctionSignatureAssertionError::class, + $place . 'Parameter #1 ($p1) is expected to be nullable. But it is required.' +); + +// return-type mismatch +Assert::exception( + function () use ($fn) { + assertSignature($fn, params('string', '?int'), 'int'); + }, + FunctionSignatureAssertionError::class, + $place . "Expected return type of type 'int', but given function declares 'void'." +);