防止在测试期间将 error_log() 消息打印到终端
Prevent error_log() messages to be printed to the terminal during tests
如标题所述,我期待找到一种方法来防止在 PHPUnit
测试期间在终端中打印 error_log()
消息。
在上面的示例中,被测方法通过 error_log('Don\'t show up'),在测试之间打印其消息。
有什么方法可以防止这种行为,让我的测试日志看起来很漂亮吗?另外,有什么方法可以捕获消息并测试其输出吗? (对于消息不是简单字符串的情况)。
您可以使用 set_error_handler()
. In the comment #112881 定义您自己的错误处理程序您可以查看使用回调的示例,您可以根据需要进行调整,例如记录到文件,简单地忽略或其他。
您可以将其放入您的 phpunit bootstrap 文件中,这样就可以了。
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn't a simple string).
首先你看到的不是测试日志。 显示 的错误消息实际上是在标准错误流上,而不是在标准输出流上。对于您所看到的,这没有太大区别,因为终端显示两者混合,记录到文件不会记录该错误消息。
这是 b/c error_log()
将错误消息写入配置的日志文件(PHP 的 error_log
ini 指令)。由于 Phpunit 使用 PHP 的 CLI 版本(在命令行上)运行,默认情况下是上述标准错误流。
这还包含所有需要的信息,而不是输出到标准错误流,而是捕获它,例如暂时测试一下:
$capture = tmpfile();
$saved = ini_set('error_log', stream_get_meta_data($capture)['uri']);
error_log("Test for this message");
ini_set('error_log', $saved);
var_dump(stream_get_contents($capture));
这将提供通过 error_log()
和临时文件输出的内容:
string(59) "[06-Jul-2017 12:14:45 Europe/Amsterdam] Test for this message
"
临时文件会在测试用例结束时自动删除。
您应该为您的脚本设置正确的日志文件路径,使其具有足够的写入权限。
您可以设置错误日志文件路径如下:
ini_set("error_log", "log_file_name.log");
你可以像
一样给出绝对路径
/tmp/logs/script_output.log
或相对路径也是如此。
如标题所述,我期待找到一种方法来防止在 PHPUnit
测试期间在终端中打印 error_log()
消息。
在上面的示例中,被测方法通过 error_log('Don\'t show up'),在测试之间打印其消息。
有什么方法可以防止这种行为,让我的测试日志看起来很漂亮吗?另外,有什么方法可以捕获消息并测试其输出吗? (对于消息不是简单字符串的情况)。
您可以使用 set_error_handler()
. In the comment #112881 定义您自己的错误处理程序您可以查看使用回调的示例,您可以根据需要进行调整,例如记录到文件,简单地忽略或其他。
您可以将其放入您的 phpunit bootstrap 文件中,这样就可以了。
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn't a simple string).
首先你看到的不是测试日志。 显示 的错误消息实际上是在标准错误流上,而不是在标准输出流上。对于您所看到的,这没有太大区别,因为终端显示两者混合,记录到文件不会记录该错误消息。
这是 b/c error_log()
将错误消息写入配置的日志文件(PHP 的 error_log
ini 指令)。由于 Phpunit 使用 PHP 的 CLI 版本(在命令行上)运行,默认情况下是上述标准错误流。
这还包含所有需要的信息,而不是输出到标准错误流,而是捕获它,例如暂时测试一下:
$capture = tmpfile();
$saved = ini_set('error_log', stream_get_meta_data($capture)['uri']);
error_log("Test for this message");
ini_set('error_log', $saved);
var_dump(stream_get_contents($capture));
这将提供通过 error_log()
和临时文件输出的内容:
string(59) "[06-Jul-2017 12:14:45 Europe/Amsterdam] Test for this message
"
临时文件会在测试用例结束时自动删除。
您应该为您的脚本设置正确的日志文件路径,使其具有足够的写入权限。
您可以设置错误日志文件路径如下:
ini_set("error_log", "log_file_name.log");
你可以像
一样给出绝对路径/tmp/logs/script_output.log
或相对路径也是如此。