PHPUnit + XHProf = BOOM!

Published in PHP, PHPUnit, Testing on Oct 13, 2015

I ran into an issue recently while trying to run PHPUnit tests in an environment using XHProf. Google didn't prove to be much help, so I thought I'd document the problem and solution here for posterity.

When I ran my tests, each failed with the same cryptic error and no backtrace.

Attempted to serialize unserializable builtin class PDO

The cause was the culmination of two rather unfortunate circumstances.

First, XHProf uses a global array variable to contain its configuration in its auto_prepend_file, which includes a PDO instance. Yet another reason to add to the list of reasons why global variables are bad.

Second, PHPUnit has a setting called @backupGlobals that is enabled by default. For reasons of which I'm uncertain, the library used for this applies and reverses serialization to variables in the global state for the purpose of creating a snapshot of it.

The method used for detecting serializability in this library unfortunately doesn't presently detect that PDO can't be serialized when an instance of it is contained within a global array variable. As a result, when PHPUnit attempts to snapshot the global state after a test has run and it encounters the PDO instance from the XHProf configuration, the error above is the result.

There appears to be a pull request with changes to this serializability detection, though I can't speak to whether it would improve it or cover the use case causing this problem. I've filed a related issue against the appropriate repo. Until it's addressed, I'd recommend either disabling @backupGlobals in your phpunit.xml file or disabling XHProf when running PHPUnit tests.

Hope this helps someone else. Thanks for reading!