Pragmatism in the real world

Replacing a built-in PHP function when testing a component

Recently I needed to test part of Slim that uses the built-in PHP functions header() and headers_sent(). To do this, I took advantage of PHP’s namespace resolution rules where it will find a function within the same namespace first before finding one with the same name in the global namespace. The idea of how to do this came courtesy of Matthew Weier O’Phinney where this approach is used for similar testing in Zend-Diactoros.

This is the relevant part of the code I want to test:

namespace Slim;

// use statements...

class App
{
    // ... 

    public function respond(ResponseInterface $response)
    {
        // Send response
        if (!headers_sent()) {
            // Headers
            foreach ($response->getHeaders() as $name => $values) {
                $first = stripos($name, 'Set-Cookie') === 0 ? false : true;
                foreach ($values as $value) {
                    header(sprintf('%s: %s', $name, $value), $first);
                    $first = false;
                }
            }
        }

        // method continues
    }

     // ... 
}

This is the relevant test (simplified):

namespace Slim\Tests;

// use statements...

class AppTest extends PHPUnit_Framework_TestCase
{
    // ... 

    public function testResponseReplacesPreviouslySetHeaders()
    {
        $app = new App();

        $response = new Response();
        $response = $response->withHeader('X-Foo', 'baz1')
                ->withAddedHeader('X-Foo', 'baz2');

        $app->respond($response);

        $expectedStack = [
            ['header' => 'X-Foo: baz1', 'replace' => true, 'status_code' => null],
            ['header' => 'X-Foo: baz2', 'replace' => false, 'status_code' => null],
        ];

        $this->assertSame($expectedStack, HeaderStackTestAsset::$headers);
    }

    // ... 
}

This code sets up a Response object with two X-Foo headers, it then calls respond() and tests that there were two calls to header() with the replace parameter set to true only for the first one.

For this to work, we need to override PHP’s header() and replace it with our own that stores the parameters into an array within the HeaderStackTestAsset class.

This is done by creating our own HeaderStackTestAsset class along with headers_sent() & header() functions that are called rather than PHP’s:

<?php
// test/Assets/HeaderFunctions.php

namespace Slim\Tests\Assets {

    class HeaderStackTestAsset
    {
        public static $headers = [];
    }
}

namespace Slim {

    function headers_sent()
    {
        return false;
    }

    function header($header, $replace = true, $statusCode = null)
    {
        \Slim\Tests\Assets\HeaderStackTestAsset::$headers[] = [
            'header' => $header,
            'replace' => $replace,
            'status_code' => $statusCode,
        ];
    }
}

The HeaderStackTestAsset class is trivial and exists entirely as a holder for our $headers array.

We then define our headers_sent() function to always return false and then header() is set up to store the function parameters to the HeaderStackTestAsset::$headers array.

The key thing here is that the headers_sent() & header() functions are in the Slim namespace. As App is also in the same namespace, when header() is called within respond(), our version is invoked and so we can ensure that Slim does the right thing with the $replace parameter.

This is a very handy trick when you need it and works for any PHP function that’s called in the global namespace (as long as the file doesn’t explicitly import it using use).

9 thoughts on “Replacing a built-in PHP function when testing a component

  1. I wonder how you would've approached it if you had written the test first. Would you have ended up doing the same thing? Or would you have solved it a completely different way, without a need to replace functions?

    1. Good question. I don't know :)

      I need to prove the the header() call has the correct parameters passed to it and I"m not sure of another way to do that.

      Open to ideas!

  2. What I do in this situation is very similar, but on a simple abstraction, which means on a object contains methods for all related c functions. The implementation is now easy testable and the simple abstraction gets test as you did but without need to know the usecase

  3. Very interesting, two thoughts to mull over:

    1) I wrap built ins in a protected method purely for testing i.e.

         protected function header($string)
         {
             header($string);
         }
    

    It's then possible to setup a mock instance with expectations for the wrapper, rather than the builtin. If it's possible to modify the SUT, this is likely the easiest way.

    2) For testing static methods I often make use of double _and_ a mock

    public function testThing()
    {
        $mock = $this->getMockBuilder('stdClass')
            ->setMethods(['something'])
            ->getMock();
    
        $mock->expects($this->atLeastOnce())
            ->method('something')
            ->with(['these', 'args'])
            ->willReturn('whatever');
            
        AnnoyingClassDouble::setMock($mock);
        $result = AnnoyingClassDouble::publicMethod();
        ...
    }
    

    Where the test double is like so:

    class AnnoyingClassDouble extends AnnoyingClass
    {
        protected static $mock;
    
        public static function setMock($mock)
        {   
            static::$mock = $mock;
        }   
    
        /** 
         * Call on the surrogate mock object
         */
        protected static function something($one, $two)
        {   
            static::$mock->something($one, $two);
        }   
    

    The same sort of technique could be used for overridden builtins:

    function header($header, $replace = true, $statusCode = null)
    {
        $mock = // get reference to mock object
        $mock->header($header, $replace, $statusCode);
    }
    
  4. Hi Rob,

    I recalled how Paul M Jones did this for Aura packages. There was a Phpfunc class

    https://github.com/auraphp/Aura.Session/blob/ac14c86ae1000cc725f4a30944c077d91d249d49/src/Phpfunc.php

    which will trigger the functions via __call. May be this have some performance penalty.

    Eg: usage https://github.com/auraphp/Aura.Session/blob/ac14c86ae1000cc725f4a30944c077d91d249d49/src/Randval.php#L57

    But test code all will look nice. Now you can pass a FakePhpfunc class for testing.

    This technique is used in Aura.Http, Aura.Session etc.

  5. When I need to replace built-in PHP functions (or other difficult to mock calls) I make use of Patchwork (https://github.com/antecedent/patchwork), which is a monkey patching library for PHP.

    Okay, so ideally you wouldn't ever want to actually do this, but there are times when you just can't avoid it if you want to write tests. Particularly when trying to salvage some old legacy code.

  6. Personally I would replace the built-in function usage with an abstraction which I can then mock. Monkey patching built-in functions seems like it would get really messy, really quickly.

Comments are closed.