testlist.inc.php 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309
  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. // $aFullTextNeedles = array('column1'),
  47. $bToDelete = false,
  48. $aValues = array()
  49. );
  50. $oQuery->AddCondition(Expression::FromOQL('DATE(NOW() - 1200 * 2) > \'2008-07-31\''));
  51. $oSubQuery1 = new SQLQuery(
  52. $sTable = 'myTable1',
  53. $sTableAlias = 'myTable1Alias',
  54. $aFields = array('column1_1'=>new FieldExpression('column1', 'myTableAlias'), 'column1_2'=>new FieldExpression('column1', 'myTableAlias')),
  55. // $aFullTextNeedles = array(),
  56. $bToDelete = false,
  57. $aValues = array()
  58. );
  59. $oSubQuery2 = new SQLQuery(
  60. $sTable = 'myTable2',
  61. $sTableAlias = 'myTable2Alias',
  62. $aFields = array('column2_1'=>new FieldExpression('column2', 'myTableAlias'), 'column2_2'=>new FieldExpression('column2', 'myTableAlias')),
  63. // $aFullTextNeedles = array(),
  64. $bToDelete = false,
  65. $aValues = array()
  66. );
  67. $oQuery->AddInnerJoin($oSubQuery1, 'column1', 'column1_1');
  68. $oQuery->AddLeftJoin($oSubQuery2, 'column2', 'column2_2');
  69. $oQuery->DisplayHtml();
  70. $oQuery->RenderDelete();
  71. $oQuery->RenderUpdate();
  72. echo '<p>'.$oQuery->RenderSelect().'</p>';
  73. $oQuery->RenderSelect(array('column1'));
  74. $oQuery->RenderSelect(array('column1', 'column2'));
  75. }
  76. }
  77. class TestOQLParser extends TestFunction
  78. {
  79. static public function GetName() {return 'Check OQL parsing';}
  80. static public function GetDescription() {return 'Attempts a series of queries, and in particular those with a bad syntax';}
  81. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  82. {
  83. $oOql = new OqlInterpreter($sQuery);
  84. try
  85. {
  86. $oTrash = $oOql->Parse(); // Not expecting a given format, otherwise use ParseExpression/ParseObjectQuery/ParseValueSetQuery
  87. self::DumpVariable($oTrash);
  88. }
  89. catch (OQLException $OqlException)
  90. {
  91. if ($bIsCorrectQuery)
  92. {
  93. echo "<p>More info on this unexpected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  94. throw $OqlException;
  95. return false;
  96. }
  97. else
  98. {
  99. // Everything is fine :-)
  100. echo "<p>More info on this expected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  101. return true;
  102. }
  103. }
  104. // The query was correctly parsed, was it expected to be correct ?
  105. if ($bIsCorrectQuery)
  106. {
  107. return true;
  108. }
  109. else
  110. {
  111. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  112. return false;
  113. }
  114. }
  115. protected function TestQuery($sQuery, $bIsCorrectQuery)
  116. {
  117. if (!$this->CheckQuery($sQuery, $bIsCorrectQuery))
  118. {
  119. return false;
  120. }
  121. return true;
  122. }
  123. public function DoExecute()
  124. {
  125. $aQueries = array(
  126. 'SELECT toto' => true,
  127. 'SELECT toto WHERE toto.a = 1' => true,
  128. 'SELECT toto WHERE toto.a = :myparameter' => true,
  129. 'SELECT toto WHERE toto.a IN (:param1)' => true,
  130. 'SELECT toto WHERE toto.a IN (:param1, :param2)' => 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. 'SELECT A JOIN B ON A.myB BELOW B.id WHERE A.col1 = 2' => true,
  179. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id BELOW B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  180. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id BELOW STRICT B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  181. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id NOT BELOW B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  182. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id NOT BELOW STRICT B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  183. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id = B.id WHERE A.col1 BELOW 2 AND B.id = 3' => false,
  184. );
  185. $iErrors = 0;
  186. foreach($aQueries as $sQuery => $bIsCorrectQuery)
  187. {
  188. $sIsOk = $bIsCorrectQuery ? 'good' : 'bad';
  189. echo "<h4>Testing query: $sQuery ($sIsOk)</h4>\n";
  190. try
  191. {
  192. $bRet = $this->TestQuery($sQuery, $bIsCorrectQuery);
  193. }
  194. catch(Exception $e)
  195. {
  196. $this->m_aErrors[] = "Exception: ".$e->getMessage();
  197. $bRet = false;
  198. }
  199. if (!$bRet) $iErrors++;
  200. }
  201. return ($iErrors == 0);
  202. }
  203. }
  204. class TestCSVParser extends TestFunction
  205. {
  206. static public function GetName() {return 'Check CSV parsing';}
  207. static public function GetDescription() {return 'Loads a set of CSV data';}
  208. public function DoExecute()
  209. {
  210. $sDataFile = '?field1?;?field2?;?field3?
  211. ?a?;?b?;?c?
  212. a;b;c
  213. ? a ? ; ? b ? ; ? c ?
  214. a ; b ; c
  215. ??;??;??
  216. ;;
  217. ?a"?;?b?;?c?
  218. ?a1
  219. a2?;?b?;?c?
  220. ?a1,a2?;?b?;?c?
  221. ?a?;?b?;?c1,",c2
  222. ,c3?
  223. ?a?;?b?;?ouf !?
  224. Espace sur la fin ; 1234; e@taloc.com ';
  225. self::DumpVariable($sDataFile);
  226. $aExpectedResult = array(
  227. //array('field1', 'field2', 'field3'),
  228. array('a', 'b', 'c'),
  229. array('a', 'b', 'c'),
  230. array(' a ', ' b ', ' c '),
  231. array('a', 'b', 'c'),
  232. array('', '', ''),
  233. array('', '', ''),
  234. array('a"', 'b', 'c'),
  235. array("a1\na2", 'b', 'c'),
  236. array('a1,a2', 'b', 'c'),
  237. array('a', 'b', "c1,\",c2\n,c3"),
  238. array('a', 'b', 'ouf !'),
  239. array('Espace sur la fin', '1234', 'e@taloc.com'),
  240. );
  241. $oCSVParser = new CSVParser($sDataFile, ';', '?');
  242. $aData = $oCSVParser->ToArray(1, null, 0);
  243. $iIssues = 0;
  244. echo "<table border=\"1\">\n";
  245. foreach ($aData as $iRow => $aRow)
  246. {
  247. echo "<tr>\n";
  248. foreach ($aRow as $iCol => $sCell)
  249. {
  250. if (empty($sCell))
  251. {
  252. $sCellValue = '&nbsp;';
  253. }
  254. else
  255. {
  256. $sCellValue = htmlentities($sCell, ENT_QUOTES, 'UTF-8');
  257. }
  258. if (!isset($aExpectedResult[$iRow][$iCol]))
  259. {
  260. $iIssues++;
  261. $sCellValue = "<span style =\"color: red; background-color: grey;\">$sCellValue</span>";
  262. }
  263. elseif ($aExpectedResult[$iRow][$iCol] != $sCell)
  264. {
  265. $iIssues++;
  266. $sCellValue = "<span style =\"color: red; background-color: lightgrey;\">$sCellValue</span>, expecting '<span style =\"color: green; background-color: lightgrey;\">".$aExpectedResult[$iRow][$iCol]."</span>'";
  267. }
  268. echo "<td><pre>$sCellValue</pre></td>";
  269. }
  270. echo "</tr>\n";
  271. }
  272. echo "</table>\n";
  273. return ($iIssues > 0);
  274. }
  275. }
  276. class TestGenericItoMyModel extends TestBizModelGeneric
  277. {
  278. static public function GetName()
  279. {
  280. return 'Generic RO test on '.self::GetConfigFile();
  281. }
  282. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  283. }
  284. class TestGenericItopBigModel extends TestBizModelGeneric
  285. {
  286. static public function GetName()
  287. {
  288. return 'Generic RO test on '.self::GetConfigFile();
  289. }
  290. static public function GetConfigFile() {return '/config-test-itopv06.php';}
  291. }
  292. class TestUserRightsMatrixItop extends TestUserRights
  293. {
  294. static public function GetName()
  295. {
  296. return 'User rights test on user rights matrix';
  297. }
  298. static public function GetDescription()
  299. {
  300. return 'blah blah blah';
  301. }
  302. public function DoPrepare()
  303. {
  304. parent::DoPrepare();
  305. MetaModel::Startup('../config-test-itopv06.php');
  306. }
  307. protected function DoExecute()
  308. {
  309. $sUser = 'Romain';
  310. echo "<p>Totor: ".(UserRights::CheckCredentials('Totor', 'toto') ? 'ok' : 'NO')."</p>\n";
  311. echo "<p>Romain: ".(UserRights::CheckCredentials('Romain', 'toto') ? 'ok' : 'NO')."</p>\n";
  312. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  313. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  314. echo "<p>Denis (impersonate) : ".(UserRights::Impersonate('Denis', 'tutu') ? 'ok' : 'NO')."</p>\n";
  315. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  316. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  317. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT bizOrganization"));
  318. echo "<p>IsActionAllowed...".(UserRights::IsActionAllowed('bizOrganization', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  319. echo "<p>IsStimulusAllowed...".(UserRights::IsStimulusAllowed('bizOrganization', 'myStimulus', $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  320. echo "<p>IsActionAllowedOnAttribute...".(UserRights::IsActionAllowedOnAttribute('bizOrganization', 'myattribute', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  321. return true;
  322. }
  323. }
  324. ///////////////////////////////////////////////////////////////////////////
  325. // Test a complex biz model on the fly
  326. ///////////////////////////////////////////////////////////////////////////
  327. class TestMyBizModel extends TestBizModel
  328. {
  329. static public function GetName()
  330. {
  331. return 'A series of tests on a weird business model';
  332. }
  333. static public function GetDescription()
  334. {
  335. return 'Attempts various operations and build complex queries';
  336. }
  337. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  338. function test_linksinfo()
  339. {
  340. echo "<h4>Enum links</h4>";
  341. self::DumpVariable(MetaModel::EnumReferencedClasses("cmdbTeam"));
  342. self::DumpVariable(MetaModel::EnumReferencingClasses("Organization"));
  343. self::DumpVariable(MetaModel::EnumLinkingClasses());
  344. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdbContact"));
  345. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdWorkshop"));
  346. self::DumpVariable(MetaModel::GetLinkLabel("Liens_entre_contacts_et_workshop", "toworkshop"));
  347. }
  348. function test_list_attributes()
  349. {
  350. echo "<h4>List attributes</h4>";
  351. foreach(MetaModel::ListAttributeDefs("cmdbTeam") as $sAttCode=>$oAttDef)
  352. {
  353. echo $oAttDef->GetLabel()." / ".$oAttDef->GetDescription()." / ".$oAttDef->GetType()."</br>\n";
  354. }
  355. }
  356. function test_search()
  357. {
  358. echo "<h4>Two searches</h4>";
  359. $oFilterAllDevs = new DBObjectSearch("cmdbTeam");
  360. $oAllDevs = new DBObjectSet($oFilterAllDevs);
  361. echo "Found ".$oAllDevs->Count()." items.</br>\n";
  362. while ($oDev = $oAllDevs->Fetch())
  363. {
  364. $aValues = array();
  365. foreach(MetaModel::GetAttributesList($oAllDevs->GetClass()) as $sAttCode)
  366. {
  367. $aValues[] = MetaModel::GetLabel(get_class($oDev), $sAttCode)." (".MetaModel::GetDescription(get_class($oDev), $sAttCode).") = ".$oDev->GetAsHTML($sAttCode);
  368. }
  369. echo $oDev->GetKey()." => ".implode(", ", $aValues)."</br>\n";
  370. }
  371. // a second one
  372. $oMyFilter = new DBObjectSearch("cmdbContact");
  373. //$oMyFilter->AddCondition("name", "aii", "Finishes with");
  374. $oMyFilter->AddCondition("name", "aii");
  375. $this->search_and_show_list($oMyFilter);
  376. }
  377. function test_reload()
  378. {
  379. echo "<h4>Reload</h4>";
  380. $team = MetaModel::GetObject("cmdbContact", "2");
  381. echo "Chargement de l'attribut headcount: {$team->Get("headcount")}</br>\n";
  382. self::DumpVariable($team);
  383. }
  384. function test_setattribute()
  385. {
  386. echo "<h4>Set attribute and update</h4>";
  387. $team = MetaModel::GetObject("cmdbTeam", "2");
  388. $team->Set("headcount", rand(1,1000));
  389. $team->Set("email", "Luis ".rand(9,250));
  390. self::DumpVariable($team->ListChanges());
  391. echo "New headcount = {$team->Get("headcount")}</br>\n";
  392. echo "Computed name = {$team->Get("name")}</br>\n";
  393. $oMyChange = MetaModel::NewObject("CMDBChange");
  394. $oMyChange->Set("date", time());
  395. $oMyChange->Set("userinfo", "test_setattribute / Made by robot #".rand(1,100));
  396. $iChangeId = $oMyChange->DBInsert();
  397. //MetaModel::StartDebugQuery();
  398. $team->DBUpdateTracked($oMyChange);
  399. //MetaModel::StopDebugQuery();
  400. echo "<h4>Check the modified team</h4>";
  401. $oTeam = MetaModel::GetObject("cmdbTeam", "2");
  402. self::DumpVariable($oTeam);
  403. }
  404. function test_newobject()
  405. {
  406. $oMyChange = MetaModel::NewObject("CMDBChange");
  407. $oMyChange->Set("date", time());
  408. $oMyChange->Set("userinfo", "test_newobject / Made by robot #".rand(1,100));
  409. $iChangeId = $oMyChange->DBInsert();
  410. echo "<h4>Create a new object (team)</h4>";
  411. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  412. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  413. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  414. $oNewTeam->Set("email", null);
  415. $oNewTeam->Set("owner", "ITOP");
  416. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  417. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  418. echo "Created new team: $iId</br>";
  419. echo "<h4>Delete team #$iId</h4>";
  420. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  421. $oTeam->DBDeleteTracked($oMyChange);
  422. echo "Deleted team: $iId</br>";
  423. self::DumpVariable($oTeam);
  424. }
  425. function test_updatecolumn()
  426. {
  427. $oMyChange = MetaModel::NewObject("CMDBChange");
  428. $oMyChange->Set("date", time());
  429. $oMyChange->Set("userinfo", "test_updatecolumn / Made by robot #".rand(1,100));
  430. $iChangeId = $oMyChange->DBInsert();
  431. $sNewEmail = "updatecol".rand(9,250)."@quedlaballe.com";
  432. echo "<h4>Update a the email: set to '$sNewEmail'</h4>";
  433. $oMyFilter = new DBObjectSearch("cmdbContact");
  434. $oMyFilter->AddCondition("name", "o", "Contains");
  435. echo "Candidates before:</br>";
  436. $this->search_and_show_list($oMyFilter);
  437. MetaModel::BulkUpdateTracked($oMyChange, $oMyFilter, array("email" => $sNewEmail));
  438. echo "Candidates after:</br>";
  439. $this->search_and_show_list($oMyFilter);
  440. }
  441. function test_error()
  442. {
  443. trigger_error("Stop requested", E_USER_ERROR);
  444. }
  445. function test_changetracking()
  446. {
  447. echo "<h4>Create a change</h4>";
  448. $oMyChange = MetaModel::NewObject("CMDBChange");
  449. $oMyChange->Set("date", time());
  450. $oMyChange->Set("userinfo", "Made by robot #".rand(1,100));
  451. $iChangeId = $oMyChange->DBInsert();
  452. echo "Created new change: $iChangeId</br>";
  453. self::DumpVariable($oMyChange);
  454. echo "<h4>Create a new object (team)</h4>";
  455. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  456. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  457. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  458. $oNewTeam->Set("email", null);
  459. $oNewTeam->Set("owner", "ITOP");
  460. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  461. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  462. echo "Created new team: $iId</br>";
  463. echo "<h4>Delete team #$iId</h4>";
  464. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  465. $oTeam->DBDeleteTracked($oMyChange);
  466. echo "Deleted team: $iId</br>";
  467. self::DumpVariable($oTeam);
  468. }
  469. function test_zlist()
  470. {
  471. echo "<h4>Test ZLists</h4>";
  472. $aZLists = MetaModel::EnumZLists();
  473. foreach ($aZLists as $sListCode)
  474. {
  475. $aListInfos = MetaModel::GetZListInfo($sListCode);
  476. echo "<h4>List '".$sListCode."' (".$aListInfos["description"].") of type '".$aListInfos["type"]."'</h5>\n";
  477. foreach (MetaModel::GetSubclasses("cmdbObjectHomeMade") as $sKlass)
  478. {
  479. $aItems = MetaModel::FlattenZlist(MetaModel::GetZListItems($sKlass, $sListCode));
  480. if (count($aItems) == 0) continue;
  481. echo "$sKlass - $sListCode : {".implode(", ", $aItems)."}</br>\n";
  482. }
  483. }
  484. echo "<h4>IsAttributeInZList()... </h4>";
  485. echo "Liens_entre_contacts_et_workshop::ws_info in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "ws_info") ? "yes" : "no")."</br>\n";
  486. echo "Liens_entre_contacts_et_workshop::toworkshop in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "toworkshop") ? "yes" : "no")."</br>\n";
  487. }
  488. function test_pkey()
  489. {
  490. echo "<h4>Test search on pkey</h4>";
  491. $sExpr1 = "SELECT cmdbContact WHERE id IN (40, 42)";
  492. $sExpr2 = "SELECT cmdbContact WHERE IN NOT IN (40, 42)";
  493. $this->search_and_show_list_from_oql($sExpr1);
  494. $this->search_and_show_list_from_oql($sExpr2);
  495. echo "Et maintenant, on fusionne....</br>\n";
  496. $oSet1 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr1));
  497. $oSet2 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr2));
  498. $oIntersect = $oSet1->CreateIntersect($oSet2);
  499. $oDelta = $oSet1->CreateDelta($oSet2);
  500. $oMerge = clone $oSet1;
  501. $oMerge->Merge($oSet2);
  502. $oMerge->Merge($oSet2);
  503. echo "Set1 - Found ".$oSet1->Count()." items.</br>\n";
  504. echo "Set2 - Found ".$oSet2->Count()." items.</br>\n";
  505. echo "Intersect - Found ".$oIntersect->Count()." items.</br>\n";
  506. echo "Delta - Found ".$oDelta->Count()." items.</br>\n";
  507. echo "Merge - Found ".$oMerge->Count()." items.</br>\n";
  508. //$this->show_list($oObjSet);
  509. }
  510. function test_relations()
  511. {
  512. echo "<h4>Test relations</h4>";
  513. //self::DumpVariable(MetaModel::EnumRelationQueries("cmdbObjectHomeMade", "Potes"));
  514. self::DumpVariable(MetaModel::EnumRelationQueries("cmdbContact", "Potes"));
  515. $iMaxDepth = 9;
  516. echo "Max depth = $iMaxDepth</br>\n";
  517. $oObj = MetaModel::GetObject("cmdbContact", 18);
  518. $aRels = $oObj->GetRelatedObjects("Potes", $iMaxDepth);
  519. echo $oObj->Get('name')." has some 'Potes'...</br>\n";
  520. foreach ($aRels as $sClass => $aObjs)
  521. {
  522. echo "$sClass, count = ".count($aObjs)." =&gt; ".implode(', ', array_keys($aObjs))."</br>\n";
  523. $oObjectSet = CMDBObjectSet::FromArray($sClass, $aObjs);
  524. $this->show_list($oObjectSet);
  525. }
  526. echo "<h4>Test relations - same results, by the mean of a OQL</h4>";
  527. $this->search_and_show_list_from_oql("cmdbContact: RELATED (Potes, $iMaxDepth) TO (cmdbContact: pkey = 18)");
  528. }
  529. function test_linkedset()
  530. {
  531. echo "<h4>Linked set attributes</h4>\n";
  532. $oObj = MetaModel::GetObject("cmdbContact", 18);
  533. echo "<h5>Current workshops</h5>\n";
  534. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  535. $this->show_list($oSetWorkshopsCurr);
  536. echo "<h5>Setting workshops</h5>\n";
  537. $oNewLink = new cmdbLiens();
  538. $oNewLink->Set('toworkshop', 2);
  539. $oNewLink->Set('function', 'mafonctioooon');
  540. $oNewLink->Set('a1', 'tralala1');
  541. $oNewLink->Set('a2', 'F7M');
  542. $oSetWorkshops = CMDBObjectSet::FromArray("cmdbLiens", array($oNewLink));
  543. $oObj->Set("myworkshops", $oSetWorkshops);
  544. $this->show_list($oSetWorkshops);
  545. echo "<h5>New workshops</h5>\n";
  546. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  547. $this->show_list($oSetWorkshopsCurr);
  548. $oMyChange = MetaModel::NewObject("CMDBChange");
  549. $oMyChange->Set("date", time());
  550. $oMyChange->Set("userinfo", "test_linkedset / Made by robot #".rand(1,100));
  551. $iChangeId = $oMyChange->DBInsert();
  552. $oObj->DBUpdateTracked($oMyChange);
  553. $oObj = MetaModel::GetObject("cmdbContact", 18);
  554. echo "<h5>After the write</h5>\n";
  555. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  556. $this->show_list($oSetWorkshopsCurr);
  557. }
  558. function test_object_lifecycle()
  559. {
  560. echo "<h4>Test object lifecycle</h4>";
  561. self::DumpVariable(MetaModel::GetStateAttributeCode("cmdbContact"));
  562. self::DumpVariable(MetaModel::EnumStates("cmdbContact"));
  563. self::DumpVariable(MetaModel::EnumStimuli("cmdbContact"));
  564. foreach(MetaModel::EnumStates("cmdbContact") as $sStateCode => $aStateDef)
  565. {
  566. echo "<p>Transition from <strong>$sStateCode</strong></p>\n";
  567. self::DumpVariable(MetaModel::EnumTransitions("cmdbContact", $sStateCode));
  568. }
  569. $oObj = MetaModel::GetObject("cmdbContact", 18);
  570. echo "Current state: ".$oObj->GetState()."... let's go to school...";
  571. self::DumpVariable($oObj->EnumTransitions());
  572. $oObj->ApplyStimulus("toschool");
  573. echo "New state: ".$oObj->GetState()."... let's get older...";
  574. self::DumpVariable($oObj->EnumTransitions());
  575. $oObj->ApplyStimulus("raise");
  576. echo "New state: ".$oObj->GetState()."... let's try to go further... (should give an error)";
  577. self::DumpVariable($oObj->EnumTransitions());
  578. $oObj->ApplyStimulus("raise"); // should give an error
  579. }
  580. protected function DoExecute()
  581. {
  582. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  583. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  584. //$this->test_linksinfo();
  585. //$this->test_list_attributes();
  586. //$this->test_search();
  587. //$this->test_reload();
  588. //$this->test_newobject();
  589. $this->test_setattribute();
  590. //$this->test_updatecolumn();
  591. //$this->test_error();
  592. //$this->test_changetracking();
  593. $this->test_zlist();
  594. $this->test_OQL();
  595. //$this->test_pkey();
  596. $this->test_relations();
  597. $this->test_linkedset();
  598. $this->test_object_lifecycle();
  599. }
  600. }
  601. ///////////////////////////////////////////////////////////////////////////
  602. // Test a complex biz model on the fly
  603. ///////////////////////////////////////////////////////////////////////////
  604. abstract class MyFarm extends TestBizModel
  605. {
  606. static public function GetConfigFile() {return '/config-test-farm.php';}
  607. protected function DoPrepare()
  608. {
  609. parent::DoPrepare();
  610. $this->ResetDB();
  611. MetaModel::DBCheckIntegrity();
  612. }
  613. protected function InsertMammal($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $sName, $iHeight, $sBirth)
  614. {
  615. $oNew = MetaModel::NewObject('Mammal');
  616. $oNew->Set('species', $sSpecies);
  617. $oNew->Set('sex', $sSex);
  618. $oNew->Set('speed', $iSpeed);
  619. $oNew->Set('mother', $iMotherid);
  620. $oNew->Set('father', $iFatherId);
  621. $oNew->Set('name', $sName);
  622. $oNew->Set('height', $iHeight);
  623. $oNew->Set('birth', $sBirth);
  624. return $this->ObjectToDB($oNew);
  625. }
  626. protected function InsertBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId)
  627. {
  628. $oNew = MetaModel::NewObject('Bird');
  629. $oNew->Set('species', $sSpecies);
  630. $oNew->Set('sex', $sSex);
  631. $oNew->Set('speed', $iSpeed);
  632. $oNew->Set('mother', $iMotherid);
  633. $oNew->Set('father', $iFatherId);
  634. return $this->ObjectToDB($oNew);
  635. }
  636. protected function InsertFlyingBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $iFlyingSpeed)
  637. {
  638. $oNew = MetaModel::NewObject('FlyingBird');
  639. $oNew->Set('species', $sSpecies);
  640. $oNew->Set('sex', $sSex);
  641. $oNew->Set('speed', $iSpeed);
  642. $oNew->Set('mother', $iMotherid);
  643. $oNew->Set('father', $iFatherId);
  644. $oNew->Set('flyingspeed', $iFlyingSpeed);
  645. return $this->ObjectToDB($oNew);
  646. }
  647. private function InsertGroup($sName, $iLeaderId)
  648. {
  649. $oNew = MetaModel::NewObject('Group');
  650. $oNew->Set('name', $sName);
  651. $oNew->Set('leader', $iLeaderId);
  652. $iId = $oNew->DBInsertNoReload();
  653. return $iId;
  654. }
  655. }
  656. class TestQueriesOnFarm extends MyFarm
  657. {
  658. static public function GetName()
  659. {
  660. return 'Farm test';
  661. }
  662. static public function GetDescription()
  663. {
  664. return 'A series of tests on the farm business model (SQL generation)';
  665. }
  666. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  667. {
  668. if ($bIsCorrectQuery)
  669. {
  670. echo "<h4 style=\"color:green;\">$sQuery</h4>\n";
  671. }
  672. else
  673. {
  674. echo "<h4 style=\"color:red;\">$sQuery</h3>\n";
  675. }
  676. try
  677. {
  678. //$oOql = new OqlInterpreter($sQuery);
  679. //$oTrash = $oOql->ParseObjectQuery();
  680. //self::DumpVariable($oTrash, true);
  681. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  682. }
  683. catch (OQLException $oOqlException)
  684. {
  685. if ($bIsCorrectQuery)
  686. {
  687. echo "<p>More info on this unexpected failure:<br/>".$oOqlException->getHtmlDesc()."</p>\n";
  688. throw $oOqlException;
  689. return false;
  690. }
  691. else
  692. {
  693. // Everything is fine :-)
  694. echo "<p>More info on this expected failure:\n";
  695. echo "<ul>\n";
  696. echo "<li>".get_class($oOqlException)."</li>\n";
  697. echo "<li>".$oOqlException->getMessage()."</li>\n";
  698. echo "<li>".$oOqlException->getHtmlDesc()."</li>\n";
  699. echo "</ul>\n";
  700. echo "</p>\n";
  701. return true;
  702. }
  703. }
  704. // The query was correctly parsed, was it expected to be correct ?
  705. if (!$bIsCorrectQuery)
  706. {
  707. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  708. return false;
  709. }
  710. echo "<p>To OQL: ".$oMyFilter->ToOQL()."</p>";
  711. $this->search_and_show_list($oMyFilter);
  712. //echo "<p>first pass<p>\n";
  713. //self::DumpVariable($oMyFilter, true);
  714. $sQuery1 = MetaModel::MakeSelectQuery($oMyFilter);
  715. //echo "<p>second pass<p>\n";
  716. //self::DumpVariable($oMyFilter, true);
  717. //$sQuery1 = MetaModel::MakeSelectQuery($oMyFilter);
  718. $sSerialize = $oMyFilter->serialize();
  719. echo "<p>Serialized:$sSerialize</p>\n";
  720. $oFilter2 = DBObjectSearch::unserialize($sSerialize);
  721. try
  722. {
  723. $sQuery2 = MetaModel::MakeSelectQuery($oFilter2);
  724. }
  725. catch (Exception $e)
  726. {
  727. echo "<p>Could not compute the query after unserialize</p>\n";
  728. echo "<p>Query 1: $sQuery1</p>\n";
  729. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  730. throw $e;
  731. }
  732. //if ($oFilter2 != $oMyFilter) no, they may differ while the resulting query is the same!
  733. if ($sQuery1 != $sQuery2)
  734. {
  735. echo "<p>serialize/unserialize mismatch :-(</p>\n";
  736. MyHelpers::var_cmp_html($sQuery1, $sQuery2);
  737. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  738. return false;
  739. }
  740. return true;
  741. }
  742. protected function DoExecute()
  743. {
  744. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  745. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  746. echo "<h3>Create protagonists...</h3>";
  747. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  748. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  749. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  750. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  751. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  752. $this->InsertBird('rooster', 'male', 12, 0, 0);
  753. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  754. // Benchmarking
  755. //
  756. if (false)
  757. {
  758. define ('COUNT_BENCHMARK', 10);
  759. echo "<h3>Parsing a long query, ".COUNT_BENCHMARK." times</h3>";
  760. $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)";
  761. $fStart = MyHelpers::getmicrotime();
  762. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  763. {
  764. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  765. }
  766. $fDuration = MyHelpers::getmicrotime() - $fStart;
  767. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  768. echo "<p>Mean time by op: $fParsingDuration</p>";
  769. }
  770. echo "<h3>Test queries...</h3>";
  771. $aQueries = array(
  772. 'SELECT Animal' => true,
  773. 'SELECT Animal WHERE Animal.pkey = 1' => false,
  774. 'SELECT Animal WHERE Animal.id = 1' => true,
  775. 'SELECT Aniiimal' => false,
  776. 'SELECTe Animal' => false,
  777. 'SELECT * FROM Animal' => false,
  778. 'SELECT Animal AS zoo WHERE zoo.species = \'human\'' => true,
  779. 'SELECT Animal AS zoo WHERE species = \'human\'' => true,
  780. 'SELECT Animal AS zoo WHERE espece = \'human\'' => false,
  781. 'SELECT Animal AS zoo WHERE zoo.species IN (\'human\', "pig")' => true,
  782. 'SELECT Animal AS zoo WHERE CONCATENATION(zoo.species, zoo.sex) LIKE "hum%male"' => false,
  783. 'SELECT Animal AS zoo WHERE CONCAT(zoo.species, zoo.sex) LIKE "hum%male"' => true,
  784. 'SELECT Animal AS zoo WHERE zoo.species NOT IN (\'human\', "pig")' => true,
  785. 'SELECT Animal AS zoo WHERE zoo.kind = \'human\'' => false,
  786. 'SELECT Animal WHERE Animal.species = \'human\' AND Animal.sex = \'female\'' => true,
  787. 'SELECT Mammal AS x WHERE (x.species = \'human\' AND x.name LIKE \'ro%\') OR (x.species = \'donkey\' AND x.name LIKE \'po%\')' => true,
  788. 'SELECT Mammal AS x WHERE x.species = \'human\' AND x.name LIKE \'ro%\' OR x.species = \'donkey\' AND x.name LIKE \'po%\'' => true,
  789. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  790. 'SELECT Mammal AS m WHERE DAY(m.birth) = 19' => true,
  791. 'SELECT Mammal AS m WHERE YEAR(m.birth) = 1971' => true,
  792. 'SELECT Mammal AS m WHERE m.birth < DATE_SUB(CURRENT_DATE(), INTERVAL 10 YEAR)' => true,
  793. 'SELECT Mammal AS m WHERE m.birth > DATE_SUB(NOW(), INTERVAL 2000 DAY)' => true,
  794. 'SELECT Mammal AS m WHERE (TO_DAYS(NOW()) - TO_DAYS(m.birth)) > 2000' => true,
  795. 'SELECT Mammal AS m WHERE m.name = IF(FLOOR(ROUND(m.height)) > 2, "pomme", "romain")' => true,
  796. 'SELECT Mammal AS m WHERE (1 + 2' => false,
  797. 'SELECT Mammal AS m WHERE (1 + 2 * 4 / 23) > 0' => true,
  798. 'SELECT Mammal AS m WHERE (4 / 23 * 2 + 1) > 0' => true,
  799. 'SELECT Mammal AS m WHERE 1/0' => true,
  800. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  801. 'SELECT Animal JOIN Group ON Group.leader = Animal.id' => true,
  802. 'SELECT Group JOIN Animal ON Group.leader = Animal.id' => true,
  803. 'SELECT Animal AS A JOIN Group AS G1 ON G1.leader = A.id' => true,
  804. 'SELECT Animal AS A JOIN Group AS G ON FooClass.leader = A.id' => false,
  805. 'SELECT Animal AS A JOIN Group AS G ON G.leader = FooClass.id' => false,
  806. 'SELECT Animal AS A JOIN Group AS G ON G.masterchief = A.id' => false,
  807. 'SELECT Animal AS A JOIN Group AS G ON A.id = G.leader' => false,
  808. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.qwerty = 123' => false,
  809. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.name LIKE "a%"' => true,
  810. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.id = 1' => true,
  811. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE id = 1' => false,
  812. 'SELECT Animal AS A JOIN Group AS G ON A.member = G.id' => false,
  813. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id' => true,
  814. 'SELECT Mammal AS M JOIN Group AS G ON A.member = G.id' => false,
  815. 'SELECT Mammal AS myAlias JOIN Group AS myAlias ON myAlias.member = myAlias.id' => false,
  816. 'SELECT Mammal AS Mammal JOIN Group AS Mammal ON Mammal.member = Mammal.id' => false,
  817. 'SELECT Group AS G WHERE G.leader_name LIKE "%"' => true,
  818. 'SELECT Group AS G WHERE G.leader_speed < 100000' => true,
  819. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  820. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_speed < 100000' => true,
  821. 'SELECT Mammal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  822. 'SELECT Mammal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  823. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  824. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  825. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id' => true,
  826. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  827. '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,
  828. '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,
  829. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  830. '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,
  831. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  832. 'SELECT Mammal AS Dad JOIN Mammal AS Child ON Child.father = Dad.id' => true,
  833. '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,
  834. // Specifying multiple objects
  835. 'SELECT Animal FROM Animal' => true,
  836. 'SELECT yelele FROM Animal' => false,
  837. 'SELECT Animal FROM Animal AS A' => false,
  838. 'SELECT A FROM Animal AS A' => true,
  839. );
  840. //$aQueries = array(
  841. // 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  842. //);
  843. foreach($aQueries as $sQuery => $bIsCorrect)
  844. {
  845. $this->CheckQuery($sQuery, $bIsCorrect);
  846. }
  847. return true;
  848. }
  849. }
  850. ///////////////////////////////////////////////////////////////////////////
  851. // Test data load
  852. ///////////////////////////////////////////////////////////////////////////
  853. class TestBulkChangeOnFarm extends TestBizModel
  854. {
  855. static public function GetName()
  856. {
  857. return 'Farm test - data load';
  858. }
  859. static public function GetDescription()
  860. {
  861. return 'Bulk load';
  862. }
  863. static public function GetConfigFile() {return '/config-test-farm.php';}
  864. protected function DoPrepare()
  865. {
  866. parent::DoPrepare();
  867. $this->ResetDB();
  868. MetaModel::DBCheckIntegrity();
  869. }
  870. protected function DoExecute()
  871. {
  872. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  873. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  874. $oParser = new CSVParser("denomination,hauteur,age
  875. suzy,123,2009-01-01
  876. chita,456,
  877. ", ',', '"');
  878. $aData = $oParser->ToArray(1, array('_name', '_height', '_birth'));
  879. self::DumpVariable($aData);
  880. $oBulk = new BulkChange(
  881. 'Mammal',
  882. $aData,
  883. // attributes
  884. array('name' => '_name', 'height' => '_height', 'birth' => '_birth'),
  885. // ext keys
  886. array(),
  887. // reconciliation
  888. array('name')
  889. );
  890. $oMyChange = MetaModel::NewObject("CMDBChange");
  891. $oMyChange->Set("date", time());
  892. $oMyChange->Set("userinfo", "Testor");
  893. $iChangeId = $oMyChange->DBInsert();
  894. // echo "Created new change: $iChangeId</br>";
  895. echo "<h3>Planned for loading...</h3>";
  896. $aRes = $oBulk->Process();
  897. self::DumpVariable($aRes);
  898. echo "<h3>Go for loading...</h3>";
  899. $aRes = $oBulk->Process($oMyChange);
  900. self::DumpVariable($aRes);
  901. return;
  902. $oRawData = array(
  903. 'Mammal',
  904. array('species', 'sex', 'speed', 'mother', 'father', 'name', 'height', 'birth'),
  905. "human,male,23,0,0,romulus,192,1971
  906. human,male,23,0,0,remus,154,-50
  907. human,male,23,0,0,julius,160,-49
  908. human,female,23,0,0,cleopatra,142,-50
  909. pig,female,23,0,0,confucius,50,2003"
  910. );
  911. }
  912. }
  913. ///////////////////////////////////////////////////////////////////////////
  914. // Test data load
  915. ///////////////////////////////////////////////////////////////////////////
  916. class TestFullTextSearchOnFarm extends MyFarm
  917. {
  918. static public function GetName()
  919. {
  920. return 'Farm test - full text search';
  921. }
  922. static public function GetDescription()
  923. {
  924. return 'Focus on the full text search feature';
  925. }
  926. protected function DoExecute()
  927. {
  928. echo "<h3>Create protagonists...</h3>";
  929. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  930. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  931. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  932. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  933. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  934. $this->InsertBird('rooster', 'male', 12, 0, 0);
  935. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  936. echo "<h3>Search...</h3>";
  937. $oSearch = new DBObjectSearch('Mammal');
  938. $oSearch->AddCondition_FullText('manof');
  939. //$oResultSet = new DBObjectSet($oSearch);
  940. $this->search_and_show_list($oSearch);
  941. }
  942. }
  943. ///////////////////////////////////////////////////////////////////////////
  944. // Test queries
  945. ///////////////////////////////////////////////////////////////////////////
  946. class TestItopEfficiency extends TestBizModel
  947. {
  948. static public function GetName()
  949. {
  950. return 'Itop - benchmark';
  951. }
  952. static public function GetDescription()
  953. {
  954. return 'Measure time to perform the queries';
  955. }
  956. static public function GetConfigFile() {return '/config-itop.php';}
  957. protected function DoBenchmark($sOqlQuery)
  958. {
  959. echo "<h3>Testing query: $sOqlQuery</h3>";
  960. $fStart = MyHelpers::getmicrotime();
  961. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  962. {
  963. $oFilter = DBObjectSearch::FromOQL($sOqlQuery);
  964. }
  965. $fDuration = MyHelpers::getmicrotime() - $fStart;
  966. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  967. $fStart = MyHelpers::getmicrotime();
  968. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  969. {
  970. $sSQL = MetaModel::MakeSelectQuery($oFilter);
  971. }
  972. $fDuration = MyHelpers::getmicrotime() - $fStart;
  973. $fBuildDuration = $fDuration / COUNT_BENCHMARK;
  974. $fStart = MyHelpers::getmicrotime();
  975. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  976. {
  977. $res = CMDBSource::Query($sSQL);
  978. }
  979. $fDuration = MyHelpers::getmicrotime() - $fStart;
  980. $fQueryDuration = $fDuration / COUNT_BENCHMARK;
  981. // The fetch could not be repeated with the same results
  982. // But we've seen so far that is was very very quick to exec
  983. // So it makes sense to benchmark it a single time
  984. $fStart = MyHelpers::getmicrotime();
  985. $aRow = CMDBSource::FetchArray($res);
  986. $fDuration = MyHelpers::getmicrotime() - $fStart;
  987. $fFetchDuration = $fDuration;
  988. $fStart = MyHelpers::getmicrotime();
  989. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  990. {
  991. $sOql = $oFilter->ToOQL();
  992. }
  993. $fDuration = MyHelpers::getmicrotime() - $fStart;
  994. $fToOqlDuration = $fDuration / COUNT_BENCHMARK;
  995. echo "<ul>\n";
  996. echo "<li>Parsing: $fParsingDuration</li>\n";
  997. echo "<li>Build: $fBuildDuration</li>\n";
  998. echo "<li>Query: $fQueryDuration</li>\n";
  999. echo "<li>Fetch: $fFetchDuration</li>\n";
  1000. echo "<li>ToOql: $fToOqlDuration</li>\n";
  1001. echo "</ul>\n";
  1002. // Everything but the ToOQL (wich is interesting, anyhow)
  1003. $fTotal = $fParsingDuration + $fBuildDuration + $fQueryDuration + $fFetchDuration;
  1004. return array(
  1005. 'rows' => CMDBSource::NbRows($res),
  1006. 'duration (s)' => round($fTotal, 4),
  1007. 'parsing (%)' => round(100 * $fParsingDuration / $fTotal, 1),
  1008. 'build SQL (%)' => round(100 * $fBuildDuration / $fTotal, 1),
  1009. 'query exec (%)' => round(100 * $fQueryDuration / $fTotal, 1),
  1010. 'fetch (%)' => round(100 * $fFetchDuration / $fTotal, 1),
  1011. 'to OQL (%)' => round(100 * $fToOqlDuration / $fTotal, 1),
  1012. 'parsing+build (%)' => round(100 * ($fParsingDuration + $fBuildDuration) / $fTotal, 1),
  1013. );
  1014. }
  1015. protected function DoExecute()
  1016. {
  1017. define ('COUNT_BENCHMARK', 3);
  1018. echo "<p>The test will be repeated ".COUNT_BENCHMARK." times</p>";
  1019. $aQueries = array(
  1020. 'SELECT CMDBChangeOpSetAttribute',
  1021. 'SELECT CMDBChangeOpSetAttribute WHERE id=10',
  1022. 'SELECT CMDBChangeOpSetAttribute WHERE id=123456789',
  1023. 'SELECT CMDBChangeOpSetAttribute WHERE CMDBChangeOpSetAttribute.id=10',
  1024. 'SELECT Ticket',
  1025. 'SELECT Ticket WHERE id=1',
  1026. 'SELECT Person',
  1027. 'SELECT Person WHERE id=1',
  1028. 'SELECT Server',
  1029. 'SELECT Server WHERE id=1',
  1030. 'SELECT Incident JOIN Person ON Incident.agent_id = Person.id WHERE Person.id = 5',
  1031. );
  1032. $aStats = array();
  1033. foreach ($aQueries as $sOQL)
  1034. {
  1035. $aStats[$sOQL] = $this->DoBenchmark($sOQL);
  1036. }
  1037. $aData = array();
  1038. foreach ($aStats as $sOQL => $aResults)
  1039. {
  1040. $aValues = array();
  1041. $aValues['OQL'] = htmlentities($sOQL, ENT_QUOTES, 'UTF-8');
  1042. foreach($aResults as $sDesc => $sInfo)
  1043. {
  1044. $aValues[$sDesc] = htmlentities($sInfo, ENT_QUOTES, 'UTF-8');
  1045. }
  1046. $aData[] = $aValues;
  1047. }
  1048. echo MyHelpers::make_table_from_assoc_array($aData);
  1049. }
  1050. }
  1051. ///////////////////////////////////////////////////////////////////////////
  1052. // Benchmark queries
  1053. ///////////////////////////////////////////////////////////////////////////
  1054. class TestQueries extends TestBizModel
  1055. {
  1056. static public function GetName()
  1057. {
  1058. return 'Itop - queries';
  1059. }
  1060. static public function GetDescription()
  1061. {
  1062. return 'Try as many queries as possible';
  1063. }
  1064. static public function GetConfigFile() {return '/config-itop.php';}
  1065. protected function DoBenchmark($sOqlQuery)
  1066. {
  1067. echo "<h5>Testing query: $sOqlQuery</h5>";
  1068. $fStart = MyHelpers::getmicrotime();
  1069. $oFilter = DBObjectSearch::FromOQL($sOqlQuery);
  1070. $fParsingDuration = MyHelpers::getmicrotime() - $fStart;
  1071. $fStart = MyHelpers::getmicrotime();
  1072. $sSQL = MetaModel::MakeSelectQuery($oFilter);
  1073. $fBuildDuration = MyHelpers::getmicrotime() - $fStart;
  1074. $fStart = MyHelpers::getmicrotime();
  1075. $res = CMDBSource::Query($sSQL);
  1076. $fQueryDuration = MyHelpers::getmicrotime() - $fStart;
  1077. // The fetch could not be repeated with the same results
  1078. // But we've seen so far that is was very very quick to exec
  1079. // So it makes sense to benchmark it a single time
  1080. $fStart = MyHelpers::getmicrotime();
  1081. $aRow = CMDBSource::FetchArray($res);
  1082. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1083. $fFetchDuration = $fDuration;
  1084. $fStart = MyHelpers::getmicrotime();
  1085. $sOql = $oFilter->ToOQL();
  1086. $fToOqlDuration = MyHelpers::getmicrotime() - $fStart;
  1087. if (false)
  1088. {
  1089. echo "<ul style=\"font-size:smaller;\">\n";
  1090. echo "<li>Parsing: $fParsingDuration</li>\n";
  1091. echo "<li>Build: $fBuildDuration</li>\n";
  1092. echo "<li>Query: $fQueryDuration</li>\n";
  1093. echo "<li>Fetch: $fFetchDuration</li>\n";
  1094. echo "<li>ToOql: $fToOqlDuration</li>\n";
  1095. echo "</ul>\n";
  1096. }
  1097. // Everything but the ToOQL (wich is interesting, anyhow)
  1098. $fTotal = $fParsingDuration + $fBuildDuration + $fQueryDuration + $fFetchDuration;
  1099. return array(
  1100. 'rows' => CMDBSource::NbRows($res),
  1101. 'duration (s)' => round($fTotal, 4),
  1102. 'parsing (%)' => round(100 * $fParsingDuration / $fTotal, 1),
  1103. 'build SQL (%)' => round(100 * $fBuildDuration / $fTotal, 1),
  1104. 'query exec (%)' => round(100 * $fQueryDuration / $fTotal, 1),
  1105. 'fetch (%)' => round(100 * $fFetchDuration / $fTotal, 1),
  1106. 'to OQL (%)' => round(100 * $fToOqlDuration / $fTotal, 1),
  1107. 'parsing+build (%)' => round(100 * ($fParsingDuration + $fBuildDuration) / $fTotal, 1),
  1108. );
  1109. }
  1110. protected function DoExecute()
  1111. {
  1112. $aQueries = array(
  1113. 'SELECT Person AS PP WHERE PP.friendlyname LIKE "%dali"',
  1114. 'SELECT Person AS PP WHERE PP.location_id_friendlyname LIKE "%ce ch%"',
  1115. 'SELECT Organization AS OO JOIN Person AS PP ON PP.org_id = OO.id',
  1116. 'SELECT lnkTeamToContact AS lnk JOIN Team AS T ON lnk.team_id = T.id',
  1117. 'SELECT lnkTeamToContact AS lnk JOIN Team AS T ON lnk.team_id = T.id JOIN Contact AS C ON lnk.contact_id = C.id',
  1118. 'SELECT Incident JOIN Person ON Incident.agent_id = Person.id WHERE Person.id = 5',
  1119. // this one is failing...
  1120. //'SELECT L, P FROM Person AS P JOIN Location AS L ON P.location_id = L.id',
  1121. );
  1122. foreach (MetaModel::GetClasses() as $sClass)
  1123. {
  1124. $aQueries[] = 'SELECT '.$sClass;
  1125. $aQueries[] = 'SELECT '.$sClass.' AS zz';
  1126. $aQueries[] = 'SELECT '.$sClass.' AS zz WHERE id = 1';
  1127. }
  1128. $aStats = array();
  1129. foreach ($aQueries as $sOQL)
  1130. {
  1131. $aStats[$sOQL] = $this->DoBenchmark($sOQL);
  1132. }
  1133. $aData = array();
  1134. foreach ($aStats as $sOQL => $aResults)
  1135. {
  1136. $aValues = array();
  1137. $aValues['OQL'] = htmlentities($sOQL, ENT_QUOTES, 'UTF-8');
  1138. foreach($aResults as $sDesc => $sInfo)
  1139. {
  1140. $aValues[$sDesc] = htmlentities($sInfo, ENT_QUOTES, 'UTF-8');
  1141. }
  1142. $aData[] = $aValues;
  1143. }
  1144. echo MyHelpers::make_table_from_assoc_array($aData);
  1145. }
  1146. }
  1147. ///////////////////////////////////////////////////////////////////////////
  1148. // Test bulk load API
  1149. ///////////////////////////////////////////////////////////////////////////
  1150. class TestItopBulkLoad extends TestBizModel
  1151. {
  1152. static public function GetName()
  1153. {
  1154. return 'Itop - test BulkChange class';
  1155. }
  1156. static public function GetDescription()
  1157. {
  1158. return 'Execute a bulk change at the Core API level';
  1159. }
  1160. static public function GetConfigFile() {return '/config-itop.php';}
  1161. protected function DoExecute()
  1162. {
  1163. $sLogin = 'testbulkload_'.time();
  1164. $oParser = new CSVParser("login,contactid->name,password,profile_list
  1165. _1_$sLogin,Picasso,secret1,profileid:10;reason:service manager|profileid->name:Problem Manager;'reason:toto;problem manager'
  1166. _2_$sLogin,Picasso,secret2,
  1167. ", ',', '"');
  1168. $aData = $oParser->ToArray(1, array('_login', '_contact_name', '_password', '_profiles'));
  1169. self::DumpVariable($aData);
  1170. $oUser = new UserLocal();
  1171. $oUser->Set('login', 'patator');
  1172. $oUser->Set('password', 'patator');
  1173. //$oUser->Set('contactid', 0);
  1174. //$oUser->Set('language', $sLanguage);
  1175. $aProfiles = array(
  1176. array(
  1177. 'profileid' => 10, // Service Manager
  1178. 'reason' => 'service manager',
  1179. ),
  1180. array(
  1181. 'profileid->name' => 'Problem Manager',
  1182. 'reason' => 'problem manager',
  1183. ),
  1184. );
  1185. $oBulk = new BulkChange(
  1186. 'UserLocal',
  1187. $aData,
  1188. // attributes
  1189. array('login' => '_login', 'password' => '_password', 'profile_list' => '_profiles'),
  1190. // ext keys
  1191. array('contactid' => array('name' => '_contact_name')),
  1192. // reconciliation
  1193. array('login'),
  1194. // Synchro - scope
  1195. "SELECT UserLocal",
  1196. // Synchro - set attribute on missing objects
  1197. array ('password' => 'terminated', 'login' => 'terminated'.time())
  1198. );
  1199. if (false)
  1200. {
  1201. $oMyChange = MetaModel::NewObject("CMDBChange");
  1202. $oMyChange->Set("date", time());
  1203. $oMyChange->Set("userinfo", "Testor");
  1204. $iChangeId = $oMyChange->DBInsert();
  1205. // echo "Created new change: $iChangeId</br>";
  1206. }
  1207. echo "<h3>Planned for loading...</h3>";
  1208. $aRes = $oBulk->Process();
  1209. self::DumpVariable($aRes);
  1210. if (false)
  1211. {
  1212. echo "<h3>Go for loading...</h3>";
  1213. $aRes = $oBulk->Process($oMyChange);
  1214. self::DumpVariable($aRes);
  1215. }
  1216. return;
  1217. }
  1218. }
  1219. ///////////////////////////////////////////////////////////////////////////
  1220. // Test data load
  1221. ///////////////////////////////////////////////////////////////////////////
  1222. class TestImportREST extends TestWebServices
  1223. {
  1224. static public function GetName()
  1225. {
  1226. return 'CSV import (REST)';
  1227. }
  1228. static public function GetDescription()
  1229. {
  1230. return 'Test various options and fonctionality of import.php';
  1231. }
  1232. protected function DoExecSingleLoad($aLoadSpec, $iTestId = null)
  1233. {
  1234. $sCsvData = $aLoadSpec['csvdata'];
  1235. echo "<div style=\"padding: 10;\">\n";
  1236. if (is_null($iTestId))
  1237. {
  1238. echo "<h3 style=\"background-color: #ddddff; padding: 10;\">{$aLoadSpec['desc']}</h3>\n";
  1239. }
  1240. else
  1241. {
  1242. echo "<h3 style=\"background-color: #ddddff; padding: 10;\"><a href=\"?todo=exec&testid=TestImportREST&subtests=$iTestId\">$iTestId</a> - {$aLoadSpec['desc']}</h3>\n";
  1243. }
  1244. $aPostData = array('csvdata' => $sCsvData);
  1245. $aGetParams = array();
  1246. $aGetParamReport = array();
  1247. foreach($aLoadSpec['args'] as $sArg => $sValue)
  1248. {
  1249. $aGetParams[] = $sArg.'='.urlencode($sValue);
  1250. $aGetParamReport[] = $sArg.'='.$sValue;
  1251. }
  1252. $sGetParams = implode('&', $aGetParams);
  1253. $sLogin = isset($aLoadSpec['login']) ? $aLoadSpec['login'] : 'admin';
  1254. $sPassword = isset($aLoadSpec['password']) ? $aLoadSpec['password'] : 'admin';
  1255. $sRes = self::DoPostRequestAuth('../webservices/import.php?'.$sGetParams, $aPostData, $sLogin, $sPassword);
  1256. $sArguments = implode('<br/>', $aGetParamReport);
  1257. if (strlen($sCsvData) > 5000)
  1258. {
  1259. $sCsvDataViewable = 'INPUT TOO LONG TO BE DISPLAYED ('.strlen($sCsvData).")\n".substr($sCsvData, 0, 500)."\n... TO BE CONTINUED";
  1260. }
  1261. else
  1262. {
  1263. $sCsvDataViewable = $sCsvData;
  1264. }
  1265. echo "<div style=\"\">\n";
  1266. echo " <div style=\"float:left; width:20%; padding:5; background-color:#eeeeff;\">\n";
  1267. echo " $sArguments\n";
  1268. echo " </div>\n";
  1269. echo " <div style=\"float:right; width:75%; padding:5; background-color:#eeeeff\">\n";
  1270. echo " <pre class=\"vardump\">$sCsvDataViewable</pre>\n";
  1271. echo " </div>\n";
  1272. echo "</div>\n";
  1273. echo "<pre class=\"vardump\" style=\"clear: both; padding: 15; background-color: black; color: green;\">$sRes</pre>\n";
  1274. echo "</div>\n";
  1275. }
  1276. protected function DoExecute()
  1277. {
  1278. $aLoads = array(
  1279. array(
  1280. 'desc' => 'Missing class',
  1281. 'login' => 'admin',
  1282. 'password' => 'admin',
  1283. 'args' => array(
  1284. ),
  1285. 'csvdata' => "xxx",
  1286. ),
  1287. array(
  1288. 'desc' => 'Wrong class',
  1289. 'login' => 'admin',
  1290. 'password' => 'admin',
  1291. 'args' => array(
  1292. 'class' => 'toto',
  1293. ),
  1294. 'csvdata' => "xxx",
  1295. ),
  1296. array(
  1297. 'desc' => 'Wrong output type',
  1298. 'login' => 'admin',
  1299. 'password' => 'admin',
  1300. 'args' => array(
  1301. 'class' => 'NetworkDevice',
  1302. 'output' => 'onthefly',
  1303. ),
  1304. 'csvdata' => "xxx",
  1305. ),
  1306. array(
  1307. 'desc' => 'Weird format, working anyhow...',
  1308. 'login' => 'admin',
  1309. 'password' => 'admin',
  1310. 'args' => array(
  1311. 'class' => 'Server',
  1312. 'output' => 'details',
  1313. 'separator' => '*',
  1314. 'qualifier' => '@',
  1315. 'reconciliationkeys' => 'org_id,name',
  1316. ),
  1317. 'csvdata' => 'name*org_id
  1318. server01*2
  1319. @server02@@combodo@* 2
  1320. server45*99',
  1321. ),
  1322. array(
  1323. 'desc' => 'Load an organization',
  1324. 'login' => 'admin',
  1325. 'password' => 'admin',
  1326. 'args' => array(
  1327. 'class' => 'Organization',
  1328. 'output' => 'details',
  1329. 'separator' => ';',
  1330. 'reconciliationkeys' => '',
  1331. ),
  1332. 'csvdata' => "name;code\nWorldCompany;WCY",
  1333. ),
  1334. array(
  1335. 'desc' => 'Load a location',
  1336. 'login' => 'admin',
  1337. 'password' => 'admin',
  1338. 'args' => array(
  1339. 'class' => 'Location',
  1340. 'output' => 'details',
  1341. 'separator' => ';',
  1342. 'reconciliationkeys' => '',
  1343. ),
  1344. 'csvdata' => "name;org_id;address\nParis;1;Centre de la Franca",
  1345. ),
  1346. array(
  1347. 'desc' => 'Load a person',
  1348. 'login' => 'admin',
  1349. 'password' => 'admin',
  1350. 'args' => array(
  1351. 'class' => 'Person',
  1352. 'output' => 'details',
  1353. 'separator' => ';',
  1354. 'reconciliationkeys' => '',
  1355. ),
  1356. 'csvdata' => "email;name;first_name;org_id;phone\njohn.foo@starac.com;Foo;John;1;+33(1)23456789",
  1357. ),
  1358. array(
  1359. 'desc' => 'Load a person - wrong email format',
  1360. 'login' => 'admin',
  1361. 'password' => 'admin',
  1362. 'args' => array(
  1363. 'class' => 'Person',
  1364. 'output' => 'details',
  1365. 'separator' => ';',
  1366. 'reconciliationkeys' => '',
  1367. ),
  1368. 'csvdata' => "email;name;first_name;org_id\nemailPASbon;Foo;John;1",
  1369. ),
  1370. array(
  1371. 'desc' => 'Load a team',
  1372. 'login' => 'admin',
  1373. 'password' => 'admin',
  1374. 'args' => array(
  1375. 'class' => 'Team',
  1376. 'output' => 'details',
  1377. 'separator' => ';',
  1378. 'reconciliationkeys' => '',
  1379. ),
  1380. 'csvdata' => "name;org_id;location_name\nSquadra Azzura2;1;Paris",
  1381. ),
  1382. array(
  1383. 'desc' => 'Load server',
  1384. 'login' => 'admin',
  1385. 'password' => 'admin',
  1386. 'args' => array(
  1387. 'class' => 'Server',
  1388. 'output' => 'details',
  1389. 'separator' => ';',
  1390. 'reconciliationkeys' => '',
  1391. ),
  1392. '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",
  1393. ),
  1394. array(
  1395. 'desc' => 'Load server (column header localized in english)',
  1396. 'login' => 'admin',
  1397. 'password' => 'admin',
  1398. 'args' => array(
  1399. 'class' => 'Server',
  1400. 'output' => 'details',
  1401. 'separator' => ';',
  1402. 'reconciliationkeys' => '',
  1403. ),
  1404. 'csvdata' => "Name;Status;Owner Organization;Location;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",
  1405. ),
  1406. array(
  1407. 'desc' => 'Load server (directly from Export results)',
  1408. 'login' => 'admin',
  1409. 'password' => 'admin',
  1410. 'args' => array(
  1411. 'class' => 'Server',
  1412. 'output' => 'details',
  1413. 'reconciliationkeys' => '',
  1414. ),
  1415. 'csvdata' => 'id,Name,Status,Owner organization,Owner organization->Name,Business criticity,Brand,Model,Serial Number,Asset Reference,Description,Location,Location->Name,Location details,Management IP,Default Gateway,CPU,RAM,Hard Disk,OS Family,OS Version
  1416. 1,"dbserver1.demo.com","production",2,"Demo","medium","HP","DL380","","","ouille
  1417. [[Server:webserver.demo.com]]",1,"Grenoble","","10.1.1.10","255.255.255.0","2","16Gb","120Gb","Linux","Debian (Lenny)"',
  1418. ),
  1419. array(
  1420. 'desc' => 'Load server - wrong value for status',
  1421. 'login' => 'admin',
  1422. 'password' => 'admin',
  1423. 'args' => array(
  1424. 'class' => 'Server',
  1425. 'output' => 'details',
  1426. 'separator' => ';',
  1427. 'reconciliationkeys' => '',
  1428. ),
  1429. '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",
  1430. ),
  1431. array(
  1432. 'desc' => 'Load NW if',
  1433. 'login' => 'admin',
  1434. 'password' => 'admin',
  1435. 'args' => array(
  1436. 'class' => 'NetworkInterface',
  1437. 'output' => 'details',
  1438. 'separator' => ';',
  1439. 'reconciliationkeys' => '',
  1440. ),
  1441. '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;;",
  1442. ),
  1443. // Data Bruno
  1444. array(
  1445. 'desc' => 'Load NW devices from real life',
  1446. 'login' => 'admin',
  1447. 'password' => 'admin',
  1448. 'args' => array(
  1449. 'class' => 'NetworkDevice',
  1450. 'output' => 'details',
  1451. 'separator' => ';',
  1452. 'reconciliationkeys' => 'org_id,Name',
  1453. ),
  1454. 'csvdata' => 'name;management_ip;importance;Owner organization->Name;type
  1455. truc-machin-bidule;172.15.255.150;high;My Company/Department;switch
  1456. 10.15.255.222;10.15.255.222;high;My Company/Department;switch',
  1457. ),
  1458. array(
  1459. 'desc' => 'Load NW ifs',
  1460. 'login' => 'admin',
  1461. 'password' => 'admin',
  1462. 'args' => array(
  1463. 'class' => 'NetworkInterface',
  1464. 'output' => 'details',
  1465. 'separator' => ';',
  1466. 'reconciliationkeys' => 'device_id->name,name',
  1467. ),
  1468. 'csvdata' => 'device_id->name;org_id->name;name;ip_address;ip_mask;speed;link_type;mac_address;physical_type
  1469. truc-machin-bidule;My Company/Department;"GigabitEthernet44";;;0;downlink;00 12 F2 CB C4 EB ;ethernet
  1470. truc-machin-bidule;My Company/Department;"GigabitEthernet38";;;0;downlink;00 12 F2 CB C4 E5 ;ethernet
  1471. un-autre;My Company/Department;"GigabitEthernet2/3";;;1000000000;uplink;00 12 F2 20 0F 1A ;ethernet',
  1472. ),
  1473. array(
  1474. 'desc' => 'The simplest data load',
  1475. 'login' => 'admin',
  1476. 'password' => 'admin',
  1477. 'args' => array(
  1478. 'class' => 'Location',
  1479. 'output' => 'details',
  1480. ),
  1481. 'csvdata' => "name\nParis",
  1482. ),
  1483. array(
  1484. 'desc' => 'The simplest data load + org',
  1485. 'login' => 'admin',
  1486. 'password' => 'admin',
  1487. 'args' => array(
  1488. 'class' => 'Location',
  1489. 'output' => 'details',
  1490. 'separator' => ';',
  1491. ),
  1492. 'csvdata' => "name;org_id\nParis;2",
  1493. ),
  1494. array(
  1495. 'desc' => 'The simplest data load + org (name)',
  1496. 'login' => 'admin',
  1497. 'password' => 'admin',
  1498. 'args' => array(
  1499. 'class' => 'Location',
  1500. 'output' => 'details',
  1501. 'separator' => ';',
  1502. ),
  1503. 'csvdata' => "name;org_name\nParis;Demo",
  1504. ),
  1505. array(
  1506. 'desc' => 'The simplest data load + org (code)',
  1507. 'login' => 'admin',
  1508. 'password' => 'admin',
  1509. 'args' => array(
  1510. 'class' => 'Location',
  1511. 'output' => 'details',
  1512. 'separator' => ';',
  1513. ),
  1514. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1515. ),
  1516. array(
  1517. 'desc' => 'Ouput: summary',
  1518. 'login' => 'admin',
  1519. 'password' => 'admin',
  1520. 'args' => array(
  1521. 'class' => 'Location',
  1522. 'output' => 'summary',
  1523. 'separator' => ';',
  1524. ),
  1525. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1526. ),
  1527. array(
  1528. 'desc' => 'Ouput: retcode',
  1529. 'login' => 'admin',
  1530. 'password' => 'admin',
  1531. 'args' => array(
  1532. 'class' => 'Location',
  1533. 'output' => 'retcode',
  1534. 'separator' => ';',
  1535. ),
  1536. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1537. ),
  1538. array(
  1539. 'desc' => 'Error in reconciliation list',
  1540. 'login' => 'admin',
  1541. 'password' => 'admin',
  1542. 'args' => array(
  1543. 'class' => 'Location',
  1544. 'output' => 'details',
  1545. 'separator' => ';',
  1546. 'reconciliationkeys' => 'org_id',
  1547. ),
  1548. 'csvdata' => "org_name;name\nDemo;Paris",
  1549. ),
  1550. array(
  1551. 'desc' => 'Error in attribute list that does not allow to compute reconciliation scheme',
  1552. 'login' => 'admin',
  1553. 'password' => 'admin',
  1554. 'args' => array(
  1555. 'class' => 'Location',
  1556. 'output' => 'details',
  1557. 'separator' => ';',
  1558. ),
  1559. 'csvdata' => "org_name;country\nDemo;France",
  1560. ),
  1561. array(
  1562. 'desc' => 'Error in attribute list - case A',
  1563. 'login' => 'admin',
  1564. 'password' => 'admin',
  1565. 'args' => array(
  1566. 'class' => 'Location',
  1567. 'output' => 'details',
  1568. 'separator' => ';',
  1569. ),
  1570. 'csvdata' => "name;org\nParis;2",
  1571. ),
  1572. array(
  1573. 'desc' => 'Error in attribute list - case B1 (key->attcode)',
  1574. 'login' => 'admin',
  1575. 'password' => 'admin',
  1576. 'args' => array(
  1577. 'class' => 'Location',
  1578. 'output' => 'details',
  1579. 'separator' => ';',
  1580. ),
  1581. 'csvdata' => "name;org->code\nParis;DEMO",
  1582. ),
  1583. array(
  1584. 'desc' => 'Error in attribute list - case B2 (key->attcode)',
  1585. 'login' => 'admin',
  1586. 'password' => 'admin',
  1587. 'args' => array(
  1588. 'class' => 'Location',
  1589. 'output' => 'details',
  1590. 'separator' => ';',
  1591. ),
  1592. 'csvdata' => "name;org_id->duns\nParis;DEMO",
  1593. ),
  1594. array(
  1595. 'desc' => 'Always changing... special comment in change tracking',
  1596. 'login' => 'admin',
  1597. 'password' => 'admin',
  1598. 'args' => array(
  1599. 'class' => 'Location',
  1600. 'output' => 'details',
  1601. 'separator' => ';',
  1602. 'comment' => 'automated testing'
  1603. ),
  1604. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;Addresse bidon:".((string)microtime(true)),
  1605. ),
  1606. array(
  1607. 'desc' => 'Always changing... but "simulate"',
  1608. 'login' => 'admin',
  1609. 'password' => 'admin',
  1610. 'args' => array(
  1611. 'class' => 'Location',
  1612. 'output' => 'details',
  1613. 'separator' => ';',
  1614. 'simulate' => '1',
  1615. 'comment' => 'SHOULD NEVER APPEAR IN THE HISTORY'
  1616. ),
  1617. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;restore address?",
  1618. ),
  1619. array(
  1620. 'desc' => 'Load a user account',
  1621. 'login' => 'admin',
  1622. 'password' => 'admin',
  1623. 'args' => array(
  1624. 'class' => 'UserLocal',
  1625. 'output' => 'details',
  1626. 'separator' => ',',
  1627. 'simulate' => '0',
  1628. 'comment' => 'automated testing'
  1629. ),
  1630. 'csvdata' => "login,password,profile_list\nby_import_csv,fakepwd,profileid->name:Configuration Manager|profileid:10;reason:direct id",
  1631. ),
  1632. );
  1633. $sSubTests = utils::ReadParam('subtests', null, true, 'raw_data');
  1634. if (is_null($sSubTests))
  1635. {
  1636. foreach ($aLoads as $iTestId => $aLoadSpec)
  1637. {
  1638. $this->DoExecSingleLoad($aLoadSpec, $iTestId);
  1639. }
  1640. }
  1641. else
  1642. {
  1643. $aSubTests = explode(',', $sSubTests);
  1644. foreach ($aSubTests as $iTestId)
  1645. {
  1646. $this->DoExecSingleLoad($aLoads[$iTestId], $iTestId);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. ///////////////////////////////////////////////////////////////////////////
  1652. // Test massive data load
  1653. ///////////////////////////////////////////////////////////////////////////
  1654. define('IMPORT_COUNT', 4000);
  1655. class TestImportRESTMassive extends TestImportREST
  1656. {
  1657. static public function GetName()
  1658. {
  1659. return 'CSV import (REST) - HUGE data set ('.IMPORT_COUNT.' PCs)';
  1660. }
  1661. static public function GetDescription()
  1662. {
  1663. return 'Stress import.php';
  1664. }
  1665. protected function DoExecute()
  1666. {
  1667. $aLoadSpec = array(
  1668. 'desc' => 'Loading PCs: '.IMPORT_COUNT,
  1669. 'args' => array(
  1670. 'class' => 'PC',
  1671. 'output' => 'summary',
  1672. ),
  1673. 'csvdata' => "name;org_id;brand\n",
  1674. );
  1675. for($i = 0 ; $i <= IMPORT_COUNT ; $i++)
  1676. {
  1677. $aLoadSpec['csvdata'] .= "pc.import.$i;2;Combodo\n";
  1678. }
  1679. $this->DoExecSingleLoad($aLoadSpec);
  1680. }
  1681. }
  1682. ///////////////////////////////////////////////////////////////////////////
  1683. // Test data exchange
  1684. ///////////////////////////////////////////////////////////////////////////
  1685. class TestDataExchange extends TestBizModel
  1686. {
  1687. static public function GetName()
  1688. {
  1689. return 'Data exchange';
  1690. }
  1691. static public function GetDescription()
  1692. {
  1693. return 'Test REST services: synchro_import and synchro_exec';
  1694. }
  1695. static public function GetConfigFile() {return '/config-itop.php';}
  1696. protected function DoExecScenario($aSingleScenario)
  1697. {
  1698. echo "<div style=\"padding: 10;\">\n";
  1699. echo "<h3 style=\"background-color: #ddddff; padding: 10;\">{$aSingleScenario['desc']}</h3>\n";
  1700. $sClass = $aSingleScenario['target_class'];
  1701. $aTargetData = $aSingleScenario['target_data'];
  1702. $aSourceData = $aSingleScenario['source_data'];
  1703. $aTargetAttributes = array_shift($aTargetData);
  1704. $aSourceAttributes = array_shift($aSourceData);
  1705. if (count($aSourceData) + 1 != count($aTargetData))
  1706. {
  1707. throw new Exception("Target data must contain exactly ".(count($aSourceData) + 1)." items, found ".count($aTargetData));
  1708. }
  1709. // Create the data source
  1710. //
  1711. $oDataSource = new SynchroDataSource();
  1712. $oDataSource->Set('name', 'Test data sync '.time());
  1713. $oDataSource->Set('description', 'unit test - created automatically');
  1714. $oDataSource->Set('status', 'production');
  1715. $oDataSource->Set('user_id', 0);
  1716. $oDataSource->Set('scope_class', $sClass);
  1717. $oDataSource->Set('scope_restriction', '');
  1718. $oDataSource->Set('full_load_periodicity', $aSingleScenario['full_load_periodicity']);
  1719. $oDataSource->Set('reconciliation_policy', $aSingleScenario['reconciliation_policy']);
  1720. $oDataSource->Set('action_on_zero', $aSingleScenario['action_on_zero']);
  1721. $oDataSource->Set('action_on_one', $aSingleScenario['action_on_one']);
  1722. $oDataSource->Set('action_on_multiple', $aSingleScenario['action_on_multiple']);
  1723. $oDataSource->Set('delete_policy', $aSingleScenario['delete_policy']);
  1724. $oDataSource->Set('delete_policy_update', $aSingleScenario['delete_policy_update']);
  1725. $oDataSource->Set('delete_policy_retention', $aSingleScenario['delete_policy_retention']);
  1726. $iDataSourceId = $this->ObjectToDB($oDataSource, true /* reload */);
  1727. $oAttributeSet = $oDataSource->Get('attribute_list');
  1728. while ($oAttribute = $oAttributeSet->Fetch())
  1729. {
  1730. if (array_key_exists($oAttribute->Get('attcode'), $aSingleScenario['attributes']))
  1731. {
  1732. $aAttribInfo = $aSingleScenario['attributes'][$oAttribute->Get('attcode')];
  1733. if (array_key_exists('reconciliation_attcode', $aAttribInfo))
  1734. {
  1735. $oAttribute->Set('reconciliation_attcode', $aAttribInfo['reconciliation_attcode']);
  1736. }
  1737. $oAttribute->Set('update', $aAttribInfo['do_update']);
  1738. $oAttribute->Set('reconcile', $aAttribInfo['do_reconcile']);
  1739. }
  1740. else
  1741. {
  1742. $oAttribute->Set('update', false);
  1743. $oAttribute->Set('reconcile', false);
  1744. }
  1745. $this->UpdateObjectInDB($oAttribute);
  1746. }
  1747. // Prepare list of prefixes -> make sure objects are unique with regard to the reconciliation scheme
  1748. $aPrefixes = array(); // attcode => prefix
  1749. foreach($aSourceAttributes as $iDummy => $sAttCode)
  1750. {
  1751. $aPrefixes[$sAttCode] = ''; // init with something
  1752. }
  1753. foreach($aSingleScenario['attributes'] as $sAttCode => $aAttribInfo)
  1754. {
  1755. if (isset($aAttribInfo['automatic_prefix']) && $aAttribInfo['automatic_prefix'])
  1756. {
  1757. $aPrefixes[$sAttCode] = 'TEST_'.$iDataSourceId.'_';
  1758. }
  1759. }
  1760. // List existing objects (to be ignored in the analysis
  1761. //
  1762. $oAllObjects = new DBObjectSet(new DBObjectSearch($sClass));
  1763. $aExisting = $oAllObjects->ToArray(true);
  1764. $sExistingIds = implode(', ', array_keys($aExisting));
  1765. // Create the initial object list
  1766. //
  1767. $aInitialTarget = $aTargetData[0];
  1768. foreach($aInitialTarget as $aObjFields)
  1769. {
  1770. $oNewTarget = MetaModel::NewObject($sClass);
  1771. foreach($aTargetAttributes as $iAtt => $sAttCode)
  1772. {
  1773. $oNewTarget->Set($sAttCode, $aPrefixes[$sAttCode].$aObjFields[$iAtt]);
  1774. }
  1775. $this->ObjectToDB($oNewTarget);
  1776. }
  1777. foreach($aTargetData as $iRow => $aExpectedObjects)
  1778. {
  1779. sleep(2);
  1780. // Check the status (while ignoring existing objects)
  1781. //
  1782. if (empty($sExistingIds))
  1783. {
  1784. $oObjects = new DBObjectSet(DBObjectSearch::FromOQL("SELECT $sClass"));
  1785. }
  1786. else
  1787. {
  1788. $oObjects = new DBObjectSet(DBObjectSearch::FromOQL("SELECT $sClass WHERE id NOT IN($sExistingIds)"));
  1789. }
  1790. $aFound = $oObjects->ToArray();
  1791. $aErrors_Unexpected = array();
  1792. foreach($aFound as $iObj => $oObj)
  1793. {
  1794. // Is this object in the expected objects list
  1795. $bFoundMatch = false;
  1796. foreach($aExpectedObjects as $iExp => $aValues)
  1797. {
  1798. $bDoesMatch = true;
  1799. foreach($aTargetAttributes as $iCol => $sAttCode)
  1800. {
  1801. if ($oObj->Get($sAttCode) != $aPrefixes[$sAttCode].$aValues[$iCol])
  1802. {
  1803. $bDoesMatch = false;
  1804. break;
  1805. }
  1806. }
  1807. if ($bDoesMatch)
  1808. {
  1809. $bFoundMatch = true;
  1810. unset($aExpectedObjects[$iExp]);
  1811. break;
  1812. }
  1813. }
  1814. if (!$bFoundMatch)
  1815. {
  1816. $aErrors_Unexpected[] = $oObj->GetKey();
  1817. }
  1818. }
  1819. // Display the current status
  1820. //
  1821. echo "<p>Status at step $iRow</p>\n";
  1822. $aCurrentDataSet = array();
  1823. foreach($aFound as $iObj => $oObj)
  1824. {
  1825. $aObjDesc = array(
  1826. 'Status' => (in_array($iObj, $aErrors_Unexpected) ? 'unexpected' : 'ok'),
  1827. 'Object' => $oObj->GetHyperLink()
  1828. );
  1829. foreach($aTargetAttributes as $iCol => $sAttCode)
  1830. {
  1831. $aObjDesc[$sAttCode] = $oObj->Get($sAttCode);
  1832. }
  1833. $aCurrentDataSet[] = $aObjDesc;
  1834. }
  1835. if (count($aExpectedObjects) > 0)
  1836. {
  1837. foreach($aExpectedObjects as $iExp => $aValues)
  1838. {
  1839. $aObjDesc = array(
  1840. 'Status' => 'missing',
  1841. 'Object' => 'n/a'
  1842. );
  1843. foreach($aTargetAttributes as $iCol => $sAttCode)
  1844. {
  1845. $aObjDesc[$sAttCode] = $aPrefixes[$sAttCode].$aValues[$iCol];
  1846. }
  1847. $aCurrentDataSet[] = $aObjDesc;
  1848. }
  1849. }
  1850. echo MyHelpers::make_table_from_assoc_array($aCurrentDataSet);
  1851. if ((count($aErrors_Unexpected) > 0) || (count($aExpectedObjects) > 0))
  1852. {
  1853. throw new UnitTestException("The current status in iTop does not match the expectations");
  1854. }
  1855. // If not on the final row, run a data exchange sequence
  1856. //
  1857. if (array_key_exists($iRow, $aSourceData))
  1858. {
  1859. $aToBeLoaded = $aSourceData[$iRow];
  1860. $sCsvData = implode(';', $aSourceAttributes)."\n";
  1861. foreach($aToBeLoaded as $aDataRow)
  1862. {
  1863. $aFinalData = array();
  1864. foreach($aDataRow as $iCol => $value)
  1865. {
  1866. if (is_null($value))
  1867. {
  1868. $aFinalData[] = '<NULL>';
  1869. }
  1870. else
  1871. {
  1872. $sAttCode = $aSourceAttributes[$iCol];
  1873. $aFinalData[] = $aPrefixes[$sAttCode].$value;
  1874. }
  1875. }
  1876. $sCsvData .= implode(';', $aFinalData)."\n";
  1877. }
  1878. $aPostData = array('csvdata' => $sCsvData);
  1879. $aImportArgs = array(
  1880. 'data_source_id' => $iDataSourceId,
  1881. 'separator' => ';',
  1882. 'simulate' => 0,
  1883. 'output' => 'details',
  1884. );
  1885. $aGetParams = array();
  1886. $aGetParamReport = array();
  1887. foreach($aImportArgs as $sArg => $sValue)
  1888. {
  1889. $aGetParams[] = $sArg.'='.urlencode($sValue);
  1890. $aGetParamReport[] = $sArg.'='.$sValue;
  1891. }
  1892. $sGetParams = implode('&', $aGetParams);
  1893. $sLogin = isset($aSingleScenario['login']) ? $aSingleScenario['login'] : 'admin';
  1894. $sPassword = isset($aSingleScenario['password']) ? $aSingleScenario['password'] : 'admin';
  1895. $sRes = self::DoPostRequestAuth('../synchro/synchro_import.php?'.$sGetParams, $aPostData, $sLogin, $sPassword);
  1896. // Report the load results
  1897. //
  1898. if (strlen($sCsvData) > 5000)
  1899. {
  1900. $sCsvDataViewable = 'INPUT TOO LONG TO BE DISPLAYED ('.strlen($sCsvData).")\n".substr($sCsvData, 0, 500)."\n... TO BE CONTINUED";
  1901. }
  1902. else
  1903. {
  1904. $sCsvDataViewable = $sCsvData;
  1905. }
  1906. $sCsvDataViewable = htmlentities($sCsvDataViewable, ENT_QUOTES, 'UTF-8');
  1907. echo "<div style=\"\">\n";
  1908. echo " <pre class=\"vardump\">$sCsvDataViewable</pre>\n";
  1909. echo "</div>\n";
  1910. echo "<pre class=\"vardump\" style=\"clear: both; padding: 15; background-color: black; color: green;\">$sRes</pre>\n";
  1911. if (stripos($sRes, 'exception') !== false)
  1912. {
  1913. throw new UnitTestException('Encountered an Exception during the last import/synchro');
  1914. }
  1915. }
  1916. }
  1917. return;
  1918. echo "</div>\n";
  1919. }
  1920. protected function DoExecute()
  1921. {
  1922. /*
  1923. $aScenarios = array(
  1924. array(
  1925. 'desc' => 'Load user logins',
  1926. 'login' => 'admin',
  1927. 'password' => 'admin',
  1928. 'target_class' => 'UserLocal',
  1929. 'full_load_periodicity' => 3600, // should be ignored in this case
  1930. 'reconciliation_policy' => 'use_attributes',
  1931. 'action_on_zero' => 'create',
  1932. 'action_on_one' => 'update',
  1933. 'action_on_multiple' => 'error',
  1934. 'delete_policy' => 'delete',
  1935. 'delete_policy_update' => '',
  1936. 'delete_policy_retention' => 0,
  1937. 'source_data' => array(
  1938. array('primary_key', 'login', 'password', 'profile_list'),
  1939. array(
  1940. array('user_A', 'login_A', 'password_A', 'profileid:10;reason:he/she is managing services'),
  1941. ),
  1942. ),
  1943. 'target_data' => array(
  1944. array('login'),
  1945. array(
  1946. // Initial state
  1947. ),
  1948. array(
  1949. array('login_A'),
  1950. ),
  1951. ),
  1952. 'attributes' => array(
  1953. 'login' => array(
  1954. 'do_reconcile' => true,
  1955. 'do_update' => true,
  1956. 'automatic_prefix' => true, // unique id (for unit testing)
  1957. ),
  1958. 'password' => array(
  1959. 'do_reconcile' => false,
  1960. 'do_update' => true,
  1961. ),
  1962. 'profile_list' => array(
  1963. 'do_reconcile' => false,
  1964. 'do_update' => true,
  1965. ),
  1966. ),
  1967. ),
  1968. );
  1969. */
  1970. $aScenarios = array(
  1971. array(
  1972. 'desc' => 'Simple scenario with delete option (and extkey given as org/name)',
  1973. 'login' => 'admin',
  1974. 'password' => 'admin',
  1975. 'target_class' => 'ApplicationSolution',
  1976. 'full_load_periodicity' => 3600, // should be ignored in this case
  1977. 'reconciliation_policy' => 'use_attributes',
  1978. 'action_on_zero' => 'create',
  1979. 'action_on_one' => 'update',
  1980. 'action_on_multiple' => 'error',
  1981. 'delete_policy' => 'delete',
  1982. 'delete_policy_update' => '',
  1983. 'delete_policy_retention' => 0,
  1984. 'source_data' => array(
  1985. array('primary_key', 'org_id', 'name', 'status'),
  1986. array(
  1987. array('obj_A', null, 'obj_A', 'production'), // org_id unchanged
  1988. array('obj_B', '_DUMMY_', 'obj_B', 'production'), // error, '_DUMMY_' unknown
  1989. array('obj_C', 'SOMECODE', 'obj_C', 'production'),
  1990. array('obj_D', null, 'obj_D', 'production'),
  1991. array('obj_E', '_DUMMY_', 'obj_E', 'production'),
  1992. ),
  1993. array(
  1994. ),
  1995. array(
  1996. ),
  1997. ),
  1998. 'target_data' => array(
  1999. array('org_id', 'name', 'status'),
  2000. array(
  2001. // Initial state
  2002. array(2, 'obj_A', 'production'),
  2003. array(2, 'obj_B', 'production'),
  2004. ),
  2005. array(
  2006. array(2, 'obj_A', 'production'),
  2007. array(2, 'obj_B', 'production'),
  2008. array(1, 'obj_C', 'production'),
  2009. ),
  2010. array(
  2011. array(2, 'obj_A', 'production'),
  2012. array(2, 'obj_B', 'production'),
  2013. // deleted !
  2014. ),
  2015. // The only diff here is into the log
  2016. array(
  2017. array(2, 'obj_A', 'production'),
  2018. array(2, 'obj_B', 'production'),
  2019. // deleted !
  2020. ),
  2021. ),
  2022. 'attributes' => array(
  2023. 'org_id' => array(
  2024. 'do_reconcile' => false,
  2025. 'do_update' => true,
  2026. 'reconciliation_attcode' => 'code',
  2027. ),
  2028. 'name' => array(
  2029. 'do_reconcile' => true,
  2030. 'do_update' => true,
  2031. 'automatic_prefix' => true, // unique id
  2032. ),
  2033. 'status' => array(
  2034. 'do_reconcile' => false,
  2035. 'do_update' => true,
  2036. ),
  2037. ),
  2038. ),
  2039. // );
  2040. // $aXXXXScenarios = array(
  2041. array(
  2042. 'desc' => 'Update then delete with retention (to complete with manual testing) and reconciliation on org/name',
  2043. 'login' => 'admin',
  2044. 'password' => 'admin',
  2045. 'target_class' => 'ApplicationSolution',
  2046. 'full_load_periodicity' => 3600,
  2047. 'reconciliation_policy' => 'use_attributes',
  2048. 'action_on_zero' => 'create',
  2049. 'action_on_one' => 'update',
  2050. 'action_on_multiple' => 'error',
  2051. 'delete_policy' => 'update_then_delete',
  2052. 'delete_policy_update' => 'status:obsolete',
  2053. 'delete_policy_retention' => 15,
  2054. 'source_data' => array(
  2055. array('primary_key', 'org_id', 'name', 'status'),
  2056. array(
  2057. array('obj_A', 'Demo', 'obj_A', 'production'),
  2058. ),
  2059. array(
  2060. ),
  2061. ),
  2062. 'target_data' => array(
  2063. array('org_id', 'name', 'status'),
  2064. array(
  2065. // Initial state
  2066. ),
  2067. array(
  2068. array(2, 'obj_A', 'production'),
  2069. ),
  2070. array(
  2071. array(2, 'obj_A', 'obsolete'),
  2072. // deleted !
  2073. ),
  2074. ),
  2075. 'attributes' => array(
  2076. 'org_id' => array(
  2077. 'do_reconcile' => true,
  2078. 'do_update' => true,
  2079. 'reconciliation_attcode' => 'name',
  2080. ),
  2081. 'name' => array(
  2082. 'do_reconcile' => true,
  2083. 'do_update' => true,
  2084. 'automatic_prefix' => true, // unique id
  2085. ),
  2086. 'status' => array(
  2087. 'do_reconcile' => false,
  2088. 'do_update' => true,
  2089. ),
  2090. ),
  2091. ),
  2092. //);
  2093. //$aXXScenarios = array(
  2094. array(
  2095. 'desc' => 'Simple scenario loading a few ApplicationSolution',
  2096. 'login' => 'admin',
  2097. 'password' => 'admin',
  2098. 'target_class' => 'ApplicationSolution',
  2099. 'full_load_periodicity' => 3600,
  2100. 'reconciliation_policy' => 'use_attributes',
  2101. 'action_on_zero' => 'create',
  2102. 'action_on_one' => 'update',
  2103. 'action_on_multiple' => 'error',
  2104. 'delete_policy' => 'update',
  2105. 'delete_policy_update' => 'status:obsolete',
  2106. 'delete_policy_retention' => 0,
  2107. 'source_data' => array(
  2108. array('primary_key', 'org_id', 'name', 'status'),
  2109. array(
  2110. array('obj_A', 2, 'obj_A', 'production'),
  2111. array('obj_B', 2, 'obj_B', 'implementation'),
  2112. array('obj_C', 2, 'obj_C', 'implementation'),
  2113. ),
  2114. array(
  2115. array('obj_A', 2, 'obj_A', 'production'),
  2116. array('obj_B', 2, 'obj_B', 'implementation'),
  2117. array('obj_C', 2, 'obj_C', 'implementation'),
  2118. ),
  2119. array(
  2120. array('obj_A', 2, 'obj_A', 'production'),
  2121. array('obj_C', 2, 'obj_C', 'implementation'),
  2122. array('obj_D', 2, 'obj_D', 'implementation'),
  2123. ),
  2124. array(
  2125. array('obj_C', 2, 'obj_C', 'production'),
  2126. ),
  2127. array(
  2128. array('obj_C', 2, 'obj_C', 'production'),
  2129. ),
  2130. ),
  2131. 'target_data' => array(
  2132. array('org_id', 'name', 'status'),
  2133. array(
  2134. // Initial state
  2135. array(2, 'obj_A', 'implementation'),
  2136. array(2, 'obj_B', 'production'),
  2137. array(2, 'obj_B', 'implementation'),
  2138. ),
  2139. array(
  2140. array(2, 'obj_A', 'production'),
  2141. array(2, 'obj_B', 'production'),
  2142. array(2, 'obj_B', 'implementation'),
  2143. array(2, 'obj_C', 'implementation'),
  2144. ),
  2145. array(
  2146. array(2, 'obj_A', 'production'),
  2147. array(2, 'obj_B', 'production'),
  2148. array(2, 'obj_B', 'implementation'),
  2149. array(2, 'obj_C', 'implementation'),
  2150. ),
  2151. array(
  2152. array(2, 'obj_A', 'production'),
  2153. array(2, 'obj_B', 'production'),
  2154. array(2, 'obj_B', 'implementation'),
  2155. array(2, 'obj_C', 'implementation'),
  2156. array(2, 'obj_D', 'implementation'),
  2157. ),
  2158. array(
  2159. array(2, 'obj_A', 'obsolete'),
  2160. array(2, 'obj_B', 'production'),
  2161. array(2, 'obj_B', 'implementation'),
  2162. array(2, 'obj_C', 'production'),
  2163. array(2, 'obj_D', 'obsolete'),
  2164. ),
  2165. array(
  2166. array(2, 'obj_A', 'obsolete'),
  2167. array(2, 'obj_B', 'production'),
  2168. array(2, 'obj_B', 'implementation'),
  2169. array(2, 'obj_C', 'production'),
  2170. array(2, 'obj_D', 'obsolete'),
  2171. ),
  2172. ),
  2173. 'attributes' => array(
  2174. 'org_id' => array(
  2175. 'do_reconcile' => false,
  2176. 'do_update' => true,
  2177. ),
  2178. 'name' => array(
  2179. 'do_reconcile' => true,
  2180. 'do_update' => true,
  2181. 'automatic_prefix' => true, // unique id
  2182. ),
  2183. 'status' => array(
  2184. 'do_reconcile' => false,
  2185. 'do_update' => true,
  2186. ),
  2187. ),
  2188. ),
  2189. );
  2190. foreach ($aScenarios as $aSingleScenario)
  2191. {
  2192. $this->DoExecScenario($aSingleScenario);
  2193. }
  2194. }
  2195. }
  2196. ///////////////////////////////////////////////////////////////////////////
  2197. // Test SOAP services
  2198. ///////////////////////////////////////////////////////////////////////////
  2199. $aCreateTicketSpecs = array(
  2200. array(
  2201. 'service_category' => 'BasicServices',
  2202. 'verb' => 'GetVersion',
  2203. // 'expected result' => '1.0.1',
  2204. 'expected result' => '$ITOP_VERSION$ [dev]',
  2205. 'explain result' => 'no comment!',
  2206. 'args' => array(),
  2207. ),
  2208. array(
  2209. 'service_category' => '',
  2210. 'verb' => 'CreateIncidentTicket',
  2211. 'expected result' => true,
  2212. 'explain result' => 'link attribute unknown + a CI not found',
  2213. 'args' => array(
  2214. 'admin', /* sLogin */
  2215. 'admin', /* sPassword */
  2216. 'desc of ticket', /* sDescription */
  2217. 'initial situation blah blah blah', /* sInitialSituation */
  2218. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2219. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2220. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Telecom and connectivity'))), /* aServiceDesc */
  2221. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Network Troubleshooting'))), /* aServiceSubcategoryDesc */
  2222. 'sub product of the service', /* sProduct */
  2223. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2224. array(
  2225. new SOAPLinkCreationSpec(
  2226. 'InfrastructureCI',
  2227. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  2228. array(new SOAPAttributeValue('impacting', 'very critical'))
  2229. ),
  2230. new SOAPLinkCreationSpec(
  2231. 'NetworkDevice',
  2232. array(new SOAPSearchCondition('name', 'switch01')),
  2233. array(new SOAPAttributeValue('impact', 'who cares'))
  2234. ),
  2235. new SOAPLinkCreationSpec(
  2236. 'Server',
  2237. array(new SOAPSearchCondition('name', 'thisone')),
  2238. array(new SOAPAttributeValue('impact', 'our lives'))
  2239. ),
  2240. ), /* aImpact */
  2241. '1', /* sImpact */
  2242. '1', /* sUrgency */
  2243. ),
  2244. ),
  2245. array(
  2246. 'service_category' => '',
  2247. 'verb' => 'CreateIncidentTicket',
  2248. 'expected result' => true,
  2249. 'explain result' => 'caller not specified',
  2250. 'args' => array(
  2251. 'admin', /* sLogin */
  2252. 'admin', /* sPassword */
  2253. 'PC burning', /* sDescription */
  2254. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2255. new SOAPExternalKeySearch(), /* aCallerDesc */
  2256. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2257. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2258. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2259. 'sub product of the service', /* sProduct */
  2260. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2261. array(
  2262. new SOAPLinkCreationSpec(
  2263. 'InfrastructureCI',
  2264. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  2265. array()
  2266. ), /* aImpact */
  2267. ),
  2268. '1', /* sImpact */
  2269. '1', /* sUrgency */
  2270. ),
  2271. ),
  2272. array(
  2273. 'service_category' => '',
  2274. 'verb' => 'CreateIncidentTicket',
  2275. 'expected result' => false,
  2276. 'explain result' => 'wrong class on CI to attach',
  2277. 'args' => array(
  2278. 'admin', /* sLogin */
  2279. 'admin', /* sPassword */
  2280. 'PC burning', /* sDescription */
  2281. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2282. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2283. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2284. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2285. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2286. 'sub product of the service', /* sProduct */
  2287. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2288. array(
  2289. new SOAPLinkCreationSpec(
  2290. 'logInfra',
  2291. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  2292. array(new SOAPAttributeValue('impact', 'very critical'))
  2293. ),
  2294. ), /* aImpact */
  2295. '1', /* sImpact */
  2296. '1', /* sUrgency */
  2297. ),
  2298. ),
  2299. array(
  2300. 'service_category' => '',
  2301. 'verb' => 'CreateIncidentTicket',
  2302. 'expected result' => false,
  2303. 'explain result' => 'wrong search condition on CI to attach',
  2304. 'args' => array(
  2305. 'admin', /* sLogin */
  2306. 'admin', /* sPassword */
  2307. 'PC burning', /* sDescription */
  2308. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2309. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2310. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2311. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2312. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2313. 'sub product of the service', /* sProduct */
  2314. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2315. array(
  2316. new SOAPLinkCreationSpec(
  2317. 'InfrastructureCI',
  2318. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  2319. array(new SOAPAttributeValue('impact', 'very critical'))
  2320. ),
  2321. ), /* aImpact */
  2322. '1', /* sImpact */
  2323. '1', /* sUrgency */
  2324. ),
  2325. ),
  2326. array(
  2327. 'service_category' => '',
  2328. 'verb' => 'CreateIncidentTicket',
  2329. 'expected result' => true,
  2330. 'explain result' => 'no CI to attach (empty array)',
  2331. 'args' => array(
  2332. 'admin', /* sLogin */
  2333. 'admin', /* sPassword */
  2334. 'Houston not reachable', /* sDescription */
  2335. 'Tried to join the shuttle', /* sInitialSituation */
  2336. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2337. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2338. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2339. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2340. 'sub product of the service', /* sProduct */
  2341. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2342. array(
  2343. ), /* aImpact */
  2344. '1', /* sImpact */
  2345. '1', /* sUrgency */
  2346. ),
  2347. ),
  2348. array(
  2349. 'service_category' => '',
  2350. 'verb' => 'CreateIncidentTicket',
  2351. 'expected result' => true,
  2352. 'explain result' => 'no CI to attach (null)',
  2353. 'args' => array(
  2354. 'admin', /* sLogin */
  2355. 'admin', /* sPassword */
  2356. 'Houston not reachable', /* sDescription */
  2357. 'Tried to join the shuttle', /* sInitialSituation */
  2358. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2359. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2360. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2361. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2362. 'sub product of the service', /* sProduct */
  2363. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2364. null, /* aImpact */
  2365. '1', /* sImpact */
  2366. '1', /* sUrgency */
  2367. ),
  2368. ),
  2369. array(
  2370. 'service_category' => '',
  2371. 'verb' => 'CreateIncidentTicket',
  2372. 'expected result' => true,
  2373. 'explain result' => 'caller unknown',
  2374. 'args' => array(
  2375. 'admin', /* sLogin */
  2376. 'admin', /* sPassword */
  2377. 'Houston not reachable', /* sDescription */
  2378. 'Tried to join the shuttle', /* sInitialSituation */
  2379. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1000))), /* aCallerDesc */
  2380. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2381. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2382. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2383. 'sub product of the service', /* sProduct */
  2384. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2385. array(
  2386. ), /* aImpact */
  2387. '1', /* sImpact */
  2388. '1', /* sUrgency */
  2389. ),
  2390. ),
  2391. array(
  2392. 'service_category' => '',
  2393. 'verb' => 'CreateIncidentTicket',
  2394. 'expected result' => false,
  2395. 'explain result' => 'wrong values for impact and urgency',
  2396. 'args' => array(
  2397. 'admin', /* sLogin */
  2398. 'admin', /* sPassword */
  2399. 'Houston not reachable', /* sDescription */
  2400. 'Tried to join the shuttle', /* sInitialSituation */
  2401. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2402. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2403. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2404. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2405. 'sub product of the service', /* sProduct */
  2406. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2407. array(
  2408. ), /* aImpact */
  2409. '6', /* sImpact */
  2410. '7', /* sUrgency */
  2411. ),
  2412. ),
  2413. array(
  2414. 'service_category' => '',
  2415. 'verb' => 'CreateIncidentTicket',
  2416. 'expected result' => false,
  2417. 'explain result' => 'wrong password',
  2418. 'args' => array(
  2419. 'admin', /* sLogin */
  2420. 'xxxxx', /* sPassword */
  2421. 'Houston not reachable', /* sDescription */
  2422. 'Tried to join the shuttle', /* sInitialSituation */
  2423. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2424. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2425. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2426. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2427. 'sub product of the service', /* sProduct */
  2428. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2429. array(
  2430. ), /* aImpact */
  2431. '1', /* sImpact */
  2432. '1', /* sUrgency */
  2433. ),
  2434. ),
  2435. array(
  2436. 'service_category' => '',
  2437. 'verb' => 'CreateIncidentTicket',
  2438. 'expected result' => false,
  2439. 'explain result' => 'wrong login',
  2440. 'args' => array(
  2441. 'xxxxx', /* sLogin */
  2442. 'yyyyy', /* sPassword */
  2443. 'Houston not reachable', /* sDescription */
  2444. 'Tried to join the shuttle', /* sInitialSituation */
  2445. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2446. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2447. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2448. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2449. 'sub product of the service', /* sProduct */
  2450. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2451. array(
  2452. ), /* aImpact */
  2453. '1', /* sImpact */
  2454. '1', /* sUrgency */
  2455. ),
  2456. ),
  2457. array(
  2458. 'service_category' => '',
  2459. 'verb' => 'SearchObjects',
  2460. 'expected result' => true,
  2461. 'explain result' => '',
  2462. 'args' => array(
  2463. 'admin', /* sLogin */
  2464. 'admin', /* sPassword */
  2465. 'SELECT Incident WHERE id > 20', /* sOQL */
  2466. ),
  2467. ),
  2468. array(
  2469. 'service_category' => '',
  2470. 'verb' => 'SearchObjects',
  2471. 'expected result' => false,
  2472. 'explain result' => 'wrong OQL',
  2473. 'args' => array(
  2474. 'admin', /* sLogin */
  2475. 'admin', /* sPassword */
  2476. 'SELECT ThisClassDoesNotExist', /* sOQL */
  2477. ),
  2478. ),
  2479. );
  2480. $aManageCloudUsersSpecs = array(
  2481. array(
  2482. 'service_category' => '',
  2483. 'verb' => 'SearchObjects',
  2484. 'expected result' => false,
  2485. 'explain result' => 'wrong OQL',
  2486. 'args' => array(
  2487. 'admin', /* sLogin */
  2488. 'admin', /* sPassword */
  2489. 'SELECT ThisClassDoesNotExist', /* sOQL */
  2490. ),
  2491. ),
  2492. array(
  2493. 'service_category' => '',
  2494. 'verb' => 'SearchObjects',
  2495. 'expected result' => true,
  2496. 'explain result' => 'ok',
  2497. 'args' => array(
  2498. 'admin', /* sLogin */
  2499. 'admin', /* sPassword */
  2500. 'SELECT Organization', /* sOQL */
  2501. ),
  2502. ),
  2503. array(
  2504. 'service_category' => 'CloudUsersManagementService',
  2505. 'verb' => 'CreateAccount',
  2506. 'expected result' => true,
  2507. 'explain result' => 'ok',
  2508. 'args' => array(
  2509. 'admin', /* sAdminLogin */
  2510. 'admin', /* sAdminPassword */
  2511. 'http://myserver.mydomain.fr:8080', /* sCloudMgrUrl */
  2512. 'andros@combodo.com', /* sLogin */
  2513. 'André', /* sFirstName */
  2514. 'Dupont', /* sLastName */
  2515. 1, /* iOrgId */
  2516. 'FR FR', /* sLanguage */
  2517. array(
  2518. array(
  2519. new SOAPKeyValue('profile_id', '2'),
  2520. new SOAPKeyValue('reason', 'whynot'),
  2521. ),
  2522. array(
  2523. new SOAPKeyValue('profile_id', '3'),
  2524. new SOAPKeyValue('reason', 'because'),
  2525. ),
  2526. ), /* aProfiles (array of key/value pairs) */
  2527. array(
  2528. ), /* aAllowedOrgs (array of key/value pairs) */
  2529. 'comment on the creation operation', /* sComment */
  2530. ),
  2531. ),
  2532. array(
  2533. 'service_category' => 'CloudUsersManagementService',
  2534. 'verb' => 'ModifyAccount',
  2535. 'expected result' => true,
  2536. 'explain result' => 'ok',
  2537. 'args' => array(
  2538. 'admin', /* sAdminLogin */
  2539. 'admin', /* sAdminPassword */
  2540. 'andros@combodo.com', /* sLogin */
  2541. 'nono', /* sFirstName */
  2542. 'robot', /* sLastName */
  2543. 2, /* iOrgId */
  2544. 'EN US', /* sLanguage */
  2545. array(
  2546. array(
  2547. new SOAPKeyValue('profile_id', '3'),
  2548. new SOAPKeyValue('reason', 'because'),
  2549. ),
  2550. ), /* aProfiles (array of key/value pairs) */
  2551. array(
  2552. ), /* aAllowedOrgs (array of key/value pairs) */
  2553. 'comment on the modify operation', /* sComment */
  2554. ),
  2555. ),
  2556. array(
  2557. 'service_category' => 'CloudUsersManagementService',
  2558. 'verb' => 'DeleteAccount',
  2559. 'expected result' => true,
  2560. 'explain result' => '',
  2561. 'args' => array(
  2562. 'admin', /* sAdminLogin */
  2563. 'admin', /* sAdminPassword */
  2564. 'andros@combodo.com', /* sLogin */
  2565. 'comment on the deletion operation', /* sComment */
  2566. ),
  2567. ),
  2568. array(
  2569. 'service_category' => 'CloudUsersManagementService',
  2570. 'verb' => 'DeleteAccount',
  2571. 'expected result' => false,
  2572. 'explain result' => 'wrong login',
  2573. 'args' => array(
  2574. 'admin', /* sAdminLogin */
  2575. 'admin', /* sAdminPassword */
  2576. 'taratatata@sdf.com', /* sLogin */
  2577. 'comment on the deletion operation', /* sComment */
  2578. ),
  2579. ),
  2580. );
  2581. abstract class TestSoap extends TestSoapWebService
  2582. {
  2583. static public function GetName() {return 'Test SOAP';}
  2584. static public function GetDescription() {return 'Do basic stuff to test the SOAP capability';}
  2585. protected $m_aTestSpecs;
  2586. protected function DoExecute()
  2587. {
  2588. 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";
  2589. $aSOAPMapping = SOAPMapping::GetMapping();
  2590. // this file is generated dynamically with location = here
  2591. $sWsdlUri = 'http'.(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off') ? 's' : '').'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER['SCRIPT_NAME']).'/../webservices/itop.wsdl.php';
  2592. ini_set("soap.wsdl_cache_enabled","0");
  2593. foreach ($this->m_aTestSpecs as $iPos => $aWebService)
  2594. {
  2595. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  2596. echo "<p>Using WSDL: $sWsdlUriForService</p>\n";
  2597. echo "<p>{$aWebService['explain result']}</p>\n";
  2598. $sWsdlUriForService = $sWsdlUri.'?service_category='.$aWebService['service_category'];
  2599. $this->m_SoapClient = new SoapClient
  2600. (
  2601. $sWsdlUriForService,
  2602. array(
  2603. 'classmap' => $aSOAPMapping,
  2604. 'trace' => 1,
  2605. )
  2606. );
  2607. if (false)
  2608. {
  2609. self::DumpVariable($this->m_SoapClient->__getTypes());
  2610. }
  2611. try
  2612. {
  2613. $oRes = call_user_func_array(array($this->m_SoapClient, $aWebService['verb']), $aWebService['args']);
  2614. }
  2615. catch(SoapFault $e)
  2616. {
  2617. print "<pre>\n";
  2618. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  2619. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  2620. print "</pre>";
  2621. print "Response in HTML: <p>".$this->m_SoapClient->__getLastResponse()."</p>";
  2622. throw $e;
  2623. }
  2624. self::DumpVariable($oRes);
  2625. print "<pre>\n";
  2626. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  2627. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  2628. print "</pre>";
  2629. if ($oRes instanceof SOAPResult)
  2630. {
  2631. $res = $oRes->status;
  2632. }
  2633. elseif ($oRes instanceof SOAPSimpleResult)
  2634. {
  2635. $res = $oRes->status;
  2636. }
  2637. else
  2638. {
  2639. $res = $oRes;
  2640. }
  2641. if ($res != $aWebService['expected result'])
  2642. {
  2643. echo "Expecting:<br/>\n";
  2644. var_dump($aWebService['expected result']);
  2645. echo "Obtained:<br/>\n";
  2646. var_dump($res);
  2647. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  2648. }
  2649. }
  2650. }
  2651. }
  2652. abstract class TestSoapDirect extends TestBizModel
  2653. {
  2654. static public function GetName() {return 'Test web services locally';}
  2655. static public function GetDescription() {return 'Invoke the service directly (troubleshooting)';}
  2656. static public function GetConfigFile() {return '/config-itop.php';}
  2657. protected $m_aTestSpecs;
  2658. protected function DoExecute()
  2659. {
  2660. foreach ($this->m_aTestSpecs as $iPos => $aWebService)
  2661. {
  2662. $sServiceClass = $aWebService['service_category'];
  2663. if (empty($sServiceClass)) $sServiceClass = 'BasicServices';
  2664. $oWebServices = new $sServiceClass();
  2665. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  2666. echo "<p>{$aWebService['explain result']}</p>\n";
  2667. $oRes = call_user_func_array(array($oWebServices, $aWebService['verb']), $aWebService['args']);
  2668. self::DumpVariable($oRes);
  2669. if ($oRes instanceof SOAPResult)
  2670. {
  2671. $res = $oRes->status;
  2672. }
  2673. elseif ($oRes instanceof SOAPSimpleResult)
  2674. {
  2675. $res = $oRes->status;
  2676. }
  2677. else
  2678. {
  2679. $res = $oRes;
  2680. }
  2681. if ($res != $aWebService['expected result'])
  2682. {
  2683. echo "Expecting:<br/>\n";
  2684. var_dump($aWebService['expected result']);
  2685. echo "Obtained:<br/>\n";
  2686. var_dump($res);
  2687. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  2688. }
  2689. }
  2690. return true;
  2691. }
  2692. }
  2693. class TestSoap_Tickets extends TestSoap
  2694. {
  2695. static public function GetName() {return 'Test SOAP - create ticket';}
  2696. protected function DoExecute()
  2697. {
  2698. global $aCreateTicketSpecs;
  2699. $this->m_aTestSpecs = $aCreateTicketSpecs;
  2700. return parent::DoExecute();
  2701. }
  2702. }
  2703. class TestSoapDirect_Tickets extends TestSoapDirect
  2704. {
  2705. static public function GetName() {return 'Test SOAP without SOAP - create ticket';}
  2706. protected function DoExecute()
  2707. {
  2708. global $aCreateTicketSpecs;
  2709. $this->m_aTestSpecs = $aCreateTicketSpecs;
  2710. return parent::DoExecute();
  2711. }
  2712. }
  2713. class TestSoap_ManageCloudUsers extends TestSoap
  2714. {
  2715. static public function GetName() {return 'Test SOAP - manage Cloud Users';}
  2716. protected function DoExecute()
  2717. {
  2718. global $aManageCloudUsersSpecs;
  2719. $this->m_aTestSpecs = $aManageCloudUsersSpecs;
  2720. return parent::DoExecute();
  2721. }
  2722. }
  2723. class TestSoapDirect_ManageCloudUsers extends TestSoapDirect
  2724. {
  2725. static public function GetName() {return 'Test SOAP without SOAP - manage Cloud Users';}
  2726. protected function DoExecute()
  2727. {
  2728. global $aManageCloudUsersSpecs;
  2729. $this->m_aTestSpecs = $aManageCloudUsersSpecs;
  2730. return parent::DoExecute();
  2731. }
  2732. }
  2733. ////////////////////// End of SOAP TESTS
  2734. class TestTriggerAndEmail extends TestBizModel
  2735. {
  2736. static public function GetName() {return 'Test trigger and email';}
  2737. static public function GetDescription() {return 'Create a trigger and an email, then activates the trigger';}
  2738. static public function GetConfigFile() {return '/config-itop.php';}
  2739. protected function CreateEmailSpec($oTrigger, $sStatus, $sTo, $sCC, $sTesterEmail)
  2740. {
  2741. $oAction = MetaModel::NewObject("ActionEmail");
  2742. $oAction->Set("status", $sStatus);
  2743. $oAction->Set("name", "New server");
  2744. $oAction->Set("test_recipient", $sTesterEmail);
  2745. $oAction->Set("from", $sTesterEmail);
  2746. $oAction->Set("reply_to", $sTesterEmail);
  2747. $oAction->Set("to", $sTo);
  2748. $oAction->Set("cc", $sCC);
  2749. $oAction->Set("bcc", "");
  2750. $oAction->Set("subject", "New server: '\$this->name()$'");
  2751. $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>");
  2752. $oAction->Set("importance", "low");
  2753. $iActionId = $this->ObjectToDB($oAction, true);
  2754. $oLink = MetaModel::NewObject("lnkTriggerAction");
  2755. $oLink->Set("trigger_id", $oTrigger->GetKey());
  2756. $oLink->Set("action_id", $iActionId);
  2757. $oLink->Set("order", "1");
  2758. $iLink = $this->ObjectToDB($oLink, true);
  2759. }
  2760. protected function DoExecute()
  2761. {
  2762. $oMyPerson = MetaModel::NewObject("Person");
  2763. $oMyPerson->Set("name", "testemail1");
  2764. $oMyPerson->Set("first_name", "theodore");
  2765. $oMyPerson->Set("org_id", "1");
  2766. $oMyPerson->Set("email", "romain.quetiez@combodo.com");
  2767. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  2768. $oMyPerson = MetaModel::NewObject("Person");
  2769. $oMyPerson->Set("name", "testemail2");
  2770. $oMyPerson->Set("first_name", "theodore");
  2771. $oMyPerson->Set("org_id", "1");
  2772. $oMyPerson->Set("email", "denis.flaven@combodo.com");
  2773. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  2774. $oMyPerson = MetaModel::NewObject("Person");
  2775. $oMyPerson->Set("name", "testemail3");
  2776. $oMyPerson->Set("first_name", "theodore");
  2777. $oMyPerson->Set("org_id", "1");
  2778. $oMyPerson->Set("email", "erwan.taloc@combodo.com");
  2779. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  2780. $oMyServer = MetaModel::NewObject("Server");
  2781. $oMyServer->Set("name", "wfr.terminator.com");
  2782. $oMyServer->Set("status", "production");
  2783. $oMyServer->Set("org_id", 2);
  2784. $iServerId = $this->ObjectToDB($oMyServer, true);
  2785. $oMyTrigger = MetaModel::NewObject("TriggerOnStateEnter");
  2786. $oMyTrigger->Set("description", "Testor");
  2787. $oMyTrigger->Set("target_class", "Server");
  2788. $oMyTrigger->Set("state", "Shipped");
  2789. $iTriggerId = $this->ObjectToDB($oMyTrigger, true);
  2790. // Error in OQL field(s)
  2791. //
  2792. $this->CreateEmailSpec
  2793. (
  2794. $oMyTrigger,
  2795. 'test',
  2796. "SELECT Person WHERE naime = 'Dali'",
  2797. "SELECT Server",
  2798. 'romain.quetiez@combodo.com'
  2799. );
  2800. // Error: no recipient
  2801. //
  2802. $this->CreateEmailSpec
  2803. (
  2804. $oMyTrigger,
  2805. 'test',
  2806. "",
  2807. "",
  2808. 'romain.quetiez@combodo.com'
  2809. );
  2810. // Test
  2811. //
  2812. $this->CreateEmailSpec
  2813. (
  2814. $oMyTrigger,
  2815. 'test',
  2816. "SELECT Person WHERE name LIKE 'testemail%'",
  2817. "SELECT Person",
  2818. 'romain.quetiez@combodo.com'
  2819. );
  2820. // Test failing because of a wrong test recipient address
  2821. //
  2822. $this->CreateEmailSpec
  2823. (
  2824. $oMyTrigger,
  2825. 'test',
  2826. "SELECT Person WHERE name LIKE 'testemail%'",
  2827. "",
  2828. 'toto@walibi.bg'
  2829. );
  2830. // Normal behavior
  2831. //
  2832. $this->CreateEmailSpec
  2833. (
  2834. $oMyTrigger,
  2835. 'enabled',
  2836. "SELECT Person WHERE name LIKE 'testemail%'",
  2837. "",
  2838. 'romain.quetiez@combodo.com'
  2839. );
  2840. // Does nothing, because it is disabled
  2841. //
  2842. $this->CreateEmailSpec
  2843. (
  2844. $oMyTrigger,
  2845. 'disabled',
  2846. "SELECT Person WHERE name = 'testemail%'",
  2847. "",
  2848. 'romain.quetiez@combodo.com'
  2849. );
  2850. $oMyTrigger->DoActivate($oMyServer->ToArgs('this'));
  2851. return true;
  2852. }
  2853. }
  2854. class TestDBProperties extends TestBizModel
  2855. {
  2856. static public function GetName()
  2857. {
  2858. return 'Itop - DB Properties';
  2859. }
  2860. static public function GetDescription()
  2861. {
  2862. return 'Write and read a dummy property';
  2863. }
  2864. static public function GetConfigFile() {return '/config-itop.php';}
  2865. protected function DoExecute()
  2866. {
  2867. $sName = 'test';
  2868. DBProperty::SetProperty($sName, 'unix time:'.time(), 'means nothing', 'done with the automated test utility');
  2869. $sValue = DBProperty::GetProperty($sName, 'defaults to this because the table has not been created (1.0.1 install?)');
  2870. echo "<p>Write... then read property <b>$sName</b>, found: '$sValue'</p>\n";
  2871. }
  2872. }
  2873. class TestCreateObjects extends TestBizModel
  2874. {
  2875. static public function GetName()
  2876. {
  2877. return 'Itop - create objects';
  2878. }
  2879. static public function GetDescription()
  2880. {
  2881. return 'Create weird objects (reproduce a bug?)';
  2882. }
  2883. static public function GetConfigFile() {return '/config-itop.php';}
  2884. protected function DoExecute()
  2885. {
  2886. $oMyObj = MetaModel::NewObject("Server");
  2887. $oMyObj->Set("name", "test".rand(1,1000));
  2888. $oMyObj->Set("org_id", 2);
  2889. $oMyObj->Set("status", 'production');
  2890. $this->ObjectToDB($oMyObj, $bReload = true);
  2891. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  2892. $sTicketRef = "I-abcdef";
  2893. echo "<p>Creating: $sTicketRef</p>";
  2894. $oMyObj = MetaModel::NewObject("Incident");
  2895. $oMyObj->Set("ref", $sTicketRef);
  2896. $oMyObj->Set("title", "my title");
  2897. $oMyObj->Set("description", "my description");
  2898. $oMyObj->Set("ticket_log", "my ticket log");
  2899. $oMyObj->Set("start_date", "2010-03-08 17:37:00");
  2900. $oMyObj->Set("status", "resolved");
  2901. $oMyObj->Set("caller_id", 1);
  2902. $oMyObj->Set("org_id", 1);
  2903. $oMyObj->Set("urgency", 3);
  2904. $oMyObj->Set("agent_id", 1);
  2905. $oMyObj->Set("close_date", "0000-00-00 00:00:00");
  2906. $oMyObj->Set("last_update", "2010-04-08 16:47:29");
  2907. $oMyObj->Set("solution", "branche ton pc!");
  2908. // External key given as a string -> should be casted to an integer
  2909. $oMyObj->Set("service_id", "1");
  2910. $oMyObj->Set("servicesubcategory_id", "1");
  2911. $oMyObj->Set("product", "");
  2912. $oMyObj->Set("impact", 2);
  2913. $oMyObj->Set("priority", 3);
  2914. $oMyObj->Set("related_problem_id", 0);
  2915. $oMyObj->Set("related_change_id", 0);
  2916. $oMyObj->Set("assignment_date", "");
  2917. $oMyObj->Set("resolution_date", "");
  2918. $oMyObj->Set("tto_escalation_deadline", "");
  2919. $oMyObj->Set("ttr_escalation_deadline", "");
  2920. $oMyObj->Set("closure_deadline", "");
  2921. $oMyObj->Set("resolution_code", "fixed");
  2922. $oMyObj->Set("user_satisfaction", "");
  2923. $oMyObj->Set("user_commment", "");
  2924. $oMyObj->Set("workgroup_id", 4);
  2925. $this->ObjectToDB($oMyObj, $bReload = true);
  2926. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  2927. }
  2928. }
  2929. class TestSetLinkset extends TestBizModel
  2930. {
  2931. static public function GetName()
  2932. {
  2933. return 'Itop - Link set from a string';
  2934. }
  2935. static public function GetDescription()
  2936. {
  2937. return 'Create a user account, setting its profile by the mean of a string (prerequisite to CSV import of linksets)';
  2938. }
  2939. static public function GetConfigFile() {return '/config-itop.php';}
  2940. protected function DoExecute()
  2941. {
  2942. $oUser = new UserLocal();
  2943. $oUser->Set('login', 'patator'.time());
  2944. $oUser->Set('password', 'patator');
  2945. //$oUser->Set('contactid', 0);
  2946. //$oUser->Set('language', $sLanguage);
  2947. $sLinkSetSpec = "profileid:10;reason:service manager|profileid->name:Problem Manager;'reason:problem manager;glandeur";
  2948. $oAttDef = MetaModel::GetAttributeDef('UserLocal', 'profile_list');
  2949. $oSet = $oAttDef->MakeValueFromString($sLinkSetSpec);
  2950. $oUser->Set('profile_list', $oSet);
  2951. // Create a change to record the history of the User object
  2952. $this->ObjectToDB($oUser, $bReload = true);
  2953. echo "<p>Created: {$oUser->GetHyperLink()}</p>";
  2954. }
  2955. }
  2956. class TestEmailAsynchronous extends TestBizModel
  2957. {
  2958. static public function GetName()
  2959. {
  2960. return 'Itop - Asynchronous email';
  2961. }
  2962. static public function GetDescription()
  2963. {
  2964. return 'Queues a request to send an email';
  2965. }
  2966. static public function GetConfigFile() {return '/config-itop.php';}
  2967. protected function DoExecute()
  2968. {
  2969. for ($i = 0 ; $i < 2 ; $i++)
  2970. {
  2971. $oMail = new Email();
  2972. $oMail->SetRecipientTO('romain.quetiez@combodo.com');
  2973. $oMail->SetRecipientFrom('romain.quetiez@combodo.com');
  2974. $oMail->SetRecipientCC('romainquetiez@yahoo.fr');
  2975. $oMail->SetSubject('automated test - '.$i);
  2976. $oMail->SetBody('this is one is entirely working fine '.time());
  2977. $iRes = $oMail->Send($aIssues, false);
  2978. switch ($iRes)
  2979. {
  2980. case EMAIL_SEND_OK:
  2981. echo "EMAIL_SEND_OK<br/>\n";
  2982. break;
  2983. case EMAIL_SEND_PENDING:
  2984. echo "EMAIL_SEND_PENDING<br/>\n";
  2985. break;
  2986. case EMAIL_SEND_ERROR:
  2987. echo "EMAIL_SEND_ERROR: <br/>\n";
  2988. foreach($aIssues as $sIssue)
  2989. {
  2990. echo "Issue: $sIssue<br/>\n";
  2991. }
  2992. break;
  2993. }
  2994. }
  2995. }
  2996. }
  2997. ?>