首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Simpletest:测试echo语句?

Simpletest:测试echo语句?
EN

Stack Overflow用户
提问于 2010-11-18 03:11:17
回答 2查看 1.2K关注 0票数 2

我刚刚用simpletest测试了一些PHP文件,发现它在实际输出(回显)任何东西的函数上都不能很好地工作。

那么,在不使用ob_buffer()的情况下,我可以做些什么来测试回显的函数呢?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-18 03:20:22

如果您要测试输出本身的有效性,则不可以。在没有输出缓冲区的情况下不能。但是,您可以使用JavaScript对其进行测试。您甚至可以使用simpletest测试它,方法是通过ajax将输出传递回另一个线程。

转来转去?哦是的宝贝儿。

票数 1
EN

Stack Overflow用户

发布于 2010-11-18 04:51:29

使用下面这种完全愚蠢的方法应该会给你想要的东西。嘿..。写起来很有趣:)

代码语言:javascript
复制
<?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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4208165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档