test.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. <?php
  2. require_once('coreexception.class.inc.php');
  3. require_once('attributedef.class.inc.php');
  4. require_once('filterdef.class.inc.php');
  5. require_once('stimulus.class.inc.php');
  6. require_once('MyHelpers.class.inc.php');
  7. require_once('expression.class.inc.php');
  8. require_once('cmdbsource.class.inc.php');
  9. require_once('sqlquery.class.inc.php');
  10. require_once('dbobject.class.php');
  11. require_once('dbobjectsearch.class.php');
  12. require_once('dbobjectset.class.php');
  13. require_once('userrights.class.inc.php');
  14. require_once('../webservices/webservices.class.inc.php');
  15. // Just to differentiate programmatically triggered exceptions and other kind of errors (usefull?)
  16. class UnitTestException extends Exception
  17. {}
  18. /**
  19. * Improved display of the backtrace
  20. *
  21. * @package iTopORM
  22. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  23. * @author Denis Flaven <denisflave@free.fr>
  24. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  25. * @link www.itop.com
  26. * @since 1.0
  27. * @version 1.1.1.1 $
  28. */
  29. class ExceptionFromError extends Exception
  30. {
  31. public function getTraceAsHtml()
  32. {
  33. $aBackTrace = $this->getTrace();
  34. return MyHelpers::get_callstack_html(0, $this->getTrace());
  35. // return "<pre>\n".$this->getTraceAsString()."</pre>\n";
  36. }
  37. }
  38. /**
  39. * Test handler API and basic helpers
  40. *
  41. * @package iTopORM
  42. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  43. * @author Denis Flaven <denisflave@free.fr>
  44. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  45. * @link www.itop.com
  46. * @since 1.0
  47. * @version 1.1.1.1 $
  48. */
  49. abstract class TestHandler
  50. {
  51. protected $m_aSuccesses;
  52. protected $m_aWarnings;
  53. protected $m_aErrors;
  54. protected $m_sOutput;
  55. public function __construct()
  56. {
  57. $this->m_aSuccesses = array();
  58. $this->m_aWarnings = array();
  59. $this->m_aErrors = array();
  60. }
  61. abstract static public function GetName();
  62. abstract static public function GetDescription();
  63. protected function DoPrepare() {return true;}
  64. abstract protected function DoExecute();
  65. protected function DoCleanup() {return true;}
  66. protected function ReportSuccess($sMessage, $sSubtestId = '')
  67. {
  68. $this->m_aSuccesses[] = $sMessage;
  69. }
  70. protected function ReportWarning($sMessage, $sSubtestId = '')
  71. {
  72. $this->m_aWarnings[] = $sMessage;
  73. }
  74. protected function ReportError($sMessage, $sSubtestId = '')
  75. {
  76. $this->m_aErrors[] = $sMessage;
  77. }
  78. public function GetResults()
  79. {
  80. return $this->m_aSuccesses;
  81. }
  82. public function GetWarnings()
  83. {
  84. return $this->m_aWarnings;
  85. }
  86. public function GetErrors()
  87. {
  88. return $this->m_aErrors;
  89. }
  90. public function GetOutput()
  91. {
  92. return $this->m_sOutput;
  93. }
  94. public function error_handler($errno, $errstr, $errfile, $errline)
  95. {
  96. // Note: return false to call the default handler (stop the program if an error)
  97. switch ($errno)
  98. {
  99. case E_USER_ERROR:
  100. $this->ReportError($errstr);
  101. //throw new ExceptionFromError("Fatal error in line $errline of file $errfile: $errstr");
  102. break;
  103. case E_USER_WARNING:
  104. $this->ReportWarning($errstr);
  105. break;
  106. case E_USER_NOTICE:
  107. $this->ReportWarning($errstr);
  108. break;
  109. default:
  110. $this->ReportWarning("Unknown error type: [$errno] $errstr in $errfile at $errline");
  111. echo "Unknown error type: [$errno] $errstr in $errfile at $errline<br />\n";
  112. break;
  113. }
  114. return true; // do not call the default handler
  115. }
  116. public function Execute()
  117. {
  118. ob_start();
  119. set_error_handler(array($this, 'error_handler'));
  120. try
  121. {
  122. $this->DoPrepare();
  123. $this->DoExecute();
  124. }
  125. catch (ExceptionFromError $e)
  126. {
  127. $this->ReportError($e->getMessage().' - '.$e->getTraceAsHtml());
  128. }
  129. catch (CoreException $e)
  130. {
  131. //$this->ReportError($e->getMessage());
  132. //$this->ReportError($e->__tostring());
  133. $this->ReportError($e->getMessage().' - '.$e->getTraceAsHtml());
  134. }
  135. catch (Exception $e)
  136. {
  137. //$this->ReportError($e->getMessage());
  138. //$this->ReportError($e->__tostring());
  139. $this->ReportError('class '.get_class($e).' --- '.$e->getMessage().' - '.$e->getTraceAsString());
  140. }
  141. restore_error_handler();
  142. $this->m_sOutput = ob_get_clean();
  143. return (count($this->GetErrors()) == 0);
  144. }
  145. }
  146. /**
  147. * Test to execute a piece of code (checks if an error occurs)
  148. *
  149. * @package iTopORM
  150. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  151. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  152. * @link www.itop.com
  153. * @since 1.0
  154. * @version $itopversion$
  155. */
  156. abstract class TestFunction extends TestHandler
  157. {
  158. // simply overload DoExecute (temporary)
  159. }
  160. /**
  161. * Test to execute a piece of code (checks if an error occurs)
  162. *
  163. * @package iTopORM
  164. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  165. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  166. * @link www.itop.com
  167. * @since 1.0
  168. * @version $itopversion$
  169. */
  170. abstract class TestWebServices extends TestHandler
  171. {
  172. // simply overload DoExecute (temporary)
  173. static protected function DoPostRequestAuth($sRelativeUrl, $aData, $sLogin = 'admin', $sPassword = 'admin', $sOptionnalHeaders = null)
  174. {
  175. $aDataAndAuth = $aData;
  176. $aDataAndAuth['operation'] = 'login';
  177. $aDataAndAuth['auth_user'] = $sLogin;
  178. $aDataAndAuth['auth_pwd'] = $sPassword;
  179. $sHost = $_SERVER['HTTP_HOST'];
  180. $sRawPath = $_SERVER['SCRIPT_NAME'];
  181. $sPath = dirname($sRawPath);
  182. $sUrl = "http://$sHost/$sPath/$sRelativeUrl";
  183. return self::DoPostRequest($sUrl, $aDataAndAuth, $sOptionnalHeaders);
  184. }
  185. // Source: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
  186. // originaly named after do_post_request
  187. // Partially adapted to our coding conventions
  188. static protected function DoPostRequest($sUrl, $aData, $sOptionnalHeaders = null)
  189. {
  190. // $sOptionnalHeaders is a string containing additional HTTP headers that you would like to send in your request.
  191. $sData = http_build_query($aData);
  192. $aParams = array('http' => array(
  193. 'method' => 'POST',
  194. 'content' => $sData,
  195. 'header'=> "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($sData)."\r\n",
  196. ));
  197. if ($sOptionnalHeaders !== null)
  198. {
  199. $aParams['http']['header'] .= $sOptionnalHeaders;
  200. }
  201. $ctx = stream_context_create($aParams);
  202. $fp = @fopen($sUrl, 'rb', false, $ctx);
  203. if (!$fp)
  204. {
  205. throw new Exception("Problem with $sUrl, $php_errormsg");
  206. }
  207. $response = @stream_get_contents($fp);
  208. if ($response === false)
  209. {
  210. throw new Exception("Problem reading data from $sUrl, $php_errormsg");
  211. }
  212. return $response;
  213. }
  214. }
  215. /**
  216. * Test to execute a piece of code (checks if an error occurs)
  217. *
  218. * @package iTopORM
  219. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  220. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  221. * @link www.itop.com
  222. * @since 1.0
  223. * @version $itopversion$
  224. */
  225. abstract class TestSoapWebService extends TestHandler
  226. {
  227. // simply overload DoExecute (temporary)
  228. function __construct()
  229. {
  230. parent::__construct();
  231. }
  232. }
  233. /**
  234. * Test to check that a function outputs some values depending on its input
  235. *
  236. * @package iTopORM
  237. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  238. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  239. * @link www.itop.com
  240. * @since 1.0
  241. * @version $itopversion$
  242. */
  243. abstract class TestFunctionInOut extends TestFunction
  244. {
  245. abstract static public function GetCallSpec(); // parameters to call_user_func
  246. abstract static public function GetInOut(); // array of input => output
  247. protected function DoExecute()
  248. {
  249. $aTests = $this->GetInOut();
  250. if (is_array($aTests))
  251. {
  252. foreach ($aTests as $iTestId => $aTest)
  253. {
  254. $ret = call_user_func_array($this->GetCallSpec(), $aTest['args']);
  255. if ($ret != $aTest['output'])
  256. {
  257. // Note: to be improved to cope with non string parameters
  258. $this->ReportError("Found '$ret' while expecting '".$aTest['output']."'", $iTestId);
  259. }
  260. else
  261. {
  262. $this->ReportSuccess("Found the expected output '$ret'", $iTestId);
  263. }
  264. }
  265. }
  266. else
  267. {
  268. $ret = call_user_func($this->GetCallSpec());
  269. $this->ReportSuccess('Finished successfully');
  270. }
  271. }
  272. }
  273. /**
  274. * Test to check an URL (Searches for Error/Warning/Etc keywords)
  275. *
  276. * @package iTopORM
  277. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  278. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  279. * @link www.itop.com
  280. * @since 1.0
  281. * @version $itopversion$
  282. */
  283. abstract class TestUrl extends TestHandler
  284. {
  285. abstract static public function GetUrl();
  286. abstract static public function GetErrorKeywords();
  287. abstract static public function GetWarningKeywords();
  288. protected function DoExecute()
  289. {
  290. return true;
  291. }
  292. }
  293. /**
  294. * Test to check a user management module
  295. *
  296. * @package iTopORM
  297. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  298. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  299. * @link www.itop.com
  300. * @since 1.0
  301. * @version $itopversion$
  302. */
  303. abstract class TestUserRights extends TestHandler
  304. {
  305. protected function DoExecute()
  306. {
  307. return true;
  308. }
  309. }
  310. /**
  311. * Test to execute a scenario on a given DB
  312. *
  313. * @package iTopORM
  314. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  315. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  316. * @link www.itop.com
  317. * @since 1.0
  318. * @version $itopversion$
  319. */
  320. abstract class TestScenarioOnDB extends TestHandler
  321. {
  322. abstract static public function GetDBHost();
  323. abstract static public function GetDBUser();
  324. abstract static public function GetDBPwd();
  325. abstract static public function GetDBName();
  326. protected function DoPrepare()
  327. {
  328. $sDBHost = $this->GetDBHost();
  329. $sDBUser = $this->GetDBUser();
  330. $sDBPwd = $this->GetDBPwd();
  331. $sDBName = $this->GetDBName();
  332. CMDBSource::Init($sDBHost, $sDBUser, $sDBPwd);
  333. if (CMDBSource::IsDB($sDBName))
  334. {
  335. CMDBSource::DropDB($sDBName);
  336. }
  337. CMDBSource::CreateDB($sDBName);
  338. }
  339. protected function DoCleanup()
  340. {
  341. // CMDBSource::DropDB($this->GetDBName());
  342. }
  343. }
  344. /**
  345. * Test to use a business model on a given DB
  346. *
  347. * @package iTopORM
  348. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  349. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  350. * @link www.itop.com
  351. * @since 1.0
  352. * @version $itopversion$
  353. */
  354. abstract class TestBizModel extends TestHandler
  355. {
  356. // abstract static public function GetDBSubName();
  357. // abstract static public function GetBusinessModelFile();
  358. abstract static public function GetConfigFile();
  359. protected function DoPrepare()
  360. {
  361. MetaModel::Startup($this->GetConfigFile(), true); // allow missing DB
  362. MetaModel::CheckDefinitions();
  363. // something here to create records... but that's another story
  364. }
  365. protected $m_oChange;
  366. protected function ObjectToDB($oNew, $bReload = false)
  367. {
  368. list($bRes, $aIssues) = $oNew->CheckToInsert();
  369. if (!$bRes)
  370. {
  371. throw new CoreException('Could not create object, unexpected values', array('attributes' => $aIssues));
  372. }
  373. if ($oNew instanceof CMDBObject)
  374. {
  375. if (!isset($this->m_oChange))
  376. {
  377. new CMDBChange();
  378. $oMyChange = MetaModel::NewObject("CMDBChange");
  379. $oMyChange->Set("date", time());
  380. $oMyChange->Set("userinfo", "Someone doing some tests");
  381. $iChangeId = $oMyChange->DBInsertNoReload();
  382. $this->m_oChange = $oMyChange;
  383. }
  384. if ($bReload)
  385. {
  386. $iId = $oNew->DBInsertTracked($this->m_oChange);
  387. }
  388. else
  389. {
  390. $iId = $oNew->DBInsertTrackedNoReload($this->m_oChange);
  391. }
  392. }
  393. else
  394. {
  395. if ($bReload)
  396. {
  397. $iId = $oNew->DBInsert();
  398. }
  399. else
  400. {
  401. $iId = $oNew->DBInsertNoReload();
  402. }
  403. }
  404. return $iId;
  405. }
  406. protected function ResetDB()
  407. {
  408. if (MetaModel::DBExists(false))
  409. {
  410. MetaModel::DBDrop();
  411. }
  412. MetaModel::DBCreate();
  413. }
  414. static protected function show_list($oObjectSet)
  415. {
  416. $oObjectSet->Rewind();
  417. $aData = array();
  418. while ($oItem = $oObjectSet->Fetch())
  419. {
  420. $aValues = array();
  421. foreach(MetaModel::GetAttributesList(get_class($oItem)) as $sAttCode)
  422. {
  423. $aValues[$sAttCode] = $oItem->GetAsHTML($sAttCode);
  424. }
  425. //echo $oItem->GetKey()." => ".implode(", ", $aValues)."</br>\n";
  426. $aData[] = $aValues;
  427. }
  428. echo MyHelpers::make_table_from_assoc_array($aData);
  429. }
  430. static protected function search_and_show_list(DBObjectSearch $oMyFilter)
  431. {
  432. $oObjSet = new CMDBObjectSet($oMyFilter);
  433. echo $oMyFilter->__DescribeHTML()."' - Found ".$oObjSet->Count()." items.</br>\n";
  434. self::show_list($oObjSet);
  435. }
  436. static protected function search_and_show_list_from_sibusql($sSibuSQL)
  437. {
  438. echo $sSibuSQL."...<br/>\n";
  439. $oNewFilter = DBObjectSearch::FromSibuSQL($sSibuSQL);
  440. self::search_and_show_list($oNewFilter);
  441. }
  442. }
  443. /**
  444. * Test to execute a scenario common to any business model (tries to build all the possible queries, etc.)
  445. *
  446. * @package iTopORM
  447. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  448. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  449. * @link www.itop.com
  450. * @since 1.0
  451. * @version $itopversion$
  452. */
  453. abstract class TestBizModelGeneric extends TestBizModel
  454. {
  455. static public function GetName()
  456. {
  457. return 'Full test on a given business model';
  458. }
  459. static public function GetDescription()
  460. {
  461. return 'Systematic tests: gets each and every existing class and tries every attribute, search filters, etc.';
  462. }
  463. protected function DoPrepare()
  464. {
  465. parent::DoPrepare();
  466. if (!MetaModel::DBExists(false))
  467. {
  468. MetaModel::DBCreate();
  469. }
  470. // something here to create records... but that's another story
  471. }
  472. protected function DoExecute()
  473. {
  474. foreach(MetaModel::GetClasses() as $sClassName)
  475. {
  476. if (MetaModel::IsAbstract($sClassName)) continue;
  477. $oNobody = MetaModel::GetObject($sClassName, 123);
  478. $oBaby = new $sClassName;
  479. $oFilter = new DBObjectSearch($sClassName);
  480. // Challenge reversibility of SibusQL / filter object
  481. //
  482. $sExpr1 = $oFilter->ToSibuSQL();
  483. $oNewFilter = DBObjectSearch::FromSibuSQL($sExpr1);
  484. $sExpr2 = $oNewFilter->ToSibuSQL();
  485. if ($sExpr1 != $sExpr2)
  486. {
  487. $this->ReportError("Found two different SibuSQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  488. }
  489. // Use the filter (perform the query)
  490. //
  491. $oSet = new CMDBObjectSet($oFilter);
  492. $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  493. }
  494. return true;
  495. }
  496. }
  497. ?>