我有一个 PHPUnit 测试,它使用正则表达式验证日志文件的输出。日志文件看起来像这样(第一行是空的,但我不知道如何在这里显示):
<empty line>
lfworker01:
-----------------------------------------------------------
Last update: 2012-06-14 11:43:17
Last Segment Sent: 2009-12-02 23:25:00 (1259792700)
Current Segement: 2009-12-03 00:25:00 (1259796300)
Clicks processed Segment: 3
Open sessions Segment: 1
Duration Segment: 0,06 sec
Speed Segment: 47,67 clicks/sec
Uptime: 0 days 00:00:00
Clicks processed overall: 3
Avg Speed overall: 81,70 clicks/sec
Current memory used: 16,75 MB
Max memory used: 16,75 MB
我正在使用正则表达式验证内容:
$strExpectedMeasurementLog = "#
lfworker01:
-----------------------------------------------------------
Last update: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}
Last Segment Sent: 2009-12-02 23:25:00 \(1259792700\)
Current Segement: 2009-12-03 00:25:00 \(1259796300\)
Clicks processed Segment: 3
Open sessions Segment: 1
Duration Segment: \d*,\d{2} sec
Speed Segment: \d*,\d{2} clicks/sec
Uptime: 0 days 00:00:00
Clicks processed overall: 3
Avg Speed overall: \d*,\d{2} clicks/sec
Current memory used: \d*,\d{2} MB
Max memory used: \d*,\d{2} MB#";
$strActualMeasurementLog = file_get_contents( dirname( __FILE__)."/applogs/measurement.log");
self::assertRegExp( $strExpectedMeasurementLog, $strActualMeasurementLog);
PHPUnit 测试是在 unix 环境中创建的。本次测试在unix测试环境下通过,但在windows测试环境下失败。我通过将此函数应用于 measurement.log 文件,将 windows 换行符替换为 unix 换行符:
public function unixtodos( $strPathFile )
{
$strCurrent = file_get_contents( $strPathFile );
$strPattern = "|\r\n|";
$strReplace = "\n";
$strNew = preg_replace( $strPattern, $strReplace, $strCurrent );
file_put_contents( $strPathFile, $strNew );
}
它仍然不匹配,我没有想法:(
最佳答案
解决方案是始终检查换行符。我在 windows 机器上用 php 创建的日志文件有 unix 换行符:
在unix中从CVS check out 的PHPUnit源文件有unix换行符:
windows中CVS check out 的PHPUnit源文件有windows换行符:
这些换行符破坏了我的正则表达式验证。所以现在我总是将换行符替换为 unix 换行符。
// replace possible windows line breaks with unix line breaks
$strExpectedMeasurementLog = preg_replace( "|\r\n|", "\n", $strExpectedMeasurementLog);
$strActualMeasurementLog = preg_replace( "|\r\n|", "\n", $strActualMeasurementLog);
关于phpunit assertRegExp() 测试在 unix 中通过,在 windows 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032186/