代码之家  ›  专栏  ›  技术社区  ›  ircmaxell

使用不同的系统ini设置进行测试

  •  1
  • ircmaxell  · 技术社区  · 15 年前

    好吧,这就是我遇到的问题。在我们的一些生产系统上,我们启用了Magic Quotes 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;
    }
    

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

    所以,我目前正在为这个方法编写一组单元测试,我遇到了一个road-bock。如何测试两个执行路径的结果 get_magic_quotes_gpc() ?我无法在运行时为此修改ini设置(因为它已加载)…我试过搜索phpunit文档,但找不到任何与此类问题相关的内容。我这里有什么东西不见了吗?或者我将不得不忍受无法测试所有可能的代码执行路径?

    谢谢

    3 回复  |  直到 15 年前
        1
  •  1
  •   Hammerite    15 年前

    对此我不是百分之百的确定,但我认为magic-quotes只是意味着所有字符串都有 addslashes() 适用于他们。因此,为了模拟具有魔力的引号,可以递归地将addslashes应用到 $_GET , $_POST $_COOKIE 数组。但这并不能解决 get_magic_quotes_gpc() 将返回错误-您只需替换 获取_magic_quotes_gpc() 具有 true 当进行适当的单元测试时,我想。

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

    “默认情况下,php指令magic_quotes_gpc处于打开状态,它基本上在所有get、post和cookie数据上运行addslashes()。”

        2
  •  1
  •   Morfildur    15 年前

    一个可能的(但不是完美的)解决方案是将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();
    }
    
        3
  •  1
  •   ircmaxell    15 年前

    嗯,我遇到了一个解决办法…

    在构造函数中,我调用 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 . 它不是很干净,但很好,因为它节省了每次递归时函数调用的开销…