2010-07-13 69 views
1

好的,所以这里是我遇到的问题。在我们的一些生产系统上,我们启用了魔术引擎gpc。我无能为力。所以,我建立了我的请求数据移交类补偿:不同的系统ini设置测试

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文档,但找不到与此类问题相关的任何内容。有什么我在这里失踪?或者我将不得不忍受无法测试所有可能的代码执行路径?

感谢

回答

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的公共方法。它不是很干净,但它很好,因为它可以节省每次递归函数调用的开销...

1

我不是100%肯定这一点,但我认为magic_quotes_gpc的只是意味着所有字符串有适用于他们addslashes()。因此,要模拟magic_quotes_gpc,可以递归应用addslashes到$_GET,$_POST$_COOKIE阵列。这并不能解决get_magic_quotes_gpc()会返回错误的事实 - 我想,在进行适当的单元测试时,您只需将get_magic_quotes_gpc()替换为true即可。

编辑:正如http://www.php.net/manual/en/function.addslashes.php

说 'PHP指令magic_quotes_gpc的默认是开启的,它基本上运行在所有的GET,POST,COOKIE数据使用addslashes()。'

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(); 
} 
+0

那么,这让我走上了正确的轨道......我实现了一些不同的东西(请参阅我的回答),但它是类似于你的两个例子(但不同)...再次感谢... – ircmaxell 2010-07-13 16:20:57