1

好的,这就是我遇到的问题。在我们的一些生产系统上,我们启用了魔术引号 gpc。我对此无能为力。所以,我建立了我的请求数据处理类来补偿:

protected static function clean($var)
{
     if (get_magic_quotes_gpc()) {
        if (is_array($var)) {
            foreach ($var as $k => $v) {
                $var[$k] = self::clean($v);
            }
        } else {
            $var = stripslashes($var);
        }
    }
    return $var;
}

我用这种方法做了一些其他的事情,但这不是问题。

因此,我目前正在尝试为该方法编写一组单元测试,但我遇到了障碍。我如何测试两个执行路径的结果get_magic_quotes_gpc()?我无法在运行时为此修改 ini 设置(因为它已经加载)...我尝试搜索 PHPUnit 文档,但找不到与此类问题相关的任何内容。有什么我在这里想念的吗?还是我必须忍受无法测试所有可能的代码执行路径?

谢谢

4

3 回答 3

1

我对此不是 100% 确定,但我认为 magic_quotes_gpc 只是意味着所有字符串都已addslashes()应用于它们。因此,要模拟具有magic_quotes_gpc,您可以将addlashes 递归地应用于$_GET,$_POST$_COOKIE数组。这并不能解决get_magic_quotes_gpc()将返回 false 的事实——我猜你只需要在进行适当的单元测试时替换get_magic_quotes_gpc()为。true

编辑:如http://www.php.net/manual/en/function.addslashes.php中所述

“默认情况下,PHP 指令 magic_quotes_gpc 处于启用状态,它基本上对所有 GET、POST 和 COOKIE 数据运行 addlashes()。”

于 2010-07-13T14:57:39.120 回答
1

一个可能的(但不是完美的)解决方案是将 get_magic_quotes_gpc() 的值作为参数传递,例如:

protected static function clean($var, $magic_quotes = null)
{
  if ($magic_quotes === null) $magic_quotes = get_magic_quotes_gpc();
  do_stuff();
}

Ofc 的缺点是……嗯,很丑,但是 ini 设置和定义总是很难测试,这就是为什么你应该尽量避免它们。避免直接使用它们的一种方法是:

class Config
{
  private static $magic_quotes = null;

  public static GetMagicQuotes()
  {
    if (Config::$magic_quotes === null)
    {
      Config::$magic_quotes = get_magic_quotes_gpc();
    }
    return Config::$magic_quotes;
  }

  public static SetMagicQuotes($new_value)
  {
    Config::$magic_quotes = $new_value;
  }
}

[...somewhere else...]

protected static function clean($var)
{
  if (Config::GetMagicQuotes())
  {
    do_stuff();
  }
}

[... in your tests...]


public test_clean_with_quotes()
{
  Config::SetMagicQuotes(true);
  doTests();
}

public test_clean_without_quotes()
{
  Config::SetMagicQuotes(false);
  doTests();
}
于 2010-07-13T14:59:18.197 回答
1

好吧,我遇到了一个解决方法...

在构造函数中,我调用get_magic_quotes_gpc()

protected $magicQuotes = null;

public function __construct() {
    $this->magicQuotes = get_magic_quotes_gpc();
}

protected function clean($var) {
    if ($this->magicQuotes) {
        //...
    }
}

然后,为了测试,我只是对它进行子类化,然后提供一个公共方法来手动设置$this->magicQuotes. 它不是很干净,但它很好,因为它节省了每次递归的函数调用开销......

于 2010-07-13T16:19:49.770 回答