test.class.inc.php 13 KB

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