add a triggered errors assertion helper
This commit is contained in:
parent
5280d5dc9c
commit
b5c209558a
66
src/Symfony/Bridge/PhpUnit/ErrorAssert.php
Normal file
66
src/Symfony/Bridge/PhpUnit/ErrorAssert.php
Normal file
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* 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 <christian.flothmann@xabbuh.de>
|
||||
*/
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user