2010-07-13 71 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