Skip to content

Commit 6759543

Browse files
committed
add a triggered errors assertion helper
1 parent c2d6450 commit 6759543

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

ErrorAssert.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bridge\PhpUnit;
13+
14+
/**
15+
* Test that your code triggers expected error messages.
16+
*
17+
* @author Christian Flothmann <[email protected]>
18+
*/
19+
final class ErrorAssert
20+
{
21+
/**
22+
* @param string[] $expectedMessages Expected deprecation messages
23+
* @param callable $testCode A callable that is expected to trigger the expected deprecation messages when being executed
24+
*/
25+
public static function assertDeprecationsAreTriggered($expectedMessages, $testCode)
26+
{
27+
if (!is_callable($testCode)) {
28+
throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode)));
29+
}
30+
31+
self::assertErrorsAreTriggered(E_USER_DEPRECATED, $expectedMessages, $testCode);
32+
}
33+
34+
/**
35+
* @param int $expectedType Expected triggered error type (pass one of PHP's E_* constants)
36+
* @param string[] $expectedMessages Expected error messages
37+
* @param callable $testCode A callable that is expected to trigger the expected messages when being executed
38+
*/
39+
public static function assertErrorsAreTriggered($expectedType, $expectedMessages, $testCode)
40+
{
41+
if (!is_callable($testCode)) {
42+
throw new \InvalidArgumentException(sprintf('The code to be tested must be a valid callable ("%s" given).', gettype($testCode)));
43+
}
44+
45+
$triggeredMessages = array();
46+
47+
try {
48+
$prevHandler = set_error_handler(function ($type, $message, $file, $line, $context) use ($expectedType, &$triggeredMessages, &$prevHandler) {
49+
if ($expectedType !== $type) {
50+
return null !== $prevHandler && call_user_func($prevHandler, $type, $message, $file, $line, $context);
51+
}
52+
$triggeredMessages[] = $message;
53+
});
54+
55+
$testCode();
56+
} finally {
57+
restore_error_handler();
58+
}
59+
60+
\PHPUnit_Framework_Assert::assertCount(count($expectedMessages), $triggeredMessages);
61+
62+
for ($i = 0; $i < count($triggeredMessages); ++$i) {
63+
\PHPUnit_Framework_Assert::assertContains($expectedMessages[$i], $triggeredMessages[$i]);
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)