10

I have this function I want to test looking like this:

class Logger {
  function error($msg){
    if (is_string($msg)){
      error_log($msg);
      die($msg);
    } elseif (is_object($msg)){
      error_log($msg.' '.$msg->getTraceAsString());
      die('exception');
    } else {
      var_dump($msg);
      die('error');
    }
  }

I want to test this function without logging the $msg. Is there a way to determine if error_log works without logging? I tried using setExpectedException but I wasn't able to catch the error and it kept logging.

Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
Donoven Rally
  • 1,670
  • 2
  • 17
  • 34
  • 1
    My interest was chiefly in how to test code that calls `error_log`, Alister's example of overriding error_log in the current namespace worked for testing. – ThorSummoner Aug 13 '15 at 16:42

3 Answers3

8

The obvious answer is a simple alias/proxy-function that itself called error_log in the Logger class (which can be easily mocked, and checked to see what is set to it),

To actually test the native error_log function however (without a proxy in the original class), can be done with namespaces. The test would end up defined to be the same namespace as the original code, and then after the test class, add a function - in this case error_log() - but that function is also defined in the namespace - and so would be run in preference to the root-namespace-equivalent from the native functions.

Unfortunately, you can't do the same overriding with die (or its alias, exit). They are 'language constructs', and cannot be overridden like error_log can.

<?php
namespace abc;
use abc\Logger;

class ThreeTest extends \PHPUnit_Framework_TestCase
{
    public function setUp() { $this->l = new Logger(); }
    // test code to exercise 'abc\Logger'

}

// Now define a function, still inside the namespace '\abc'.
public function error_log($msg)
{
   // this will be called from abc\Logger::error
   // instead of the native error_log() function
   echo "ERR: $msg, ";
}
Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
1

you can use a function-mocking framework like php-mock (there are others as well) to mock the call to error_log (and check whether it is called with your expected parameters).

Unfortunately you will not be able to use that for the die-construct as that is not a normal function but anlanguage construct.

I'd replace the die() with a 'throw new \Exception()' (or any other appropriate exception) as you can then

  • test for the thrown exception and
  • can decide in your programming whether execution shall be stopped on calling the logger or whether you want to go on by wrapping the call into a try/catch

But I'd also ask myself whether the execution has to stop when calling a logger

heiglandreas
  • 3,803
  • 1
  • 17
  • 23
0

Capturing error_log() output in a variable

If you want to redirect the error_log() output in a way that lets you inspect it with PHPUnit assertions, the following code works for me:

$errorLogTmpfile = tmpfile();
$errorLogLocationBackup = ini_set('error_log', stream_get_meta_data($errorLogTmpfile)['uri']);
error_log("Test for this message");
ini_set('error_log', $errorLogLocationBackup);
$result = stream_get_contents($errorLogTmpfile);
// Result: [11-May-2022 22:27:08 UTC] Test for this message

As you can see, it uses a temporary file to collect the output, then grabs the content into a variable and resets the error_log config.

Re-usable methods

Personally, I've organized this into a pair of methods that I inject into the PHPUnit object with a trait so I can re-use them.

Of course the code below won't work out of the box, but it serves to demonstrate how you can make this system re-usable:

trait WithWPTestCaseGeneralTools {
    
    var $gvErrorLogLocationBackup = "";
    var $gvErrorLogTmpfile = "";

    public function gvErrorLogStartListening() {
        
        $this->gvErrorLogTmpfile = tmpfile();
        $streamUri = stream_get_meta_data($this->gvErrorLogTmpfile)['uri'];
        $this->gvErrorLogLocationBackup = ini_set('error_log', $streamUri);
    }

    public function gvErrorLogGetContents() {
        
        ini_set('error_log', $this->gvErrorLogLocationBackup);      
        return stream_get_contents($this->gvErrorLogTmpfile);
    }
}

You could of course achieve the same things with a couple of functions that use globals, I'll leave that to you if it's what you need!

jerclarke
  • 1,219
  • 1
  • 13
  • 23