bartlett/phpunit-loggertestlistener

PHPUnit Test Suite listener for compatible PSR-3 logger

Installs: 66

Dependents: 3

Stars: 1

Watchers: 1

Forks: 1

Language: PHP

1.5.0 2015-05-04 11:26 UTC

README

Goal is to provide a standard PHPUnit Listener that is capable to send unit test results to any PSR-3 compatible logger.

The listener implement the PHPUnit_Framework_TestListener interface, and used these log levels/events mapping.

ERROR
  • addError(), when an error occurred

  • addFailure(), when a failure occured

WARNING
  • addIncompleteTest(), on incomplete test

  • addRiskyTest(), on risky test

  • addSkippedTest(), when a test was skipped

INFO
  • startTest(), when a test started

  • endTest(), when a test ended

NOTICE
  • startTestSuite(), when a test suite started

  • endTestSuite(), when a test suite ended

Installation

Important For demonstration purpose, a Growl Handler and an AdvancedFilter Handler were used but are not yet available as a GitHub or Packagist version. Source code are provided in extra folder.
$ php composer.phar require bartlett/phpunit-loggertestlistener=~1.1

Usage with basic PSR-3 Logger

We will use a very basic PSR-3 logger for our first steps. Suppose we have such following implementation.

<?php

use Psr\Log\AbstractLogger;

class YourLogger extends AbstractLogger
{
    private $channel;

    public function __construct($name = 'YourLoggerChannel')
    {
        $this->channel = $name;
    }

    public function log($level, $message, array $context = array())
    {
        error_log(
            sprintf(
                '%s.%s: %s',
                $this->channel,
                strtoupper($level),
                $this->interpolate($message, $context)
            )
        );
    }

    protected function interpolate($message, array $context = array())
    {
        // build a replacement array with braces around the context keys
        $replace = array();
        foreach ($context as $key => $val) {
            if (is_scalar($val)) {
                $replace['{' . $key . '}'] = $val;
            }
        }

        // interpolate replacement values into the message and return
        return strtr($message, $replace);
    }
}

Add in your phpunit.xml configuration file the Bartlett\LoggerTestListener test listener, using our basic PSR-3 logger (YourLogger).

Using default behavior of your logger
<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <listeners>
        <listener class="Bartlett\LoggerTestListener">
            <arguments>
                <object class="YourLogger" />
            </arguments>
        </listener>
    </listeners>
</phpunit>

We can change name of the channel (from default YourLoggerChannel to value YourPSR3Logger) as follow :

Configure the channel name of your logger
<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <listeners>
        <listener class="Bartlett\LoggerTestListener">
            <arguments>
                <object class="YourLogger">
                    <arguments>
                        <string>YourPSR3Logger</string>
                    </arguments>
                </object>
            </arguments>
        </listener>
    </listeners>
</phpunit>

If you want to have advanced logging strategies, I suggest you to have a look on famous Monolog PHP Library.

Usage with Monolog

Without handler (then default output will be send to STDERR), we could have such kind of configuration, with logger channel name set to YourMonologChannel.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <listeners>
        <listener class="Bartlett\LoggerTestListener">
            <arguments>
                <object class="Monolog\Logger">
                    <arguments>
                        <string>YourMonologChannel</string>
                    </arguments>
                </object>
            </arguments>
        </listener>
    </listeners>
</phpunit>

Add some handlers, with basic logging Monolog Strategy (filter on level only).

<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <listeners>
        <listener class="Bartlett\LoggerTestListener">
            <arguments>
                <object class="Monolog\Logger">
                    <arguments>
                        <string>YourMonologChannel</string>
                        <array>
                            <element>
                                <object class="Monolog\Handler\StreamHandler">
                                    <arguments>
                                        <string>/var/logs/monolog.log</string>
                                    </arguments>
                                </object>
                            </element>
                            <element>
                                <object class="Bartlett\GrowlHandler">
                                    <arguments>
                                        <array></array>
                                        <integer>250</integer> <!-- NOTICE -->
                                    </arguments>
                                </object>
                            </element>
                        </array>
                    </arguments>
                </object>
            </arguments>
        </listener>
    </listeners>
</phpunit>
Warning When we used desktop notification such as growl, or mobile notifications powered by Pushover, you probably don’t want to receive all log records, but just the most important ones (errors, failures, testsuites ended).

Actually Monolog can’t do this. So this is the reason of the Pull Request to add filter capability.

Now create a pre-defined logger with all handlers we wished on and the filter rules for each handlers.

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

use Bartlett\Monolog\Handler\GrowlHandler;
use Bartlett\Monolog\Handler\CallbackFilterHandler;

class YourMonolog extends Logger
{
    public function __construct($name = 'PHPUnit')
    {
        $filter1 = function($record, $handlerLevel) {
            if ($record['level'] < $handlerLevel) {
                return false;
            }
            if ($record['level'] > $handlerLevel) {
                return true;
            }
            return (
                preg_match('/^TestSuite(.*)ended\./', $record['message']) === 1
                and
                $record['level'] == $handlerLevel
            );
        };

        $stream = new StreamHandler('/var/logs/monolog.log');

        $handlers = array($stream);

        try {
            $growl = new GrowlHandler(array(), Logger::NOTICE);

            $filterGrowl = new CallbackFilterHandler(
                $growl,
                array($filter1)
            );
            $handlers[] = $filterGrowl;

        } catch (\Exception $e) {
            // Growl client is probably not started
            echo $e->getMessage(), PHP_EOL, PHP_EOL;
        }

        parent::__construct($name, $handlers);
    }
}

And of course, declare our new listener like that :

<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <listeners>
        <listener class="Bartlett\LoggerTestListener">
            <arguments>
                <object class="YourMonolog" />
            </arguments>
        </listener>
    </listeners>
</phpunit>

We will get all PHPUnit log messages recorded via the StreamHandler, and only important notifications via GrowlHandler (see filter rule with callback $filter1).

Run the test suite example :

$ php phpunit-4.5.1.phar -c /home/github/phpunit-LoggerTestListener/examples/phpunit.xml

And you will get something like:

PHPUnit 4.5.1 by Sebastian Bergmann and contributors.

Configuration read from /home/github/phpunit-LoggerTestListener/examples/phpunit.xml

IF

Time: 1.1 seconds, Memory: 4.00Mb

There was 1 failure:

1) Your\Name_Space\YourTestSuite::testFailure
Failed asserting that an array is empty.

/home/github/phpunit-LoggerTestListener/examples/testSuite.php:20

FAILURES!
Tests: 2, Assertions: 2, Failures: 1, Incomplete: 1.
Test Suite results with Monolog Stream Handler
[2015-04-05 09:38:43] PHPUnit.NOTICE: TestSuite 'Demo Test Suite' started. {"suiteName":"Demo Test Suite","operation":"startTestSuite"} []
[2015-04-05 09:38:43] PHPUnit.NOTICE: TestSuite 'Your\Name_Space\YourTestSuite' started. {"suiteName":"Your\\Name_Space\\YourTestSuite","operation":"startTestSuite"} []
[2015-04-05 09:38:43] PHPUnit.INFO: Test 'testIncomplete' started. {"testName":"testIncomplete","operation":"startTest"} []
[2015-04-05 09:38:43] PHPUnit.WARNING: Test 'testIncomplete' is incomplete. {"testName":"testIncomplete","operation":"addIncompleteTest","reason":"This test has not been implemented yet."} []
[2015-04-05 09:38:43] PHPUnit.INFO: Test 'testIncomplete' ended. {"testName":"testIncomplete","operation":"endTest"} []
[2015-04-05 09:38:43] PHPUnit.INFO: Test 'testFailure' started. {"testName":"testFailure","operation":"startTest"} []
[2015-04-05 09:38:43] PHPUnit.ERROR: Test 'testFailure' failed. {"testName":"testFailure","operation":"addFailure","reason":"Failed asserting that an array is empty."} []
[2015-04-05 09:38:43] PHPUnit.INFO: Test 'testFailure' ended. {"testName":"testFailure","operation":"endTest"} []
[2015-04-05 09:38:43] PHPUnit.NOTICE: TestSuite 'Your\Name_Space\YourTestSuite' ended. {"suiteName":"Your\\Name_Space\\YourTestSuite","operation":"endTestSuite","testCount":2,"assertionCount":2,"failureCount":1,"errorCount":0,"incompleteCount":1,"skipCount":0,"riskyCount":0} []
[2015-04-05 09:38:43] PHPUnit.NOTICE: TestSuite 'Demo Test Suite' ended. Tests: 2, Assertions: 2, Failures: 1, Incompleted: 1 {"suiteName":"Demo Test Suite","operation":"endTestSuite","testCount":2,"assertionCount":2,"failureCount":1,"errorCount":0,"incompleteCount":1,"skipCount":0,"riskyCount":0} []
Test Suite results with Growl Handler

growl notifications

Note Produced by Growl for Windows (2.0.9 and Smokestack display) with PHP GNTP library.

License

LoggerTestListener is licensed under the BSD-3 Clause License - see the LICENSE file for details