[英]Simpletest: Testing echo statements?
我剛剛用最簡單的方法測試了一些PHP文件,發現它與實際輸出(回聲)任何東西的功能不能很好地配合使用。
那么,在PHP中不使用ob_buffer()
情況下,我可以做些什么來測試回聲的功能嗎?
謝謝
如果要測試輸出本身的有效性,則否。 不是沒有輸出緩沖區。 但是,您可以使用JavaScript對其進行測試。 您甚至可以通過將輸出通過ajax返回到另一個線程來以最簡單的方式對其進行測試。
迂回? 哦耶寶寶。
使用以下完全愚蠢的方法應該可以為您提供所需的信息。 嘿...寫起來很有趣:)
<?php
/**
* The function which output you want to test.
*
* @param string $arg1
* @param string $arg2
*/
function function_with_echo($arg1, $arg2) {
$c = array();
echo "X";
foreach (range(0,2) as $i) {
print $i * 2 . $arg2;
}
echo "Yir $arg1";
}
/**
* Stupid, too big, ugly function that takes a function and creates a new
* function with two underscores prefixed (__) where all echo and print
* statements instead are collected into a temporary variable and returned.
* Does not work for functions that already returns something, although
* that could be fixed too!
*
* @param string $function_name
*/
function change_output_to_return($function_name) {
$r = new ReflectionFunction($function_name);
$lines = array_slice(
file($r->getFileName()),
$r->getStartLine() - 1,
$r->getEndLine() - $r->getStartLine() + 1
);
$first = array_shift($lines);
array_unshift($lines, $first, '$__temp = "";' . "\n");
$last = array_pop($lines);
array_push($lines, 'return $__temp;' . "\n", $last);
$code = "<?php " . implode("", $lines);
$echo_free_code = '';
foreach(token_get_all($code) as $token) {
if(is_array($token)) {
if (in_array(token_name($token[0]), array('T_ECHO', 'T_PRINT'))) {
$echo_free_code .= '$__temp .= ';
} else {
$echo_free_code .= $token[1];
}
} else {
$echo_free_code .= $token;
}
}
$echo_free_code = str_replace($function_name, "__$function_name", $echo_free_code);
eval("?>$echo_free_code");
}
// Creates a function called "__function_with_echo" that returns a string
// instead of outputting it using "print" and "echo".
change_output_to_return('function_with_echo');
// Stuff contains the outputted data from "function_with_echo".
$stuff = __function_with_echo('fun', 'stuff');
var_dump($stuff);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.