diff --git a/src/Symfony/Bridge/PhpUnit/ErrorAssert.php b/src/Symfony/Bridge/PhpUnit/ErrorAssert.php new file mode 100644 index 000000000000..b1594cbc915a --- /dev/null +++ b/src/Symfony/Bridge/PhpUnit/ErrorAssert.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\PhpUnit; + +/** + * Test that your code triggers expected error messages. + * + * @author Christian Flothmann + */ +final class ErrorAssert +{ + /** + * @param string[] $expectedMessages Expected deprecation messages + * @param callable $testCode A callable that is expected to trigger the expected deprecation messages when being executed + */ + public static function assertDeprecationsAreTriggered($expectedMessages, $testCode) + { + if (!is_callable($testCode)) { + throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode))); + } + + self::assertErrorsAreTriggered(E_USER_DEPRECATED, $expectedMessages, $testCode); + } + + /** + * @param int $expectedType Expected triggered error type (pass one of PHP's E_* constants) + * @param string[] $expectedMessages Expected error messages + * @param callable $testCode A callable that is expected to trigger the expected messages when being executed + */ + public static function assertErrorsAreTriggered($expectedType, $expectedMessages, $testCode) + { + if (!is_callable($testCode)) { + throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode))); + } + + $triggeredMessages = array(); + + try { + $prevHandler = set_error_handler(function ($type, $message, $file, $line, $context) use ($expectedType, &$triggeredMessages, &$prevHandler) { + if ($expectedType !== $type) { + return null !== $prevHandler && call_user_func($prevHandler, $type, $message, $file, $line, $context); + } + $triggeredMessages[] = $message; + }); + + $testCode(); + } finally { + restore_error_handler(); + } + + \PHPUnit_Framework_Assert::assertCount(count($expectedMessages), $triggeredMessages); + + for ($i = 0; $i < count($triggeredMessages); ++$i) { + \PHPUnit_Framework_Assert::assertContains($expectedMessages[$i], $triggeredMessages[$i]); + } + } +}