I have a library, and I didn’t notice that it was giving deprecation warnings until someone created an issue on GitHub. I’ve enabled:
error_reporting(E_ALL);
And fixed all deprecation warnings. But the question is: can you make the code always fail (I think about unit tests) if there are deprecation warnings? I was thinking maybe about adding ob_
buffering with a regular expression to test if there are no warnings and throw an error. But this would require some code that will not look pretty.
Is there an easy way to just toggle some options to make warnings real errors? So the unit test doesn’t pass and the code always fails? I want my code to be future-proof and don’t fail when PHP decides to replace deprecation with real error.
2
Answers
Yes, you can make PHP treat all errors, including E_DEPRECATED and E_USER_DEPRECATED, as exceptions by using the set_error_handler function. This function allows you to define a custom error handler function that will be called whenever an error occurs
Use the
<phpunit
failOnDeprecation="true"
>
attribute¹, PHPUnit shows aD
in the standard test-runner when a deprecation occured during tests (E_DEPRECATED
,E_USER_DEPRECATED
, or PHPUnit deprecation).This will make it always fail then.
Command line options exist, too, taken from
phpunit --help
invocation:‑‑display‑deprecations
D
.‑‑fail‑on‑deprecation
failOnDeprecation
XML attribute above.‑‑stop‑on‑deprecation
stopOnDeprecation
XML attribute.Not in (your) case of PHP language deprecation, but perhaps noteworthy for a future visitor:
PHPUnit doesn’t populate the information about
@
-suppressed triggeredE_USER_DEPRECATED
errors. To make it working with PHPUnit nevertheless, use the-d xdebug.scream=1
PHP (not PHPUnit) command line parameter for the ini setting of the Xdebug extension. Setupxdebug.mode
appropriately, forxdebug.scream
the development helpers² must be enabled (-d xdebug.mode=develop
, often default). If other features from Xdebug are also required for PHPUnit, codecoverage for example, append the mode with a comma (","). More information is available in the Xdebug documentation.failOnDeprecation
Attribute — PHPUnit 5. The XML Configuration File