函數
今天忽然想到的,就寫了一段測試php函數的代碼。
<?php
/**
* 參數數組$ParamList說明
*
* 數組的第一維索引是需要測試的函數的參數名,第二維的每個元素是該參數需要測試的可能值,元素值可以為數組。
*/
$ParamList = array("Param1" => array(3,4,3,2,1),
"Param2" => array(3,2,5),
"Param3" => array(0,0.5,1,1.5));
// 測試函數
sysTestFunction("Test", $ParamList);
// 待測試的函數
function Test($Param1, $Param2, $Param3)
{
return $Param1 . "|" . $Param2 . "|" . $Param3;
}
/**
* 自動化的測試
*
* @author 李玉鵬<leeyupeng@163.com>
* @param string $FunctionName 函數名稱
* @param array $ParamList 參數列表
* @return array
*/
function sysTestFunction($FunctionName, $ParamList)
{
if(empty($FunctionName))
{
echo "函數名不可為空";
return false;
}
if(!is_array(current($ParamList)))
{
echo "參數不是2維數組";
return false;
}
$TestParamList = sysCombineArray($ParamList);
echo "開始測試函數" . $FunctionName . "<br />";
foreach($TestParamList as $Key => $TestParamInfo)
{
echo "開始測試第" . $Key . "組參數:<br />";
foreach($TestParamInfo as $ParamKey => $Param)
{
${"Param" . $ParamKey} = $Param;
$TempParamList[] = "$Param" . $ParamKey;
if(is_array($Param))
{
echo "參數" . $ParamKey . ",類型為數組:";
echo "<pre>";
print_r($Param);
}
elseif(is_bool($Param))
{
echo "參數" . $ParamKey . ",類型為boll:";
if($Param)
{
echo "true";
}
else
{
echo "false";
}
}
else
{
echo "參數" . $ParamKey . ",類型為字串或數字:";
echo $Param;
}
echo "<br />";
}
$Params = join(", ", $TempParamList);
unset($TempParamList);
eval("$TestReturnResult = " . $FunctionName . "(" . $Params . ");");
if(is_array($TestReturnResult))
{
echo "函數返回數組:<pre>";
print_r($TestReturnResult);
}
elseif(is_bool($TestReturnResult))
{
if($TestReturnResult)
{
echo "函數返回true";
}
else
{
echo "函數返回false";
}
}
else
{
echo "函數返回數字或字串:" . $TestReturnResult;
}
echo "<br /><br />";
}
}
/**
* 計算群組合的函數
*
* @author 李玉鵬<leeyupeng@163.com>
* @param array $CombinList 待排列組合的2維數組
* @return array 組合後的數組
*/
function sysCombineArray($CombinList)
{
if(!is_array(current($CombinList)))
{
echo "參數不是2維數組";
return false;
}
/* 計算C(a,1) * C(b, 1) * ... * C(n, 1)的值 */
$CombineCount = 1;
foreach($CombinList as $Key => $Value)
{
$CombineCount *= count($Value);
}
$RepeatTime = $CombineCount;
foreach($CombinList as $ClassNo => $ParamList)
{
// $ParamList中的元素在拆分成組合後縱向出現的最大重複次數
$RepeatTime = $RepeatTime / count($ParamList);
$StartPosition = 1;
foreach($ParamList as $Param)
{
$TempStartPosition = $StartPosition;
$SpaceCount = $CombineCount / count($ParamList) / $RepeatTime;
for($J = 1; $J <= $SpaceCount; $J ++)
{
for($I = 0; $I < $RepeatTime; $I ++)
{
$Result[$TempStartPosition + $I][$ClassNo] = $Param;
}
$TempStartPosition += $RepeatTime * count($ParamList);
}
$StartPosition += $RepeatTime;
}
}
return $Result;
}
?>