testlist.inc.php 104 KB

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