testlist.inc.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  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 test list
  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. class TestSQLQuery extends TestScenarioOnDB
  25. {
  26. static public function GetName() {return 'SQLQuery';}
  27. static public function GetDescription() {return 'SQLQuery does not depend on the rest of the framework, therefore it makes sense to have a separate test framework for it';}
  28. static public function GetDBHost() {return 'localhost';}
  29. static public function GetDBUser() {return 'root';}
  30. static public function GetDBPwd() {return '';}
  31. static public function GetDBName() {return 'TestSQLQuery';}
  32. static public function GetDBSubName() {return 'taratata';}
  33. protected function DoPrepare()
  34. {
  35. parent::DoPrepare();
  36. cmdbSource::CreateTable('CREATE TABLE `myTable` (myKey INT(11) NOT NULL auto_increment, column1 VARCHAR(255), column2 VARCHAR(255), PRIMARY KEY (`myKey`)) ENGINE = '.MYSQL_ENGINE);
  37. cmdbSource::CreateTable('CREATE TABLE `myTable1` (myKey1 INT(11) NOT NULL auto_increment, column1_1 VARCHAR(255), column1_2 VARCHAR(255), PRIMARY KEY (`myKey1`)) ENGINE = '.MYSQL_ENGINE);
  38. cmdbSource::CreateTable('CREATE TABLE `myTable2` (myKey2 INT(11) NOT NULL auto_increment, column2_1 VARCHAR(255), column2_2 VARCHAR(255), PRIMARY KEY (`myKey2`)) ENGINE = '.MYSQL_ENGINE);
  39. }
  40. protected function DoExecute()
  41. {
  42. $oQuery = new SQLQuery(
  43. $sTable = 'myTable',
  44. $sTableAlias = 'myTableAlias',
  45. $aFields = array('column1'=>new FieldExpression('column1', 'myTableAlias'), 'column2'=>new FieldExpression('column2', 'myTableAlias')),
  46. $oCondition = new BinaryExpression(new FieldExpression('column1', 'myTableAlias'), 'LIKE', new ScalarExpression('trash')),
  47. $aFullTextNeedles = array('column1'),
  48. $bToDelete = false,
  49. $aValues = array()
  50. );
  51. $oQuery->AddCondition(Expression::FromOQL('DATE(NOW() - 1200 * 2) > \'2008-07-31\''));
  52. $oSubQuery1 = new SQLQuery(
  53. $sTable = 'myTable1',
  54. $sTableAlias = 'myTable1Alias',
  55. $aFields = array('column1_1'=>new FieldExpression('column1', 'myTableAlias'), 'column1_2'=>new FieldExpression('column1', 'myTableAlias')),
  56. $oCondition = new TrueSQLExpression,
  57. $aFullTextNeedles = array(),
  58. $bToDelete = false,
  59. $aValues = array()
  60. );
  61. $oSubQuery2 = new SQLQuery(
  62. $sTable = 'myTable2',
  63. $sTableAlias = 'myTable2Alias',
  64. $aFields = array('column2_1'=>new FieldExpression('column2', 'myTableAlias'), 'column2_2'=>new FieldExpression('column2', 'myTableAlias')),
  65. $oCondition = new TrueSQLExpression,
  66. $aFullTextNeedles = array(),
  67. $bToDelete = false,
  68. $aValues = array()
  69. );
  70. $oQuery->AddInnerJoin($oSubQuery1, 'column1', 'column1_1');
  71. $oQuery->AddLeftJoin($oSubQuery2, 'column2', 'column2_2');
  72. $oQuery->DisplayHtml();
  73. $oQuery->RenderDelete();
  74. $oQuery->RenderUpdate();
  75. echo '<p>'.$oQuery->RenderSelect().'</p>';
  76. $oQuery->RenderSelect(array('column1'));
  77. $oQuery->RenderSelect(array('column1', 'column2'));
  78. }
  79. }
  80. class TestOQLParser extends TestFunction
  81. {
  82. static public function GetName() {return 'Check OQL parsing';}
  83. static public function GetDescription() {return 'Attempts a series of queries, and in particular those with a bad syntax';}
  84. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  85. {
  86. $oOql = new OqlInterpreter($sQuery);
  87. try
  88. {
  89. $oTrash = $oOql->Parse(); // Not expecting a given format, otherwise use ParseExpression/ParseObjectQuery/ParseValueSetQuery
  90. self::DumpVariable($oTrash);
  91. }
  92. catch (OQLException $OqlException)
  93. {
  94. if ($bIsCorrectQuery)
  95. {
  96. echo "<p>More info on this unexpected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  97. throw $OqlException;
  98. return false;
  99. }
  100. else
  101. {
  102. // Everything is fine :-)
  103. echo "<p>More info on this expected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  104. return true;
  105. }
  106. }
  107. // The query was correctly parsed, was it expected to be correct ?
  108. if ($bIsCorrectQuery)
  109. {
  110. return true;
  111. }
  112. else
  113. {
  114. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  115. return false;
  116. }
  117. }
  118. protected function TestQuery($sQuery, $bIsCorrectQuery)
  119. {
  120. if (!$this->CheckQuery($sQuery, $bIsCorrectQuery))
  121. {
  122. return false;
  123. }
  124. return true;
  125. }
  126. public function DoExecute()
  127. {
  128. $aQueries = array(
  129. 'SELECT toto' => true,
  130. 'SELECT toto WHERE toto.a = 1' => true,
  131. 'SELECT toto WHERE toto.a=1' => true,
  132. 'SELECT toto WHERE toto.a = "1"' => true,
  133. 'SELECT toto WHHHERE toto.a = "1"' => false,
  134. 'SELECT toto WHERE toto.a == "1"' => false,
  135. 'SELECT toto WHERE toto.a % 1' => false,
  136. //'SELECT toto WHERE toto.a LIKE 1' => false,
  137. 'SELECT toto WHERE toto.a like \'arg\'' => false,
  138. 'SELECT toto WHERE toto.a NOT LIKE "That\'s it"' => true,
  139. 'SELECT toto WHERE toto.a NOT LIKE "That\'s "it""' => false,
  140. 'SELECT toto WHERE toto.a NOT LIKE "That\'s \\"it\\""' => true,
  141. 'SELECT toto WHERE toto.a NOT LIKE \'That"s it\'' => true,
  142. 'SELECT toto WHERE toto.a NOT LIKE \'That\'s it\'' => false,
  143. 'SELECT toto WHERE toto.a NOT LIKE \'That\\\'s it\'' => true,
  144. 'SELECT toto WHERE toto.a NOT LIKE "blah \\ truc"' => false,
  145. 'SELECT toto WHERE toto.a NOT LIKE "blah \\\\ truc"' => true,
  146. 'SELECT toto WHERE toto.a NOT LIKE \'blah \\ truc\'' => false,
  147. 'SELECT toto WHERE toto.a NOT LIKE \'blah \\\\ truc\'' => true,
  148. 'SELECT toto WHERE toto.a NOT LIKE "\\\\"' => true,
  149. 'SELECT toto WHERE toto.a NOT LIKE "\\""' => true,
  150. 'SELECT toto WHERE toto.a NOT LIKE "\\"\\\\"' => true,
  151. 'SELECT toto WHERE toto.a NOT LIKE "\\\\\\""' => true,
  152. 'SELECT toto WHERE toto.a NOT LIKE ""' => true,
  153. 'SELECT toto WHERE toto.a NOT LIKE "\\\\"' => true,
  154. "SELECT UserRightsMatrixClassGrant WHERE UserRightsMatrixClassGrant.class = 'lnkContactRealObject' AND UserRightsMatrixClassGrant.action = 'modify' AND UserRightsMatrixClassGrant.login = 'Denis'" => true,
  155. "SELECT A WHERE A.col1 = 'lit1' AND A.col2 = 'lit2' AND A.col3 = 'lit3'" => true,
  156. 'SELECT toto WHERE toto.a NOT LIKE "blah" AND toto.b LIKE "foo"' => true,
  157. //'SELECT toto WHERE toto.a > \'asd\'' => false,
  158. 'SELECT toto WHERE toto.a = 1 AND toto.b LIKE "x" AND toto.f >= 12345' => true,
  159. 'SELECT Device JOIN Site ON Device.site = Site.id' => true,
  160. 'SELECT Device JOIN Site ON Device.site = Site.id JOIN Country ON Site.location = Country.id' => true,
  161. "SELECT A JOIN B ON A.myB = B.id WHERE (A.col1 = 123 AND B.col1 = 'aa') OR (A.col3 = 'zzz' AND B.col4 > 100)" => true,
  162. "SELECT A JOIN B ON A.myB = B.id WHERE (A.col1 = B.col2 AND B.col1 = A.col2) OR (A.col3 = '' AND B.col4 > 100)" => true,
  163. "SELECT A JOIN B ON A.myB = B.id WHERE A.col1 + B.col2 * B.col1 = A.col2" => true,
  164. "SELECT A JOIN B ON A.myB = B.id WHERE A.col1 + (B.col2 * B.col1) = A.col2" => true,
  165. "SELECT A JOIN B ON A.myB = B.id WHERE (A.col1 + B.col2) * B.col1 = A.col2" => true,
  166. 'SELECT Device AS D_ JOIN Site AS S_ ON D_.site = S_.id WHERE S_.country = "Francia"' => true,
  167. // Several objects in a row...
  168. //
  169. 'SELECT A FROM A' => true,
  170. 'SELECT A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  171. 'SELECT A FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  172. 'SELECT B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  173. 'SELECT A,B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  174. 'SELECT A, B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  175. 'SELECT B,A FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  176. 'SELECT A, B,C FROM A JOIN B ON A.myB = B.id' => false,
  177. 'SELECT C FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => false,
  178. );
  179. $iErrors = 0;
  180. foreach($aQueries as $sQuery => $bIsCorrectQuery)
  181. {
  182. $sIsOk = $bIsCorrectQuery ? 'good' : 'bad';
  183. echo "<h4>Testing query: $sQuery ($sIsOk)</h4>\n";
  184. $bRet = $this->TestQuery($sQuery, $bIsCorrectQuery);
  185. if (!$bRet) $iErrors++;
  186. }
  187. return ($iErrors == 0);
  188. }
  189. }
  190. class TestCSVParser extends TestFunction
  191. {
  192. static public function GetName() {return 'Check CSV parsing';}
  193. static public function GetDescription() {return 'Loads a set of CSV data';}
  194. public function DoExecute()
  195. {
  196. $sDataFile = '?field1?;?field2?;?field3?
  197. ?a?;?b?;?c?
  198. a;b;c
  199. ? a ? ; ? b ? ; ? c ?
  200. a ; b ; c
  201. ??;??;??
  202. ;;
  203. ?a"?;?b?;?c?
  204. ?a1
  205. a2?;?b?;?c?
  206. ?a1,a2?;?b?;?c?
  207. ?a?;?b?;?c1,",c2
  208. ,c3?
  209. ?a?;?b?;?ouf !?
  210. Espace sur la fin ; 1234; e@taloc.com ';
  211. self::DumpVariable($sDataFile);
  212. $aExpectedResult = array(
  213. //array('field1', 'field2', 'field3'),
  214. array('a', 'b', 'c'),
  215. array('a', 'b', 'c'),
  216. array(' a ', ' b ', ' c '),
  217. array('a', 'b', 'c'),
  218. array('', '', ''),
  219. array('', '', ''),
  220. array('a"', 'b', 'c'),
  221. array("a1\na2", 'b', 'c'),
  222. array('a1,a2', 'b', 'c'),
  223. array('a', 'b', "c1,\",c2\n,c3"),
  224. array('a', 'b', 'ouf !'),
  225. array('Espace sur la fin', '1234', 'e@taloc.com'),
  226. );
  227. $oCSVParser = new CSVParser($sDataFile, ';', '?');
  228. $aData = $oCSVParser->ToArray(1, null, 0);
  229. $iIssues = 0;
  230. echo "<table border=\"1\">\n";
  231. foreach ($aData as $iRow => $aRow)
  232. {
  233. echo "<tr>\n";
  234. foreach ($aRow as $iCol => $sCell)
  235. {
  236. if (empty($sCell))
  237. {
  238. $sCellValue = '&nbsp;';
  239. }
  240. else
  241. {
  242. $sCellValue = htmlentities($sCell);
  243. }
  244. if (!isset($aExpectedResult[$iRow][$iCol]))
  245. {
  246. $iIssues++;
  247. $sCellValue = "<span style =\"color: red; background-color: grey;\">$sCellValue</span>";
  248. }
  249. elseif ($aExpectedResult[$iRow][$iCol] != $sCell)
  250. {
  251. $iIssues++;
  252. $sCellValue = "<span style =\"color: red; background-color: lightgrey;\">$sCellValue</span>, expecting '<span style =\"color: green; background-color: lightgrey;\">".$aExpectedResult[$iRow][$iCol]."</span>'";
  253. }
  254. echo "<td><pre>$sCellValue</pre></td>";
  255. }
  256. echo "</tr>\n";
  257. }
  258. echo "</table>\n";
  259. return ($iIssues > 0);
  260. }
  261. }
  262. class TestGenericItoMyModel extends TestBizModelGeneric
  263. {
  264. static public function GetName()
  265. {
  266. return 'Generic RO test on '.self::GetConfigFile();
  267. }
  268. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  269. }
  270. class TestGenericItopBigModel extends TestBizModelGeneric
  271. {
  272. static public function GetName()
  273. {
  274. return 'Generic RO test on '.self::GetConfigFile();
  275. }
  276. static public function GetConfigFile() {return '/config-test-itopv06.php';}
  277. }
  278. class TestUserRightsMatrixItop extends TestUserRights
  279. {
  280. static public function GetName()
  281. {
  282. return 'User rights test on user rights matrix';
  283. }
  284. static public function GetDescription()
  285. {
  286. return 'blah blah blah';
  287. }
  288. public function DoPrepare()
  289. {
  290. parent::DoPrepare();
  291. MetaModel::Startup('../config-test-itopv06.php');
  292. }
  293. protected function DoExecute()
  294. {
  295. $sUser = 'Romain';
  296. echo "<p>Totor: ".(UserRights::CheckCredentials('Totor', 'toto') ? 'ok' : 'NO')."</p>\n";
  297. echo "<p>Romain: ".(UserRights::CheckCredentials('Romain', 'toto') ? 'ok' : 'NO')."</p>\n";
  298. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  299. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  300. echo "<p>Denis (impersonate) : ".(UserRights::Impersonate('Denis', 'tutu') ? 'ok' : 'NO')."</p>\n";
  301. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  302. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  303. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT bizOrganization"));
  304. echo "<p>IsActionAllowed...".(UserRights::IsActionAllowed('bizOrganization', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  305. echo "<p>IsStimulusAllowed...".(UserRights::IsStimulusAllowed('bizOrganization', 'myStimulus', $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  306. echo "<p>IsActionAllowedOnAttribute...".(UserRights::IsActionAllowedOnAttribute('bizOrganization', 'myattribute', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  307. return true;
  308. }
  309. }
  310. ///////////////////////////////////////////////////////////////////////////
  311. // Test a complex biz model on the fly
  312. ///////////////////////////////////////////////////////////////////////////
  313. class TestMyBizModel extends TestBizModel
  314. {
  315. static public function GetName()
  316. {
  317. return 'A series of tests on a weird business model';
  318. }
  319. static public function GetDescription()
  320. {
  321. return 'Attempts various operations and build complex queries';
  322. }
  323. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  324. function test_linksinfo()
  325. {
  326. echo "<h4>Enum links</h4>";
  327. self::DumpVariable(MetaModel::EnumReferencedClasses("cmdbTeam"));
  328. self::DumpVariable(MetaModel::EnumReferencingClasses("Organization"));
  329. self::DumpVariable(MetaModel::EnumLinkingClasses());
  330. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdbContact"));
  331. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdWorkshop"));
  332. self::DumpVariable(MetaModel::GetLinkLabel("Liens_entre_contacts_et_workshop", "toworkshop"));
  333. }
  334. function test_list_attributes()
  335. {
  336. echo "<h4>List attributes</h4>";
  337. foreach(MetaModel::ListAttributeDefs("cmdbTeam") as $sAttCode=>$oAttDef)
  338. {
  339. echo $oAttDef->GetLabel()." / ".$oAttDef->GetDescription()." / ".$oAttDef->GetType()."</br>\n";
  340. }
  341. }
  342. function test_search()
  343. {
  344. echo "<h4>Two searches</h4>";
  345. $oFilterAllDevs = new DBObjectSearch("cmdbTeam");
  346. $oAllDevs = new DBObjectSet($oFilterAllDevs);
  347. echo "Found ".$oAllDevs->Count()." items.</br>\n";
  348. while ($oDev = $oAllDevs->Fetch())
  349. {
  350. $aValues = array();
  351. foreach(MetaModel::GetAttributesList($oAllDevs->GetClass()) as $sAttCode)
  352. {
  353. $aValues[] = MetaModel::GetLabel(get_class($oDev), $sAttCode)." (".MetaModel::GetDescription(get_class($oDev), $sAttCode).") = ".$oDev->GetAsHTML($sAttCode);
  354. }
  355. echo $oDev->GetKey()." => ".implode(", ", $aValues)."</br>\n";
  356. }
  357. // a second one
  358. $oMyFilter = new DBObjectSearch("cmdbContact");
  359. //$oMyFilter->AddCondition("name", "aii", "Finishes with");
  360. $oMyFilter->AddCondition("name", "aii");
  361. $this->search_and_show_list($oMyFilter);
  362. }
  363. function test_reload()
  364. {
  365. echo "<h4>Reload</h4>";
  366. $team = MetaModel::GetObject("cmdbContact", "2");
  367. echo "Chargement de l'attribut headcount: {$team->Get("headcount")}</br>\n";
  368. self::DumpVariable($team);
  369. }
  370. function test_setattribute()
  371. {
  372. echo "<h4>Set attribute and update</h4>";
  373. $team = MetaModel::GetObject("cmdbTeam", "2");
  374. $team->Set("headcount", rand(1,1000));
  375. $team->Set("email", "Luis ".rand(9,250));
  376. self::DumpVariable($team->ListChanges());
  377. echo "New headcount = {$team->Get("headcount")}</br>\n";
  378. echo "Computed name = {$team->Get("name")}</br>\n";
  379. $oMyChange = MetaModel::NewObject("CMDBChange");
  380. $oMyChange->Set("date", time());
  381. $oMyChange->Set("userinfo", "test_setattribute / Made by robot #".rand(1,100));
  382. $iChangeId = $oMyChange->DBInsert();
  383. //MetaModel::StartDebugQuery();
  384. $team->DBUpdateTracked($oMyChange);
  385. //MetaModel::StopDebugQuery();
  386. echo "<h4>Check the modified team</h4>";
  387. $oTeam = MetaModel::GetObject("cmdbTeam", "2");
  388. self::DumpVariable($oTeam);
  389. }
  390. function test_newobject()
  391. {
  392. $oMyChange = MetaModel::NewObject("CMDBChange");
  393. $oMyChange->Set("date", time());
  394. $oMyChange->Set("userinfo", "test_newobject / Made by robot #".rand(1,100));
  395. $iChangeId = $oMyChange->DBInsert();
  396. echo "<h4>Create a new object (team)</h4>";
  397. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  398. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  399. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  400. $oNewTeam->Set("email", null);
  401. $oNewTeam->Set("owner", "ITOP");
  402. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  403. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  404. echo "Created new team: $iId</br>";
  405. echo "<h4>Delete team #$iId</h4>";
  406. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  407. $oTeam->DBDeleteTracked($oMyChange);
  408. echo "Deleted team: $iId</br>";
  409. self::DumpVariable($oTeam);
  410. }
  411. function test_updatecolumn()
  412. {
  413. $oMyChange = MetaModel::NewObject("CMDBChange");
  414. $oMyChange->Set("date", time());
  415. $oMyChange->Set("userinfo", "test_updatecolumn / Made by robot #".rand(1,100));
  416. $iChangeId = $oMyChange->DBInsert();
  417. $sNewEmail = "updatecol".rand(9,250)."@quedlaballe.com";
  418. echo "<h4>Update a the email: set to '$sNewEmail'</h4>";
  419. $oMyFilter = new DBObjectSearch("cmdbContact");
  420. $oMyFilter->AddCondition("name", "o", "Contains");
  421. echo "Candidates before:</br>";
  422. $this->search_and_show_list($oMyFilter);
  423. MetaModel::BulkUpdateTracked($oMyChange, $oMyFilter, array("email" => $sNewEmail));
  424. echo "Candidates after:</br>";
  425. $this->search_and_show_list($oMyFilter);
  426. }
  427. function test_error()
  428. {
  429. trigger_error("Stop requested", E_USER_ERROR);
  430. }
  431. function test_changetracking()
  432. {
  433. echo "<h4>Create a change</h4>";
  434. $oMyChange = MetaModel::NewObject("CMDBChange");
  435. $oMyChange->Set("date", time());
  436. $oMyChange->Set("userinfo", "Made by robot #".rand(1,100));
  437. $iChangeId = $oMyChange->DBInsert();
  438. echo "Created new change: $iChangeId</br>";
  439. self::DumpVariable($oMyChange);
  440. echo "<h4>Create a new object (team)</h4>";
  441. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  442. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  443. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  444. $oNewTeam->Set("email", null);
  445. $oNewTeam->Set("owner", "ITOP");
  446. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  447. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  448. echo "Created new team: $iId</br>";
  449. echo "<h4>Delete team #$iId</h4>";
  450. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  451. $oTeam->DBDeleteTracked($oMyChange);
  452. echo "Deleted team: $iId</br>";
  453. self::DumpVariable($oTeam);
  454. }
  455. function test_zlist()
  456. {
  457. echo "<h4>Test ZLists</h4>";
  458. $aZLists = MetaModel::EnumZLists();
  459. foreach ($aZLists as $sListCode)
  460. {
  461. $aListInfos = MetaModel::GetZListInfo($sListCode);
  462. echo "<h4>List '".$sListCode."' (".$aListInfos["description"].") of type '".$aListInfos["type"]."'</h5>\n";
  463. foreach (MetaModel::GetSubclasses("cmdbObjectHomeMade") as $sKlass)
  464. {
  465. $aItems = MetaModel::GetZListItems($sKlass, $sListCode);
  466. if (count($aItems) == 0) continue;
  467. echo "$sKlass - $sListCode : {".implode(", ", $aItems)."}</br>\n";
  468. }
  469. }
  470. echo "<h4>IsAttributeInZList()... </h4>";
  471. echo "Liens_entre_contacts_et_workshop::ws_info in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "ws_info") ? "yes" : "no")."</br>\n";
  472. echo "Liens_entre_contacts_et_workshop::toworkshop in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "toworkshop") ? "yes" : "no")."</br>\n";
  473. }
  474. function test_pkey()
  475. {
  476. echo "<h4>Test search on pkey</h4>";
  477. $sExpr1 = "SELECT cmdbContact WHERE id IN (40, 42)";
  478. $sExpr2 = "SELECT cmdbContact WHERE IN NOT IN (40, 42)";
  479. $this->search_and_show_list_from_oql($sExpr1);
  480. $this->search_and_show_list_from_oql($sExpr2);
  481. echo "Et maintenant, on fusionne....</br>\n";
  482. $oSet1 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr1));
  483. $oSet2 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr2));
  484. $oIntersect = $oSet1->CreateIntersect($oSet2);
  485. $oDelta = $oSet1->CreateDelta($oSet2);
  486. $oMerge = clone $oSet1;
  487. $oMerge->Merge($oSet2);
  488. $oMerge->Merge($oSet2);
  489. echo "Set1 - Found ".$oSet1->Count()." items.</br>\n";
  490. echo "Set2 - Found ".$oSet2->Count()." items.</br>\n";
  491. echo "Intersect - Found ".$oIntersect->Count()." items.</br>\n";
  492. echo "Delta - Found ".$oDelta->Count()." items.</br>\n";
  493. echo "Merge - Found ".$oMerge->Count()." items.</br>\n";
  494. //$this->show_list($oObjSet);
  495. }
  496. function test_relations()
  497. {
  498. echo "<h4>Test relations</h4>";
  499. //self::DumpVariable(MetaModel::EnumRelationQueries("cmdbObjectHomeMade", "Potes"));
  500. self::DumpVariable(MetaModel::EnumRelationQueries("cmdbContact", "Potes"));
  501. $iMaxDepth = 9;
  502. echo "Max depth = $iMaxDepth</br>\n";
  503. $oObj = MetaModel::GetObject("cmdbContact", 18);
  504. $aRels = $oObj->GetRelatedObjects("Potes", $iMaxDepth);
  505. echo $oObj->Get('name')." has some 'Potes'...</br>\n";
  506. foreach ($aRels as $sClass => $aObjs)
  507. {
  508. echo "$sClass, count = ".count($aObjs)." =&gt; ".implode(', ', array_keys($aObjs))."</br>\n";
  509. $oObjectSet = CMDBObjectSet::FromArray($sClass, $aObjs);
  510. $this->show_list($oObjectSet);
  511. }
  512. echo "<h4>Test relations - same results, by the mean of a OQL</h4>";
  513. $this->search_and_show_list_from_oql("cmdbContact: RELATED (Potes, $iMaxDepth) TO (cmdbContact: pkey = 18)");
  514. }
  515. function test_linkedset()
  516. {
  517. echo "<h4>Linked set attributes</h4>\n";
  518. $oObj = MetaModel::GetObject("cmdbContact", 18);
  519. echo "<h5>Current workshops</h5>\n";
  520. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  521. $this->show_list($oSetWorkshopsCurr);
  522. echo "<h5>Setting workshops</h5>\n";
  523. $oNewLink = new cmdbLiens();
  524. $oNewLink->Set('toworkshop', 2);
  525. $oNewLink->Set('function', 'mafonctioooon');
  526. $oNewLink->Set('a1', 'tralala1');
  527. $oNewLink->Set('a2', 'F7M');
  528. $oSetWorkshops = CMDBObjectSet::FromArray("cmdbLiens", array($oNewLink));
  529. $oObj->Set("myworkshops", $oSetWorkshops);
  530. $this->show_list($oSetWorkshops);
  531. echo "<h5>New workshops</h5>\n";
  532. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  533. $this->show_list($oSetWorkshopsCurr);
  534. $oMyChange = MetaModel::NewObject("CMDBChange");
  535. $oMyChange->Set("date", time());
  536. $oMyChange->Set("userinfo", "test_linkedset / Made by robot #".rand(1,100));
  537. $iChangeId = $oMyChange->DBInsert();
  538. $oObj->DBUpdateTracked($oMyChange);
  539. $oObj = MetaModel::GetObject("cmdbContact", 18);
  540. echo "<h5>After the write</h5>\n";
  541. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  542. $this->show_list($oSetWorkshopsCurr);
  543. }
  544. function test_object_lifecycle()
  545. {
  546. echo "<h4>Test object lifecycle</h4>";
  547. self::DumpVariable(MetaModel::GetStateAttributeCode("cmdbContact"));
  548. self::DumpVariable(MetaModel::EnumStates("cmdbContact"));
  549. self::DumpVariable(MetaModel::EnumStimuli("cmdbContact"));
  550. foreach(MetaModel::EnumStates("cmdbContact") as $sStateCode => $aStateDef)
  551. {
  552. echo "<p>Transition from <strong>$sStateCode</strong></p>\n";
  553. self::DumpVariable(MetaModel::EnumTransitions("cmdbContact", $sStateCode));
  554. }
  555. $oObj = MetaModel::GetObject("cmdbContact", 18);
  556. echo "Current state: ".$oObj->GetState()."... let's go to school...";
  557. self::DumpVariable($oObj->EnumTransitions());
  558. $oObj->ApplyStimulus("toschool");
  559. echo "New state: ".$oObj->GetState()."... let's get older...";
  560. self::DumpVariable($oObj->EnumTransitions());
  561. $oObj->ApplyStimulus("raise");
  562. echo "New state: ".$oObj->GetState()."... let's try to go further... (should give an error)";
  563. self::DumpVariable($oObj->EnumTransitions());
  564. $oObj->ApplyStimulus("raise"); // should give an error
  565. }
  566. protected function DoExecute()
  567. {
  568. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  569. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  570. //$this->test_linksinfo();
  571. //$this->test_list_attributes();
  572. //$this->test_search();
  573. //$this->test_reload();
  574. //$this->test_newobject();
  575. $this->test_setattribute();
  576. //$this->test_updatecolumn();
  577. //$this->test_error();
  578. //$this->test_changetracking();
  579. $this->test_zlist();
  580. $this->test_OQL();
  581. //$this->test_pkey();
  582. $this->test_relations();
  583. $this->test_linkedset();
  584. $this->test_object_lifecycle();
  585. }
  586. }
  587. ///////////////////////////////////////////////////////////////////////////
  588. // Test a complex biz model on the fly
  589. ///////////////////////////////////////////////////////////////////////////
  590. abstract class MyFarm extends TestBizModel
  591. {
  592. static public function GetConfigFile() {return '/config-test-farm.php';}
  593. protected function DoPrepare()
  594. {
  595. parent::DoPrepare();
  596. $this->ResetDB();
  597. MetaModel::DBCheckIntegrity();
  598. }
  599. protected function InsertMammal($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $sName, $iHeight, $sBirth)
  600. {
  601. $oNew = MetaModel::NewObject('Mammal');
  602. $oNew->Set('species', $sSpecies);
  603. $oNew->Set('sex', $sSex);
  604. $oNew->Set('speed', $iSpeed);
  605. $oNew->Set('mother', $iMotherid);
  606. $oNew->Set('father', $iFatherId);
  607. $oNew->Set('name', $sName);
  608. $oNew->Set('height', $iHeight);
  609. $oNew->Set('birth', $sBirth);
  610. return $this->ObjectToDB($oNew);
  611. }
  612. protected function InsertBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId)
  613. {
  614. $oNew = MetaModel::NewObject('Bird');
  615. $oNew->Set('species', $sSpecies);
  616. $oNew->Set('sex', $sSex);
  617. $oNew->Set('speed', $iSpeed);
  618. $oNew->Set('mother', $iMotherid);
  619. $oNew->Set('father', $iFatherId);
  620. return $this->ObjectToDB($oNew);
  621. }
  622. protected function InsertFlyingBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $iFlyingSpeed)
  623. {
  624. $oNew = MetaModel::NewObject('FlyingBird');
  625. $oNew->Set('species', $sSpecies);
  626. $oNew->Set('sex', $sSex);
  627. $oNew->Set('speed', $iSpeed);
  628. $oNew->Set('mother', $iMotherid);
  629. $oNew->Set('father', $iFatherId);
  630. $oNew->Set('flyingspeed', $iFlyingSpeed);
  631. return $this->ObjectToDB($oNew);
  632. }
  633. private function InsertGroup($sName, $iLeaderId)
  634. {
  635. $oNew = MetaModel::NewObject('Group');
  636. $oNew->Set('name', $sName);
  637. $oNew->Set('leader', $iLeaderId);
  638. $iId = $oNew->DBInsertNoReload();
  639. return $iId;
  640. }
  641. }
  642. class TestQueriesOnFarm extends MyFarm
  643. {
  644. static public function GetName()
  645. {
  646. return 'Farm test';
  647. }
  648. static public function GetDescription()
  649. {
  650. return 'A series of tests on the farm business model (SQL generation)';
  651. }
  652. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  653. {
  654. if ($bIsCorrectQuery)
  655. {
  656. echo "<h4 style=\"color:green;\">$sQuery</h4>\n";
  657. }
  658. else
  659. {
  660. echo "<h4 style=\"color:red;\">$sQuery</h3>\n";
  661. }
  662. try
  663. {
  664. //$oOql = new OqlInterpreter($sQuery);
  665. //$oTrash = $oOql->ParseObjectQuery();
  666. //self::DumpVariable($oTrash, true);
  667. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  668. }
  669. catch (OQLException $oOqlException)
  670. {
  671. if ($bIsCorrectQuery)
  672. {
  673. echo "<p>More info on this unexpected failure:<br/>".$oOqlException->getHtmlDesc()."</p>\n";
  674. throw $oOqlException;
  675. return false;
  676. }
  677. else
  678. {
  679. // Everything is fine :-)
  680. echo "<p>More info on this expected failure:\n";
  681. echo "<ul>\n";
  682. echo "<li>".get_class($oOqlException)."</li>\n";
  683. echo "<li>".$oOqlException->getMessage()."</li>\n";
  684. echo "<li>".$oOqlException->getHtmlDesc()."</li>\n";
  685. echo "</ul>\n";
  686. echo "</p>\n";
  687. return true;
  688. }
  689. }
  690. // The query was correctly parsed, was it expected to be correct ?
  691. if (!$bIsCorrectQuery)
  692. {
  693. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  694. return false;
  695. }
  696. echo "<p>To OQL: ".$oMyFilter->ToOQL()."</p>";
  697. $this->search_and_show_list($oMyFilter);
  698. //echo "<p>first pass<p>\n";
  699. //self::DumpVariable($oMyFilter, true);
  700. $sQuery1 = MetaModel::MakeSelectQuery($oMyFilter);
  701. //echo "<p>second pass<p>\n";
  702. //self::DumpVariable($oMyFilter, true);
  703. //$sQuery1 = MetaModel::MakeSelectQuery($oMyFilter);
  704. $sSerialize = $oMyFilter->serialize();
  705. echo "<p>Serialized:$sSerialize</p>\n";
  706. $oFilter2 = DBObjectSearch::unserialize($sSerialize);
  707. try
  708. {
  709. $sQuery2 = MetaModel::MakeSelectQuery($oFilter2);
  710. }
  711. catch (Exception $e)
  712. {
  713. echo "<p>Could not compute the query after unserialize</p>\n";
  714. echo "<p>Query 1: $sQuery1</p>\n";
  715. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  716. throw $e;
  717. }
  718. //if ($oFilter2 != $oMyFilter) no, they may differ while the resulting query is the same!
  719. if ($sQuery1 != $sQuery2)
  720. {
  721. echo "<p>serialize/unserialize mismatch :-(</p>\n";
  722. MyHelpers::var_cmp_html($sQuery1, $sQuery2);
  723. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  724. return false;
  725. }
  726. return true;
  727. }
  728. protected function DoExecute()
  729. {
  730. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  731. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  732. echo "<h3>Create protagonists...</h3>";
  733. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  734. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  735. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  736. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  737. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  738. $this->InsertBird('rooster', 'male', 12, 0, 0);
  739. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  740. // Benchmarking
  741. //
  742. if (false)
  743. {
  744. define ('COUNT_BENCHMARK', 10);
  745. echo "<h3>Parsing a long query, ".COUNT_BENCHMARK." times</h3>";
  746. $sQuery = "SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id WHERE Dad.birth < DATE_SUB(CURRENT_DATE(), INTERVAL 10 YEAR) AND Dad.height * 2 <= ROUND(TO_DAYS(Dad.birth) / (3 + 1) * 5 - 3)";
  747. $fStart = MyHelpers::getmicrotime();
  748. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  749. {
  750. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  751. }
  752. $fDuration = MyHelpers::getmicrotime() - $fStart;
  753. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  754. echo "<p>Mean time by op: $fParsingDuration</p>";
  755. }
  756. echo "<h3>Test queries...</h3>";
  757. $aQueries = array(
  758. 'SELECT Animal' => true,
  759. 'SELECT Animal WHERE Animal.pkey = 1' => false,
  760. 'SELECT Animal WHERE Animal.id = 1' => true,
  761. 'SELECT Aniiimal' => false,
  762. 'SELECTe Animal' => false,
  763. 'SELECT * FROM Animal' => false,
  764. 'SELECT Animal AS zoo WHERE zoo.species = \'human\'' => true,
  765. 'SELECT Animal AS zoo WHERE species = \'human\'' => true,
  766. 'SELECT Animal AS zoo WHERE espece = \'human\'' => false,
  767. 'SELECT Animal AS zoo WHERE zoo.species IN (\'human\', "pig")' => true,
  768. 'SELECT Animal AS zoo WHERE CONCATENATION(zoo.species, zoo.sex) LIKE "hum%male"' => false,
  769. 'SELECT Animal AS zoo WHERE CONCAT(zoo.species, zoo.sex) LIKE "hum%male"' => true,
  770. 'SELECT Animal AS zoo WHERE zoo.species NOT IN (\'human\', "pig")' => true,
  771. 'SELECT Animal AS zoo WHERE zoo.kind = \'human\'' => false,
  772. 'SELECT Animal WHERE Animal.species = \'human\' AND Animal.sex = \'female\'' => true,
  773. 'SELECT Mammal AS x WHERE (x.species = \'human\' AND x.name LIKE \'ro%\') OR (x.species = \'donkey\' AND x.name LIKE \'po%\')' => true,
  774. 'SELECT Mammal AS x WHERE x.species = \'human\' AND x.name LIKE \'ro%\' OR x.species = \'donkey\' AND x.name LIKE \'po%\'' => true,
  775. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  776. 'SELECT Mammal AS m WHERE DAY(m.birth) = 19' => true,
  777. 'SELECT Mammal AS m WHERE YEAR(m.birth) = 1971' => true,
  778. 'SELECT Mammal AS m WHERE m.birth < DATE_SUB(CURRENT_DATE(), INTERVAL 10 YEAR)' => true,
  779. 'SELECT Mammal AS m WHERE m.birth > DATE_SUB(NOW(), INTERVAL 2000 DAY)' => true,
  780. 'SELECT Mammal AS m WHERE (TO_DAYS(NOW()) - TO_DAYS(m.birth)) > 2000' => true,
  781. 'SELECT Mammal AS m WHERE m.name = IF(FLOOR(ROUND(m.height)) > 2, "pomme", "romain")' => true,
  782. 'SELECT Mammal AS m WHERE (1 + 2' => false,
  783. 'SELECT Mammal AS m WHERE (1 + 2 * 4 / 23) > 0' => true,
  784. 'SELECT Mammal AS m WHERE (4 / 23 * 2 + 1) > 0' => true,
  785. 'SELECT Mammal AS m WHERE 1/0' => true,
  786. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  787. 'SELECT Animal JOIN Group ON Group.leader = Animal.id' => true,
  788. 'SELECT Group JOIN Animal ON Group.leader = Animal.id' => true,
  789. 'SELECT Animal AS A JOIN Group AS G1 ON G1.leader = A.id' => true,
  790. 'SELECT Animal AS A JOIN Group AS G ON FooClass.leader = A.id' => false,
  791. 'SELECT Animal AS A JOIN Group AS G ON G.leader = FooClass.id' => false,
  792. 'SELECT Animal AS A JOIN Group AS G ON G.masterchief = A.id' => false,
  793. 'SELECT Animal AS A JOIN Group AS G ON A.id = G.leader' => false,
  794. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.qwerty = 123' => false,
  795. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.name LIKE "a%"' => true,
  796. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.id = 1' => true,
  797. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE id = 1' => false,
  798. 'SELECT Animal AS A JOIN Group AS G ON A.member = G.id' => false,
  799. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id' => true,
  800. 'SELECT Mammal AS M JOIN Group AS G ON A.member = G.id' => false,
  801. 'SELECT Mammal AS myAlias JOIN Group AS myAlias ON myAlias.member = myAlias.id' => false,
  802. 'SELECT Mammal AS Mammal JOIN Group AS Mammal ON Mammal.member = Mammal.id' => false,
  803. 'SELECT Group AS G WHERE G.leader_name LIKE "%"' => true,
  804. 'SELECT Group AS G WHERE G.leader_speed < 100000' => true,
  805. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  806. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_speed < 100000' => true,
  807. 'SELECT Mammal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  808. 'SELECT Mammal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  809. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  810. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  811. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id' => true,
  812. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  813. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id WHERE Dad.id = 1' => true,
  814. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id WHERE Dad.name = \'romanoff\'' => false,
  815. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  816. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id WHERE Dad.name = \'romanoff\' OR Mum.speed = 0' => true,
  817. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  818. 'SELECT Mammal AS Dad JOIN Mammal AS Child ON Child.father = Dad.id' => true,
  819. 'SELECT Mammal AS Dad JOIN Mammal AS Child ON Child.father = Dad.id JOIN Mammal AS Mum ON Child.mother = Mum.id WHERE Dad.name = \'romanoff\' OR Mum.name=\'chloe\' OR Child.name=\'bizounours\'' => true,
  820. // Specifying multiple objects
  821. 'SELECT Animal FROM Animal' => true,
  822. 'SELECT yelele FROM Animal' => false,
  823. 'SELECT Animal FROM Animal AS A' => false,
  824. 'SELECT A FROM Animal AS A' => true,
  825. );
  826. //$aQueries = array(
  827. // 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  828. //);
  829. foreach($aQueries as $sQuery => $bIsCorrect)
  830. {
  831. $this->CheckQuery($sQuery, $bIsCorrect);
  832. }
  833. return true;
  834. }
  835. }
  836. ///////////////////////////////////////////////////////////////////////////
  837. // Test data load
  838. ///////////////////////////////////////////////////////////////////////////
  839. class TestBulkChangeOnFarm extends TestBizModel
  840. {
  841. static public function GetName()
  842. {
  843. return 'Farm test - data load';
  844. }
  845. static public function GetDescription()
  846. {
  847. return 'Bulk load';
  848. }
  849. static public function GetConfigFile() {return '/config-test-farm.php';}
  850. protected function DoPrepare()
  851. {
  852. parent::DoPrepare();
  853. $this->ResetDB();
  854. MetaModel::DBCheckIntegrity();
  855. }
  856. protected function DoExecute()
  857. {
  858. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  859. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  860. $oParser = new CSVParser("denomination,hauteur,age
  861. suzy,123,2009-01-01
  862. chita,456,
  863. ");
  864. $aData = $oParser->ToArray(array('_name', '_height', '_birth'), ',');
  865. self::DumpVariable($aData);
  866. $oBulk = new BulkChange(
  867. 'Mammal',
  868. $aData,
  869. // attributes
  870. array('name' => '_name', 'height' => '_height', 'birth' => '_birth'),
  871. // ext keys
  872. array(),
  873. // reconciliation
  874. array('name')
  875. );
  876. $oMyChange = MetaModel::NewObject("CMDBChange");
  877. $oMyChange->Set("date", time());
  878. $oMyChange->Set("userinfo", "Testor");
  879. $iChangeId = $oMyChange->DBInsert();
  880. // echo "Created new change: $iChangeId</br>";
  881. echo "<h3>Planned for loading...</h3>";
  882. $aRes = $oBulk->Process();
  883. self::DumpVariable($aRes);
  884. echo "<h3>Go for loading...</h3>";
  885. $aRes = $oBulk->Process($oMyChange);
  886. self::DumpVariable($aRes);
  887. return;
  888. $oRawData = array(
  889. 'Mammal',
  890. array('species', 'sex', 'speed', 'mother', 'father', 'name', 'height', 'birth'),
  891. "human,male,23,0,0,romulus,192,1971
  892. human,male,23,0,0,remus,154,-50
  893. human,male,23,0,0,julius,160,-49
  894. human,female,23,0,0,cleopatra,142,-50
  895. pig,female,23,0,0,confucius,50,2003"
  896. );
  897. }
  898. }
  899. ///////////////////////////////////////////////////////////////////////////
  900. // Test data load
  901. ///////////////////////////////////////////////////////////////////////////
  902. class TestFullTextSearchOnFarm extends MyFarm
  903. {
  904. static public function GetName()
  905. {
  906. return 'Farm test - full text search';
  907. }
  908. static public function GetDescription()
  909. {
  910. return 'Focus on the full text search feature';
  911. }
  912. protected function DoExecute()
  913. {
  914. echo "<h3>Create protagonists...</h3>";
  915. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  916. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  917. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  918. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  919. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  920. $this->InsertBird('rooster', 'male', 12, 0, 0);
  921. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  922. echo "<h3>Search...</h3>";
  923. $oSearch = new DBObjectSearch('Mammal');
  924. $oSearch->AddCondition_FullText('manof');
  925. //$oResultSet = new DBObjectSet($oSearch);
  926. $this->search_and_show_list($oSearch);
  927. }
  928. }
  929. ///////////////////////////////////////////////////////////////////////////
  930. // Benchmark queries
  931. ///////////////////////////////////////////////////////////////////////////
  932. class TestItopEfficiency extends TestBizModel
  933. {
  934. static public function GetName()
  935. {
  936. return 'Itop - benchmark';
  937. }
  938. static public function GetDescription()
  939. {
  940. return 'Measure time to perform the queries';
  941. }
  942. static public function GetConfigFile() {return '/config-itop.php';}
  943. protected function DoBenchmark($sOqlQuery)
  944. {
  945. echo "<h3>Testing query: $sOqlQuery</h3>";
  946. $fStart = MyHelpers::getmicrotime();
  947. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  948. {
  949. $oFilter = DBObjectSearch::FromOQL($sOqlQuery);
  950. }
  951. $fDuration = MyHelpers::getmicrotime() - $fStart;
  952. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  953. $fStart = MyHelpers::getmicrotime();
  954. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  955. {
  956. $sSQL = MetaModel::MakeSelectQuery($oFilter);
  957. }
  958. $fDuration = MyHelpers::getmicrotime() - $fStart;
  959. $fBuildDuration = $fDuration / COUNT_BENCHMARK;
  960. $fStart = MyHelpers::getmicrotime();
  961. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  962. {
  963. $res = CMDBSource::Query($sSQL);
  964. }
  965. $fDuration = MyHelpers::getmicrotime() - $fStart;
  966. $fQueryDuration = $fDuration / COUNT_BENCHMARK;
  967. // The fetch could not be repeated with the same results
  968. // But we've seen so far that is was very very quick to exec
  969. // So it makes sense to benchmark it a single time
  970. $fStart = MyHelpers::getmicrotime();
  971. $aRow = CMDBSource::FetchArray($res);
  972. $fDuration = MyHelpers::getmicrotime() - $fStart;
  973. $fFetchDuration = $fDuration;
  974. $fStart = MyHelpers::getmicrotime();
  975. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  976. {
  977. $sOql = $oFilter->ToOQL();
  978. }
  979. $fDuration = MyHelpers::getmicrotime() - $fStart;
  980. $fToOqlDuration = $fDuration / COUNT_BENCHMARK;
  981. echo "<ul>\n";
  982. echo "<li>Parsing: $fParsingDuration</li>\n";
  983. echo "<li>Build: $fBuildDuration</li>\n";
  984. echo "<li>Query: $fQueryDuration</li>\n";
  985. echo "<li>Fetch: $fFetchDuration</li>\n";
  986. echo "<li>ToOql: $fToOqlDuration</li>\n";
  987. echo "</ul>\n";
  988. // Everything but the ToOQL (wich is interesting, anyhow)
  989. $fTotal = $fParsingDuration + $fBuildDuration + $fQueryDuration + $fFetchDuration;
  990. return array(
  991. 'rows' => CMDBSource::NbRows($res),
  992. 'duration (s)' => round($fTotal, 4),
  993. 'parsing (%)' => round(100 * $fParsingDuration / $fTotal, 1),
  994. 'build SQL (%)' => round(100 * $fBuildDuration / $fTotal, 1),
  995. 'query exec (%)' => round(100 * $fQueryDuration / $fTotal, 1),
  996. 'fetch (%)' => round(100 * $fFetchDuration / $fTotal, 1),
  997. 'to OQL (%)' => round(100 * $fToOqlDuration / $fTotal, 1),
  998. 'parsing+build (%)' => round(100 * ($fParsingDuration + $fBuildDuration) / $fTotal, 1),
  999. );
  1000. }
  1001. protected function DoExecute()
  1002. {
  1003. define ('COUNT_BENCHMARK', 3);
  1004. echo "<p>The test will be repeated ".COUNT_BENCHMARK." times</p>";
  1005. $aQueries = array(
  1006. 'SELECT CMDBChangeOpSetAttribute',
  1007. 'SELECT CMDBChangeOpSetAttribute WHERE id=10',
  1008. 'SELECT CMDBChangeOpSetAttribute WHERE id=123456789',
  1009. 'SELECT CMDBChangeOpSetAttribute WHERE CMDBChangeOpSetAttribute.id=10',
  1010. 'SELECT Ticket',
  1011. 'SELECT Ticket WHERE id=1',
  1012. 'SELECT Person',
  1013. 'SELECT Person WHERE id=1',
  1014. 'SELECT Server',
  1015. 'SELECT Server WHERE id=1',
  1016. 'SELECT Incident JOIN Person ON Incident.agent_id = Person.id WHERE Person.id = 5',
  1017. );
  1018. $aStats = array();
  1019. foreach ($aQueries as $sOQL)
  1020. {
  1021. $aStats[$sOQL] = $this->DoBenchmark($sOQL);
  1022. }
  1023. $aData = array();
  1024. foreach ($aStats as $sOQL => $aResults)
  1025. {
  1026. $aValues = array();
  1027. $aValues['OQL'] = htmlentities($sOQL);
  1028. foreach($aResults as $sDesc => $sInfo)
  1029. {
  1030. $aValues[$sDesc] = htmlentities($sInfo);
  1031. }
  1032. $aData[] = $aValues;
  1033. }
  1034. echo MyHelpers::make_table_from_assoc_array($aData);
  1035. }
  1036. }
  1037. ///////////////////////////////////////////////////////////////////////////
  1038. // Test data load
  1039. ///////////////////////////////////////////////////////////////////////////
  1040. class TestImportREST extends TestWebServices
  1041. {
  1042. static public function GetName()
  1043. {
  1044. return 'CSV import (REST)';
  1045. }
  1046. static public function GetDescription()
  1047. {
  1048. return 'Test various options and fonctionality of import.php';
  1049. }
  1050. protected function DoExecSingleLoad($aLoadSpec)
  1051. {
  1052. $sCsvData = $aLoadSpec['csvdata'];
  1053. echo "<div style=\"padding: 10;\">\n";
  1054. echo "<h3 style=\"background-color: #ddddff; padding: 10;\">{$aLoadSpec['desc']}</h3>\n";
  1055. $aPostData = array('csvdata' => $sCsvData);
  1056. $aGetParams = array();
  1057. $aGetParamReport = array();
  1058. foreach($aLoadSpec['args'] as $sArg => $sValue)
  1059. {
  1060. $aGetParams[] = $sArg.'='.urlencode($sValue);
  1061. $aGetParamReport[] = $sArg.'='.$sValue;
  1062. }
  1063. $sGetParams = implode('&', $aGetParams);
  1064. $sLogin = isset($aLoadSpec['login']) ? $aLoadSpec['login'] : 'admin';
  1065. $sPassword = isset($aLoadSpec['password']) ? $aLoadSpec['password'] : 'admin';
  1066. $sRes = self::DoPostRequestAuth('../webservices/import.php?'.$sGetParams, $aPostData, $sLogin, $sPassword);
  1067. $sArguments = implode('<br/>', $aGetParamReport);
  1068. if (strlen($sCsvData) > 5000)
  1069. {
  1070. $sCsvDataViewable = 'INPUT TOO LONG TO BE DISPLAYED ('.strlen($sCsvData).")\n".substr($sCsvData, 0, 500)."\n... TO BE CONTINUED";
  1071. }
  1072. else
  1073. {
  1074. $sCsvDataViewable = $sCsvData;
  1075. }
  1076. echo "<div style=\"\">\n";
  1077. echo " <div style=\"float:left; width:20%; padding:5; background-color:#eeeeff;\">\n";
  1078. echo " $sArguments\n";
  1079. echo " </div>\n";
  1080. echo " <div style=\"float:right; width:75%; padding:5; background-color:#eeeeff\">\n";
  1081. echo " <pre class=\"vardump\">$sCsvDataViewable</pre>\n";
  1082. echo " </div>\n";
  1083. echo "</div>\n";
  1084. echo "<pre class=\"vardump\" style=\"clear: both; padding: 15; background-color: black; color: green;\">$sRes</pre>\n";
  1085. echo "</div>\n";
  1086. }
  1087. protected function DoExecute()
  1088. {
  1089. $aLoads = array(
  1090. array(
  1091. 'desc' => 'Missing class',
  1092. 'login' => 'admin',
  1093. 'password' => 'admin',
  1094. 'args' => array(
  1095. ),
  1096. 'csvdata' => "xxx",
  1097. ),
  1098. array(
  1099. 'desc' => 'Wrong class',
  1100. 'login' => 'admin',
  1101. 'password' => 'admin',
  1102. 'args' => array(
  1103. 'class' => 'toto',
  1104. ),
  1105. 'csvdata' => "xxx",
  1106. ),
  1107. array(
  1108. 'desc' => 'Wrong output type',
  1109. 'login' => 'admin',
  1110. 'password' => 'admin',
  1111. 'args' => array(
  1112. 'class' => 'NetworkDevice',
  1113. 'output' => 'onthefly',
  1114. ),
  1115. 'csvdata' => "xxx",
  1116. ),
  1117. array(
  1118. 'desc' => 'Wrong report level',
  1119. 'login' => 'admin',
  1120. 'password' => 'admin',
  1121. 'args' => array(
  1122. 'class' => 'NetworkDevice',
  1123. 'reportlevel' => 'errors|ouarnings|changed',
  1124. ),
  1125. 'csvdata' => "xxx",
  1126. ),
  1127. array(
  1128. 'desc' => 'Weird format, working anyhow...',
  1129. 'login' => 'admin',
  1130. 'password' => 'admin',
  1131. 'args' => array(
  1132. 'class' => 'Server',
  1133. 'output' => 'details',
  1134. 'separator' => '*',
  1135. 'qualifier' => '@',
  1136. 'reconciliationkeys' => 'org_id,name',
  1137. ),
  1138. 'csvdata' => 'name*org_id
  1139. server01*2
  1140. @server02@@combodo@* 2
  1141. server45*99',
  1142. ),
  1143. array(
  1144. 'desc' => 'Load an organization',
  1145. 'login' => 'admin',
  1146. 'password' => 'admin',
  1147. 'args' => array(
  1148. 'class' => 'Organization',
  1149. 'output' => 'details',
  1150. 'reconciliationkeys' => '',
  1151. ),
  1152. 'csvdata' => "name;code\nWorldCompany;WCY",
  1153. ),
  1154. array(
  1155. 'desc' => 'Load a location',
  1156. 'login' => 'admin',
  1157. 'password' => 'admin',
  1158. 'args' => array(
  1159. 'class' => 'Location',
  1160. 'output' => 'details',
  1161. 'reconciliationkeys' => '',
  1162. ),
  1163. 'csvdata' => "name;org_id;address\nParis;1;Centre de la Franca",
  1164. ),
  1165. array(
  1166. 'desc' => 'Load a person',
  1167. 'login' => 'admin',
  1168. 'password' => 'admin',
  1169. 'args' => array(
  1170. 'class' => 'Person',
  1171. 'output' => 'details',
  1172. 'reconciliationkeys' => '',
  1173. ),
  1174. 'csvdata' => "email;name;first_name;org_id;phone\njohn.foo@starac.com;Foo;John;1;+33(1)23456789",
  1175. ),
  1176. array(
  1177. 'desc' => 'Load a person - wrong email format',
  1178. 'login' => 'admin',
  1179. 'password' => 'admin',
  1180. 'args' => array(
  1181. 'class' => 'Person',
  1182. 'output' => 'details',
  1183. 'reconciliationkeys' => '',
  1184. ),
  1185. 'csvdata' => "email;name;first_name;org_id\nemailPASbon;Foo;John;1",
  1186. ),
  1187. array(
  1188. 'desc' => 'Load a team',
  1189. 'login' => 'admin',
  1190. 'password' => 'admin',
  1191. 'args' => array(
  1192. 'class' => 'Team',
  1193. 'output' => 'details',
  1194. 'reconciliationkeys' => '',
  1195. ),
  1196. 'csvdata' => "name;org_id;location_name\nSquadra Azzura2;1;Paris",
  1197. ),
  1198. array(
  1199. 'desc' => 'Load server',
  1200. 'login' => 'admin',
  1201. 'password' => 'admin',
  1202. 'args' => array(
  1203. 'class' => 'Server',
  1204. 'output' => 'details',
  1205. 'reconciliationkeys' => '',
  1206. ),
  1207. 'csvdata' => "name;status;owner_name;location_name;location_id->org_name;os_family;os_version;management_ip;cpu;ram;brand;model;serial_number\nlocalhost.;production;Demo;Grenoble;Demo;Ubuntu 9.10;2.6.31-19-generic-#56-Ubuntu SMP Thu Jan 28 01:26:53 UTC 2010;16.16.230.232;Intel(R) Core(TM)2 Duo CPU T7100 @ 1.80GHz;2005;Hewlett-Packard;HP Compaq 6510b (GM108UC#ABF);CNU7370BNP",
  1208. ),
  1209. array(
  1210. 'desc' => 'Load server - wrong value for status',
  1211. 'login' => 'admin',
  1212. 'password' => 'admin',
  1213. 'args' => array(
  1214. 'class' => 'Server',
  1215. 'output' => 'details',
  1216. 'reconciliationkeys' => '',
  1217. ),
  1218. 'csvdata' => "name;status;owner_name;location_name;location_id->org_name;os_family;os_version;management_ip;cpu;ram;brand;model;serial_number\nlocalhost.;Production;Demo;Grenoble;Demo;Ubuntu 9.10;2.6.31-19-generic-#56-Ubuntu SMP Thu Jan 28 01:26:53 UTC 2010;16.16.230.232;Intel(R) Core(TM)2 Duo CPU T7100 @ 1.80GHz;2005;Hewlett-Packard;HP Compaq 6510b (GM108UC#ABF);CNU7370BNP",
  1219. ),
  1220. array(
  1221. 'desc' => 'Load NW if',
  1222. 'login' => 'admin',
  1223. 'password' => 'admin',
  1224. 'args' => array(
  1225. 'class' => 'NetworkInterface',
  1226. 'output' => 'details',
  1227. 'reconciliationkeys' => '',
  1228. ),
  1229. 'csvdata' => "name;status;org_id;device_name;physical_type;ip_address;ip_mask;mac_address;speed\neth0;implementation;2;localhost.;ethernet;16.16.230.232;255.255.240.0;00:1a:4b:68:e3:97;\nlo;implementation;2;localhost.;ethernet;127.0.0.1;255.0.0.0;;",
  1230. ),
  1231. // Data Bruno
  1232. array(
  1233. 'desc' => 'Load NW devices from real life',
  1234. 'login' => 'admin',
  1235. 'password' => 'admin',
  1236. 'args' => array(
  1237. 'class' => 'NetworkDevice',
  1238. 'output' => 'details',
  1239. 'reconciliationkeys' => 'org_id->name,name',
  1240. ),
  1241. 'csvdata' => 'name;management_ip;importance;org_id->name;type
  1242. truc-machin-bidule;172.15.255.150;high;My Company/Department;switch
  1243. 10.15.255.222;10.15.255.222;high;My Company/Department;switch',
  1244. ),
  1245. array(
  1246. 'desc' => 'Load NW ifs',
  1247. 'login' => 'admin',
  1248. 'password' => 'admin',
  1249. 'args' => array(
  1250. 'class' => 'NetworkInterface',
  1251. 'output' => 'details',
  1252. 'reconciliationkeys' => 'device_id->name,name',
  1253. ),
  1254. 'csvdata' => 'device_id->name;org_id->name;name;ip_address;ip_mask;speed;link_type;mac_address;physical_type
  1255. truc-machin-bidule;My Company/Department;"GigabitEthernet44";;;0;downlink;00 12 F2 CB C4 EB ;ethernet
  1256. truc-machin-bidule;My Company/Department;"GigabitEthernet38";;;0;downlink;00 12 F2 CB C4 E5 ;ethernet
  1257. un-autre;My Company/Department;"GigabitEthernet2/3";;;1000000000;uplink;00 12 F2 20 0F 1A ;ethernet',
  1258. ),
  1259. array(
  1260. 'desc' => 'The simplest data load',
  1261. 'login' => 'admin',
  1262. 'password' => 'admin',
  1263. 'args' => array(
  1264. 'class' => 'Location',
  1265. 'output' => 'details',
  1266. ),
  1267. 'csvdata' => "name\nParis",
  1268. ),
  1269. array(
  1270. 'desc' => 'The simplest data load + org',
  1271. 'login' => 'admin',
  1272. 'password' => 'admin',
  1273. 'args' => array(
  1274. 'class' => 'Location',
  1275. 'output' => 'details',
  1276. ),
  1277. 'csvdata' => "name;org_id\nParis;2",
  1278. ),
  1279. array(
  1280. 'desc' => 'The simplest data load + org (name)',
  1281. 'login' => 'admin',
  1282. 'password' => 'admin',
  1283. 'args' => array(
  1284. 'class' => 'Location',
  1285. 'output' => 'details',
  1286. ),
  1287. 'csvdata' => "name;org_name\nParis;Demo",
  1288. ),
  1289. array(
  1290. 'desc' => 'The simplest data load + org (code)',
  1291. 'login' => 'admin',
  1292. 'password' => 'admin',
  1293. 'args' => array(
  1294. 'class' => 'Location',
  1295. 'output' => 'details',
  1296. ),
  1297. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1298. ),
  1299. array(
  1300. 'desc' => 'Ouput: summary',
  1301. 'login' => 'admin',
  1302. 'password' => 'admin',
  1303. 'args' => array(
  1304. 'class' => 'Location',
  1305. 'output' => 'summary',
  1306. ),
  1307. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1308. ),
  1309. array(
  1310. 'desc' => 'Ouput: retcode',
  1311. 'login' => 'admin',
  1312. 'password' => 'admin',
  1313. 'args' => array(
  1314. 'class' => 'Location',
  1315. 'output' => 'retcode',
  1316. ),
  1317. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1318. ),
  1319. array(
  1320. 'desc' => 'Error in reconciliation list',
  1321. 'login' => 'admin',
  1322. 'password' => 'admin',
  1323. 'args' => array(
  1324. 'class' => 'Location',
  1325. 'output' => 'details',
  1326. 'reconciliationkeys' => 'org_id',
  1327. ),
  1328. 'csvdata' => "org_name;name\nDemo;Paris",
  1329. ),
  1330. array(
  1331. 'desc' => 'Error in attribute list that does not allow to compute reconciliation scheme',
  1332. 'login' => 'admin',
  1333. 'password' => 'admin',
  1334. 'args' => array(
  1335. 'class' => 'Location',
  1336. 'output' => 'details',
  1337. ),
  1338. 'csvdata' => "org_name;country\nDemo;France",
  1339. ),
  1340. array(
  1341. 'desc' => 'Error in attribute list - case A',
  1342. 'login' => 'admin',
  1343. 'password' => 'admin',
  1344. 'args' => array(
  1345. 'class' => 'Location',
  1346. 'output' => 'details',
  1347. ),
  1348. 'csvdata' => "name;org\nParis;2",
  1349. ),
  1350. array(
  1351. 'desc' => 'Error in attribute list - case B1 (key->attcode)',
  1352. 'login' => 'admin',
  1353. 'password' => 'admin',
  1354. 'args' => array(
  1355. 'class' => 'Location',
  1356. 'output' => 'details',
  1357. ),
  1358. 'csvdata' => "name;org->code\nParis;DEMO",
  1359. ),
  1360. array(
  1361. 'desc' => 'Error in attribute list - case B2 (key->attcode)',
  1362. 'login' => 'admin',
  1363. 'password' => 'admin',
  1364. 'args' => array(
  1365. 'class' => 'Location',
  1366. 'output' => 'details',
  1367. ),
  1368. 'csvdata' => "name;org_id->duns\nParis;DEMO",
  1369. ),
  1370. array(
  1371. 'desc' => 'Always changing... special comment in change tracking',
  1372. 'login' => 'admin',
  1373. 'password' => 'admin',
  1374. 'args' => array(
  1375. 'class' => 'Location',
  1376. 'output' => 'details',
  1377. 'comment' => 'automated testing'
  1378. ),
  1379. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;Addresse bidon:".((string)microtime(true)),
  1380. ),
  1381. array(
  1382. 'desc' => 'Always changing... but "simulate"',
  1383. 'login' => 'admin',
  1384. 'password' => 'admin',
  1385. 'args' => array(
  1386. 'class' => 'Location',
  1387. 'output' => 'details',
  1388. 'simulate' => '1',
  1389. 'comment' => 'SHOULD NEVER APPEAR IN THE HISTORY'
  1390. ),
  1391. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;restore address?",
  1392. ),
  1393. );
  1394. foreach ($aLoads as $aLoadSpec)
  1395. {
  1396. $this->DoExecSingleLoad($aLoadSpec);
  1397. }
  1398. }
  1399. }
  1400. ///////////////////////////////////////////////////////////////////////////
  1401. // Test massive data load
  1402. ///////////////////////////////////////////////////////////////////////////
  1403. define('IMPORT_COUNT', 4000);
  1404. class TestImportRESTMassive extends TestImportREST
  1405. {
  1406. static public function GetName()
  1407. {
  1408. return 'CSV import (REST) - HUGE data set ('.IMPORT_COUNT.' PCs)';
  1409. }
  1410. static public function GetDescription()
  1411. {
  1412. return 'Stress import.php';
  1413. }
  1414. protected function DoExecute()
  1415. {
  1416. $aLoadSpec = array(
  1417. 'desc' => 'Loading PCs: '.IMPORT_COUNT,
  1418. 'args' => array(
  1419. 'class' => 'PC',
  1420. 'output' => 'summary',
  1421. ),
  1422. 'csvdata' => "name;org_id;brand\n",
  1423. );
  1424. for($i = 0 ; $i <= IMPORT_COUNT ; $i++)
  1425. {
  1426. $aLoadSpec['csvdata'] .= "pc.import.$i;2;Combodo\n";
  1427. }
  1428. $this->DoExecSingleLoad($aLoadSpec);
  1429. }
  1430. }
  1431. ///////////////////////////////////////////////////////////////////////////
  1432. // Test SOAP services
  1433. ///////////////////////////////////////////////////////////////////////////
  1434. $aWebServices = array(
  1435. array(
  1436. 'verb' => 'GetVersion',
  1437. 'expected result' => WebServices::GetVersion(),
  1438. 'explain result' => 'no comment!',
  1439. 'args' => array(),
  1440. ),
  1441. array(
  1442. 'verb' => 'CreateIncidentTicket',
  1443. 'expected result' => true,
  1444. 'explain result' => 'link attribute unknown + a CI not found',
  1445. 'args' => array(
  1446. 'admin', /* sLogin */
  1447. 'admin', /* sPassword */
  1448. 'desc of ticket', /* sDescription */
  1449. 'initial situation blah blah blah', /* sInitialSituation */
  1450. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1451. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1452. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1453. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1454. 'sub product of the service', /* sProduct */
  1455. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1456. array(
  1457. new SOAPLinkCreationSpec(
  1458. 'InfrastructureCI',
  1459. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  1460. array(new SOAPAttributeValue('impacting', 'very critical'))
  1461. ),
  1462. new SOAPLinkCreationSpec(
  1463. 'NetworkDevice',
  1464. array(new SOAPSearchCondition('name', 'switch01')),
  1465. array(new SOAPAttributeValue('impact', 'who cares'))
  1466. ),
  1467. new SOAPLinkCreationSpec(
  1468. 'Server',
  1469. array(new SOAPSearchCondition('name', 'thisone')),
  1470. array(new SOAPAttributeValue('impact', 'our lives'))
  1471. ),
  1472. ), /* aImpact */
  1473. '1', /* sImpact */
  1474. '1', /* sUrgency */
  1475. ),
  1476. ),
  1477. array(
  1478. 'verb' => 'CreateIncidentTicket',
  1479. 'expected result' => true,
  1480. 'explain result' => 'caller not specified',
  1481. 'args' => array(
  1482. 'admin', /* sLogin */
  1483. 'admin', /* sPassword */
  1484. 'PC burning', /* sDescription */
  1485. 'The power supply suddenly started to warm up', /* sInitialSituation */
  1486. new SOAPExternalKeySearch(), /* aCallerDesc */
  1487. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1488. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1489. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1490. 'sub product of the service', /* sProduct */
  1491. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1492. array(
  1493. new SOAPLinkCreationSpec(
  1494. 'InfrastructureCI',
  1495. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  1496. array()
  1497. ), /* aImpact */
  1498. ),
  1499. '1', /* sImpact */
  1500. '1', /* sUrgency */
  1501. ),
  1502. ),
  1503. array(
  1504. 'verb' => 'CreateIncidentTicket',
  1505. 'expected result' => false,
  1506. 'explain result' => 'wrong class on CI to attach',
  1507. 'args' => array(
  1508. 'admin', /* sLogin */
  1509. 'admin', /* sPassword */
  1510. 'PC burning', /* sDescription */
  1511. 'The power supply suddenly started to warm up', /* sInitialSituation */
  1512. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1513. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1514. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1515. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1516. 'sub product of the service', /* sProduct */
  1517. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1518. array(
  1519. new SOAPLinkCreationSpec(
  1520. 'logInfra',
  1521. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  1522. array(new SOAPAttributeValue('impact', 'very critical'))
  1523. ),
  1524. ), /* aImpact */
  1525. '1', /* sImpact */
  1526. '1', /* sUrgency */
  1527. ),
  1528. ),
  1529. array(
  1530. 'verb' => 'CreateIncidentTicket',
  1531. 'expected result' => false,
  1532. 'explain result' => 'wrong search condition on CI to attach',
  1533. 'args' => array(
  1534. 'admin', /* sLogin */
  1535. 'admin', /* sPassword */
  1536. 'PC burning', /* sDescription */
  1537. 'The power supply suddenly started to warm up', /* sInitialSituation */
  1538. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1539. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1540. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1541. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1542. 'sub product of the service', /* sProduct */
  1543. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1544. array(
  1545. new SOAPLinkCreationSpec(
  1546. 'InfrastructureCI',
  1547. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  1548. array(new SOAPAttributeValue('impact', 'very critical'))
  1549. ),
  1550. ), /* aImpact */
  1551. '1', /* sImpact */
  1552. '1', /* sUrgency */
  1553. ),
  1554. ),
  1555. array(
  1556. 'verb' => 'CreateIncidentTicket',
  1557. 'expected result' => true,
  1558. 'explain result' => 'no CI to attach (empty array)',
  1559. 'args' => array(
  1560. 'admin', /* sLogin */
  1561. 'admin', /* sPassword */
  1562. 'Houston not reachable', /* sDescription */
  1563. 'Tried to join the shuttle', /* sInitialSituation */
  1564. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1565. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1566. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1567. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1568. 'sub product of the service', /* sProduct */
  1569. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1570. array(
  1571. ), /* aImpact */
  1572. '1', /* sImpact */
  1573. '1', /* sUrgency */
  1574. ),
  1575. ),
  1576. array(
  1577. 'verb' => 'CreateIncidentTicket',
  1578. 'expected result' => true,
  1579. 'explain result' => 'no CI to attach (null)',
  1580. 'args' => array(
  1581. 'admin', /* sLogin */
  1582. 'admin', /* sPassword */
  1583. 'Houston not reachable', /* sDescription */
  1584. 'Tried to join the shuttle', /* sInitialSituation */
  1585. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1586. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1587. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1588. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1589. 'sub product of the service', /* sProduct */
  1590. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1591. null, /* aImpact */
  1592. '1', /* sImpact */
  1593. '1', /* sUrgency */
  1594. ),
  1595. ),
  1596. array(
  1597. 'verb' => 'CreateIncidentTicket',
  1598. 'expected result' => true,
  1599. 'explain result' => 'caller unknown',
  1600. 'args' => array(
  1601. 'admin', /* sLogin */
  1602. 'admin', /* sPassword */
  1603. 'Houston not reachable', /* sDescription */
  1604. 'Tried to join the shuttle', /* sInitialSituation */
  1605. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1000))), /* aCallerDesc */
  1606. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1607. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1608. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1609. 'sub product of the service', /* sProduct */
  1610. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1611. array(
  1612. ), /* aImpact */
  1613. '1', /* sImpact */
  1614. '1', /* sUrgency */
  1615. ),
  1616. ),
  1617. array(
  1618. 'verb' => 'CreateIncidentTicket',
  1619. 'expected result' => false,
  1620. 'explain result' => 'wrong values for impact and urgency',
  1621. 'args' => array(
  1622. 'admin', /* sLogin */
  1623. 'admin', /* sPassword */
  1624. 'Houston not reachable', /* sDescription */
  1625. 'Tried to join the shuttle', /* sInitialSituation */
  1626. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1627. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1628. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1629. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1630. 'sub product of the service', /* sProduct */
  1631. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1632. array(
  1633. ), /* aImpact */
  1634. '6', /* sImpact */
  1635. '7', /* sUrgency */
  1636. ),
  1637. ),
  1638. array(
  1639. 'verb' => 'CreateIncidentTicket',
  1640. 'expected result' => false,
  1641. 'explain result' => 'wrong password',
  1642. 'args' => array(
  1643. 'admin', /* sLogin */
  1644. 'xxxxx', /* sPassword */
  1645. 'Houston not reachable', /* sDescription */
  1646. 'Tried to join the shuttle', /* sInitialSituation */
  1647. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1648. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1649. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1650. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1651. 'sub product of the service', /* sProduct */
  1652. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1653. array(
  1654. ), /* aImpact */
  1655. '1', /* sImpact */
  1656. '1', /* sUrgency */
  1657. ),
  1658. ),
  1659. array(
  1660. 'verb' => 'CreateIncidentTicket',
  1661. 'expected result' => false,
  1662. 'explain result' => 'wrong login',
  1663. 'args' => array(
  1664. 'xxxxx', /* sLogin */
  1665. 'yyyyy', /* sPassword */
  1666. 'Houston not reachable', /* sDescription */
  1667. 'Tried to join the shuttle', /* sInitialSituation */
  1668. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  1669. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  1670. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  1671. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  1672. 'sub product of the service', /* sProduct */
  1673. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  1674. array(
  1675. ), /* aImpact */
  1676. '1', /* sImpact */
  1677. '1', /* sUrgency */
  1678. ),
  1679. ),
  1680. );
  1681. class TestSoap extends TestSoapWebService
  1682. {
  1683. static public function GetName() {return 'Test SOAP';}
  1684. static public function GetDescription() {return 'Do basic stuff to test the SOAP capability';}
  1685. protected function DoExecute()
  1686. {
  1687. echo "<p>Note: You may also want to try the sample SOAP client <a href=\"../webservices/itopsoap.examples.php\">itopsoap.examples.php</a></p>\n";
  1688. global $aSOAPMapping;
  1689. // this file is generated dynamically with location = here
  1690. $sWsdlUri = 'http'.(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off') ? 's' : '').'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER['SCRIPT_NAME']).'/../webservices/itop.wsdl.php';
  1691. ini_set("soap.wsdl_cache_enabled","0");
  1692. $this->m_SoapClient = new SoapClient
  1693. (
  1694. $sWsdlUri,
  1695. array(
  1696. 'classmap' => $aSOAPMapping,
  1697. 'trace' => 1,
  1698. )
  1699. );
  1700. if (false)
  1701. {
  1702. self::DumpVariable($this->m_SoapClient->__getTypes());
  1703. }
  1704. global $aWebServices;
  1705. foreach ($aWebServices as $iPos => $aWebService)
  1706. {
  1707. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  1708. echo "<p>{$aWebService['explain result']}</p>\n";
  1709. try
  1710. {
  1711. $oRes = call_user_func_array(array($this->m_SoapClient, $aWebService['verb']), $aWebService['args']);
  1712. }
  1713. catch(SoapFault $e)
  1714. {
  1715. print "<pre>\n";
  1716. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  1717. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  1718. print "</pre>";
  1719. print "Response in HTML: <p>".$this->m_SoapClient->__getLastResponse()."</p>";
  1720. throw $e;
  1721. }
  1722. self::DumpVariable($oRes);
  1723. print "<pre>\n";
  1724. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  1725. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  1726. print "</pre>";
  1727. if ($oRes instanceof SOAPResult)
  1728. {
  1729. $res = $oRes->status;
  1730. }
  1731. else
  1732. {
  1733. $res = $oRes;
  1734. }
  1735. if ($res != $aWebService['expected result'])
  1736. {
  1737. echo "Expecting:<br/>\n";
  1738. var_dump($aWebService['expected result']);
  1739. echo "Obtained:<br/>\n";
  1740. var_dump($res);
  1741. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  1742. }
  1743. }
  1744. }
  1745. }
  1746. class TestWebServicesDirect extends TestBizModel
  1747. {
  1748. static public function GetName() {return 'Test web services locally';}
  1749. static public function GetDescription() {return 'Invoke the service directly (troubleshooting)';}
  1750. static public function GetConfigFile() {return '/config-itop.php';}
  1751. protected function DoExecute()
  1752. {
  1753. $oWebServices = new WebServices();
  1754. global $aWebServices;
  1755. foreach ($aWebServices as $iPos => $aWebService)
  1756. {
  1757. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  1758. echo "<p>{$aWebService['explain result']}</p>\n";
  1759. $oRes = call_user_func_array(array($oWebServices, $aWebService['verb']), $aWebService['args']);
  1760. self::DumpVariable($oRes);
  1761. if ($oRes instanceof SOAPResult)
  1762. {
  1763. $res = $oRes->status;
  1764. }
  1765. else
  1766. {
  1767. $res = $oRes;
  1768. }
  1769. if ($res != $aWebService['expected result'])
  1770. {
  1771. echo "Expecting:<br/>\n";
  1772. var_dump($aWebService['expected result']);
  1773. echo "Obtained:<br/>\n";
  1774. var_dump($res);
  1775. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  1776. }
  1777. }
  1778. return true;
  1779. }
  1780. }
  1781. class TestTriggerAndEmail extends TestBizModel
  1782. {
  1783. static public function GetName() {return 'Test trigger and email';}
  1784. static public function GetDescription() {return 'Create a trigger and an email, then activates the trigger';}
  1785. static public function GetConfigFile() {return '/config-itop.php';}
  1786. protected function CreateEmailSpec($oTrigger, $sStatus, $sTo, $sCC, $sTesterEmail)
  1787. {
  1788. $oAction = MetaModel::NewObject("ActionEmail");
  1789. $oAction->Set("status", $sStatus);
  1790. $oAction->Set("name", "New server");
  1791. $oAction->Set("test_recipient", $sTesterEmail);
  1792. $oAction->Set("from", $sTesterEmail);
  1793. $oAction->Set("reply_to", $sTesterEmail);
  1794. $oAction->Set("to", $sTo);
  1795. $oAction->Set("cc", $sCC);
  1796. $oAction->Set("bcc", "");
  1797. $oAction->Set("subject", "New server: '\$this->name()$'");
  1798. $oAction->Set("body", "<html><body><p>Dear customer,</p><p>We have created the server \$this->hyperlink()$ in the IT infrastructure database.</p><p>You will be further notified when it is in <strong>Production</strong>.</p><p>The IT infrastructure management team.</p><p>Here are some accentuated characters for french people: 'ééà'</p></body></html>");
  1799. $oAction->Set("importance", "low");
  1800. $iActionId = $this->ObjectToDB($oAction, true);
  1801. $oLink = MetaModel::NewObject("lnkTriggerAction");
  1802. $oLink->Set("trigger_id", $oTrigger->GetKey());
  1803. $oLink->Set("action_id", $iActionId);
  1804. $oLink->Set("order", "1");
  1805. $iLink = $this->ObjectToDB($oLink, true);
  1806. }
  1807. protected function DoExecute()
  1808. {
  1809. $oMyPerson = MetaModel::NewObject("bizPerson");
  1810. $oMyPerson->Set("name", "testemail1");
  1811. $oMyPerson->Set("org_id", "1");
  1812. $oMyPerson->Set("email", "romain.quetiez@hp.com");
  1813. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  1814. $oMyPerson = MetaModel::NewObject("bizPerson");
  1815. $oMyPerson->Set("name", "testemail2");
  1816. $oMyPerson->Set("org_id", "1");
  1817. $oMyPerson->Set("email", "denis.flaven@hp.com");
  1818. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  1819. $oMyPerson = MetaModel::NewObject("bizPerson");
  1820. $oMyPerson->Set("name", "testemail3");
  1821. $oMyPerson->Set("org_id", "1");
  1822. $oMyPerson->Set("email", "erwan.taloc@hp.com");
  1823. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  1824. $oMyServer = MetaModel::NewObject("bizServer");
  1825. $oMyServer->Set("name", "wfr.terminator.com");
  1826. $oMyServer->Set("severity", "low");
  1827. $oMyServer->Set("status", "production");
  1828. $oMyServer->Set("org_id", 2);
  1829. $oMyServer->Set("location_id", 2);
  1830. $iServerId = $this->ObjectToDB($oMyServer, true);
  1831. $oMyTrigger = MetaModel::NewObject("TriggerOnStateEnter");
  1832. $oMyTrigger->Set("description", "Testor");
  1833. $oMyTrigger->Set("target_class", "bizServer");
  1834. $oMyTrigger->Set("state", "Shipped");
  1835. $iTriggerId = $this->ObjectToDB($oMyTrigger, true);
  1836. // Error in OQL field(s)
  1837. //
  1838. $this->CreateEmailSpec
  1839. (
  1840. $oMyTrigger,
  1841. 'test',
  1842. "SELECT bizPerson WHERE naime = 'Dali'",
  1843. "SELECT bizServer",
  1844. 'romain.quetiez@hp.com'
  1845. );
  1846. // Error: no recipient
  1847. //
  1848. $this->CreateEmailSpec
  1849. (
  1850. $oMyTrigger,
  1851. 'test',
  1852. "",
  1853. "",
  1854. 'romain.quetiez@hp.com'
  1855. );
  1856. // Test
  1857. //
  1858. $this->CreateEmailSpec
  1859. (
  1860. $oMyTrigger,
  1861. 'test',
  1862. "SELECT bizPerson WHERE name LIKE 'testemail%'",
  1863. "SELECT bizPerson",
  1864. 'romain.quetiez@hp.com'
  1865. );
  1866. // Test failing because of a wrong test recipient address
  1867. //
  1868. $this->CreateEmailSpec
  1869. (
  1870. $oMyTrigger,
  1871. 'test',
  1872. "SELECT bizPerson WHERE name LIKE 'testemail%'",
  1873. "",
  1874. 'toto@walibi.bg'
  1875. );
  1876. // Normal behavior
  1877. //
  1878. $this->CreateEmailSpec
  1879. (
  1880. $oMyTrigger,
  1881. 'enabled',
  1882. "SELECT bizPerson WHERE name LIKE 'testemail%'",
  1883. "",
  1884. 'romain.quetiez@hp.com'
  1885. );
  1886. // Does nothing, because it is disabled
  1887. //
  1888. $this->CreateEmailSpec
  1889. (
  1890. $oMyTrigger,
  1891. 'disabled',
  1892. "SELECT bizPerson WHERE name = 'testemail%'",
  1893. "",
  1894. 'romain.quetiez@hp.com'
  1895. );
  1896. $oMyTrigger->DoActivate($oMyServer->ToArgs('this'));
  1897. return true;
  1898. }
  1899. }
  1900. class TestDBProperties extends TestBizModel
  1901. {
  1902. static public function GetName()
  1903. {
  1904. return 'Itop - DB Properties';
  1905. }
  1906. static public function GetDescription()
  1907. {
  1908. return 'Write and read a dummy property';
  1909. }
  1910. static public function GetConfigFile() {return '/config-itop.php';}
  1911. protected function DoExecute()
  1912. {
  1913. $sName = 'test';
  1914. DBProperty::SetProperty($sName, 'unix time:'.time(), 'means nothing', 'done with the automated test utility');
  1915. $sValue = DBProperty::GetProperty($sName);
  1916. echo "<p>Write... then read property <b>$sName</b>, found: '$sValue'</p>\n";
  1917. }
  1918. }
  1919. class TestCreateObjects extends TestBizModel
  1920. {
  1921. static public function GetName()
  1922. {
  1923. return 'Itop - create objects';
  1924. }
  1925. static public function GetDescription()
  1926. {
  1927. return 'Create weird objects (reproduce a bug?)';
  1928. }
  1929. static public function GetConfigFile() {return '/config-itop.php';}
  1930. protected function DoExecute()
  1931. {
  1932. $oMyObj = MetaModel::NewObject("Server");
  1933. $oMyObj->Set("name", "test".rand(1,1000));
  1934. $oMyObj->Set("org_id", 2);
  1935. $oMyObj->Set("status", 'production');
  1936. $this->ObjectToDB($oMyObj, $bReload = true);
  1937. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  1938. $sTicketRef = "I-abcdef";
  1939. echo "<p>Creating: $sTicketRef</p>";
  1940. $oMyObj = MetaModel::NewObject("Incident");
  1941. $oMyObj->Set("ref", $sTicketRef);
  1942. $oMyObj->Set("title", "my title");
  1943. $oMyObj->Set("description", "my description");
  1944. $oMyObj->Set("ticket_log", "my ticket log");
  1945. $oMyObj->Set("start_date", "2010-03-08 17:37:00");
  1946. $oMyObj->Set("status", "resolved");
  1947. $oMyObj->Set("caller_id", 1);
  1948. $oMyObj->Set("org_id", 1);
  1949. $oMyObj->Set("urgency", 3);
  1950. $oMyObj->Set("agent_id", 1);
  1951. $oMyObj->Set("close_date", "0000-00-00 00:00:00");
  1952. $oMyObj->Set("last_update", "2010-04-08 16:47:29");
  1953. $oMyObj->Set("solution", "branche ton pc!");
  1954. // External key given as a string -> should be casted to an integer
  1955. $oMyObj->Set("service_id", "1");
  1956. $oMyObj->Set("servicesubcategory_id", "1");
  1957. $oMyObj->Set("product", "");
  1958. $oMyObj->Set("impact", 2);
  1959. $oMyObj->Set("priority", 3);
  1960. $oMyObj->Set("related_problem_id", 0);
  1961. $oMyObj->Set("related_change_id", 0);
  1962. $oMyObj->Set("assignment_date", "");
  1963. $oMyObj->Set("resolution_date", "");
  1964. $oMyObj->Set("tto_escalation_deadline", "");
  1965. $oMyObj->Set("ttr_escalation_deadline", "");
  1966. $oMyObj->Set("closure_deadline", "");
  1967. $oMyObj->Set("resolution_code", "fixed");
  1968. $oMyObj->Set("user_satisfaction", "");
  1969. $oMyObj->Set("user_commment", "");
  1970. $oMyObj->Set("workgroup_id", 4);
  1971. $this->ObjectToDB($oMyObj, $bReload = true);
  1972. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  1973. }
  1974. }
  1975. ?>