test.class.inc.php 14 KB

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