Unit testing 使用不同的系统ini设置进行测试
好吧,这就是我遇到的问题。在我们的一些生产系统上,我们启用了magic quotes gpc。对此我无能为力。因此,我构建了请求数据处理类来补偿:Unit testing 使用不同的系统ini设置进行测试,unit-testing,phpunit,php,magic-quotes-gpc,Unit Testing,Phpunit,Php,Magic Quotes Gpc,好吧,这就是我遇到的问题。在我们的一些生产系统上,我们启用了magic quotes gpc。对此我无能为力。因此,我构建了请求数据处理类来补偿: protected static function clean($var) { if (get_magic_quotes_gpc()) { if (is_array($var)) { foreach ($var as $k => $v) { $var[$k] =
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\u magic\u quotes\u gpc()
的结果测试两个执行路径?我无法在运行时为此修改ini设置(因为它已加载)。。。我尝试搜索PHPUnit文档,但找不到任何与此类问题相关的内容。这里有我遗漏的东西吗?还是我必须忍受无法测试所有可能的代码执行路径
谢谢对此我不是100%肯定,但我认为magic\u quotes\u gpc只是意味着所有字符串都应用了
addslashes()
。因此,为了模拟magic_quotes_gpc,您可以对$\u GET
、$\u POST
和$\u COOKIE
数组递归应用addslashes。这并不能解决这样一个事实,即get\u magic\u quotes\u gpc()
将返回false——我想,在进行适当的单元测试时,您只需将get\u magic\u quotes\u gpc()
替换为true
编辑:如中所述
“PHP指令magic\u quotes\u gpc在默认情况下是打开的,它基本上对所有GET、POST和COOKIE数据运行addslashes()。一个可能的(但不是完美的)解决方案是将GET\u magic\u quotes\u 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();
}
嗯,我遇到了一个解决办法 在构造函数中,我调用
get\u magic\u quotes\u gpc()
:
然后,为了进行测试,我只需对它进行子类化,然后提供一个公共方法来手动设置
$this->magicQuotes
。它不是很干净,但很好,因为它节省了每次递归时函数调用的开销…好吧,这让我走上了正确的轨道。。。我实现了一些不同的东西(见我的答案),但它与您的两个示例相似(但不同)。。。再次感谢。。。
protected $magicQuotes = null;
public function __construct() {
$this->magicQuotes = get_magic_quotes_gpc();
}
protected function clean($var) {
if ($this->magicQuotes) {
//...
}
}