testlist.inc.php 96 KB

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