【问题标题】:PHPUnit ExpectOutputString failure shows binary output that is difficult to readPHPUnit ExpectOutputString 失败显示二进制输出难以阅读
【发布时间】:2016-10-24 21:46:03
【问题描述】:

我正在编写输出包含非打印字符(例如 ESCAPE (\033))的字符串的代码。如果我使用没有转义字符的 PHPUnit expectOutputString 并且它失败了,那么它很容易阅读:

public function test_output() {

    echo "foo";
    $this->expectOutputString("foob");
}

这将失败并显示给我:

Failed asserting that two strings are equal.
Expected :'foob'
Actual   :'foo'

这很容易调试,但是当我有一个包含 ESCAPE 字符的字符串时:

public function test_escape_output() {
    echo "\033[0m";
    $this->expectOutputString("\033[0mm");
}

...它失败了,它显示了二进制输出:

Failed asserting that two strings are equal.
Expected :Binary String: 0x1b5b306d6d
Actual   :Binary String: 0x1b5b306d

一旦字符串开始变得复杂和长,这很难调试。

这似乎在最近一次对 PhpStorm 的升级中发生了变化,我目前正在运行 2016.1.2。早些时候,如果它向我显示失败,它只会隐藏转义序列,但会在标准输出中显示其余字符,因此对于“\033[0m”,它将显示“.[0m”(或实际上是我有 .") 的方形字符。无论如何,这更容易调试,因为我最感兴趣的是可打印字符。

我似乎找不到任何方法来要求 PHPUnit 以不同的方式显示它,或者 PhpStorm。我也不清楚为什么会出现这种区别。帮助!

【问题讨论】:

  • 尝试在test_escape_output中使用echo pack("H*" , "\033[0m")
  • @CarlosCarucce - 感谢您的建议,不幸的是,phpunit 响应:pack():Type H:非法十六进制数字,我认为这是指转义字符

标签: php phpunit phpstorm


【解决方案1】:

好的,所以在对此大惊小怪一段时间后,我最终使用 PHPUnit 测试替身来解决这个问题。

在正在测试的类中,我将所有转义序列集中到一个方法中。然后为该方法创建一个存根,以使用回调到另一个函数,用转义的 \e 替换所有转义字符,使其成为常规字符(而不是触发 PHPStorm 以二进制形式显示整个字符串)。

然后我可以将预期输出与普通字符串进行比较,PHPStorm 以普通文本而不是二进制形式向我显示字符串,从而使调试过程变得更加轻松。

class EscapeStrings {

    // the method that all output is sent through, so it can be stubbed
    public function output($text) {
        echo $text;
    }
}

class testClass extends PHPUnit_Framework_TestCase
{

    // replace the escape character with a printable \\e character
    public function printableEscape($text) {
        return str_replace("\e","\\e",$text);
    }

    public function testOutput() {

        // create a mock
        $stub = $this->createMock(EscapeStrings::class);

        // switch the output method to call the printable escape method with the $text parameter
        $stub->method('output')
            ->will($this->returnCallback([$this,'printableEscape']));


        // now can do normal string compare and easier debugging
        $this->assertEquals("\\e[0mHello", $stub->output("\e[0mHello"));
    }

}

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多