Testing output in php: // stdout with PHPUnit

I use Symfony\Component\Console\Output\ConsoleOutputto write to the console.

Obviously, I am writing php://stdout.

In my unit tests, I would like to check the output to the console.

Using the PHPUnit method expectOutputString(), I can check the output:

// Passes, as expected

public function testOutputBufferingEcho()
{
    $this->expectOutputString('Hello');

    echo 'Hello';
}

This also works with output to php://output:

// Passes, as expected

public function testOutputBufferingOutput()
{
    $this->expectOutputString('Hello');

    $out = fopen('php://output', 'w');
    fputs ($out, 'Hello');
    fclose($out);
}

However, it does not work with output on php://stdout(one ConsoleOutputuses by default):

// Failed asserting that two strings are equal.
// --- Expected
// +++ Actual
// @@ @@
// -'Hello'
// +''

public function testOutputBufferingStdOut()
{
    $this->expectOutputString('Hello');

    $out = fopen('php://stdout', 'w');
    fputs ($out, 'Hello');
    fclose($out);
}

In addition, it seems impossible to use functions ob_*to directly output output to php://stdout.

Is there a way to check the output on php://stdoutusing PHPUnit?

Or is there another way to capture output in php://stdouta string (and therefore a test in PHPUnit)?

The above tests were performed in PHPUnit 5.5.5.

Thanks in advance.

+4
2

php://stdout ( ) - .

:

class Intercept extends php_user_filter
{
    public static $cache = '';
    public function filter($in, $out, &$consumed, $closing)
    {
        while ($bucket = stream_bucket_make_writeable($in)) {
            self::$cache .= $bucket->data;
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}

stream_filter_register("intercept", "Intercept");

$stdout = fopen('php://stdout', 'w'); // or $yerSymfonyThingy->getStream()
stream_filter_append($stdout, "intercept");

fwrite($stdout, "Hello\n");
var_dump(Intercept::$cache);

:

Hello
string(6) "Hello
"

, , Intercept::$cache .

, PSFS_PASS_ON PSFS_FEED_ME, .

+6

STDOUT : . "1" (STDOUT), .

fclose(STDOUT);
$fakestdout = fopen('php://memory', 'r+');

$fakestdout, .

, . STDOUT ( "" ) $fakestdout, , . STDOUT .

PHPUnit --stderr, STDERR PHPUnit, .

+1

Source: https://habr.com/ru/post/1656304/


All Articles