14

Is there any way to run a test on output created from a call to 'error_log("Message")' when doing unit tests with phpunit?

Example code, one of my functions tests a credit card with a luhn algorithm:

if($checkLuhn && ($this->_luhn_check($cardNumber) == false)) {
    error_log(__METHOD__ . " cardNumber failed luhn algorithm check.");
    return false;
}

$checkLuhn is a boolean passed in to tell it whether to do the check, the _luhn_check() returns true if the $cardNumber passes. Problem is, I have more than one test in this function that can return false. I can use assertEquals on the return value, but also want to check why the error was thrown.

Can you override error_log or otherwise grab syslog output in a unit test somehow?

4
  • 1
    Does your $this->_luhn_check($cardNumber) throw an exception there? If so, you can get that exception and log it in your test. Commented Apr 21, 2014 at 15:53
  • 2
    I think you are missing some level of abstraction on your error detection / logging. If you employ a class for logging all errors, you just have to mock that class on your tests. Then you'd also test that class to check that works as expected. What you want to test here is that the error is triggered, not what happens when an error is triggered.
    – gontrollez
    Commented Apr 22, 2014 at 9:25
  • I agree with @gontrollez, logging should definitely be abstracted out of the code and introduced as a service. You'll be able to write better (and easier) tests, plus you'll get a lot of flexibility and can write to more than one log. Commented Apr 23, 2014 at 8:40
  • I posted a solution for PHPUnit testing error_log() on a similar question, please see: stackoverflow.com/a/72208381/209859
    – jerclarke
    Commented May 12, 2022 at 18:56

4 Answers 4

9

There are a few different ways to direct where error_log() sends data.

First is to just as error_log() to send it some where else. An example would be:

error_log( 'This is a message from error_log()', 3, '/dev/stdout' );

That uses the destination option for error_log().

Another approach is to override the error_log ini setting in PHP. That would look something like:

$cur_error_log = ini_get( 'error_log' );
ini_set( 'error_log', '/dev/stdout' );
error_log( 'This is a message from error_log()' );
ini_set( 'error_log', $cur_error_log );

Of the two options I generally prefer using the destination option in error_log() when possible.

From there you could use expectOutputString() from PHPUnit to look for the data sent from error_log().

3
  • 1
    You don't need to use ini_get as ini_set returns the previous value: php.net/manual/en/function.ini-set.php
    – DanielM
    Commented Feb 26, 2017 at 12:38
  • Not sure why but this didn't work for me. A similar solution, but using tmpfile() did work though, see my answer below.
    – jerclarke
    Commented May 11, 2022 at 22:51
  • My answer was removed because I had posted it on several questions. See my solution here: stackoverflow.com/a/72208381/209859
    – jerclarke
    Commented May 12, 2022 at 18:56
1

You can use the uopz extension from Zend to overload functions like these. I use them all the time. Here is an example:

/**
 * Requires the following set in php.ini: 
 * - zend_extension=php_uopz.dll;
 * - uopz.overloads=1
 * 
* @author Aap Noot
*/
class MyClass extends PHPUnit_Framework_TestCase {
    public static $error_log = array();

     /**
     * Overload error_log function
     * @see PHPUnit_Framework_TestCase::setUpBeforeClass()
     */
    public static function setUpBeforeClass() {
        uopz_backup ( "error_log" );
        uopz_function ( "error_log", function ($message, $message_type = null, $destination = null, $extra_headers = null) {
            // We are only interested in the message
            MyClass::$error_log[] = $message;
        } );
        parent::setUpBeforeClass ();

    /**
     * Restore function(s)
     * @see PHPUnit_Framework_TestCase::tearDownAfterClass()
     */
    public static function tearDownAfterClass() {
        uopz_restore ( "error_log" );
        parent::tearDownAfterClass ();
    } 

    /**
    * Set up per test case
    * @see PHPUnit_Framework_TestCase::setUp()
    */
    protected function setUp() {
        parent::setUp ();
        MyClass::$error_log = array();
    }

    /**
     * Test error log
     * MyClass::$error_log should be an array with the error message
     */
    public function testErrorLog() {
        // Test response
        error_log("This message will be captured");

        // Test error log
        $this->assertNotEmpty(MyClass::$error_log);
    }
}
0

I couldn't get this working with error_log, but was able to check the error using trigger_error. Try using annotations.

 * @expectedException PHPUnit_Framework_Exception
 * @expectedExceptionMessageRegExp /failed/

https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.expectedException

See also :

How to execute code after trigger_error(..., E_USER_WARNING) in unit test (PHPUnit)?

2
  • 1
    The issue here is that trigger_error() and error_log() are not equivalent. Trigger_error actually interrupts the flow of logic, whereas error_log() can be used to safely send messages to the log without actually indicating a problem. I use error_log() a lot for informational or debugging purposes, and I want tests that can ensure such logs get saved.
    – jerclarke
    Commented May 11, 2022 at 21:40
  • I'll also add that I think the PHPDoc notations you indicate are no longer the right way. Now we expect exceptions with assertion methods like this: $this->expectException('PHPUnit\Framework\Exception');
    – jerclarke
    Commented May 11, 2022 at 21:41
0

Another way of doing it, is move all error_log uses into a class method then extend the class in your tests and override the error logging method. Here's an example:

final class MyClassTest extends TestCase
{
    public function testSomething()
    {
        $mock = new MyClassMock();
        $mock->run();

        static::expectOutputString('test');
    }
}

class MyClass
{
    public function run()
    {
        $this->errorLog('test');
    }

    protected function errorLog(string $error)
    {
        error_log($error);
    }
}

class MyClassMock extends MyClass
{
    protected function errorLog(string $error)
    {
        echo $error;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.