testlist.inc.php 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Core test list
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class TestBeHappy extends TestHandler // TestFunctionInOut, TestBizModel...
  25. {
  26. static public function GetName()
  27. {
  28. return 'Be happy!';
  29. }
  30. static public function GetDescription()
  31. {
  32. return 'Sample test with success';
  33. }
  34. protected function DoExecute()
  35. {
  36. echo "<p>Am I happy?</p>";
  37. echo "<p>Yes, I am!</p>";
  38. }
  39. }
  40. class TestBeSad extends TestHandler
  41. {
  42. static public function GetName()
  43. {
  44. return 'Be sad...';
  45. }
  46. static public function GetDescription()
  47. {
  48. return 'Sample test with failure';
  49. }
  50. protected function DoExecute()
  51. {
  52. echo "Am I happy?";
  53. throw new Exception('jamais content');
  54. }
  55. }
  56. class TestSQLQuery extends TestScenarioOnDB
  57. {
  58. static public function GetName() {return 'SQLQuery';}
  59. 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';}
  60. static public function GetDBHost() {return 'localhost';}
  61. static public function GetDBUser() {return 'root';}
  62. static public function GetDBPwd() {return '';}
  63. static public function GetDBName() {return 'TestSQLQuery';}
  64. static public function GetDBSubName() {return 'taratata';}
  65. protected function DoPrepare()
  66. {
  67. parent::DoPrepare();
  68. cmdbSource::CreateTable('CREATE TABLE `myTable` (myKey INT(11) NOT NULL auto_increment, column1 VARCHAR(255), column2 VARCHAR(255), PRIMARY KEY (`myKey`)) ENGINE = '.MYSQL_ENGINE);
  69. 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);
  70. 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);
  71. }
  72. protected function DoExecute()
  73. {
  74. $oQuery = new SQLObjectQuery(
  75. $sTable = 'myTable',
  76. $sTableAlias = 'myTableAlias',
  77. $aFields = array('column1'=>new FieldExpression('column1', 'myTableAlias'), 'column2'=>new FieldExpression('column2', 'myTableAlias')),
  78. // $aFullTextNeedles = array('column1'),
  79. $bToDelete = false,
  80. $aValues = array()
  81. );
  82. $oQuery->AddCondition(Expression::FromOQL('DATE(NOW() - 1200 * 2) > \'2008-07-31\''));
  83. $oSubQuery1 = new SQLObjectQuery(
  84. $sTable = 'myTable1',
  85. $sTableAlias = 'myTable1Alias',
  86. $aFields = array('column1_1'=>new FieldExpression('column1', 'myTableAlias'), 'column1_2'=>new FieldExpression('column1', 'myTableAlias')),
  87. // $aFullTextNeedles = array(),
  88. $bToDelete = false,
  89. $aValues = array()
  90. );
  91. $oSubQuery2 = new SQLObjectQuery(
  92. $sTable = 'myTable2',
  93. $sTableAlias = 'myTable2Alias',
  94. $aFields = array('column2_1'=>new FieldExpression('column2', 'myTableAlias'), 'column2_2'=>new FieldExpression('column2', 'myTableAlias')),
  95. // $aFullTextNeedles = array(),
  96. $bToDelete = false,
  97. $aValues = array()
  98. );
  99. $oQuery->AddInnerJoin($oSubQuery1, 'column1', 'column1_1');
  100. $oQuery->AddLeftJoin($oSubQuery2, 'column2', 'column2_2');
  101. $oQuery->DisplayHtml();
  102. $oQuery->RenderDelete();
  103. $oQuery->RenderUpdate();
  104. echo '<p>'.$oQuery->RenderSelect().'</p>';
  105. $oQuery->RenderSelect(array('column1'));
  106. $oQuery->RenderSelect(array('column1', 'column2'));
  107. }
  108. }
  109. class TestOQLParser extends TestFunction
  110. {
  111. static public function GetName() {return 'Check OQL parsing';}
  112. static public function GetDescription() {return 'Attempts a series of queries, and in particular those with a bad syntax';}
  113. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  114. {
  115. $oOql = new OqlInterpreter($sQuery);
  116. try
  117. {
  118. $oTrash = $oOql->Parse(); // Not expecting a given format, otherwise use ParseExpression/ParseObjectQuery/ParseValueSetQuery
  119. self::DumpVariable($oTrash);
  120. }
  121. catch (OQLException $OqlException)
  122. {
  123. if ($bIsCorrectQuery)
  124. {
  125. echo "<p>More info on this unexpected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  126. throw $OqlException;
  127. return false;
  128. }
  129. else
  130. {
  131. // Everything is fine :-)
  132. echo "<p>More info on this expected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  133. return true;
  134. }
  135. }
  136. catch (Exception $e)
  137. {
  138. if ($bIsCorrectQuery)
  139. {
  140. echo "<p>More info on this <b>un</b>expected failure:<br/>".htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8')."</p>\n";
  141. throw $OqlException;
  142. return false;
  143. }
  144. else
  145. {
  146. // Everything is fine :-)
  147. echo "<p>More info on this expected failure:<br/>".htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8')."</p>\n";
  148. return true;
  149. }
  150. }
  151. // The query was correctly parsed, was it expected to be correct ?
  152. if ($bIsCorrectQuery)
  153. {
  154. return true;
  155. }
  156. else
  157. {
  158. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  159. return false;
  160. }
  161. }
  162. protected function TestQuery($sQuery, $bIsCorrectQuery)
  163. {
  164. if (!$this->CheckQuery($sQuery, $bIsCorrectQuery))
  165. {
  166. return false;
  167. }
  168. return true;
  169. }
  170. public function DoExecute()
  171. {
  172. $aQueries = array(
  173. 'SELECT toto' => true,
  174. 'SELECT toto WHERE toto.a = 1' => true,
  175. 'SELECT toto WHERE toto.a = -1' => true,
  176. 'SELECT toto WHERE toto.a = (1-1)' => true,
  177. 'SELECT toto WHERE toto.a = (-1+3)' => true,
  178. 'SELECT toto WHERE toto.a = (3+-1)' => true,
  179. 'SELECT toto WHERE toto.a = (3--1)' => true,
  180. 'SELECT toto WHERE toto.a = (3++1)' => false,
  181. 'SELECT toto WHERE toto.a = 0xC' => true,
  182. 'SELECT toto WHERE toto.a = \'AXDVFS0xCZ32\'' => true,
  183. 'SELECT toto WHERE toto.a = :myparameter' => true,
  184. 'SELECT toto WHERE toto.a IN (:param1)' => true,
  185. 'SELECT toto WHERE toto.a IN (:param1, :param2)' => true,
  186. 'SELECT toto WHERE toto.a=1' => true,
  187. 'SELECT toto WHERE toto.a = "1"' => true,
  188. 'SELECT toto WHHHERE toto.a = "1"' => false,
  189. 'SELECT toto WHERE toto.a == "1"' => false,
  190. 'SELECT toto WHERE toto.a % 1' => false,
  191. 'SELECT toto WHERE toto.a & 1' => true, // bitwise and
  192. 'SELECT toto WHERE toto.a | 1' => true, // bitwise or
  193. 'SELECT toto WHERE toto.a ^ 1' => true, // bitwise xor
  194. 'SELECT toto WHERE toto.a << 1' => true, // bitwise left shift
  195. 'SELECT toto WHERE toto.a >> 1' => true, // bitwise right shift
  196. //'SELECT toto WHERE toto.a LIKE 1' => false,
  197. 'SELECT toto WHERE toto.a like \'arg\'' => false,
  198. 'SELECT toto WHERE toto.a NOT LIKE "That\'s it"' => true,
  199. 'SELECT toto WHERE toto.a NOT LIKE "That\'s "it""' => false,
  200. 'SELECT toto WHERE toto.a NOT LIKE "That\'s \\"it\\""' => true,
  201. 'SELECT toto WHERE toto.a NOT LIKE \'That"s it\'' => true,
  202. 'SELECT toto WHERE toto.a NOT LIKE \'That\'s it\'' => false,
  203. 'SELECT toto WHERE toto.a NOT LIKE \'That\\\'s it\'' => true,
  204. 'SELECT toto WHERE toto.a NOT LIKE "blah \\ truc"' => false,
  205. 'SELECT toto WHERE toto.a NOT LIKE "blah \\\\ truc"' => true,
  206. 'SELECT toto WHERE toto.a NOT LIKE \'blah \\ truc\'' => false,
  207. 'SELECT toto WHERE toto.a NOT LIKE \'blah \\\\ truc\'' => true,
  208. 'SELECT toto WHERE toto.a NOT LIKE "\\\\"' => true,
  209. 'SELECT toto WHERE toto.a NOT LIKE "\\""' => true,
  210. 'SELECT toto WHERE toto.a NOT LIKE "\\"\\\\"' => true,
  211. 'SELECT toto WHERE toto.a NOT LIKE "\\\\\\""' => true,
  212. 'SELECT toto WHERE toto.a NOT LIKE ""' => true,
  213. 'SELECT toto WHERE toto.a NOT LIKE "\\\\"' => true,
  214. "SELECT UserRightsMatrixClassGrant WHERE UserRightsMatrixClassGrant.class = 'lnkContactRealObject' AND UserRightsMatrixClassGrant.action = 'modify' AND UserRightsMatrixClassGrant.login = 'Denis'" => true,
  215. "SELECT A WHERE A.col1 = 'lit1' AND A.col2 = 'lit2' AND A.col3 = 'lit3'" => true,
  216. 'SELECT toto WHERE toto.a NOT LIKE "blah" AND toto.b LIKE "foo"' => true,
  217. //'SELECT toto WHERE toto.a > \'asd\'' => false,
  218. 'SELECT toto WHERE toto.a = 1 AND toto.b LIKE "x" AND toto.f >= 12345' => true,
  219. 'SELECT Device JOIN Site ON Device.site = Site.id' => true,
  220. 'SELECT Device JOIN Site ON Device.site = Site.id JOIN Country ON Site.location = Country.id' => true,
  221. "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,
  222. "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,
  223. "SELECT A JOIN B ON A.myB = B.id WHERE A.col1 + B.col2 * B.col1 = A.col2" => true,
  224. "SELECT A JOIN B ON A.myB = B.id WHERE A.col1 + (B.col2 * B.col1) = A.col2" => true,
  225. "SELECT A JOIN B ON A.myB = B.id WHERE (A.col1 + B.col2) * B.col1 = A.col2" => true,
  226. "SELECT A JOIN B ON A.myB = B.id WHERE (A.col1 & B.col2) = A.col2" => true,
  227. 'SELECT Device AS D_ JOIN Site AS S_ ON D_.site = S_.id WHERE S_.country = "Francia"' => true,
  228. // Several objects in a row...
  229. //
  230. 'SELECT A FROM A' => true,
  231. 'SELECT A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  232. 'SELECT A FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  233. 'SELECT B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  234. 'SELECT A,B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  235. 'SELECT A, B FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  236. 'SELECT B,A FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  237. 'SELECT A, B,C FROM A JOIN B ON A.myB = B.id' => true,
  238. 'SELECT C FROM A JOIN B ON A.myB = B.id WHERE A.col1 = 2' => true,
  239. 'SELECT A JOIN B ON A.myB BELOW B.id WHERE A.col1 = 2' => true,
  240. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id BELOW B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  241. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id BELOW STRICT B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  242. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id NOT BELOW B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  243. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id NOT BELOW STRICT B.id WHERE A.col1 = 2 AND B.id = 3' => true,
  244. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id = B.id WHERE A.col1 BELOW 2 AND B.id = 3' => false,
  245. // Unions
  246. //
  247. 'SELECT A UNION SELECT B' => true,
  248. 'SELECT A WHERE A.b = "sdf" UNION SELECT B WHERE B.a = "sfde"' => true,
  249. 'SELECT A UNION SELECT B UNION SELECT C' => true,
  250. 'SELECT A UNION SELECT B UNION SELECT C UNION SELECT D' => true,
  251. 'SELECT A JOIN B ON A.myB = B.id JOIN C ON C.parent_id NOT BELOW B.id WHERE A.col1 = 2 AND B.id = 3 UNION SELECT Device JOIN Site ON Device.site = Site.id JOIN Country ON Site.location = Country.id' => true,
  252. );
  253. $iErrors = 0;
  254. foreach($aQueries as $sQuery => $bIsCorrectQuery)
  255. {
  256. $sIsOk = $bIsCorrectQuery ? 'good' : 'bad';
  257. echo "<h4>Testing query: $sQuery ($sIsOk)</h4>\n";
  258. try
  259. {
  260. $bRet = $this->TestQuery($sQuery, $bIsCorrectQuery);
  261. }
  262. catch(Exception $e)
  263. {
  264. $this->m_aErrors[] = $e->getMessage();
  265. $bRet = false;
  266. }
  267. if (!$bRet) $iErrors++;
  268. }
  269. return ($iErrors == 0);
  270. }
  271. }
  272. class TestOQLNormalization extends TestBizModel
  273. {
  274. static public function GetName() {return 'Check OQL normalization';}
  275. static public function GetDescription() {return 'Attempts a series of queries, and in particular those with unknown or inconsistent class/attributes. Assumes a very standard installation!';}
  276. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  277. {
  278. try
  279. {
  280. $oSearch = DBObjectSearch::FromOQL($sQuery);
  281. self::DumpVariable($sQuery);
  282. }
  283. catch (OQLNormalizeException $OqlException)
  284. {
  285. if ($bIsCorrectQuery)
  286. {
  287. echo "<p>More info on this unexpected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  288. throw $OqlException;
  289. return false;
  290. }
  291. else
  292. {
  293. // Everything is fine :-)
  294. echo "<p>More info on this expected failure:<br/>".$OqlException->getHtmlDesc()."</p>\n";
  295. return true;
  296. }
  297. }
  298. catch (Exception $e)
  299. {
  300. if ($bIsCorrectQuery)
  301. {
  302. echo "<p>More info on this <b>un</b>expected failure:<br/>".htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8')."</p>\n";
  303. throw $e;
  304. return false;
  305. }
  306. else
  307. {
  308. // Everything is fine :-)
  309. echo "<p>More info on this expected failure:<br/>".htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8')."</p>\n";
  310. return true;
  311. }
  312. }
  313. // The query was correctly parsed, was it expected to be correct ?
  314. if ($bIsCorrectQuery)
  315. {
  316. return true;
  317. }
  318. else
  319. {
  320. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  321. return false;
  322. }
  323. }
  324. protected function TestQuery($sQuery, $bIsCorrectQuery)
  325. {
  326. if (!$this->CheckQuery($sQuery, $bIsCorrectQuery))
  327. {
  328. return false;
  329. }
  330. return true;
  331. }
  332. public function DoExecute()
  333. {
  334. $aQueries = array(
  335. 'SELECT Contact' => true,
  336. 'SELECT Contact WHERE nom_de_famille = "foo"' => false,
  337. 'SELECT Contact AS c WHERE name = "foo"' => true,
  338. 'SELECT Contact AS c WHERE nom_de_famille = "foo"' => false,
  339. 'SELECT Contact AS c WHERE c.name = "foo"' => true,
  340. 'SELECT Contact AS c WHERE Contact.name = "foo"' => false,
  341. 'SELECT Contact AS c WHERE x.name = "foo"' => false,
  342. 'SELECT RelationProfessionnelle' => false,
  343. 'SELECT RelationProfessionnelle AS c WHERE name = "foo"' => false,
  344. // The first query is the base query altered only in one place in the subsequent queries
  345. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE p.name LIKE "foo"' => true,
  346. 'SELECT Person AS p JOIN lnkXXXXXXXXXXXX AS lnk ON lnk.person_id = p.id WHERE p.name LIKE "foo"' => false,
  347. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON p.person_id = p.id WHERE p.name LIKE "foo"' => false,
  348. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON person_id = p.id WHERE p.name LIKE "foo"' => false,
  349. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = id WHERE p.name LIKE "foo"' => false,
  350. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.role = p.id WHERE p.name LIKE "foo"' => false,
  351. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.team_id = p.id WHERE p.name LIKE "foo"' => false,
  352. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id BELOW p.id WHERE p.name LIKE "foo"' => false,
  353. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.org_id WHERE p.name LIKE "foo"' => false,
  354. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON p.id = lnk.person_id WHERE p.name LIKE "foo"' => false, // inverted the JOIN spec
  355. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE name LIKE "foo"' => true,
  356. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE x.name LIKE "foo"' => false,
  357. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE p.eman LIKE "foo"' => false,
  358. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE eman LIKE "foo"' => false,
  359. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON lnk.person_id = p.id WHERE id = 1' => false,
  360. 'SELECT Person AS p JOIN lnkPersonToTeam AS lnk ON p.id = lnk.person_id WHERE p.name LIKE "foo"' => false,
  361. 'SELECT Person AS p JOIN Organization AS o ON p.org_id = o.id WHERE p.name LIKE "foo" AND o.name LIKE "land"' => true,
  362. 'SELECT Person AS p JOIN Organization AS o ON p.location_id = o.id WHERE p.name LIKE "foo" AND o.name LIKE "land"' => false,
  363. 'SELECT Person AS p JOIN Organization AS o ON p.name = o.id WHERE p.name LIKE "foo" AND o.name LIKE "land"' => false,
  364. 'SELECT Person AS p JOIN Organization AS o ON p.org_id = o.id JOIN Person AS p ON p.org_id = o.id' => false,
  365. 'SELECT Person JOIN Organization AS o ON Person.org_id = o.id JOIN Person ON Person.org_id = o.id' => false,
  366. 'SELECT Person AS p JOIN Location AS l ON p.location_id = l.id' => true,
  367. 'SELECT Person AS p JOIN Location AS l ON p.location_id BELOW l.id' => false,
  368. 'SELECT Person FROM Person JOIN Location ON Person.location_id = Location.id' => true,
  369. 'SELECT p FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => true,
  370. 'SELECT l FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => true,
  371. 'SELECT l, p FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => true,
  372. 'SELECT p, l FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => true,
  373. 'SELECT foo FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => false,
  374. 'SELECT p, foo FROM Person AS p JOIN Location AS l ON p.location_id = l.id' => false,
  375. // Joins based on AttributeObjectKey
  376. //
  377. 'SELECT Attachment AS a JOIN UserRequest AS r ON a.item_id = r.id' => true,
  378. 'SELECT UserRequest AS r JOIN Attachment AS a ON a.item_id = r.id' => true,
  379. );
  380. $iErrors = 0;
  381. foreach($aQueries as $sQuery => $bIsCorrectQuery)
  382. {
  383. $sIsOk = $bIsCorrectQuery ? 'good' : 'bad';
  384. echo "<h4>Testing query: $sQuery ($sIsOk)</h4>\n";
  385. try
  386. {
  387. $bRet = $this->TestQuery($sQuery, $bIsCorrectQuery);
  388. }
  389. catch(Exception $e)
  390. {
  391. $this->m_aErrors[] = $e->getMessage();
  392. $bRet = false;
  393. }
  394. if (!$bRet) $iErrors++;
  395. }
  396. return ($iErrors == 0);
  397. }
  398. }
  399. class TestCSVParser extends TestFunction
  400. {
  401. static public function GetName() {return 'Check CSV parsing';}
  402. static public function GetDescription() {return 'Loads a set of CSV data';}
  403. public function DoExecute()
  404. {
  405. $sDataFile = '?field1?;?field2?;?field3?
  406. ?a?;?b?;?c?
  407. a;b;c
  408. ? a ? ; ? b ? ; ? c ?
  409. a ; b ; c
  410. ??;??;??
  411. ;;
  412. ?a"?;?b?;?c?
  413. ?a1
  414. a2?;?b?;?c?
  415. ?a1,a2?;?b?;?c?
  416. ?a?;?b?;?c1,",c2
  417. ,c3?
  418. ?a?;?b?;?ouf !?
  419. Espace sur la fin ; 1234; e@taloc.com ';
  420. self::DumpVariable($sDataFile);
  421. $aExpectedResult = array(
  422. //array('field1', 'field2', 'field3'),
  423. array('a', 'b', 'c'),
  424. array('a', 'b', 'c'),
  425. array(' a ', ' b ', ' c '),
  426. array('a', 'b', 'c'),
  427. array('', '', ''),
  428. array('', '', ''),
  429. array('a"', 'b', 'c'),
  430. array("a1\na2", 'b', 'c'),
  431. array('a1,a2', 'b', 'c'),
  432. array('a', 'b', "c1,\",c2\n,c3"),
  433. array('a', 'b', 'ouf !'),
  434. array('Espace sur la fin', '1234', 'e@taloc.com'),
  435. );
  436. $oCSVParser = new CSVParser($sDataFile, ';', '?');
  437. $aData = $oCSVParser->ToArray(1, null, 0);
  438. $iIssues = 0;
  439. echo "<table border=\"1\">\n";
  440. foreach ($aData as $iRow => $aRow)
  441. {
  442. echo "<tr>\n";
  443. foreach ($aRow as $iCol => $sCell)
  444. {
  445. if (empty($sCell))
  446. {
  447. $sCellValue = '&nbsp;';
  448. }
  449. else
  450. {
  451. $sCellValue = htmlentities($sCell, ENT_QUOTES, 'UTF-8');
  452. }
  453. if (!isset($aExpectedResult[$iRow][$iCol]))
  454. {
  455. $iIssues++;
  456. $sCellValue = "<span style =\"color: red; background-color: grey;\">$sCellValue</span>";
  457. }
  458. elseif ($aExpectedResult[$iRow][$iCol] != $sCell)
  459. {
  460. $iIssues++;
  461. $sCellValue = "<span style =\"color: red; background-color: lightgrey;\">$sCellValue</span>, expecting '<span style =\"color: green; background-color: lightgrey;\">".$aExpectedResult[$iRow][$iCol]."</span>'";
  462. }
  463. echo "<td><pre>$sCellValue</pre></td>";
  464. }
  465. echo "</tr>\n";
  466. }
  467. echo "</table>\n";
  468. return ($iIssues > 0);
  469. }
  470. }
  471. class TestGenericItoMyModel extends TestBizModelGeneric
  472. {
  473. static public function GetName()
  474. {
  475. return 'Generic RO test on '.self::GetConfigFile();
  476. }
  477. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  478. }
  479. class TestGenericItopBigModel extends TestBizModelGeneric
  480. {
  481. static public function GetName()
  482. {
  483. return 'Generic RO test on '.self::GetConfigFile();
  484. }
  485. static public function GetConfigFile() {return '/config-test-itopv06.php';}
  486. }
  487. class TestUserRightsMatrixItop extends TestUserRights
  488. {
  489. static public function GetName()
  490. {
  491. return 'User rights test on user rights matrix';
  492. }
  493. static public function GetDescription()
  494. {
  495. return 'blah blah blah';
  496. }
  497. public function DoPrepare()
  498. {
  499. parent::DoPrepare();
  500. MetaModel::Startup('../config-test-itopv06.php');
  501. }
  502. protected function DoExecute()
  503. {
  504. $sUser = 'Romain';
  505. echo "<p>Totor: ".(UserRights::CheckCredentials('Totor', 'toto') ? 'ok' : 'NO')."</p>\n";
  506. echo "<p>Romain: ".(UserRights::CheckCredentials('Romain', 'toto') ? 'ok' : 'NO')."</p>\n";
  507. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  508. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  509. echo "<p>Denis (impersonate) : ".(UserRights::Impersonate('Denis', 'tutu') ? 'ok' : 'NO')."</p>\n";
  510. echo "<p>User: ".UserRights::GetUser()."</p>\n";
  511. echo "<p>On behalf of...".UserRights::GetRealUser()."</p>\n";
  512. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT bizOrganization"));
  513. echo "<p>IsActionAllowed...".(UserRights::IsActionAllowed('bizOrganization', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  514. echo "<p>IsStimulusAllowed...".(UserRights::IsStimulusAllowed('bizOrganization', 'myStimulus', $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  515. echo "<p>IsActionAllowedOnAttribute...".(UserRights::IsActionAllowedOnAttribute('bizOrganization', 'myattribute', UR_ACTION_MODIFY, $oSet) == UR_ALLOWED_YES ? 'ok' : 'NO')."</p>\n";
  516. return true;
  517. }
  518. }
  519. ///////////////////////////////////////////////////////////////////////////
  520. // Test a complex biz model on the fly
  521. ///////////////////////////////////////////////////////////////////////////
  522. class TestMyBizModel extends TestBizModel
  523. {
  524. static public function GetName()
  525. {
  526. return 'A series of tests on a weird business model';
  527. }
  528. static public function GetDescription()
  529. {
  530. return 'Attempts various operations and build complex queries';
  531. }
  532. static public function GetConfigFile() {return '/config-test-mymodel.php';}
  533. function test_linksinfo()
  534. {
  535. echo "<h4>Enum links</h4>";
  536. self::DumpVariable(MetaModel::EnumReferencedClasses("cmdbTeam"));
  537. self::DumpVariable(MetaModel::EnumReferencingClasses("Organization"));
  538. self::DumpVariable(MetaModel::EnumLinkingClasses());
  539. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdbContact"));
  540. self::DumpVariable(MetaModel::EnumLinkingClasses("cmdWorkshop"));
  541. self::DumpVariable(MetaModel::GetLinkLabel("Liens_entre_contacts_et_workshop", "toworkshop"));
  542. }
  543. function test_list_attributes()
  544. {
  545. echo "<h4>List attributes</h4>";
  546. foreach(MetaModel::ListAttributeDefs("cmdbTeam") as $sAttCode=>$oAttDef)
  547. {
  548. echo $oAttDef->GetLabel()." / ".$oAttDef->GetDescription()." / ".$oAttDef->GetType()."</br>\n";
  549. }
  550. }
  551. function test_search()
  552. {
  553. echo "<h4>Two searches</h4>";
  554. $oFilterAllDevs = new DBObjectSearch("cmdbTeam");
  555. $oAllDevs = new DBObjectSet($oFilterAllDevs);
  556. echo "Found ".$oAllDevs->Count()." items.</br>\n";
  557. while ($oDev = $oAllDevs->Fetch())
  558. {
  559. $aValues = array();
  560. foreach(MetaModel::GetAttributesList($oAllDevs->GetClass()) as $sAttCode)
  561. {
  562. $aValues[] = MetaModel::GetLabel(get_class($oDev), $sAttCode)." (".MetaModel::GetDescription(get_class($oDev), $sAttCode).") = ".$oDev->GetAsHTML($sAttCode);
  563. }
  564. echo $oDev->GetKey()." => ".implode(", ", $aValues)."</br>\n";
  565. }
  566. // a second one
  567. $oMyFilter = new DBObjectSearch("cmdbContact");
  568. //$oMyFilter->AddCondition("name", "aii", "Finishes with");
  569. $oMyFilter->AddCondition("name", "aii");
  570. $this->search_and_show_list($oMyFilter);
  571. }
  572. function test_reload()
  573. {
  574. echo "<h4>Reload</h4>";
  575. $team = MetaModel::GetObject("cmdbContact", "2");
  576. echo "Chargement de l'attribut headcount: {$team->Get("headcount")}</br>\n";
  577. self::DumpVariable($team);
  578. }
  579. function test_setattribute()
  580. {
  581. echo "<h4>Set attribute and update</h4>";
  582. $team = MetaModel::GetObject("cmdbTeam", "2");
  583. $team->Set("headcount", rand(1,1000));
  584. $team->Set("email", "Luis ".rand(9,250));
  585. self::DumpVariable($team->ListChanges());
  586. echo "New headcount = {$team->Get("headcount")}</br>\n";
  587. echo "Computed name = {$team->Get("name")}</br>\n";
  588. $oMyChange = MetaModel::NewObject("CMDBChange");
  589. $oMyChange->Set("date", time());
  590. $oMyChange->Set("userinfo", "test_setattribute / Made by robot #".rand(1,100));
  591. $iChangeId = $oMyChange->DBInsert();
  592. //DBSearch::StartDebugQuery();
  593. $team->DBUpdateTracked($oMyChange);
  594. //DBSearch::StopDebugQuery();
  595. echo "<h4>Check the modified team</h4>";
  596. $oTeam = MetaModel::GetObject("cmdbTeam", "2");
  597. self::DumpVariable($oTeam);
  598. }
  599. function test_newobject()
  600. {
  601. $oMyChange = MetaModel::NewObject("CMDBChange");
  602. $oMyChange->Set("date", time());
  603. $oMyChange->Set("userinfo", "test_newobject / Made by robot #".rand(1,100));
  604. $iChangeId = $oMyChange->DBInsert();
  605. echo "<h4>Create a new object (team)</h4>";
  606. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  607. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  608. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  609. $oNewTeam->Set("email", null);
  610. $oNewTeam->Set("owner", "ITOP");
  611. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  612. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  613. echo "Created new team: $iId</br>";
  614. echo "<h4>Delete team #$iId</h4>";
  615. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  616. $oTeam->DBDeleteTracked($oMyChange);
  617. echo "Deleted team: $iId</br>";
  618. self::DumpVariable($oTeam);
  619. }
  620. function test_updatecolumn()
  621. {
  622. $oMyChange = MetaModel::NewObject("CMDBChange");
  623. $oMyChange->Set("date", time());
  624. $oMyChange->Set("userinfo", "test_updatecolumn / Made by robot #".rand(1,100));
  625. $iChangeId = $oMyChange->DBInsert();
  626. $sNewEmail = "updatecol".rand(9,250)."@quedlaballe.com";
  627. echo "<h4>Update a the email: set to '$sNewEmail'</h4>";
  628. $oMyFilter = new DBObjectSearch("cmdbContact");
  629. $oMyFilter->AddCondition("name", "o", "Contains");
  630. echo "Candidates before:</br>";
  631. $this->search_and_show_list($oMyFilter);
  632. MetaModel::BulkUpdateTracked($oMyChange, $oMyFilter, array("email" => $sNewEmail));
  633. echo "Candidates after:</br>";
  634. $this->search_and_show_list($oMyFilter);
  635. }
  636. function test_error()
  637. {
  638. trigger_error("Stop requested", E_USER_ERROR);
  639. }
  640. function test_changetracking()
  641. {
  642. echo "<h4>Create a change</h4>";
  643. $oMyChange = MetaModel::NewObject("CMDBChange");
  644. $oMyChange->Set("date", time());
  645. $oMyChange->Set("userinfo", "Made by robot #".rand(1,100));
  646. $iChangeId = $oMyChange->DBInsert();
  647. echo "Created new change: $iChangeId</br>";
  648. self::DumpVariable($oMyChange);
  649. echo "<h4>Create a new object (team)</h4>";
  650. $oNewTeam = MetaModel::NewObject("cmdbTeam");
  651. $oNewTeam->Set("name", "ekip2choc #".rand(1000, 2000));
  652. $oNewTeam->Set("email", "machin".rand(1,100)."@tnut.com");
  653. $oNewTeam->Set("email", null);
  654. $oNewTeam->Set("owner", "ITOP");
  655. $oNewTeam->Set("headcount", "0".rand(38000, 38999)); // should be reset to an int value
  656. $iId = $oNewTeam->DBInsertTracked($oMyChange);
  657. echo "Created new team: $iId</br>";
  658. echo "<h4>Delete team #$iId</h4>";
  659. $oTeam = MetaModel::GetObject("cmdbTeam", $iId);
  660. $oTeam->DBDeleteTracked($oMyChange);
  661. echo "Deleted team: $iId</br>";
  662. self::DumpVariable($oTeam);
  663. }
  664. function test_zlist()
  665. {
  666. echo "<h4>Test ZLists</h4>";
  667. $aZLists = MetaModel::EnumZLists();
  668. foreach ($aZLists as $sListCode)
  669. {
  670. $aListInfos = MetaModel::GetZListInfo($sListCode);
  671. echo "<h4>List '".$sListCode."' (".$aListInfos["description"].") of type '".$aListInfos["type"]."'</h5>\n";
  672. foreach (MetaModel::GetSubclasses("cmdbObjectHomeMade") as $sKlass)
  673. {
  674. $aItems = MetaModel::FlattenZlist(MetaModel::GetZListItems($sKlass, $sListCode));
  675. if (count($aItems) == 0) continue;
  676. echo "$sKlass - $sListCode : {".implode(", ", $aItems)."}</br>\n";
  677. }
  678. }
  679. echo "<h4>IsAttributeInZList()... </h4>";
  680. echo "Liens_entre_contacts_et_workshop::ws_info in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "ws_info") ? "yes" : "no")."</br>\n";
  681. echo "Liens_entre_contacts_et_workshop::toworkshop in list1 ? ".(MetaModel::IsAttributeInZList("Liens_entre_contacts_et_workshop", "list1", "toworkshop") ? "yes" : "no")."</br>\n";
  682. }
  683. function test_pkey()
  684. {
  685. echo "<h4>Test search on pkey</h4>";
  686. $sExpr1 = "SELECT cmdbContact WHERE id IN (40, 42)";
  687. $sExpr2 = "SELECT cmdbContact WHERE IN NOT IN (40, 42)";
  688. $this->search_and_show_list_from_oql($sExpr1);
  689. $this->search_and_show_list_from_oql($sExpr2);
  690. echo "Et maintenant, on fusionne....</br>\n";
  691. $oSet1 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr1));
  692. $oSet2 = new CMDBObjectSet(DBObjectSearch::FromOQL($sExpr2));
  693. $oIntersect = $oSet1->CreateIntersect($oSet2);
  694. $oDelta = $oSet1->CreateDelta($oSet2);
  695. $oMerge = clone $oSet1;
  696. $oAppend->Append($oSet2);
  697. $oAppend->Append($oSet2);
  698. echo "Set1 - Found ".$oSet1->Count()." items.</br>\n";
  699. echo "Set2 - Found ".$oSet2->Count()." items.</br>\n";
  700. echo "Intersect - Found ".$oIntersect->Count()." items.</br>\n";
  701. echo "Delta - Found ".$oDelta->Count()." items.</br>\n";
  702. echo "Append - Found ".$oAppend->Count()." items.</br>\n";
  703. //$this->show_list($oObjSet);
  704. }
  705. function test_relations()
  706. {
  707. echo "<h4>Test relations</h4>";
  708. //self::DumpVariable(MetaModel::EnumRelationQueries("cmdbObjectHomeMade", "Potes"));
  709. self::DumpVariable(MetaModel::EnumRelationQueries("cmdbContact", "Potes"));
  710. $iMaxDepth = 9;
  711. echo "Max depth = $iMaxDepth</br>\n";
  712. $oObj = MetaModel::GetObject("cmdbContact", 18);
  713. $aRels = $oObj->GetRelatedObjects("Potes", $iMaxDepth);
  714. echo $oObj->Get('name')." has some 'Potes'...</br>\n";
  715. foreach ($aRels as $sClass => $aObjs)
  716. {
  717. echo "$sClass, count = ".count($aObjs)." =&gt; ".implode(', ', array_keys($aObjs))."</br>\n";
  718. $oObjectSet = CMDBObjectSet::FromArray($sClass, $aObjs);
  719. $this->show_list($oObjectSet);
  720. }
  721. echo "<h4>Test relations - same results, by the mean of a OQL</h4>";
  722. $this->search_and_show_list_from_oql("cmdbContact: RELATED (Potes, $iMaxDepth) TO (cmdbContact: pkey = 18)");
  723. }
  724. function test_linkedset()
  725. {
  726. echo "<h4>Linked set attributes</h4>\n";
  727. $oObj = MetaModel::GetObject("cmdbContact", 18);
  728. echo "<h5>Current workshops</h5>\n";
  729. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  730. $this->show_list($oSetWorkshopsCurr);
  731. echo "<h5>Setting workshops</h5>\n";
  732. $oNewLink = new cmdbLiens();
  733. $oNewLink->Set('toworkshop', 2);
  734. $oNewLink->Set('function', 'mafonctioooon');
  735. $oNewLink->Set('a1', 'tralala1');
  736. $oNewLink->Set('a2', 'F7M');
  737. $oSetWorkshops = CMDBObjectSet::FromArray("cmdbLiens", array($oNewLink));
  738. $oObj->Set("myworkshops", $oSetWorkshops);
  739. $this->show_list($oSetWorkshops);
  740. echo "<h5>New workshops</h5>\n";
  741. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  742. $this->show_list($oSetWorkshopsCurr);
  743. $oMyChange = MetaModel::NewObject("CMDBChange");
  744. $oMyChange->Set("date", time());
  745. $oMyChange->Set("userinfo", "test_linkedset / Made by robot #".rand(1,100));
  746. $iChangeId = $oMyChange->DBInsert();
  747. $oObj->DBUpdateTracked($oMyChange);
  748. $oObj = MetaModel::GetObject("cmdbContact", 18);
  749. echo "<h5>After the write</h5>\n";
  750. $oSetWorkshopsCurr = $oObj->Get("myworkshops");
  751. $this->show_list($oSetWorkshopsCurr);
  752. }
  753. function test_object_lifecycle()
  754. {
  755. echo "<h4>Test object lifecycle</h4>";
  756. self::DumpVariable(MetaModel::GetStateAttributeCode("cmdbContact"));
  757. self::DumpVariable(MetaModel::EnumStates("cmdbContact"));
  758. self::DumpVariable(MetaModel::EnumStimuli("cmdbContact"));
  759. foreach(MetaModel::EnumStates("cmdbContact") as $sStateCode => $aStateDef)
  760. {
  761. echo "<p>Transition from <strong>$sStateCode</strong></p>\n";
  762. self::DumpVariable(MetaModel::EnumTransitions("cmdbContact", $sStateCode));
  763. }
  764. $oObj = MetaModel::GetObject("cmdbContact", 18);
  765. echo "Current state: ".$oObj->GetState()."... let's go to school...";
  766. self::DumpVariable($oObj->EnumTransitions());
  767. $oObj->ApplyStimulus("toschool");
  768. echo "New state: ".$oObj->GetState()."... let's get older...";
  769. self::DumpVariable($oObj->EnumTransitions());
  770. $oObj->ApplyStimulus("raise");
  771. echo "New state: ".$oObj->GetState()."... let's try to go further... (should give an error)";
  772. self::DumpVariable($oObj->EnumTransitions());
  773. $oObj->ApplyStimulus("raise"); // should give an error
  774. }
  775. protected function DoExecute()
  776. {
  777. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  778. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  779. //$this->test_linksinfo();
  780. //$this->test_list_attributes();
  781. //$this->test_search();
  782. //$this->test_reload();
  783. //$this->test_newobject();
  784. $this->test_setattribute();
  785. //$this->test_updatecolumn();
  786. //$this->test_error();
  787. //$this->test_changetracking();
  788. $this->test_zlist();
  789. $this->test_OQL();
  790. //$this->test_pkey();
  791. $this->test_relations();
  792. $this->test_linkedset();
  793. $this->test_object_lifecycle();
  794. }
  795. }
  796. ///////////////////////////////////////////////////////////////////////////
  797. // Test a complex biz model on the fly
  798. ///////////////////////////////////////////////////////////////////////////
  799. abstract class MyFarm extends TestBizModel
  800. {
  801. static public function GetConfigFile() {return '/config-test-farm.php';}
  802. protected function DoPrepare()
  803. {
  804. parent::DoPrepare();
  805. $this->ResetDB();
  806. MetaModel::DBCheckIntegrity();
  807. }
  808. protected function InsertMammal($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $sName, $iHeight, $sBirth)
  809. {
  810. $oNew = MetaModel::NewObject('Mammal');
  811. $oNew->Set('species', $sSpecies);
  812. $oNew->Set('sex', $sSex);
  813. $oNew->Set('speed', $iSpeed);
  814. $oNew->Set('mother', $iMotherid);
  815. $oNew->Set('father', $iFatherId);
  816. $oNew->Set('name', $sName);
  817. $oNew->Set('height', $iHeight);
  818. $oNew->Set('birth', $sBirth);
  819. return $this->ObjectToDB($oNew);
  820. }
  821. protected function InsertBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId)
  822. {
  823. $oNew = MetaModel::NewObject('Bird');
  824. $oNew->Set('species', $sSpecies);
  825. $oNew->Set('sex', $sSex);
  826. $oNew->Set('speed', $iSpeed);
  827. $oNew->Set('mother', $iMotherid);
  828. $oNew->Set('father', $iFatherId);
  829. return $this->ObjectToDB($oNew);
  830. }
  831. protected function InsertFlyingBird($sSpecies, $sSex, $iSpeed, $iMotherid, $iFatherId, $iFlyingSpeed)
  832. {
  833. $oNew = MetaModel::NewObject('FlyingBird');
  834. $oNew->Set('species', $sSpecies);
  835. $oNew->Set('sex', $sSex);
  836. $oNew->Set('speed', $iSpeed);
  837. $oNew->Set('mother', $iMotherid);
  838. $oNew->Set('father', $iFatherId);
  839. $oNew->Set('flyingspeed', $iFlyingSpeed);
  840. return $this->ObjectToDB($oNew);
  841. }
  842. private function InsertGroup($sName, $iLeaderId)
  843. {
  844. $oNew = MetaModel::NewObject('Group');
  845. $oNew->Set('name', $sName);
  846. $oNew->Set('leader', $iLeaderId);
  847. $iId = $oNew->DBInsertNoReload();
  848. return $iId;
  849. }
  850. }
  851. class TestQueriesOnFarm extends MyFarm
  852. {
  853. static public function GetName()
  854. {
  855. return 'Farm test';
  856. }
  857. static public function GetDescription()
  858. {
  859. return 'A series of tests on the farm business model (SQL generation)';
  860. }
  861. protected function CheckQuery($sQuery, $bIsCorrectQuery)
  862. {
  863. if ($bIsCorrectQuery)
  864. {
  865. echo "<h4 style=\"color:green;\">$sQuery</h4>\n";
  866. }
  867. else
  868. {
  869. echo "<h4 style=\"color:red;\">$sQuery</h3>\n";
  870. }
  871. try
  872. {
  873. //$oOql = new OqlInterpreter($sQuery);
  874. //$oTrash = $oOql->ParseQuery();
  875. //self::DumpVariable($oTrash, true);
  876. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  877. }
  878. catch (OQLException $oOqlException)
  879. {
  880. if ($bIsCorrectQuery)
  881. {
  882. echo "<p>More info on this unexpected failure:<br/>".$oOqlException->getHtmlDesc()."</p>\n";
  883. throw $oOqlException;
  884. return false;
  885. }
  886. else
  887. {
  888. // Everything is fine :-)
  889. echo "<p>More info on this expected failure:\n";
  890. echo "<ul>\n";
  891. echo "<li>".get_class($oOqlException)."</li>\n";
  892. echo "<li>".$oOqlException->getMessage()."</li>\n";
  893. echo "<li>".$oOqlException->getHtmlDesc()."</li>\n";
  894. echo "</ul>\n";
  895. echo "</p>\n";
  896. return true;
  897. }
  898. }
  899. // The query was correctly parsed, was it expected to be correct ?
  900. if (!$bIsCorrectQuery)
  901. {
  902. throw new UnitTestException("The query '$sQuery' was parsed with success, while it shouldn't (?)");
  903. return false;
  904. }
  905. echo "<p>To OQL: ".$oMyFilter->ToOQL()."</p>";
  906. $this->search_and_show_list($oMyFilter);
  907. //echo "<p>first pass<p>\n";
  908. //self::DumpVariable($oMyFilter, true);
  909. $sQuery1 = $oMyFilter->MakeSelectQuery();
  910. //echo "<p>second pass<p>\n";
  911. //self::DumpVariable($oMyFilter, true);
  912. //$sQuery1 = $oMyFilter->MakeSelectQuery();
  913. $sSerialize = $oMyFilter->serialize();
  914. echo "<p>Serialized:$sSerialize</p>\n";
  915. $oFilter2 = DBObjectSearch::unserialize($sSerialize);
  916. try
  917. {
  918. $sQuery2 = $oMyFilter2->MakeSelectQuery();
  919. }
  920. catch (Exception $e)
  921. {
  922. echo "<p>Could not compute the query after unserialize</p>\n";
  923. echo "<p>Query 1: $sQuery1</p>\n";
  924. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  925. throw $e;
  926. }
  927. //if ($oFilter2 != $oMyFilter) no, they may differ while the resulting query is the same!
  928. if ($sQuery1 != $sQuery2)
  929. {
  930. echo "<p>serialize/unserialize mismatch :-(</p>\n";
  931. MyHelpers::var_cmp_html($sQuery1, $sQuery2);
  932. MyHelpers::var_cmp_html($oMyFilter, $oFilter2);
  933. return false;
  934. }
  935. return true;
  936. }
  937. protected function DoExecute()
  938. {
  939. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  940. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  941. echo "<h3>Create protagonists...</h3>";
  942. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  943. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  944. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  945. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  946. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  947. $this->InsertBird('rooster', 'male', 12, 0, 0);
  948. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  949. // Benchmarking
  950. //
  951. if (false)
  952. {
  953. define ('COUNT_BENCHMARK', 10);
  954. echo "<h3>Parsing a long query, ".COUNT_BENCHMARK." times</h3>";
  955. $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)";
  956. $fStart = MyHelpers::getmicrotime();
  957. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  958. {
  959. $oMyFilter = DBObjectSearch::FromOQL($sQuery);
  960. }
  961. $fDuration = MyHelpers::getmicrotime() - $fStart;
  962. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  963. echo "<p>Mean time by op: $fParsingDuration</p>";
  964. }
  965. echo "<h3>Test queries...</h3>";
  966. $aQueries = array(
  967. 'SELECT Animal' => true,
  968. 'SELECT Animal WHERE Animal.pkey = 1' => false,
  969. 'SELECT Animal WHERE Animal.id = 1' => true,
  970. 'SELECT Aniiimal' => false,
  971. 'SELECTe Animal' => false,
  972. 'SELECT * FROM Animal' => false,
  973. 'SELECT Animal AS zoo WHERE zoo.species = \'human\'' => true,
  974. 'SELECT Animal AS zoo WHERE species = \'human\'' => true,
  975. 'SELECT Animal AS zoo WHERE espece = \'human\'' => false,
  976. 'SELECT Animal AS zoo WHERE zoo.species IN (\'human\', "pig")' => true,
  977. 'SELECT Animal AS zoo WHERE CONCATENATION(zoo.species, zoo.sex) LIKE "hum%male"' => false,
  978. 'SELECT Animal AS zoo WHERE CONCAT(zoo.species, zoo.sex) LIKE "hum%male"' => true,
  979. 'SELECT Animal AS zoo WHERE zoo.species NOT IN (\'human\', "pig")' => true,
  980. 'SELECT Animal AS zoo WHERE zoo.kind = \'human\'' => false,
  981. 'SELECT Animal WHERE Animal.species = \'human\' AND Animal.sex = \'female\'' => true,
  982. 'SELECT Mammal AS x WHERE (x.species = \'human\' AND x.name LIKE \'ro%\') OR (x.species = \'donkey\' AND x.name LIKE \'po%\')' => true,
  983. 'SELECT Mammal AS x WHERE x.species = \'human\' AND x.name LIKE \'ro%\' OR x.species = \'donkey\' AND x.name LIKE \'po%\'' => true,
  984. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  985. 'SELECT Mammal AS m WHERE DAY(m.birth) = 19' => true,
  986. 'SELECT Mammal AS m WHERE YEAR(m.birth) = 1971' => true,
  987. 'SELECT Mammal AS m WHERE m.birth < DATE_SUB(CURRENT_DATE(), INTERVAL 10 YEAR)' => true,
  988. 'SELECT Mammal AS m WHERE m.birth > DATE_SUB(NOW(), INTERVAL 2000 DAY)' => true,
  989. 'SELECT Mammal AS m WHERE (TO_DAYS(NOW()) - TO_DAYS(m.birth)) > 2000' => true,
  990. 'SELECT Mammal AS m WHERE m.name = IF(FLOOR(ROUND(m.height)) > 2, "pomme", "romain")' => true,
  991. 'SELECT Mammal AS m WHERE (1 + 2' => false,
  992. 'SELECT Mammal AS m WHERE (1 + 2 * 4 / 23) > 0' => true,
  993. 'SELECT Mammal AS m WHERE (4 / 23 * 2 + 1) > 0' => true,
  994. 'SELECT Mammal AS m WHERE 1/0' => true,
  995. 'SELECT Mammal AS m WHERE MONTH(m.birth) = 7' => true,
  996. 'SELECT Animal JOIN Group ON Group.leader = Animal.id' => true,
  997. 'SELECT Group JOIN Animal ON Group.leader = Animal.id' => true,
  998. 'SELECT Animal AS A JOIN Group AS G1 ON G1.leader = A.id' => true,
  999. 'SELECT Animal AS A JOIN Group AS G ON FooClass.leader = A.id' => false,
  1000. 'SELECT Animal AS A JOIN Group AS G ON G.leader = FooClass.id' => false,
  1001. 'SELECT Animal AS A JOIN Group AS G ON G.masterchief = A.id' => false,
  1002. 'SELECT Animal AS A JOIN Group AS G ON A.id = G.leader' => false,
  1003. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.qwerty = 123' => false,
  1004. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.sex=\'male\' OR G.name LIKE "a%"' => true,
  1005. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE A.id = 1' => true,
  1006. 'SELECT Animal AS A JOIN Group AS G ON G.leader = A.id WHERE id = 1' => false,
  1007. 'SELECT Animal AS A JOIN Group AS G ON A.member = G.id' => false,
  1008. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id' => true,
  1009. 'SELECT Mammal AS M JOIN Group AS G ON A.member = G.id' => false,
  1010. 'SELECT Mammal AS myAlias JOIN Group AS myAlias ON myAlias.member = myAlias.id' => false,
  1011. 'SELECT Mammal AS Mammal JOIN Group AS Mammal ON Mammal.member = Mammal.id' => false,
  1012. 'SELECT Group AS G WHERE G.leader_name LIKE "%"' => true,
  1013. 'SELECT Group AS G WHERE G.leader_speed < 100000' => true,
  1014. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  1015. 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_speed < 100000' => true,
  1016. 'SELECT Mammal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  1017. 'SELECT Mammal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  1018. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  1019. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id' => true,
  1020. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id' => true,
  1021. 'SELECT Animal AS Child JOIN Animal AS Dad ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  1022. '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,
  1023. '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,
  1024. 'SELECT Animal AS Child JOIN Mammal AS Dad ON Child.father = Dad.id' => true,
  1025. '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,
  1026. 'SELECT Animal AS Dad JOIN Animal AS Child ON Child.father = Dad.id JOIN Animal AS Mum ON Child.mother = Mum.id' => true,
  1027. 'SELECT Mammal AS Dad JOIN Mammal AS Child ON Child.father = Dad.id' => true,
  1028. '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,
  1029. // Specifying multiple objects
  1030. 'SELECT Animal FROM Animal' => true,
  1031. 'SELECT yelele FROM Animal' => false,
  1032. 'SELECT Animal FROM Animal AS A' => false,
  1033. 'SELECT A FROM Animal AS A' => true,
  1034. );
  1035. //$aQueries = array(
  1036. // 'SELECT Mammal AS M JOIN Group AS G ON M.member = G.id WHERE G.leader_name LIKE "%"' => true,
  1037. //);
  1038. foreach($aQueries as $sQuery => $bIsCorrect)
  1039. {
  1040. $this->CheckQuery($sQuery, $bIsCorrect);
  1041. }
  1042. return true;
  1043. }
  1044. }
  1045. ///////////////////////////////////////////////////////////////////////////
  1046. // Test data load
  1047. ///////////////////////////////////////////////////////////////////////////
  1048. class TestBulkChangeOnFarm extends TestBizModel
  1049. {
  1050. static public function GetName()
  1051. {
  1052. return 'Farm test - data load';
  1053. }
  1054. static public function GetDescription()
  1055. {
  1056. return 'Bulk load';
  1057. }
  1058. static public function GetConfigFile() {return '/config-test-farm.php';}
  1059. protected function DoPrepare()
  1060. {
  1061. parent::DoPrepare();
  1062. $this->ResetDB();
  1063. MetaModel::DBCheckIntegrity();
  1064. }
  1065. protected function DoExecute()
  1066. {
  1067. // $this->ReportError("Found two different OQL expression out of the (same?) filter: <em>$sExpr1</em> != <em>$sExpr2</em>");
  1068. // $this->ReportSuccess('Found '.$oSet->Count()." objects of class $sClassName");
  1069. $oParser = new CSVParser("denomination,hauteur,age
  1070. suzy,123,2009-01-01
  1071. chita,456,
  1072. ", ',', '"');
  1073. $aData = $oParser->ToArray(1, array('_name', '_height', '_birth'));
  1074. self::DumpVariable($aData);
  1075. $oBulk = new BulkChange(
  1076. 'Mammal',
  1077. $aData,
  1078. // attributes
  1079. array('name' => '_name', 'height' => '_height', 'birth' => '_birth'),
  1080. // ext keys
  1081. array(),
  1082. // reconciliation
  1083. array('name')
  1084. );
  1085. $oMyChange = MetaModel::NewObject("CMDBChange");
  1086. $oMyChange->Set("date", time());
  1087. $oMyChange->Set("userinfo", "Testor");
  1088. $iChangeId = $oMyChange->DBInsert();
  1089. // echo "Created new change: $iChangeId</br>";
  1090. echo "<h3>Planned for loading...</h3>";
  1091. $aRes = $oBulk->Process();
  1092. self::DumpVariable($aRes);
  1093. echo "<h3>Go for loading...</h3>";
  1094. $aRes = $oBulk->Process($oMyChange);
  1095. self::DumpVariable($aRes);
  1096. return;
  1097. $oRawData = array(
  1098. 'Mammal',
  1099. array('species', 'sex', 'speed', 'mother', 'father', 'name', 'height', 'birth'),
  1100. "human,male,23,0,0,romulus,192,1971
  1101. human,male,23,0,0,remus,154,-50
  1102. human,male,23,0,0,julius,160,-49
  1103. human,female,23,0,0,cleopatra,142,-50
  1104. pig,female,23,0,0,confucius,50,2003"
  1105. );
  1106. }
  1107. }
  1108. ///////////////////////////////////////////////////////////////////////////
  1109. // Test data load
  1110. ///////////////////////////////////////////////////////////////////////////
  1111. class TestFullTextSearchOnFarm extends MyFarm
  1112. {
  1113. static public function GetName()
  1114. {
  1115. return 'Farm test - full text search';
  1116. }
  1117. static public function GetDescription()
  1118. {
  1119. return 'Focus on the full text search feature';
  1120. }
  1121. protected function DoExecute()
  1122. {
  1123. echo "<h3>Create protagonists...</h3>";
  1124. $iId1 = $this->InsertMammal('human', 'male', 10, 0, 0, 'romanoff', 192, '1971-07-19');
  1125. $iId2 = $this->InsertMammal('human', 'female', 9, 0, 0, 'rouanita', 165, '1983-01-23');
  1126. $this->InsertMammal('human', 'female', 3, $iId2, $iId1, 'pomme', 169, '2008-02-23');
  1127. $this->InsertMammal('pig', 'female', 3, 0, 0, 'grouinkette', 85, '2006-06-01');
  1128. $this->InsertMammal('donkey', 'female', 3, 0, 0, 'muleta', 124, '2003-11-11');
  1129. $this->InsertBird('rooster', 'male', 12, 0, 0);
  1130. $this->InsertFlyingBird('pie', 'female', 11, 0, 0, 35);
  1131. echo "<h3>Search...</h3>";
  1132. $oSearch = new DBObjectSearch('Mammal');
  1133. $oSearch->AddCondition_FullText('manof');
  1134. //$oResultSet = new DBObjectSet($oSearch);
  1135. $this->search_and_show_list($oSearch);
  1136. }
  1137. }
  1138. ///////////////////////////////////////////////////////////////////////////
  1139. // Test queries
  1140. ///////////////////////////////////////////////////////////////////////////
  1141. class TestItopEfficiency extends TestBizModel
  1142. {
  1143. static public function GetName()
  1144. {
  1145. return 'Itop - benchmark';
  1146. }
  1147. static public function GetDescription()
  1148. {
  1149. return 'Measure time to perform the queries';
  1150. }
  1151. protected function DoBenchmark($sOqlQuery)
  1152. {
  1153. echo "<h3>Testing query: $sOqlQuery</h3>";
  1154. $fStart = MyHelpers::getmicrotime();
  1155. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  1156. {
  1157. $oFilter = DBObjectSearch::FromOQL($sOqlQuery);
  1158. }
  1159. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1160. $fParsingDuration = $fDuration / COUNT_BENCHMARK;
  1161. $fStart = MyHelpers::getmicrotime();
  1162. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  1163. {
  1164. $sSQL = $oFilter->MakeSelectQuery();
  1165. }
  1166. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1167. $fBuildDuration = $fDuration / COUNT_BENCHMARK;
  1168. $fStart = MyHelpers::getmicrotime();
  1169. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  1170. {
  1171. $res = CMDBSource::Query($sSQL);
  1172. }
  1173. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1174. $fQueryDuration = $fDuration / COUNT_BENCHMARK;
  1175. // The fetch could not be repeated with the same results
  1176. // But we've seen so far that is was very very quick to exec
  1177. // So it makes sense to benchmark it a single time
  1178. $fStart = MyHelpers::getmicrotime();
  1179. $aRow = CMDBSource::FetchArray($res);
  1180. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1181. $fFetchDuration = $fDuration;
  1182. $fStart = MyHelpers::getmicrotime();
  1183. for($i=0 ; $i < COUNT_BENCHMARK ; $i++)
  1184. {
  1185. $sOql = $oFilter->ToOQL();
  1186. }
  1187. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1188. $fToOqlDuration = $fDuration / COUNT_BENCHMARK;
  1189. echo "<ul>\n";
  1190. echo "<li>Parsing: $fParsingDuration</li>\n";
  1191. echo "<li>Build: $fBuildDuration</li>\n";
  1192. echo "<li>Query: $fQueryDuration</li>\n";
  1193. echo "<li>Fetch: $fFetchDuration</li>\n";
  1194. echo "<li>ToOql: $fToOqlDuration</li>\n";
  1195. echo "</ul>\n";
  1196. // Everything but the ToOQL (wich is interesting, anyhow)
  1197. $fTotal = $fParsingDuration + $fBuildDuration + $fQueryDuration + $fFetchDuration;
  1198. return array(
  1199. 'rows' => CMDBSource::NbRows($res),
  1200. 'duration (s)' => round($fTotal, 4),
  1201. 'parsing (%)' => round(100 * $fParsingDuration / $fTotal, 1),
  1202. 'build SQL (%)' => round(100 * $fBuildDuration / $fTotal, 1),
  1203. 'query exec (%)' => round(100 * $fQueryDuration / $fTotal, 1),
  1204. 'fetch (%)' => round(100 * $fFetchDuration / $fTotal, 1),
  1205. 'to OQL (%)' => round(100 * $fToOqlDuration / $fTotal, 1),
  1206. 'parsing+build (%)' => round(100 * ($fParsingDuration + $fBuildDuration) / $fTotal, 1),
  1207. );
  1208. }
  1209. protected function DoExecute()
  1210. {
  1211. define ('COUNT_BENCHMARK', 3);
  1212. echo "<p>The test will be repeated ".COUNT_BENCHMARK." times</p>";
  1213. $aQueries = array(
  1214. 'SELECT CMDBChangeOpSetAttribute',
  1215. 'SELECT CMDBChangeOpSetAttribute WHERE id=10',
  1216. 'SELECT CMDBChangeOpSetAttribute WHERE id=123456789',
  1217. 'SELECT CMDBChangeOpSetAttribute WHERE CMDBChangeOpSetAttribute.id=10',
  1218. 'SELECT Ticket',
  1219. 'SELECT Ticket WHERE id=1',
  1220. 'SELECT Person',
  1221. 'SELECT Person WHERE id=1',
  1222. 'SELECT Server',
  1223. 'SELECT Server WHERE id=1',
  1224. 'SELECT Incident JOIN Person ON Incident.agent_id = Person.id WHERE Person.id = 5',
  1225. );
  1226. $aStats = array();
  1227. foreach ($aQueries as $sOQL)
  1228. {
  1229. $aStats[$sOQL] = $this->DoBenchmark($sOQL);
  1230. }
  1231. $aData = array();
  1232. foreach ($aStats as $sOQL => $aResults)
  1233. {
  1234. $aValues = array();
  1235. $aValues['OQL'] = htmlentities($sOQL, ENT_QUOTES, 'UTF-8');
  1236. foreach($aResults as $sDesc => $sInfo)
  1237. {
  1238. $aValues[$sDesc] = htmlentities($sInfo, ENT_QUOTES, 'UTF-8');
  1239. }
  1240. $aData[] = $aValues;
  1241. }
  1242. echo MyHelpers::make_table_from_assoc_array($aData);
  1243. }
  1244. }
  1245. ///////////////////////////////////////////////////////////////////////////
  1246. // Benchmark queries
  1247. ///////////////////////////////////////////////////////////////////////////
  1248. class TestQueries extends TestBizModel
  1249. {
  1250. static public function GetName()
  1251. {
  1252. return 'Itop - queries';
  1253. }
  1254. static public function GetDescription()
  1255. {
  1256. return 'Try as many queries as possible';
  1257. }
  1258. protected function DoBenchmark($sOqlQuery)
  1259. {
  1260. echo "<h5>Testing query: $sOqlQuery</h5>";
  1261. $fStart = MyHelpers::getmicrotime();
  1262. $oFilter = DBObjectSearch::FromOQL($sOqlQuery);
  1263. $fParsingDuration = MyHelpers::getmicrotime() - $fStart;
  1264. $fStart = MyHelpers::getmicrotime();
  1265. $sSQL = $oFilter->MakeSelectQuery();
  1266. $fBuildDuration = MyHelpers::getmicrotime() - $fStart;
  1267. $fStart = MyHelpers::getmicrotime();
  1268. $res = CMDBSource::Query($sSQL);
  1269. $fQueryDuration = MyHelpers::getmicrotime() - $fStart;
  1270. // The fetch could not be repeated with the same results
  1271. // But we've seen so far that is was very very quick to exec
  1272. // So it makes sense to benchmark it a single time
  1273. $fStart = MyHelpers::getmicrotime();
  1274. $aRow = CMDBSource::FetchArray($res);
  1275. $fDuration = MyHelpers::getmicrotime() - $fStart;
  1276. $fFetchDuration = $fDuration;
  1277. $fStart = MyHelpers::getmicrotime();
  1278. $sOql = $oFilter->ToOQL();
  1279. $fToOqlDuration = MyHelpers::getmicrotime() - $fStart;
  1280. if (false)
  1281. {
  1282. echo "<ul style=\"font-size:smaller;\">\n";
  1283. echo "<li>Parsing: $fParsingDuration</li>\n";
  1284. echo "<li>Build: $fBuildDuration</li>\n";
  1285. echo "<li>Query: $fQueryDuration</li>\n";
  1286. echo "<li>Fetch: $fFetchDuration</li>\n";
  1287. echo "<li>ToOql: $fToOqlDuration</li>\n";
  1288. echo "</ul>\n";
  1289. }
  1290. // Everything but the ToOQL (wich is interesting, anyhow)
  1291. $fTotal = $fParsingDuration + $fBuildDuration + $fQueryDuration + $fFetchDuration;
  1292. return array(
  1293. 'rows' => CMDBSource::NbRows($res),
  1294. 'duration (s)' => round($fTotal, 4),
  1295. 'parsing (%)' => round(100 * $fParsingDuration / $fTotal, 1),
  1296. 'build SQL (%)' => round(100 * $fBuildDuration / $fTotal, 1),
  1297. 'query exec (%)' => round(100 * $fQueryDuration / $fTotal, 1),
  1298. 'fetch (%)' => round(100 * $fFetchDuration / $fTotal, 1),
  1299. 'to OQL (%)' => round(100 * $fToOqlDuration / $fTotal, 1),
  1300. 'parsing+build (%)' => round(100 * ($fParsingDuration + $fBuildDuration) / $fTotal, 1),
  1301. );
  1302. }
  1303. protected function DoExecute()
  1304. {
  1305. $aQueries = array(
  1306. 'SELECT Person AS PP WHERE PP.friendlyname LIKE "%dali"',
  1307. 'SELECT Person AS PP WHERE PP.location_id_friendlyname LIKE "%ce ch%"',
  1308. 'SELECT Organization AS OO JOIN Person AS PP ON PP.org_id = OO.id',
  1309. 'SELECT lnkPersonToTeam AS lnk JOIN Team AS T ON lnk.team_id = T.id',
  1310. 'SELECT lnkPersonToTeam AS lnk JOIN Team AS T ON lnk.team_id = T.id JOIN Person AS p ON lnk.person_id = p.id',
  1311. 'SELECT UserRequest AS ur JOIN Person ON ur.agent_id = Person.id WHERE Person.id = 5',
  1312. // this one is failing...
  1313. //'SELECT L, P FROM Person AS P JOIN Location AS L ON P.location_id = L.id',
  1314. );
  1315. foreach (MetaModel::GetClasses() as $sClass)
  1316. {
  1317. $aQueries[] = 'SELECT '.$sClass;
  1318. $aQueries[] = 'SELECT '.$sClass.' AS zz';
  1319. $aQueries[] = 'SELECT '.$sClass.' AS zz WHERE id = 1';
  1320. }
  1321. $aStats = array();
  1322. foreach ($aQueries as $sOQL)
  1323. {
  1324. $aStats[$sOQL] = $this->DoBenchmark($sOQL);
  1325. }
  1326. $aData = array();
  1327. foreach ($aStats as $sOQL => $aResults)
  1328. {
  1329. $aValues = array();
  1330. $aValues['OQL'] = htmlentities($sOQL, ENT_QUOTES, 'UTF-8');
  1331. foreach($aResults as $sDesc => $sInfo)
  1332. {
  1333. $aValues[$sDesc] = htmlentities($sInfo, ENT_QUOTES, 'UTF-8');
  1334. }
  1335. $aData[] = $aValues;
  1336. }
  1337. echo MyHelpers::make_table_from_assoc_array($aData);
  1338. }
  1339. }
  1340. ///////////////////////////////////////////////////////////////////////////
  1341. // Check programmaticaly built queries
  1342. ///////////////////////////////////////////////////////////////////////////
  1343. class TestQueriesByAPI extends TestBizModel
  1344. {
  1345. static public function GetName()
  1346. {
  1347. return 'Itop - queries build programmaticaly';
  1348. }
  1349. static public function GetDescription()
  1350. {
  1351. return 'Validate the DBObjectSearch API, through a set of complex (though realistic cases)';
  1352. }
  1353. protected function DoExecute()
  1354. {
  1355. // Note: relying on eval() - after upgrading to PHP 5.3 we can move to closure (aka anonymous functions)
  1356. $aQueries = array(
  1357. 'Basic (validate the test)' => array(
  1358. 'search' => '
  1359. $oSearch = DBObjectSearch::FromOQL("SELECT P FROM Organization AS O JOIN Person AS P ON P.org_id = O.id WHERE org_id = 2");
  1360. ',
  1361. 'oql' => 'SELECT P FROM Organization AS O JOIN Person AS P ON P.org_id = O.id WHERE P.org_id = 2'
  1362. ),
  1363. 'Double constraint' => array(
  1364. 'search' => '
  1365. $oSearch = DBObjectSearch::FromOQL("SELECT Contact AS c");
  1366. $sClass = $oSearch->GetClass();
  1367. $sFilterCode = "org_id";
  1368. $oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
  1369. if ($oAttDef->IsExternalKey())
  1370. {
  1371. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
  1372. if ($sHierarchicalKeyCode !== false)
  1373. {
  1374. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass(), "ORGA");
  1375. $oFilter->AddCondition("id", 2);
  1376. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass(), "ORGA");
  1377. $oHKFilter->AddCondition_PointingTo(clone $oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
  1378. $oSearch->AddCondition_PointingTo(clone $oHKFilter, $sFilterCode);
  1379. $oFilter = new DBObjectSearch($oAttDef->GetTargetClass(), "ORGA");
  1380. $oFilter->AddCondition("id", 2);
  1381. $oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass(), "ORGA");
  1382. $oHKFilter->AddCondition_PointingTo(clone $oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW);
  1383. $oSearch->AddCondition_PointingTo(clone $oHKFilter, $sFilterCode);
  1384. }
  1385. }
  1386. ',
  1387. 'oql' => 'SELECT Contact AS C JOIN Organization ???'
  1388. ),
  1389. 'Simplified issue' => array(
  1390. 'search' => '
  1391. $oSearch = DBObjectSearch::FromOQL("SELECT P FROM Organization AS O JOIN Person AS P ON P.org_id = O.id WHERE O.id = 2");
  1392. $oOrgSearch = new DBObjectSearch("Organization", "O2");
  1393. $oOrgSearch->AddCondition("id", 2);
  1394. $oSearch->AddCondition_PointingTo($oOrgSearch, "org_id");
  1395. ',
  1396. 'oql' => 'SELECT P FROM Organization AS O JOIN Person AS P ON P.org_id = O.id JOIN Organization AS O2 ON P.org_id = O2.id WHERE O.id = 2 AND O2.id = 2'
  1397. ),
  1398. );
  1399. foreach ($aQueries as $sQueryDesc => $aQuerySpec)
  1400. {
  1401. echo "<h2>Query $sQueryDesc</h2>\n";
  1402. echo "<p>Using code: ".highlight_string("<?php\n".trim($aQuerySpec['search'])."\n?".'>', true)."</p>\n";
  1403. echo "<p>Expected OQL: ".$aQuerySpec['oql']."</p>\n";
  1404. if (isset($oSearch))
  1405. {
  1406. unset($oSearch);
  1407. }
  1408. eval($aQuerySpec['search']);
  1409. $sResOQL = $oSearch->ToOQL();
  1410. echo "<p>Resulting OQL: ".$sResOQL."</p>\n";
  1411. echo "<pre>";
  1412. print_r($oSearch);
  1413. echo "</pre>";
  1414. $sSQL = $oSearch->MakeSelectQuery();
  1415. $res = CMDBSource::Query($sSQL);
  1416. foreach (CMDBSource::ExplainQuery($sSQL) as $aRow)
  1417. {
  1418. }
  1419. }
  1420. // throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  1421. }
  1422. }
  1423. ///////////////////////////////////////////////////////////////////////////
  1424. // Test bulk load API
  1425. ///////////////////////////////////////////////////////////////////////////
  1426. class TestItopBulkLoad extends TestBizModel
  1427. {
  1428. static public function GetName()
  1429. {
  1430. return 'Itop - test BulkChange class';
  1431. }
  1432. static public function GetDescription()
  1433. {
  1434. return 'Execute a bulk change at the Core API level';
  1435. }
  1436. protected function DoExecute()
  1437. {
  1438. $sLogin = 'testbulkload_'.time();
  1439. $oParser = new CSVParser("login,contactid->name,password,profile_list
  1440. _1_$sLogin,Picasso,secret1,profileid:10;reason:service manager|profileid->name:Problem Manager;'reason:toto;problem manager'
  1441. _2_$sLogin,Picasso,secret2,
  1442. ", ',', '"');
  1443. $aData = $oParser->ToArray(1, array('_login', '_contact_name', '_password', '_profiles'));
  1444. self::DumpVariable($aData);
  1445. $oUser = new UserLocal();
  1446. $oUser->Set('login', 'patator');
  1447. $oUser->Set('password', 'patator');
  1448. //$oUser->Set('contactid', 0);
  1449. //$oUser->Set('language', $sLanguage);
  1450. $aProfiles = array(
  1451. array(
  1452. 'profileid' => 10, // Service Manager
  1453. 'reason' => 'service manager',
  1454. ),
  1455. array(
  1456. 'profileid->name' => 'Problem Manager',
  1457. 'reason' => 'problem manager',
  1458. ),
  1459. );
  1460. $oBulk = new BulkChange(
  1461. 'UserLocal',
  1462. $aData,
  1463. // attributes
  1464. array('login' => '_login', 'password' => '_password', 'profile_list' => '_profiles'),
  1465. // ext keys
  1466. array('contactid' => array('name' => '_contact_name')),
  1467. // reconciliation
  1468. array('login'),
  1469. // Synchro - scope
  1470. "SELECT UserLocal",
  1471. // Synchro - set attribute on missing objects
  1472. array ('password' => 'terminated', 'login' => 'terminated'.time())
  1473. );
  1474. if (false)
  1475. {
  1476. $oMyChange = MetaModel::NewObject("CMDBChange");
  1477. $oMyChange->Set("date", time());
  1478. $oMyChange->Set("userinfo", "Testor");
  1479. $iChangeId = $oMyChange->DBInsert();
  1480. // echo "Created new change: $iChangeId</br>";
  1481. }
  1482. echo "<h3>Planned for loading...</h3>";
  1483. $aRes = $oBulk->Process();
  1484. self::DumpVariable($aRes);
  1485. if (false)
  1486. {
  1487. echo "<h3>Go for loading...</h3>";
  1488. $aRes = $oBulk->Process($oMyChange);
  1489. self::DumpVariable($aRes);
  1490. }
  1491. return;
  1492. }
  1493. }
  1494. ///////////////////////////////////////////////////////////////////////////
  1495. // Test data load
  1496. ///////////////////////////////////////////////////////////////////////////
  1497. class TestImportREST extends TestWebServices
  1498. {
  1499. static public function GetName()
  1500. {
  1501. return 'CSV import (REST)';
  1502. }
  1503. static public function GetDescription()
  1504. {
  1505. return 'Test various options and fonctionality of import.php';
  1506. }
  1507. protected function DoExecSingleLoad($aLoadSpec, $iTestId = null)
  1508. {
  1509. $sCsvData = $aLoadSpec['csvdata'];
  1510. echo "<div style=\"padding: 10;\">\n";
  1511. if (is_null($iTestId))
  1512. {
  1513. echo "<h3 style=\"background-color: #ddddff; padding: 10;\">{$aLoadSpec['desc']}</h3>\n";
  1514. }
  1515. else
  1516. {
  1517. echo "<h3 style=\"background-color: #ddddff; padding: 10;\"><a href=\"?todo=exec&testid=TestImportREST&subtests=$iTestId\">$iTestId</a> - {$aLoadSpec['desc']}</h3>\n";
  1518. }
  1519. $aPostData = array('csvdata' => $sCsvData);
  1520. $aGetParams = array();
  1521. $aGetParamReport = array();
  1522. foreach($aLoadSpec['args'] as $sArg => $sValue)
  1523. {
  1524. $aGetParams[] = $sArg.'='.urlencode($sValue);
  1525. $aGetParamReport[] = $sArg.'='.$sValue;
  1526. }
  1527. $sGetParams = implode('&', $aGetParams);
  1528. $sLogin = isset($aLoadSpec['login']) ? $aLoadSpec['login'] : 'admin';
  1529. $sPassword = isset($aLoadSpec['password']) ? $aLoadSpec['password'] : 'admin';
  1530. $sRes = self::DoPostRequestAuth('../webservices/import.php?'.$sGetParams, $aPostData, $sLogin, $sPassword);
  1531. $sArguments = implode('<br/>', $aGetParamReport);
  1532. if (strlen($sCsvData) > 5000)
  1533. {
  1534. $sCsvDataViewable = 'INPUT TOO LONG TO BE DISPLAYED ('.strlen($sCsvData).")\n".substr($sCsvData, 0, 500)."\n... TO BE CONTINUED";
  1535. }
  1536. else
  1537. {
  1538. $sCsvDataViewable = $sCsvData;
  1539. }
  1540. echo "<div style=\"\">\n";
  1541. echo " <div style=\"float:left; width:20%; padding:5; background-color:#eeeeff;\">\n";
  1542. echo " $sArguments\n";
  1543. echo " </div>\n";
  1544. echo " <div style=\"float:right; width:75%; padding:5; background-color:#eeeeff\">\n";
  1545. echo " <pre class=\"vardump\">$sCsvDataViewable</pre>\n";
  1546. echo " </div>\n";
  1547. echo "</div>\n";
  1548. echo "<pre class=\"vardump\" style=\"clear: both; padding: 15; background-color: black; color: green;\">$sRes</pre>\n";
  1549. echo "</div>\n";
  1550. }
  1551. protected function DoExecute()
  1552. {
  1553. $aLoads = array(
  1554. array(
  1555. 'desc' => 'Missing class',
  1556. 'login' => 'admin',
  1557. 'password' => 'admin',
  1558. 'args' => array(
  1559. ),
  1560. 'csvdata' => "xxx",
  1561. ),
  1562. array(
  1563. 'desc' => 'Wrong class',
  1564. 'login' => 'admin',
  1565. 'password' => 'admin',
  1566. 'args' => array(
  1567. 'class' => 'toto',
  1568. ),
  1569. 'csvdata' => "xxx",
  1570. ),
  1571. array(
  1572. 'desc' => 'Wrong output type',
  1573. 'login' => 'admin',
  1574. 'password' => 'admin',
  1575. 'args' => array(
  1576. 'class' => 'NetworkDevice',
  1577. 'output' => 'onthefly',
  1578. ),
  1579. 'csvdata' => "xxx",
  1580. ),
  1581. array(
  1582. 'desc' => 'Weird format, working anyhow...',
  1583. 'login' => 'admin',
  1584. 'password' => 'admin',
  1585. 'args' => array(
  1586. 'class' => 'Server',
  1587. 'output' => 'details',
  1588. 'separator' => '*',
  1589. 'qualifier' => '@',
  1590. 'reconciliationkeys' => 'org_id,name',
  1591. ),
  1592. 'csvdata' => 'name*org_id
  1593. server01*2
  1594. @server02@@combodo@* 2
  1595. server45*99',
  1596. ),
  1597. array(
  1598. 'desc' => 'Load an organization',
  1599. 'login' => 'admin',
  1600. 'password' => 'admin',
  1601. 'args' => array(
  1602. 'class' => 'Organization',
  1603. 'output' => 'details',
  1604. 'separator' => ';',
  1605. 'reconciliationkeys' => '',
  1606. ),
  1607. 'csvdata' => "name;code\nWorldCompany;WCY",
  1608. ),
  1609. array(
  1610. 'desc' => 'Load a location',
  1611. 'login' => 'admin',
  1612. 'password' => 'admin',
  1613. 'args' => array(
  1614. 'class' => 'Location',
  1615. 'output' => 'details',
  1616. 'separator' => ';',
  1617. 'reconciliationkeys' => '',
  1618. ),
  1619. 'csvdata' => "name;org_id;address\nParis;1;Centre de la Franca",
  1620. ),
  1621. array(
  1622. 'desc' => 'Load a person',
  1623. 'login' => 'admin',
  1624. 'password' => 'admin',
  1625. 'args' => array(
  1626. 'class' => 'Person',
  1627. 'output' => 'details',
  1628. 'separator' => ';',
  1629. 'reconciliationkeys' => '',
  1630. ),
  1631. 'csvdata' => "email;name;first_name;org_id;phone\njohn.foo@starac.com;Foo;John;1;+33(1)23456789",
  1632. ),
  1633. array(
  1634. 'desc' => 'Load a person - wrong email format',
  1635. 'login' => 'admin',
  1636. 'password' => 'admin',
  1637. 'args' => array(
  1638. 'class' => 'Person',
  1639. 'output' => 'details',
  1640. 'separator' => ';',
  1641. 'reconciliationkeys' => '',
  1642. ),
  1643. 'csvdata' => "email;name;first_name;org_id\nemailPASbon;Foo;John;1",
  1644. ),
  1645. array(
  1646. 'desc' => 'Load a team',
  1647. 'login' => 'admin',
  1648. 'password' => 'admin',
  1649. 'args' => array(
  1650. 'class' => 'Team',
  1651. 'output' => 'details',
  1652. 'separator' => ';',
  1653. 'reconciliationkeys' => '',
  1654. ),
  1655. 'csvdata' => "name;org_id;location_name\nSquadra Azzura2;1;Paris",
  1656. ),
  1657. array(
  1658. 'desc' => 'Load server',
  1659. 'login' => 'admin',
  1660. 'password' => 'admin',
  1661. 'args' => array(
  1662. 'class' => 'Server',
  1663. 'output' => 'details',
  1664. 'separator' => ';',
  1665. 'reconciliationkeys' => '',
  1666. ),
  1667. '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",
  1668. ),
  1669. array(
  1670. 'desc' => 'Load server (column header localized in english)',
  1671. 'login' => 'admin',
  1672. 'password' => 'admin',
  1673. 'args' => array(
  1674. 'class' => 'Server',
  1675. 'output' => 'details',
  1676. 'separator' => ';',
  1677. 'reconciliationkeys' => '',
  1678. ),
  1679. '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",
  1680. ),
  1681. array(
  1682. 'desc' => 'Load server (directly from Export results)',
  1683. 'login' => 'admin',
  1684. 'password' => 'admin',
  1685. 'args' => array(
  1686. 'class' => 'Server',
  1687. 'output' => 'details',
  1688. 'reconciliationkeys' => '',
  1689. ),
  1690. '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
  1691. 1,"dbserver1.demo.com","production",2,"Demo","medium","HP","DL380","","","ouille
  1692. [[Server:webserver.demo.com]]",1,"Grenoble","","10.1.1.10","255.255.255.0","2","16Gb","120Gb","Linux","Debian (Lenny)"',
  1693. ),
  1694. array(
  1695. 'desc' => 'Load server - wrong value for status',
  1696. 'login' => 'admin',
  1697. 'password' => 'admin',
  1698. 'args' => array(
  1699. 'class' => 'Server',
  1700. 'output' => 'details',
  1701. 'separator' => ';',
  1702. 'reconciliationkeys' => '',
  1703. ),
  1704. '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",
  1705. ),
  1706. array(
  1707. 'desc' => 'Load NW if',
  1708. 'login' => 'admin',
  1709. 'password' => 'admin',
  1710. 'args' => array(
  1711. 'class' => 'NetworkInterface',
  1712. 'output' => 'details',
  1713. 'separator' => ';',
  1714. 'reconciliationkeys' => '',
  1715. ),
  1716. '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;;",
  1717. ),
  1718. // Data Bruno
  1719. array(
  1720. 'desc' => 'Load NW devices from real life',
  1721. 'login' => 'admin',
  1722. 'password' => 'admin',
  1723. 'args' => array(
  1724. 'class' => 'NetworkDevice',
  1725. 'output' => 'details',
  1726. 'separator' => ';',
  1727. 'reconciliationkeys' => 'org_id,Name',
  1728. ),
  1729. 'csvdata' => 'name;management_ip;importance;Owner organization->Name;type
  1730. truc-machin-bidule;172.15.255.150;high;My Company/Department;switch
  1731. 10.15.255.222;10.15.255.222;high;My Company/Department;switch',
  1732. ),
  1733. array(
  1734. 'desc' => 'Load NW ifs',
  1735. 'login' => 'admin',
  1736. 'password' => 'admin',
  1737. 'args' => array(
  1738. 'class' => 'NetworkInterface',
  1739. 'output' => 'details',
  1740. 'separator' => ';',
  1741. 'reconciliationkeys' => 'device_id->name,name',
  1742. ),
  1743. 'csvdata' => 'device_id->name;org_id->name;name;ip_address;ip_mask;speed;link_type;mac_address;physical_type
  1744. truc-machin-bidule;My Company/Department;"GigabitEthernet44";;;0;downlink;00 12 F2 CB C4 EB ;ethernet
  1745. truc-machin-bidule;My Company/Department;"GigabitEthernet38";;;0;downlink;00 12 F2 CB C4 E5 ;ethernet
  1746. un-autre;My Company/Department;"GigabitEthernet2/3";;;1000000000;uplink;00 12 F2 20 0F 1A ;ethernet',
  1747. ),
  1748. array(
  1749. 'desc' => 'The simplest data load',
  1750. 'login' => 'admin',
  1751. 'password' => 'admin',
  1752. 'args' => array(
  1753. 'class' => 'Location',
  1754. 'output' => 'details',
  1755. ),
  1756. 'csvdata' => "name\nParis",
  1757. ),
  1758. array(
  1759. 'desc' => 'The simplest data load + org',
  1760. 'login' => 'admin',
  1761. 'password' => 'admin',
  1762. 'args' => array(
  1763. 'class' => 'Location',
  1764. 'output' => 'details',
  1765. 'separator' => ';',
  1766. ),
  1767. 'csvdata' => "name;org_id\nParis;2",
  1768. ),
  1769. array(
  1770. 'desc' => 'The simplest data load + org (name)',
  1771. 'login' => 'admin',
  1772. 'password' => 'admin',
  1773. 'args' => array(
  1774. 'class' => 'Location',
  1775. 'output' => 'details',
  1776. 'separator' => ';',
  1777. ),
  1778. 'csvdata' => "name;org_name\nParis;Demo",
  1779. ),
  1780. array(
  1781. 'desc' => 'The simplest data load + org (code)',
  1782. 'login' => 'admin',
  1783. 'password' => 'admin',
  1784. 'args' => array(
  1785. 'class' => 'Location',
  1786. 'output' => 'details',
  1787. 'separator' => ';',
  1788. ),
  1789. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1790. ),
  1791. array(
  1792. 'desc' => 'Ouput: summary',
  1793. 'login' => 'admin',
  1794. 'password' => 'admin',
  1795. 'args' => array(
  1796. 'class' => 'Location',
  1797. 'output' => 'summary',
  1798. 'separator' => ';',
  1799. ),
  1800. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1801. ),
  1802. array(
  1803. 'desc' => 'Ouput: retcode',
  1804. 'login' => 'admin',
  1805. 'password' => 'admin',
  1806. 'args' => array(
  1807. 'class' => 'Location',
  1808. 'output' => 'retcode',
  1809. 'separator' => ';',
  1810. ),
  1811. 'csvdata' => "name;org_id->code\nParis;DEMO",
  1812. ),
  1813. array(
  1814. 'desc' => 'Error in reconciliation list',
  1815. 'login' => 'admin',
  1816. 'password' => 'admin',
  1817. 'args' => array(
  1818. 'class' => 'Location',
  1819. 'output' => 'details',
  1820. 'separator' => ';',
  1821. 'reconciliationkeys' => 'org_id',
  1822. ),
  1823. 'csvdata' => "org_name;name\nDemo;Paris",
  1824. ),
  1825. array(
  1826. 'desc' => 'Error in attribute list that does not allow to compute reconciliation scheme',
  1827. 'login' => 'admin',
  1828. 'password' => 'admin',
  1829. 'args' => array(
  1830. 'class' => 'Location',
  1831. 'output' => 'details',
  1832. 'separator' => ';',
  1833. ),
  1834. 'csvdata' => "org_name;country\nDemo;France",
  1835. ),
  1836. array(
  1837. 'desc' => 'Error in attribute list - case A',
  1838. 'login' => 'admin',
  1839. 'password' => 'admin',
  1840. 'args' => array(
  1841. 'class' => 'Location',
  1842. 'output' => 'details',
  1843. 'separator' => ';',
  1844. ),
  1845. 'csvdata' => "name;org\nParis;2",
  1846. ),
  1847. array(
  1848. 'desc' => 'Error in attribute list - case B1 (key->attcode)',
  1849. 'login' => 'admin',
  1850. 'password' => 'admin',
  1851. 'args' => array(
  1852. 'class' => 'Location',
  1853. 'output' => 'details',
  1854. 'separator' => ';',
  1855. ),
  1856. 'csvdata' => "name;org->code\nParis;DEMO",
  1857. ),
  1858. array(
  1859. 'desc' => 'Error in attribute list - case B2 (key->attcode)',
  1860. 'login' => 'admin',
  1861. 'password' => 'admin',
  1862. 'args' => array(
  1863. 'class' => 'Location',
  1864. 'output' => 'details',
  1865. 'separator' => ';',
  1866. ),
  1867. 'csvdata' => "name;org_id->duns\nParis;DEMO",
  1868. ),
  1869. array(
  1870. 'desc' => 'Always changing... special comment in change tracking',
  1871. 'login' => 'admin',
  1872. 'password' => 'admin',
  1873. 'args' => array(
  1874. 'class' => 'Location',
  1875. 'output' => 'details',
  1876. 'separator' => ';',
  1877. 'comment' => 'automated testing'
  1878. ),
  1879. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;Addresse bidon:".((string)microtime(true)),
  1880. ),
  1881. array(
  1882. 'desc' => 'Always changing... but "simulate"',
  1883. 'login' => 'admin',
  1884. 'password' => 'admin',
  1885. 'args' => array(
  1886. 'class' => 'Location',
  1887. 'output' => 'details',
  1888. 'separator' => ';',
  1889. 'simulate' => '1',
  1890. 'comment' => 'SHOULD NEVER APPEAR IN THE HISTORY'
  1891. ),
  1892. 'csvdata' => "org_name;name;address\nDemo;Le pantheon;restore address?",
  1893. ),
  1894. array(
  1895. 'desc' => 'Load a user account',
  1896. 'login' => 'admin',
  1897. 'password' => 'admin',
  1898. 'args' => array(
  1899. 'class' => 'UserLocal',
  1900. 'output' => 'details',
  1901. 'separator' => ',',
  1902. 'simulate' => '0',
  1903. 'comment' => 'automated testing'
  1904. ),
  1905. 'csvdata' => "login,password,profile_list\nby_import_csv,fakepwd,profileid->name:Configuration Manager|profileid:10;reason:direct id",
  1906. ),
  1907. );
  1908. $sSubTests = utils::ReadParam('subtests', null, true, 'raw_data');
  1909. if (is_null($sSubTests))
  1910. {
  1911. foreach ($aLoads as $iTestId => $aLoadSpec)
  1912. {
  1913. $this->DoExecSingleLoad($aLoadSpec, $iTestId);
  1914. }
  1915. }
  1916. else
  1917. {
  1918. $aSubTests = explode(',', $sSubTests);
  1919. foreach ($aSubTests as $iTestId)
  1920. {
  1921. $this->DoExecSingleLoad($aLoads[$iTestId], $iTestId);
  1922. }
  1923. }
  1924. }
  1925. }
  1926. ///////////////////////////////////////////////////////////////////////////
  1927. // Test massive data load
  1928. ///////////////////////////////////////////////////////////////////////////
  1929. define('IMPORT_COUNT', 4000);
  1930. class TestImportRESTMassive extends TestImportREST
  1931. {
  1932. static public function GetName()
  1933. {
  1934. return 'CSV import (REST) - HUGE data set ('.IMPORT_COUNT.' PCs)';
  1935. }
  1936. static public function GetDescription()
  1937. {
  1938. return 'Stress import.php';
  1939. }
  1940. protected function DoExecute()
  1941. {
  1942. $aLoadSpec = array(
  1943. 'desc' => 'Loading PCs: '.IMPORT_COUNT,
  1944. 'args' => array(
  1945. 'class' => 'PC',
  1946. 'output' => 'summary',
  1947. ),
  1948. 'csvdata' => "name;org_id;brand\n",
  1949. );
  1950. for($i = 0 ; $i <= IMPORT_COUNT ; $i++)
  1951. {
  1952. $aLoadSpec['csvdata'] .= "pc.import.$i;2;Combodo\n";
  1953. }
  1954. $this->DoExecSingleLoad($aLoadSpec);
  1955. }
  1956. }
  1957. ///////////////////////////////////////////////////////////////////////////
  1958. // Test data exchange
  1959. ///////////////////////////////////////////////////////////////////////////
  1960. class TestDataExchange extends TestBizModel
  1961. {
  1962. static public function GetName()
  1963. {
  1964. return 'Data exchange';
  1965. }
  1966. static public function GetDescription()
  1967. {
  1968. return 'Test REST services: synchro_import and synchro_exec';
  1969. }
  1970. protected function DoExecScenario($aSingleScenario)
  1971. {
  1972. echo "<div style=\"padding: 10;\">\n";
  1973. echo "<h3 style=\"background-color: #ddddff; padding: 10;\">{$aSingleScenario['desc']}</h3>\n";
  1974. $sClass = $aSingleScenario['target_class'];
  1975. $aTargetData = $aSingleScenario['target_data'];
  1976. $aSourceData = $aSingleScenario['source_data'];
  1977. $aTargetAttributes = array_shift($aTargetData);
  1978. $aSourceAttributes = array_shift($aSourceData);
  1979. if (count($aSourceData) + 1 != count($aTargetData))
  1980. {
  1981. throw new Exception("Target data must contain exactly ".(count($aSourceData) + 1)." items, found ".count($aTargetData));
  1982. }
  1983. // Create the data source
  1984. //
  1985. $oDataSource = new SynchroDataSource();
  1986. $oDataSource->Set('name', 'Test data sync '.time());
  1987. $oDataSource->Set('description', 'unit test - created automatically');
  1988. $oDataSource->Set('status', 'production');
  1989. $oDataSource->Set('user_id', 0);
  1990. $oDataSource->Set('scope_class', $sClass);
  1991. $oDataSource->Set('scope_restriction', '');
  1992. $oDataSource->Set('full_load_periodicity', $aSingleScenario['full_load_periodicity']);
  1993. $oDataSource->Set('reconciliation_policy', $aSingleScenario['reconciliation_policy']);
  1994. $oDataSource->Set('action_on_zero', $aSingleScenario['action_on_zero']);
  1995. $oDataSource->Set('action_on_one', $aSingleScenario['action_on_one']);
  1996. $oDataSource->Set('action_on_multiple', $aSingleScenario['action_on_multiple']);
  1997. $oDataSource->Set('delete_policy', $aSingleScenario['delete_policy']);
  1998. $oDataSource->Set('delete_policy_update', $aSingleScenario['delete_policy_update']);
  1999. $oDataSource->Set('delete_policy_retention', $aSingleScenario['delete_policy_retention']);
  2000. $iDataSourceId = $this->ObjectToDB($oDataSource, true /* reload */);
  2001. $oAttributeSet = $oDataSource->Get('attribute_list');
  2002. while ($oAttribute = $oAttributeSet->Fetch())
  2003. {
  2004. if (array_key_exists($oAttribute->Get('attcode'), $aSingleScenario['attributes']))
  2005. {
  2006. $aAttribInfo = $aSingleScenario['attributes'][$oAttribute->Get('attcode')];
  2007. if (array_key_exists('reconciliation_attcode', $aAttribInfo))
  2008. {
  2009. $oAttribute->Set('reconciliation_attcode', $aAttribInfo['reconciliation_attcode']);
  2010. }
  2011. $oAttribute->Set('update', $aAttribInfo['do_update']);
  2012. $oAttribute->Set('reconcile', $aAttribInfo['do_reconcile']);
  2013. }
  2014. else
  2015. {
  2016. $oAttribute->Set('update', false);
  2017. $oAttribute->Set('reconcile', false);
  2018. }
  2019. $this->UpdateObjectInDB($oAttribute);
  2020. }
  2021. // Prepare list of prefixes -> make sure objects are unique with regard to the reconciliation scheme
  2022. $aPrefixes = array(); // attcode => prefix
  2023. foreach($aSourceAttributes as $iDummy => $sAttCode)
  2024. {
  2025. $aPrefixes[$sAttCode] = ''; // init with something
  2026. }
  2027. foreach($aSingleScenario['attributes'] as $sAttCode => $aAttribInfo)
  2028. {
  2029. if (isset($aAttribInfo['automatic_prefix']) && $aAttribInfo['automatic_prefix'])
  2030. {
  2031. $aPrefixes[$sAttCode] = 'TEST_'.$iDataSourceId.'_';
  2032. }
  2033. }
  2034. // List existing objects (to be ignored in the analysis
  2035. //
  2036. $oAllObjects = new DBObjectSet(new DBObjectSearch($sClass));
  2037. $aExisting = $oAllObjects->ToArray(true);
  2038. $sExistingIds = implode(', ', array_keys($aExisting));
  2039. // Create the initial object list
  2040. //
  2041. $aInitialTarget = $aTargetData[0];
  2042. foreach($aInitialTarget as $aObjFields)
  2043. {
  2044. $oNewTarget = MetaModel::NewObject($sClass);
  2045. foreach($aTargetAttributes as $iAtt => $sAttCode)
  2046. {
  2047. $oNewTarget->Set($sAttCode, $aPrefixes[$sAttCode].$aObjFields[$iAtt]);
  2048. }
  2049. $this->ObjectToDB($oNewTarget);
  2050. }
  2051. foreach($aTargetData as $iRow => $aExpectedObjects)
  2052. {
  2053. sleep(2);
  2054. // Check the status (while ignoring existing objects)
  2055. //
  2056. if (empty($sExistingIds))
  2057. {
  2058. $oObjects = new DBObjectSet(DBObjectSearch::FromOQL("SELECT $sClass"));
  2059. }
  2060. else
  2061. {
  2062. $oObjects = new DBObjectSet(DBObjectSearch::FromOQL("SELECT $sClass WHERE id NOT IN($sExistingIds)"));
  2063. }
  2064. $aFound = $oObjects->ToArray();
  2065. $aErrors_Unexpected = array();
  2066. foreach($aFound as $iObj => $oObj)
  2067. {
  2068. // Is this object in the expected objects list
  2069. $bFoundMatch = false;
  2070. foreach($aExpectedObjects as $iExp => $aValues)
  2071. {
  2072. $bDoesMatch = true;
  2073. foreach($aTargetAttributes as $iCol => $sAttCode)
  2074. {
  2075. if ($oObj->Get($sAttCode) != $aPrefixes[$sAttCode].$aValues[$iCol])
  2076. {
  2077. $bDoesMatch = false;
  2078. break;
  2079. }
  2080. }
  2081. if ($bDoesMatch)
  2082. {
  2083. $bFoundMatch = true;
  2084. unset($aExpectedObjects[$iExp]);
  2085. break;
  2086. }
  2087. }
  2088. if (!$bFoundMatch)
  2089. {
  2090. $aErrors_Unexpected[] = $oObj->GetKey();
  2091. }
  2092. }
  2093. // Display the current status
  2094. //
  2095. echo "<p>Status at step $iRow</p>\n";
  2096. $aCurrentDataSet = array();
  2097. foreach($aFound as $iObj => $oObj)
  2098. {
  2099. $aObjDesc = array(
  2100. 'Status' => (in_array($iObj, $aErrors_Unexpected) ? 'unexpected' : 'ok'),
  2101. 'Object' => $oObj->GetHyperLink()
  2102. );
  2103. foreach($aTargetAttributes as $iCol => $sAttCode)
  2104. {
  2105. $aObjDesc[$sAttCode] = $oObj->Get($sAttCode);
  2106. }
  2107. $aCurrentDataSet[] = $aObjDesc;
  2108. }
  2109. if (count($aExpectedObjects) > 0)
  2110. {
  2111. foreach($aExpectedObjects as $iExp => $aValues)
  2112. {
  2113. $aObjDesc = array(
  2114. 'Status' => 'missing',
  2115. 'Object' => 'n/a'
  2116. );
  2117. foreach($aTargetAttributes as $iCol => $sAttCode)
  2118. {
  2119. $aObjDesc[$sAttCode] = $aPrefixes[$sAttCode].$aValues[$iCol];
  2120. }
  2121. $aCurrentDataSet[] = $aObjDesc;
  2122. }
  2123. }
  2124. echo MyHelpers::make_table_from_assoc_array($aCurrentDataSet);
  2125. if ((count($aErrors_Unexpected) > 0) || (count($aExpectedObjects) > 0))
  2126. {
  2127. throw new UnitTestException("The current status in iTop does not match the expectations");
  2128. }
  2129. // If not on the final row, run a data exchange sequence
  2130. //
  2131. if (array_key_exists($iRow, $aSourceData))
  2132. {
  2133. $aToBeLoaded = $aSourceData[$iRow];
  2134. $sCsvData = implode(';', $aSourceAttributes)."\n";
  2135. foreach($aToBeLoaded as $aDataRow)
  2136. {
  2137. $aFinalData = array();
  2138. foreach($aDataRow as $iCol => $value)
  2139. {
  2140. if (is_null($value))
  2141. {
  2142. $aFinalData[] = '<NULL>';
  2143. }
  2144. else
  2145. {
  2146. $sAttCode = $aSourceAttributes[$iCol];
  2147. $aFinalData[] = $aPrefixes[$sAttCode].$value;
  2148. }
  2149. }
  2150. $sCsvData .= implode(';', $aFinalData)."\n";
  2151. }
  2152. $aPostData = array('csvdata' => $sCsvData);
  2153. $aImportArgs = array(
  2154. 'data_source_id' => $iDataSourceId,
  2155. 'separator' => ';',
  2156. 'simulate' => 0,
  2157. 'output' => 'details',
  2158. );
  2159. $aGetParams = array();
  2160. $aGetParamReport = array();
  2161. foreach($aImportArgs as $sArg => $sValue)
  2162. {
  2163. $aGetParams[] = $sArg.'='.urlencode($sValue);
  2164. $aGetParamReport[] = $sArg.'='.$sValue;
  2165. }
  2166. $sGetParams = implode('&', $aGetParams);
  2167. $sLogin = isset($aSingleScenario['login']) ? $aSingleScenario['login'] : 'admin';
  2168. $sPassword = isset($aSingleScenario['password']) ? $aSingleScenario['password'] : 'admin';
  2169. $sRes = self::DoPostRequestAuth('../synchro/synchro_import.php?'.$sGetParams, $aPostData, $sLogin, $sPassword);
  2170. // Report the load results
  2171. //
  2172. if (strlen($sCsvData) > 5000)
  2173. {
  2174. $sCsvDataViewable = 'INPUT TOO LONG TO BE DISPLAYED ('.strlen($sCsvData).")\n".substr($sCsvData, 0, 500)."\n... TO BE CONTINUED";
  2175. }
  2176. else
  2177. {
  2178. $sCsvDataViewable = $sCsvData;
  2179. }
  2180. $sCsvDataViewable = htmlentities($sCsvDataViewable, ENT_QUOTES, 'UTF-8');
  2181. echo "<div style=\"\">\n";
  2182. echo " <pre class=\"vardump\">$sCsvDataViewable</pre>\n";
  2183. echo "</div>\n";
  2184. echo "<pre class=\"vardump\" style=\"clear: both; padding: 15; background-color: black; color: green;\">$sRes</pre>\n";
  2185. if (stripos($sRes, 'exception') !== false)
  2186. {
  2187. throw new UnitTestException('Encountered an Exception during the last import/synchro');
  2188. }
  2189. }
  2190. }
  2191. return;
  2192. echo "</div>\n";
  2193. }
  2194. protected function DoExecute()
  2195. {
  2196. /*
  2197. $aScenarios = array(
  2198. array(
  2199. 'desc' => 'Load user logins',
  2200. 'login' => 'admin',
  2201. 'password' => 'admin',
  2202. 'target_class' => 'UserLocal',
  2203. 'full_load_periodicity' => 3600, // should be ignored in this case
  2204. 'reconciliation_policy' => 'use_attributes',
  2205. 'action_on_zero' => 'create',
  2206. 'action_on_one' => 'update',
  2207. 'action_on_multiple' => 'error',
  2208. 'delete_policy' => 'delete',
  2209. 'delete_policy_update' => '',
  2210. 'delete_policy_retention' => 0,
  2211. 'source_data' => array(
  2212. array('primary_key', 'login', 'password', 'profile_list'),
  2213. array(
  2214. array('user_A', 'login_A', 'password_A', 'profileid:10;reason:he/she is managing services'),
  2215. ),
  2216. ),
  2217. 'target_data' => array(
  2218. array('login'),
  2219. array(
  2220. // Initial state
  2221. ),
  2222. array(
  2223. array('login_A'),
  2224. ),
  2225. ),
  2226. 'attributes' => array(
  2227. 'login' => array(
  2228. 'do_reconcile' => true,
  2229. 'do_update' => true,
  2230. 'automatic_prefix' => true, // unique id (for unit testing)
  2231. ),
  2232. 'password' => array(
  2233. 'do_reconcile' => false,
  2234. 'do_update' => true,
  2235. ),
  2236. 'profile_list' => array(
  2237. 'do_reconcile' => false,
  2238. 'do_update' => true,
  2239. ),
  2240. ),
  2241. ),
  2242. );
  2243. */
  2244. $aScenarios = array(
  2245. array(
  2246. 'desc' => 'Simple scenario with delete option (and extkey given as org/name)',
  2247. 'login' => 'admin',
  2248. 'password' => 'admin',
  2249. 'target_class' => 'ApplicationSolution',
  2250. 'full_load_periodicity' => 3600, // should be ignored in this case
  2251. 'reconciliation_policy' => 'use_attributes',
  2252. 'action_on_zero' => 'create',
  2253. 'action_on_one' => 'update',
  2254. 'action_on_multiple' => 'error',
  2255. 'delete_policy' => 'delete',
  2256. 'delete_policy_update' => '',
  2257. 'delete_policy_retention' => 0,
  2258. 'source_data' => array(
  2259. array('primary_key', 'org_id', 'name', 'status'),
  2260. array(
  2261. array('obj_A', null, 'obj_A', 'production'), // org_id unchanged
  2262. array('obj_B', '_DUMMY_', 'obj_B', 'production'), // error, '_DUMMY_' unknown
  2263. array('obj_C', 'SOMECODE', 'obj_C', 'production'),
  2264. array('obj_D', null, 'obj_D', 'production'),
  2265. array('obj_E', '_DUMMY_', 'obj_E', 'production'),
  2266. ),
  2267. array(
  2268. ),
  2269. array(
  2270. ),
  2271. ),
  2272. 'target_data' => array(
  2273. array('org_id', 'name', 'status'),
  2274. array(
  2275. // Initial state
  2276. array(2, 'obj_A', 'production'),
  2277. array(2, 'obj_B', 'production'),
  2278. ),
  2279. array(
  2280. array(2, 'obj_A', 'production'),
  2281. array(2, 'obj_B', 'production'),
  2282. array(1, 'obj_C', 'production'),
  2283. ),
  2284. array(
  2285. array(2, 'obj_A', 'production'),
  2286. array(2, 'obj_B', 'production'),
  2287. // deleted !
  2288. ),
  2289. // The only diff here is into the log
  2290. array(
  2291. array(2, 'obj_A', 'production'),
  2292. array(2, 'obj_B', 'production'),
  2293. // deleted !
  2294. ),
  2295. ),
  2296. 'attributes' => array(
  2297. 'org_id' => array(
  2298. 'do_reconcile' => false,
  2299. 'do_update' => true,
  2300. 'reconciliation_attcode' => 'code',
  2301. ),
  2302. 'name' => array(
  2303. 'do_reconcile' => true,
  2304. 'do_update' => true,
  2305. 'automatic_prefix' => true, // unique id
  2306. ),
  2307. 'status' => array(
  2308. 'do_reconcile' => false,
  2309. 'do_update' => true,
  2310. ),
  2311. ),
  2312. ),
  2313. // );
  2314. // $aXXXXScenarios = array(
  2315. array(
  2316. 'desc' => 'Update then delete with retention (to complete with manual testing) and reconciliation on org/name',
  2317. 'login' => 'admin',
  2318. 'password' => 'admin',
  2319. 'target_class' => 'ApplicationSolution',
  2320. 'full_load_periodicity' => 3600,
  2321. 'reconciliation_policy' => 'use_attributes',
  2322. 'action_on_zero' => 'create',
  2323. 'action_on_one' => 'update',
  2324. 'action_on_multiple' => 'error',
  2325. 'delete_policy' => 'update_then_delete',
  2326. 'delete_policy_update' => 'status:obsolete',
  2327. 'delete_policy_retention' => 15,
  2328. 'source_data' => array(
  2329. array('primary_key', 'org_id', 'name', 'status'),
  2330. array(
  2331. array('obj_A', 'Demo', 'obj_A', 'production'),
  2332. ),
  2333. array(
  2334. ),
  2335. ),
  2336. 'target_data' => array(
  2337. array('org_id', 'name', 'status'),
  2338. array(
  2339. // Initial state
  2340. ),
  2341. array(
  2342. array(2, 'obj_A', 'production'),
  2343. ),
  2344. array(
  2345. array(2, 'obj_A', 'obsolete'),
  2346. // deleted !
  2347. ),
  2348. ),
  2349. 'attributes' => array(
  2350. 'org_id' => array(
  2351. 'do_reconcile' => true,
  2352. 'do_update' => true,
  2353. 'reconciliation_attcode' => 'name',
  2354. ),
  2355. 'name' => array(
  2356. 'do_reconcile' => true,
  2357. 'do_update' => true,
  2358. 'automatic_prefix' => true, // unique id
  2359. ),
  2360. 'status' => array(
  2361. 'do_reconcile' => false,
  2362. 'do_update' => true,
  2363. ),
  2364. ),
  2365. ),
  2366. //);
  2367. //$aXXScenarios = array(
  2368. array(
  2369. 'desc' => 'Simple scenario loading a few ApplicationSolution',
  2370. 'login' => 'admin',
  2371. 'password' => 'admin',
  2372. 'target_class' => 'ApplicationSolution',
  2373. 'full_load_periodicity' => 3600,
  2374. 'reconciliation_policy' => 'use_attributes',
  2375. 'action_on_zero' => 'create',
  2376. 'action_on_one' => 'update',
  2377. 'action_on_multiple' => 'error',
  2378. 'delete_policy' => 'update',
  2379. 'delete_policy_update' => 'status:obsolete',
  2380. 'delete_policy_retention' => 0,
  2381. 'source_data' => array(
  2382. array('primary_key', 'org_id', 'name', 'status'),
  2383. array(
  2384. array('obj_A', 2, 'obj_A', 'production'),
  2385. array('obj_B', 2, 'obj_B', 'implementation'),
  2386. array('obj_C', 2, 'obj_C', 'implementation'),
  2387. ),
  2388. array(
  2389. array('obj_A', 2, 'obj_A', 'production'),
  2390. array('obj_B', 2, 'obj_B', 'implementation'),
  2391. array('obj_C', 2, 'obj_C', 'implementation'),
  2392. ),
  2393. array(
  2394. array('obj_A', 2, 'obj_A', 'production'),
  2395. array('obj_C', 2, 'obj_C', 'implementation'),
  2396. array('obj_D', 2, 'obj_D', 'implementation'),
  2397. ),
  2398. array(
  2399. array('obj_C', 2, 'obj_C', 'production'),
  2400. ),
  2401. array(
  2402. array('obj_C', 2, 'obj_C', 'production'),
  2403. ),
  2404. ),
  2405. 'target_data' => array(
  2406. array('org_id', 'name', 'status'),
  2407. array(
  2408. // Initial state
  2409. array(2, 'obj_A', 'implementation'),
  2410. array(2, 'obj_B', 'production'),
  2411. array(2, 'obj_B', 'implementation'),
  2412. ),
  2413. array(
  2414. array(2, 'obj_A', 'production'),
  2415. array(2, 'obj_B', 'production'),
  2416. array(2, 'obj_B', 'implementation'),
  2417. array(2, 'obj_C', 'implementation'),
  2418. ),
  2419. array(
  2420. array(2, 'obj_A', 'production'),
  2421. array(2, 'obj_B', 'production'),
  2422. array(2, 'obj_B', 'implementation'),
  2423. array(2, 'obj_C', 'implementation'),
  2424. ),
  2425. array(
  2426. array(2, 'obj_A', 'production'),
  2427. array(2, 'obj_B', 'production'),
  2428. array(2, 'obj_B', 'implementation'),
  2429. array(2, 'obj_C', 'implementation'),
  2430. array(2, 'obj_D', 'implementation'),
  2431. ),
  2432. array(
  2433. array(2, 'obj_A', 'obsolete'),
  2434. array(2, 'obj_B', 'production'),
  2435. array(2, 'obj_B', 'implementation'),
  2436. array(2, 'obj_C', 'production'),
  2437. array(2, 'obj_D', 'obsolete'),
  2438. ),
  2439. array(
  2440. array(2, 'obj_A', 'obsolete'),
  2441. array(2, 'obj_B', 'production'),
  2442. array(2, 'obj_B', 'implementation'),
  2443. array(2, 'obj_C', 'production'),
  2444. array(2, 'obj_D', 'obsolete'),
  2445. ),
  2446. ),
  2447. 'attributes' => array(
  2448. 'org_id' => array(
  2449. 'do_reconcile' => false,
  2450. 'do_update' => true,
  2451. ),
  2452. 'name' => array(
  2453. 'do_reconcile' => true,
  2454. 'do_update' => true,
  2455. 'automatic_prefix' => true, // unique id
  2456. ),
  2457. 'status' => array(
  2458. 'do_reconcile' => false,
  2459. 'do_update' => true,
  2460. ),
  2461. ),
  2462. ),
  2463. );
  2464. foreach ($aScenarios as $aSingleScenario)
  2465. {
  2466. $this->DoExecScenario($aSingleScenario);
  2467. }
  2468. }
  2469. }
  2470. ///////////////////////////////////////////////////////////////////////////
  2471. // Test SOAP services
  2472. ///////////////////////////////////////////////////////////////////////////
  2473. $aCreateTicketSpecs = array(
  2474. array(
  2475. 'service_category' => 'BasicServices',
  2476. 'verb' => 'GetVersion',
  2477. // 'expected result' => '1.0.1',
  2478. 'expected result' => '$ITOP_VERSION$ [dev]',
  2479. 'explain result' => 'no comment!',
  2480. 'args' => array(),
  2481. ),
  2482. array(
  2483. 'service_category' => '',
  2484. 'verb' => 'CreateIncidentTicket',
  2485. 'expected result' => true,
  2486. 'explain result' => 'link attribute unknown + a CI not found',
  2487. 'args' => array(
  2488. 'admin', /* sLogin */
  2489. 'admin', /* sPassword */
  2490. 'desc of ticket', /* sDescription */
  2491. 'initial situation blah blah blah', /* sInitialSituation */
  2492. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2493. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2494. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Telecom and connectivity'))), /* aServiceDesc */
  2495. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Network Troubleshooting'))), /* aServiceSubcategoryDesc */
  2496. 'sub product of the service', /* sProduct */
  2497. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2498. array(
  2499. new SOAPLinkCreationSpec(
  2500. 'InfrastructureCI',
  2501. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  2502. array(new SOAPAttributeValue('impacting', 'very critical'))
  2503. ),
  2504. new SOAPLinkCreationSpec(
  2505. 'NetworkDevice',
  2506. array(new SOAPSearchCondition('name', 'switch01')),
  2507. array(new SOAPAttributeValue('impact', 'who cares'))
  2508. ),
  2509. new SOAPLinkCreationSpec(
  2510. 'Server',
  2511. array(new SOAPSearchCondition('name', 'thisone')),
  2512. array(new SOAPAttributeValue('impact', 'our lives'))
  2513. ),
  2514. ), /* aImpact */
  2515. '1', /* sImpact */
  2516. '1', /* sUrgency */
  2517. ),
  2518. ),
  2519. array(
  2520. 'service_category' => '',
  2521. 'verb' => 'CreateIncidentTicket',
  2522. 'expected result' => true,
  2523. 'explain result' => 'caller not specified',
  2524. 'args' => array(
  2525. 'admin', /* sLogin */
  2526. 'admin', /* sPassword */
  2527. 'PC burning', /* sDescription */
  2528. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2529. new SOAPExternalKeySearch(), /* aCallerDesc */
  2530. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2531. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2532. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2533. 'sub product of the service', /* sProduct */
  2534. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2535. array(
  2536. new SOAPLinkCreationSpec(
  2537. 'InfrastructureCI',
  2538. array(new SOAPSearchCondition('name', 'dbserver1.demo.com')),
  2539. array()
  2540. ), /* aImpact */
  2541. ),
  2542. '1', /* sImpact */
  2543. '1', /* sUrgency */
  2544. ),
  2545. ),
  2546. array(
  2547. 'service_category' => '',
  2548. 'verb' => 'CreateIncidentTicket',
  2549. 'expected result' => false,
  2550. 'explain result' => 'wrong class on CI to attach',
  2551. 'args' => array(
  2552. 'admin', /* sLogin */
  2553. 'admin', /* sPassword */
  2554. 'PC burning', /* sDescription */
  2555. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2556. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2557. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2558. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2559. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2560. 'sub product of the service', /* sProduct */
  2561. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2562. array(
  2563. new SOAPLinkCreationSpec(
  2564. 'logInfra',
  2565. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  2566. array(new SOAPAttributeValue('impact', 'very critical'))
  2567. ),
  2568. ), /* aImpact */
  2569. '1', /* sImpact */
  2570. '1', /* sUrgency */
  2571. ),
  2572. ),
  2573. array(
  2574. 'service_category' => '',
  2575. 'verb' => 'CreateIncidentTicket',
  2576. 'expected result' => false,
  2577. 'explain result' => 'wrong search condition on CI to attach',
  2578. 'args' => array(
  2579. 'admin', /* sLogin */
  2580. 'admin', /* sPassword */
  2581. 'PC burning', /* sDescription */
  2582. 'The power supply suddenly started to warm up', /* sInitialSituation */
  2583. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2584. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2585. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2586. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2587. 'sub product of the service', /* sProduct */
  2588. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2589. array(
  2590. new SOAPLinkCreationSpec(
  2591. 'InfrastructureCI',
  2592. array(new SOAPSearchCondition('dummyfiltercode', 2)),
  2593. array(new SOAPAttributeValue('impact', 'very critical'))
  2594. ),
  2595. ), /* aImpact */
  2596. '1', /* sImpact */
  2597. '1', /* sUrgency */
  2598. ),
  2599. ),
  2600. array(
  2601. 'service_category' => '',
  2602. 'verb' => 'CreateIncidentTicket',
  2603. 'expected result' => true,
  2604. 'explain result' => 'no CI to attach (empty array)',
  2605. 'args' => array(
  2606. 'admin', /* sLogin */
  2607. 'admin', /* sPassword */
  2608. 'Houston not reachable', /* sDescription */
  2609. 'Tried to join the shuttle', /* sInitialSituation */
  2610. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2611. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2612. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2613. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2614. 'sub product of the service', /* sProduct */
  2615. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2616. array(
  2617. ), /* aImpact */
  2618. '1', /* sImpact */
  2619. '1', /* sUrgency */
  2620. ),
  2621. ),
  2622. array(
  2623. 'service_category' => '',
  2624. 'verb' => 'CreateIncidentTicket',
  2625. 'expected result' => true,
  2626. 'explain result' => 'no CI to attach (null)',
  2627. 'args' => array(
  2628. 'admin', /* sLogin */
  2629. 'admin', /* sPassword */
  2630. 'Houston not reachable', /* sDescription */
  2631. 'Tried to join the shuttle', /* sInitialSituation */
  2632. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2633. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2634. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2635. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2636. 'sub product of the service', /* sProduct */
  2637. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2638. null, /* aImpact */
  2639. '1', /* sImpact */
  2640. '1', /* sUrgency */
  2641. ),
  2642. ),
  2643. array(
  2644. 'service_category' => '',
  2645. 'verb' => 'CreateIncidentTicket',
  2646. 'expected result' => true,
  2647. 'explain result' => 'caller unknown',
  2648. 'args' => array(
  2649. 'admin', /* sLogin */
  2650. 'admin', /* sPassword */
  2651. 'Houston not reachable', /* sDescription */
  2652. 'Tried to join the shuttle', /* sInitialSituation */
  2653. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1000))), /* aCallerDesc */
  2654. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2655. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2656. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2657. 'sub product of the service', /* sProduct */
  2658. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2659. array(
  2660. ), /* aImpact */
  2661. '1', /* sImpact */
  2662. '1', /* sUrgency */
  2663. ),
  2664. ),
  2665. array(
  2666. 'service_category' => '',
  2667. 'verb' => 'CreateIncidentTicket',
  2668. 'expected result' => false,
  2669. 'explain result' => 'wrong values for impact and urgency',
  2670. 'args' => array(
  2671. 'admin', /* sLogin */
  2672. 'admin', /* sPassword */
  2673. 'Houston not reachable', /* sDescription */
  2674. 'Tried to join the shuttle', /* sInitialSituation */
  2675. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2676. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2677. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2678. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2679. 'sub product of the service', /* sProduct */
  2680. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2681. array(
  2682. ), /* aImpact */
  2683. '6', /* sImpact */
  2684. '7', /* sUrgency */
  2685. ),
  2686. ),
  2687. array(
  2688. 'service_category' => '',
  2689. 'verb' => 'CreateIncidentTicket',
  2690. 'expected result' => false,
  2691. 'explain result' => 'wrong password',
  2692. 'args' => array(
  2693. 'admin', /* sLogin */
  2694. 'xxxxx', /* sPassword */
  2695. 'Houston not reachable', /* sDescription */
  2696. 'Tried to join the shuttle', /* sInitialSituation */
  2697. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2698. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2699. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2700. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2701. 'sub product of the service', /* sProduct */
  2702. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2703. array(
  2704. ), /* aImpact */
  2705. '1', /* sImpact */
  2706. '1', /* sUrgency */
  2707. ),
  2708. ),
  2709. array(
  2710. 'service_category' => '',
  2711. 'verb' => 'CreateIncidentTicket',
  2712. 'expected result' => false,
  2713. 'explain result' => 'wrong login',
  2714. 'args' => array(
  2715. 'xxxxx', /* sLogin */
  2716. 'yyyyy', /* sPassword */
  2717. 'Houston not reachable', /* sDescription */
  2718. 'Tried to join the shuttle', /* sInitialSituation */
  2719. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aCallerDesc */
  2720. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Demo'))), /* aCustomerDesc */
  2721. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Computers and peripherals'))), /* aServiceDesc */
  2722. new SOAPExternalKeySearch(array(new SOAPSearchCondition('id', 1))), /* aServiceSubcategoryDesc */
  2723. 'sub product of the service', /* sProduct */
  2724. new SOAPExternalKeySearch(array(new SOAPSearchCondition('name', 'Hardware support'))), /* aWorkgroupDesc */
  2725. array(
  2726. ), /* aImpact */
  2727. '1', /* sImpact */
  2728. '1', /* sUrgency */
  2729. ),
  2730. ),
  2731. array(
  2732. 'service_category' => '',
  2733. 'verb' => 'SearchObjects',
  2734. 'expected result' => true,
  2735. 'explain result' => '',
  2736. 'args' => array(
  2737. 'admin', /* sLogin */
  2738. 'admin', /* sPassword */
  2739. 'SELECT Incident WHERE id > 20', /* sOQL */
  2740. ),
  2741. ),
  2742. array(
  2743. 'service_category' => '',
  2744. 'verb' => 'SearchObjects',
  2745. 'expected result' => false,
  2746. 'explain result' => 'wrong OQL',
  2747. 'args' => array(
  2748. 'admin', /* sLogin */
  2749. 'admin', /* sPassword */
  2750. 'SELECT ThisClassDoesNotExist', /* sOQL */
  2751. ),
  2752. ),
  2753. );
  2754. $aManageCloudUsersSpecs = array(
  2755. array(
  2756. 'service_category' => '',
  2757. 'verb' => 'SearchObjects',
  2758. 'expected result' => false,
  2759. 'explain result' => 'wrong OQL',
  2760. 'args' => array(
  2761. 'admin', /* sLogin */
  2762. 'admin', /* sPassword */
  2763. 'SELECT ThisClassDoesNotExist', /* sOQL */
  2764. ),
  2765. ),
  2766. array(
  2767. 'service_category' => '',
  2768. 'verb' => 'SearchObjects',
  2769. 'expected result' => true,
  2770. 'explain result' => 'ok',
  2771. 'args' => array(
  2772. 'admin', /* sLogin */
  2773. 'admin', /* sPassword */
  2774. 'SELECT Organization', /* sOQL */
  2775. ),
  2776. ),
  2777. array(
  2778. 'service_category' => 'CloudUsersManagementService',
  2779. 'verb' => 'CreateAccount',
  2780. 'expected result' => true,
  2781. 'explain result' => 'ok',
  2782. 'args' => array(
  2783. 'admin', /* sAdminLogin */
  2784. 'admin', /* sAdminPassword */
  2785. 'http://myserver.mydomain.fr:8080', /* sCloudMgrUrl */
  2786. 'andros@combodo.com', /* sLogin */
  2787. 'André', /* sFirstName */
  2788. 'Dupont', /* sLastName */
  2789. 1, /* iOrgId */
  2790. 'FR FR', /* sLanguage */
  2791. array(
  2792. array(
  2793. new SOAPKeyValue('profile_id', '2'),
  2794. new SOAPKeyValue('reason', 'whynot'),
  2795. ),
  2796. array(
  2797. new SOAPKeyValue('profile_id', '3'),
  2798. new SOAPKeyValue('reason', 'because'),
  2799. ),
  2800. ), /* aProfiles (array of key/value pairs) */
  2801. array(
  2802. ), /* aAllowedOrgs (array of key/value pairs) */
  2803. 'comment on the creation operation', /* sComment */
  2804. ),
  2805. ),
  2806. array(
  2807. 'service_category' => 'CloudUsersManagementService',
  2808. 'verb' => 'ModifyAccount',
  2809. 'expected result' => true,
  2810. 'explain result' => 'ok',
  2811. 'args' => array(
  2812. 'admin', /* sAdminLogin */
  2813. 'admin', /* sAdminPassword */
  2814. 'andros@combodo.com', /* sLogin */
  2815. 'nono', /* sFirstName */
  2816. 'robot', /* sLastName */
  2817. 2, /* iOrgId */
  2818. 'EN US', /* sLanguage */
  2819. array(
  2820. array(
  2821. new SOAPKeyValue('profile_id', '3'),
  2822. new SOAPKeyValue('reason', 'because'),
  2823. ),
  2824. ), /* aProfiles (array of key/value pairs) */
  2825. array(
  2826. ), /* aAllowedOrgs (array of key/value pairs) */
  2827. 'comment on the modify operation', /* sComment */
  2828. ),
  2829. ),
  2830. array(
  2831. 'service_category' => 'CloudUsersManagementService',
  2832. 'verb' => 'DeleteAccount',
  2833. 'expected result' => true,
  2834. 'explain result' => '',
  2835. 'args' => array(
  2836. 'admin', /* sAdminLogin */
  2837. 'admin', /* sAdminPassword */
  2838. 'andros@combodo.com', /* sLogin */
  2839. 'comment on the deletion operation', /* sComment */
  2840. ),
  2841. ),
  2842. array(
  2843. 'service_category' => 'CloudUsersManagementService',
  2844. 'verb' => 'DeleteAccount',
  2845. 'expected result' => false,
  2846. 'explain result' => 'wrong login',
  2847. 'args' => array(
  2848. 'admin', /* sAdminLogin */
  2849. 'admin', /* sAdminPassword */
  2850. 'taratatata@sdf.com', /* sLogin */
  2851. 'comment on the deletion operation', /* sComment */
  2852. ),
  2853. ),
  2854. );
  2855. abstract class TestSoap extends TestSoapWebService
  2856. {
  2857. static public function GetName() {return 'Test SOAP';}
  2858. static public function GetDescription() {return 'Do basic stuff to test the SOAP capability';}
  2859. protected $m_aTestSpecs;
  2860. protected function DoExecute()
  2861. {
  2862. 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";
  2863. $aSOAPMapping = SOAPMapping::GetMapping();
  2864. // this file is generated dynamically with location = here
  2865. $sWsdlUri = 'http'.(utils::IsConnectionSecure() ? 's' : '').'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER['SCRIPT_NAME']).'/../webservices/itop.wsdl.php';
  2866. ini_set("soap.wsdl_cache_enabled","0");
  2867. foreach ($this->m_aTestSpecs as $iPos => $aWebService)
  2868. {
  2869. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  2870. echo "<p>Using WSDL: $sWsdlUriForService</p>\n";
  2871. echo "<p>{$aWebService['explain result']}</p>\n";
  2872. $sWsdlUriForService = $sWsdlUri.'?service_category='.$aWebService['service_category'];
  2873. $this->m_SoapClient = new SoapClient
  2874. (
  2875. $sWsdlUriForService,
  2876. array(
  2877. 'classmap' => $aSOAPMapping,
  2878. 'trace' => 1,
  2879. )
  2880. );
  2881. if (false)
  2882. {
  2883. self::DumpVariable($this->m_SoapClient->__getTypes());
  2884. }
  2885. try
  2886. {
  2887. $oRes = call_user_func_array(array($this->m_SoapClient, $aWebService['verb']), $aWebService['args']);
  2888. }
  2889. catch(SoapFault $e)
  2890. {
  2891. print "<pre>\n";
  2892. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  2893. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  2894. print "</pre>";
  2895. print "Response in HTML: <p>".$this->m_SoapClient->__getLastResponse()."</p>";
  2896. throw $e;
  2897. }
  2898. self::DumpVariable($oRes);
  2899. print "<pre>\n";
  2900. print "Request: \n".htmlspecialchars($this->m_SoapClient->__getLastRequest()) ."\n";
  2901. print "Response: \n".htmlspecialchars($this->m_SoapClient->__getLastResponse())."\n";
  2902. print "</pre>";
  2903. if ($oRes instanceof SOAPResult)
  2904. {
  2905. $res = $oRes->status;
  2906. }
  2907. elseif ($oRes instanceof SOAPSimpleResult)
  2908. {
  2909. $res = $oRes->status;
  2910. }
  2911. else
  2912. {
  2913. $res = $oRes;
  2914. }
  2915. if ($res != $aWebService['expected result'])
  2916. {
  2917. echo "Expecting:<br/>\n";
  2918. var_dump($aWebService['expected result']);
  2919. echo "Obtained:<br/>\n";
  2920. var_dump($res);
  2921. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  2922. }
  2923. }
  2924. }
  2925. }
  2926. abstract class TestSoapDirect extends TestBizModel
  2927. {
  2928. static public function GetName() {return 'Test web services locally';}
  2929. static public function GetDescription() {return 'Invoke the service directly (troubleshooting)';}
  2930. protected $m_aTestSpecs;
  2931. protected function DoExecute()
  2932. {
  2933. foreach ($this->m_aTestSpecs as $iPos => $aWebService)
  2934. {
  2935. $sServiceClass = $aWebService['service_category'];
  2936. if (empty($sServiceClass)) $sServiceClass = 'BasicServices';
  2937. $oWebServices = new $sServiceClass();
  2938. echo "<h2>SOAP call #$iPos - {$aWebService['verb']}</h2>\n";
  2939. echo "<p>{$aWebService['explain result']}</p>\n";
  2940. $oRes = call_user_func_array(array($oWebServices, $aWebService['verb']), $aWebService['args']);
  2941. self::DumpVariable($oRes);
  2942. if ($oRes instanceof SOAPResult)
  2943. {
  2944. $res = $oRes->status;
  2945. }
  2946. elseif ($oRes instanceof SOAPSimpleResult)
  2947. {
  2948. $res = $oRes->status;
  2949. }
  2950. else
  2951. {
  2952. $res = $oRes;
  2953. }
  2954. if ($res != $aWebService['expected result'])
  2955. {
  2956. echo "Expecting:<br/>\n";
  2957. var_dump($aWebService['expected result']);
  2958. echo "Obtained:<br/>\n";
  2959. var_dump($res);
  2960. throw new UnitTestException("Expecting result '{$aWebService['expected result']}', but got '$res'");
  2961. }
  2962. }
  2963. return true;
  2964. }
  2965. }
  2966. class TestSoap_Tickets extends TestSoap
  2967. {
  2968. static public function GetName() {return 'Test SOAP - create ticket';}
  2969. protected function DoExecute()
  2970. {
  2971. global $aCreateTicketSpecs;
  2972. $this->m_aTestSpecs = $aCreateTicketSpecs;
  2973. return parent::DoExecute();
  2974. }
  2975. }
  2976. class TestSoapDirect_Tickets extends TestSoapDirect
  2977. {
  2978. static public function GetName() {return 'Test SOAP without SOAP - create ticket';}
  2979. protected function DoExecute()
  2980. {
  2981. global $aCreateTicketSpecs;
  2982. $this->m_aTestSpecs = $aCreateTicketSpecs;
  2983. return parent::DoExecute();
  2984. }
  2985. }
  2986. class TestSoap_ManageCloudUsers extends TestSoap
  2987. {
  2988. static public function GetName() {return 'Test SOAP - manage Cloud Users';}
  2989. protected function DoExecute()
  2990. {
  2991. global $aManageCloudUsersSpecs;
  2992. $this->m_aTestSpecs = $aManageCloudUsersSpecs;
  2993. return parent::DoExecute();
  2994. }
  2995. }
  2996. class TestSoapDirect_ManageCloudUsers extends TestSoapDirect
  2997. {
  2998. static public function GetName() {return 'Test SOAP without SOAP - manage Cloud Users';}
  2999. protected function DoExecute()
  3000. {
  3001. global $aManageCloudUsersSpecs;
  3002. $this->m_aTestSpecs = $aManageCloudUsersSpecs;
  3003. return parent::DoExecute();
  3004. }
  3005. }
  3006. ////////////////////// End of SOAP TESTS
  3007. class TestTriggerAndEmail extends TestBizModel
  3008. {
  3009. static public function GetName() {return 'Test trigger and email';}
  3010. static public function GetDescription() {return 'Create a trigger and an email, then activates the trigger';}
  3011. protected function CreateEmailSpec($oTrigger, $sStatus, $sTo, $sCC, $sTesterEmail)
  3012. {
  3013. $oAction = MetaModel::NewObject("ActionEmail");
  3014. $oAction->Set("status", $sStatus);
  3015. $oAction->Set("name", "New server");
  3016. $oAction->Set("test_recipient", $sTesterEmail);
  3017. $oAction->Set("from", $sTesterEmail);
  3018. $oAction->Set("reply_to", $sTesterEmail);
  3019. $oAction->Set("to", $sTo);
  3020. $oAction->Set("cc", $sCC);
  3021. $oAction->Set("bcc", "");
  3022. $oAction->Set("subject", "New server: '\$this->name()$'");
  3023. $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>");
  3024. $oAction->Set("importance", "low");
  3025. $iActionId = $this->ObjectToDB($oAction, true);
  3026. $oLink = MetaModel::NewObject("lnkTriggerAction");
  3027. $oLink->Set("trigger_id", $oTrigger->GetKey());
  3028. $oLink->Set("action_id", $iActionId);
  3029. $oLink->Set("order", "1");
  3030. $iLink = $this->ObjectToDB($oLink, true);
  3031. }
  3032. protected function DoExecute()
  3033. {
  3034. $oMyPerson = MetaModel::NewObject("Person");
  3035. $oMyPerson->Set("name", "testemail1");
  3036. $oMyPerson->Set("first_name", "theodore");
  3037. $oMyPerson->Set("org_id", "1");
  3038. $oMyPerson->Set("email", "romain.quetiez@combodo.com");
  3039. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  3040. $oMyPerson = MetaModel::NewObject("Person");
  3041. $oMyPerson->Set("name", "testemail2");
  3042. $oMyPerson->Set("first_name", "theodore");
  3043. $oMyPerson->Set("org_id", "1");
  3044. $oMyPerson->Set("email", "denis.flaven@combodo.com");
  3045. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  3046. $oMyPerson = MetaModel::NewObject("Person");
  3047. $oMyPerson->Set("name", "testemail3");
  3048. $oMyPerson->Set("first_name", "theodore");
  3049. $oMyPerson->Set("org_id", "1");
  3050. $oMyPerson->Set("email", "erwan.taloc@combodo.com");
  3051. $iPersonId = $this->ObjectToDB($oMyPerson, true);
  3052. $oMyServer = MetaModel::NewObject("Server");
  3053. $oMyServer->Set("name", "wfr.terminator.com");
  3054. $oMyServer->Set("status", "production");
  3055. $oMyServer->Set("org_id", 2);
  3056. $iServerId = $this->ObjectToDB($oMyServer, true);
  3057. $oMyTrigger = MetaModel::NewObject("TriggerOnStateEnter");
  3058. $oMyTrigger->Set("description", "Testor");
  3059. $oMyTrigger->Set("target_class", "Server");
  3060. $oMyTrigger->Set("state", "Shipped");
  3061. $iTriggerId = $this->ObjectToDB($oMyTrigger, true);
  3062. // Error in OQL field(s)
  3063. //
  3064. $this->CreateEmailSpec
  3065. (
  3066. $oMyTrigger,
  3067. 'test',
  3068. "SELECT Person WHERE naime = 'Dali'",
  3069. "SELECT Server",
  3070. 'romain.quetiez@combodo.com'
  3071. );
  3072. // Error: no recipient
  3073. //
  3074. $this->CreateEmailSpec
  3075. (
  3076. $oMyTrigger,
  3077. 'test',
  3078. "",
  3079. "",
  3080. 'romain.quetiez@combodo.com'
  3081. );
  3082. // Test
  3083. //
  3084. $this->CreateEmailSpec
  3085. (
  3086. $oMyTrigger,
  3087. 'test',
  3088. "SELECT Person WHERE name LIKE 'testemail%'",
  3089. "SELECT Person",
  3090. 'romain.quetiez@combodo.com'
  3091. );
  3092. // Test failing because of a wrong test recipient address
  3093. //
  3094. $this->CreateEmailSpec
  3095. (
  3096. $oMyTrigger,
  3097. 'test',
  3098. "SELECT Person WHERE name LIKE 'testemail%'",
  3099. "",
  3100. 'toto@walibi.bg'
  3101. );
  3102. // Normal behavior
  3103. //
  3104. $this->CreateEmailSpec
  3105. (
  3106. $oMyTrigger,
  3107. 'enabled',
  3108. "SELECT Person WHERE name LIKE 'testemail%'",
  3109. "",
  3110. 'romain.quetiez@combodo.com'
  3111. );
  3112. // Does nothing, because it is disabled
  3113. //
  3114. $this->CreateEmailSpec
  3115. (
  3116. $oMyTrigger,
  3117. 'disabled',
  3118. "SELECT Person WHERE name = 'testemail%'",
  3119. "",
  3120. 'romain.quetiez@combodo.com'
  3121. );
  3122. $oMyTrigger->DoActivate($oMyServer->ToArgs('this'));
  3123. return true;
  3124. }
  3125. }
  3126. class TestDBProperties extends TestBizModel
  3127. {
  3128. static public function GetName()
  3129. {
  3130. return 'Itop - DB Properties';
  3131. }
  3132. static public function GetDescription()
  3133. {
  3134. return 'Write and read a dummy property';
  3135. }
  3136. protected function DoExecute()
  3137. {
  3138. $sName = 'test';
  3139. DBProperty::SetProperty($sName, 'unix time:'.time(), 'means nothing', 'done with the automated test utility');
  3140. $sValue = DBProperty::GetProperty($sName, 'defaults to this because the table has not been created (1.0.1 install?)');
  3141. echo "<p>Write... then read property <b>$sName</b>, found: '$sValue'</p>\n";
  3142. }
  3143. }
  3144. class TestCreateObjects extends TestBizModel
  3145. {
  3146. static public function GetName()
  3147. {
  3148. return 'Itop - create objects';
  3149. }
  3150. static public function GetDescription()
  3151. {
  3152. return 'Create weird objects (reproduce a bug?)';
  3153. }
  3154. protected function DoExecute()
  3155. {
  3156. $oMyObj = MetaModel::NewObject("Server");
  3157. $oMyObj->Set("name", "test".rand(1,1000));
  3158. $oMyObj->Set("org_id", 2);
  3159. $oMyObj->Set("status", 'production');
  3160. $this->ObjectToDB($oMyObj, $bReload = true);
  3161. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  3162. $sTicketRef = "I-abcdef";
  3163. echo "<p>Creating: $sTicketRef</p>";
  3164. $oMyObj = MetaModel::NewObject("Incident");
  3165. $oMyObj->Set("ref", $sTicketRef);
  3166. $oMyObj->Set("title", "my title");
  3167. $oMyObj->Set("description", "my description");
  3168. $oMyObj->Set("ticket_log", "my ticket log");
  3169. $oMyObj->Set("start_date", "2010-03-08 17:37:00");
  3170. $oMyObj->Set("status", "resolved");
  3171. $oMyObj->Set("caller_id", 1);
  3172. $oMyObj->Set("org_id", 1);
  3173. $oMyObj->Set("urgency", 3);
  3174. $oMyObj->Set("agent_id", 1);
  3175. $oMyObj->Set("close_date", "0000-00-00 00:00:00");
  3176. $oMyObj->Set("last_update", "2010-04-08 16:47:29");
  3177. $oMyObj->Set("solution", "branche ton pc!");
  3178. // External key given as a string -> should be casted to an integer
  3179. $oMyObj->Set("service_id", "1");
  3180. $oMyObj->Set("servicesubcategory_id", "1");
  3181. $oMyObj->Set("product", "");
  3182. $oMyObj->Set("impact", 2);
  3183. $oMyObj->Set("priority", 3);
  3184. $oMyObj->Set("related_problem_id", 0);
  3185. $oMyObj->Set("related_change_id", 0);
  3186. $oMyObj->Set("assignment_date", "");
  3187. $oMyObj->Set("resolution_date", "");
  3188. $oMyObj->Set("tto_escalation_deadline", "");
  3189. $oMyObj->Set("ttr_escalation_deadline", "");
  3190. $oMyObj->Set("closure_deadline", "");
  3191. $oMyObj->Set("resolution_code", "fixed");
  3192. $oMyObj->Set("user_satisfaction", "");
  3193. $oMyObj->Set("user_commment", "");
  3194. $oMyObj->Set("workgroup_id", 4);
  3195. $this->ObjectToDB($oMyObj, $bReload = true);
  3196. echo "<p>Created: {$oMyObj->GetHyperLink()}</p>";
  3197. }
  3198. }
  3199. class TestSetLinkset extends TestBizModel
  3200. {
  3201. static public function GetName()
  3202. {
  3203. return 'Itop - Link set from a string';
  3204. }
  3205. static public function GetDescription()
  3206. {
  3207. return 'Create a user account, setting its profile by the mean of a string (prerequisite to CSV import of linksets)';
  3208. }
  3209. protected function DoExecute()
  3210. {
  3211. $oUser = new UserLocal();
  3212. $oUser->Set('login', 'patator'.time());
  3213. $oUser->Set('password', 'patator');
  3214. //$oUser->Set('contactid', 0);
  3215. //$oUser->Set('language', $sLanguage);
  3216. $sLinkSetSpec = "profileid:10;reason:service manager|profileid->name:Problem Manager;'reason:problem manager;glandeur";
  3217. $oAttDef = MetaModel::GetAttributeDef('UserLocal', 'profile_list');
  3218. $oSet = $oAttDef->MakeValueFromString($sLinkSetSpec, $bLocalizedValue = false);
  3219. $oUser->Set('profile_list', $oSet);
  3220. // Create a change to record the history of the User object
  3221. $this->ObjectToDB($oUser, $bReload = true);
  3222. echo "<p>Created: {$oUser->GetHyperLink()}</p>";
  3223. }
  3224. }
  3225. class TestEmailAsynchronous extends TestBizModel
  3226. {
  3227. static public function GetName()
  3228. {
  3229. return 'Itop - Asynchronous email';
  3230. }
  3231. static public function GetDescription()
  3232. {
  3233. return 'Queues a request to send an email';
  3234. }
  3235. protected function DoExecute()
  3236. {
  3237. for ($i = 0 ; $i < 2 ; $i++)
  3238. {
  3239. $oMail = new Email();
  3240. $oMail->SetRecipientTO('romain.quetiez@combodo.com');
  3241. $oMail->SetRecipientFrom('romain.quetiez@combodo.com');
  3242. $oMail->SetRecipientCC('romainquetiez@yahoo.fr');
  3243. $oMail->SetSubject('automated test - '.$i);
  3244. $oMail->SetBody('this is one is entirely working fine '.time());
  3245. $iRes = $oMail->Send($aIssues, false);
  3246. switch ($iRes)
  3247. {
  3248. case EMAIL_SEND_OK:
  3249. echo "EMAIL_SEND_OK<br/>\n";
  3250. break;
  3251. case EMAIL_SEND_PENDING:
  3252. echo "EMAIL_SEND_PENDING<br/>\n";
  3253. break;
  3254. case EMAIL_SEND_ERROR:
  3255. echo "EMAIL_SEND_ERROR: <br/>\n";
  3256. foreach($aIssues as $sIssue)
  3257. {
  3258. echo "Issue: $sIssue<br/>\n";
  3259. }
  3260. break;
  3261. }
  3262. }
  3263. }
  3264. }
  3265. class TestLinkSetRecording_NN_WithDuplicates extends TestBizModel
  3266. {
  3267. static public function GetName()
  3268. {
  3269. return 'Linkset N-N having duplicated allowed (Connectable CI to Network Device)';
  3270. }
  3271. static public function GetDescription()
  3272. {
  3273. return 'Simulate CSV/data synchro type of recording. Check the values and the history. Lots of issues there: #1145, #1146 and #1147';
  3274. }
  3275. protected function DoExecute()
  3276. {
  3277. CMDBSource::Query('START TRANSACTION');
  3278. //CMDBSource::Query('ROLLBACK'); automatique !
  3279. ////////////////////////////////////////////////////////////////////////////////
  3280. // Set the stage
  3281. //
  3282. $oServer = MetaModel::NewObject('Server');
  3283. $oServer->Set('name', 'unit test linkset');
  3284. $oServer->Set('org_id', 3);
  3285. $oServer->DBInsert();
  3286. $iServer = $oServer->GetKey();
  3287. $oTypes = new DBObjectSet(DBObjectSearch::FromOQL('SELECT NetworkDeviceType WHERE name = "Router"'));
  3288. $oType = $oTypes->fetch();
  3289. $oDevice = MetaModel::NewObject('NetworkDevice');
  3290. $oDevice->Set('name', 'test device A');
  3291. $oDevice->Set('org_id', 3);
  3292. $oDevice->Set('networkdevicetype_id', $oType->GetKey());
  3293. $oDevice->DBInsert();
  3294. $iDev1 = $oDevice->GetKey();
  3295. $oDevice = MetaModel::NewObject('NetworkDevice');
  3296. $oDevice->Set('name', 'test device B');
  3297. $oDevice->Set('org_id', 3);
  3298. $oDevice->Set('networkdevicetype_id', $oType->GetKey());
  3299. $oDevice->DBInsert();
  3300. $iDev2 = $oDevice->GetKey();
  3301. ////////////////////////////////////////////////////////////////////////////////
  3302. // Scenarii
  3303. //
  3304. $aScenarii = array(
  3305. array(
  3306. 'description' => 'Add the first item',
  3307. 'links' => array(
  3308. array(
  3309. 'networkdevice_id' => $iDev1,
  3310. 'connectableci_id' => $iServer,
  3311. 'network_port' => '',
  3312. 'device_port' => '',
  3313. ),
  3314. ),
  3315. 'expected-res' => array (
  3316. "$iDev1, test device A, unit test linkset, , , downlink, test device A",
  3317. ),
  3318. 'history_added' => 1,
  3319. 'history_removed' => 0,
  3320. 'history_modified' => 0,
  3321. ),
  3322. array(
  3323. 'description' => 'Modify the unique item',
  3324. 'links' => array(
  3325. array(
  3326. 'networkdevice_id' => $iDev1,
  3327. 'connectableci_id' => $iServer,
  3328. 'network_port' => 'devTagada',
  3329. 'device_port' => '',
  3330. ),
  3331. ),
  3332. 'expected-res' => array (
  3333. "$iDev1, test device A, unit test linkset, devTagada, , downlink, test device A",
  3334. ),
  3335. 'history_added' => 1,
  3336. 'history_removed' => 1,
  3337. 'history_modified' => 0,
  3338. ),
  3339. array(
  3340. 'description' => 'Modify again the original item and add a second item',
  3341. 'links' => array(
  3342. array(
  3343. 'networkdevice_id' => $iDev1,
  3344. 'connectableci_id' => $iServer,
  3345. 'network_port' => '',
  3346. 'device_port' => '',
  3347. ),
  3348. array(
  3349. 'networkdevice_id' => $iDev2,
  3350. 'connectableci_id' => $iServer,
  3351. 'network_port' => '',
  3352. 'device_port' => '',
  3353. ),
  3354. ),
  3355. 'expected-res' => array (
  3356. "$iDev1, test device A, unit test linkset, , , downlink, test device A",
  3357. "$iDev2, test device B, unit test linkset, , , downlink, test device B",
  3358. ),
  3359. 'history_added' => 2,
  3360. 'history_removed' => 1,
  3361. 'history_modified' => 0,
  3362. ),
  3363. array(
  3364. 'description' => 'No change, the links are added in the reverse order',
  3365. 'links' => array(
  3366. array(
  3367. 'networkdevice_id' => $iDev2,
  3368. 'connectableci_id' => $iServer,
  3369. 'network_port' => '',
  3370. 'device_port' => '',
  3371. ),
  3372. array(
  3373. 'networkdevice_id' => $iDev1,
  3374. 'connectableci_id' => $iServer,
  3375. 'network_port' => '',
  3376. 'device_port' => '',
  3377. ),
  3378. ),
  3379. 'expected-res' => array (
  3380. "$iDev1, test device A, unit test linkset, , , downlink, test device A",
  3381. "$iDev2, test device B, unit test linkset, , , downlink, test device B",
  3382. ),
  3383. 'history_added' => 0,
  3384. 'history_removed' => 0,
  3385. 'history_modified' => 0,
  3386. ),
  3387. array(
  3388. 'description' => 'Change on attribute on both links at the same time',
  3389. 'links' => array(
  3390. array(
  3391. 'networkdevice_id' => $iDev2,
  3392. 'connectableci_id' => $iServer,
  3393. 'network_port' => 'PortDev B',
  3394. 'device_port' => '',
  3395. ),
  3396. array(
  3397. 'networkdevice_id' => $iDev1,
  3398. 'connectableci_id' => $iServer,
  3399. 'network_port' => 'PortDev A',
  3400. 'device_port' => '',
  3401. ),
  3402. ),
  3403. 'expected-res' => array (
  3404. "$iDev1, test device A, unit test linkset, PortDev A, , downlink, test device A",
  3405. "$iDev2, test device B, unit test linkset, PortDev B, , downlink, test device B",
  3406. ),
  3407. 'history_added' => 2,
  3408. 'history_removed' => 2,
  3409. 'history_modified' => 0,
  3410. ),
  3411. array(
  3412. 'description' => 'Removing A',
  3413. 'links' => array(
  3414. array(
  3415. 'networkdevice_id' => $iDev2,
  3416. 'connectableci_id' => $iServer,
  3417. 'network_port' => 'PortDev B',
  3418. 'device_port' => '',
  3419. ),
  3420. ),
  3421. 'expected-res' => array (
  3422. "$iDev2, test device B, unit test linkset, PortDev B, , downlink, test device B",
  3423. ),
  3424. 'history_added' => 0,
  3425. 'history_removed' => 1,
  3426. 'history_modified' => 0,
  3427. ),
  3428. array(
  3429. 'description' => 'Adding B again - with a different port (duplicate!)',
  3430. 'links' => array(
  3431. array(
  3432. 'networkdevice_id' => $iDev2,
  3433. 'connectableci_id' => $iServer,
  3434. 'network_port' => 'port_123',
  3435. 'device_port' => '',
  3436. ),
  3437. array(
  3438. 'networkdevice_id' => $iDev2,
  3439. 'connectableci_id' => $iServer,
  3440. 'network_port' => 'port_456',
  3441. 'device_port' => '',
  3442. ),
  3443. ),
  3444. 'expected-res' => array (
  3445. "$iDev2, test device B, unit test linkset, port_123, , downlink, test device B",
  3446. "$iDev2, test device B, unit test linkset, port_456, , downlink, test device B",
  3447. ),
  3448. 'history_added' => 2,
  3449. 'history_removed' => 1,
  3450. 'history_modified' => 0,
  3451. ),
  3452. array(
  3453. 'description' => 'No change (creating a set with the reloaded links, like in the UI)',
  3454. 'links' => array(
  3455. array(
  3456. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer AND network_port = 'port_123'",
  3457. 'networkdevice_id' => $iDev2,
  3458. 'connectableci_id' => $iServer,
  3459. 'network_port' => 'port_123',
  3460. 'device_port' => '',
  3461. ),
  3462. array(
  3463. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer AND network_port = 'port_456'",
  3464. 'networkdevice_id' => $iDev2,
  3465. 'connectableci_id' => $iServer,
  3466. 'network_port' => 'port_456',
  3467. 'device_port' => '',
  3468. ),
  3469. ),
  3470. 'expected-res' => array (
  3471. "$iDev2, test device B, unit test linkset, port_123, , downlink, test device B",
  3472. "$iDev2, test device B, unit test linkset, port_456, , downlink, test device B",
  3473. ),
  3474. 'history_added' => 0,
  3475. 'history_removed' => 0,
  3476. 'history_modified' => 0,
  3477. ),
  3478. array(
  3479. 'description' => 'Change an attribute on one link (based on reloaded links, like in the UI)',
  3480. 'links' => array(
  3481. array(
  3482. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer AND network_port = 'port_123'",
  3483. 'networkdevice_id' => $iDev2,
  3484. 'connectableci_id' => $iServer,
  3485. 'network_port' => 'port_123_modified',
  3486. 'device_port' => '',
  3487. ),
  3488. array(
  3489. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer AND network_port = 'port_456'",
  3490. 'networkdevice_id' => $iDev2,
  3491. 'connectableci_id' => $iServer,
  3492. 'network_port' => 'port_456',
  3493. 'device_port' => '',
  3494. ),
  3495. ),
  3496. 'expected-res' => array (
  3497. "$iDev2, test device B, unit test linkset, port_123_modified, , downlink, test device B",
  3498. "$iDev2, test device B, unit test linkset, port_456, , downlink, test device B",
  3499. ),
  3500. 'history_added' => 0,
  3501. 'history_removed' => 0,
  3502. 'history_modified' => 1,
  3503. ),
  3504. array(
  3505. 'description' => 'Remove the second link (set based on reloaded links, like in the UI)',
  3506. 'links' => array(
  3507. array(
  3508. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer AND network_port = 'port_123_modified'",
  3509. 'networkdevice_id' => $iDev2,
  3510. 'connectableci_id' => $iServer,
  3511. 'network_port' => 'port_123_modified',
  3512. 'device_port' => '',
  3513. ),
  3514. ),
  3515. 'expected-res' => array (
  3516. "$iDev2, test device B, unit test linkset, port_123_modified, , downlink, test device B",
  3517. ),
  3518. 'history_added' => 0,
  3519. 'history_removed' => 1,
  3520. 'history_modified' => 0,
  3521. ),
  3522. array(
  3523. 'description' => 'Remove all',
  3524. 'links' => array(
  3525. ),
  3526. 'expected-res' => array (
  3527. ),
  3528. 'history_added' => 0,
  3529. 'history_removed' => 1,
  3530. 'history_modified' => 0,
  3531. ),
  3532. array(
  3533. 'description' => 'Create one link from scratch, no port, to prepare for the next test case',
  3534. 'links' => array(
  3535. array(
  3536. 'networkdevice_id' => $iDev2,
  3537. 'connectableci_id' => $iServer,
  3538. 'network_port' => '',
  3539. 'device_port' => '',
  3540. ),
  3541. ),
  3542. 'expected-res' => array (
  3543. "$iDev2, test device B, unit test linkset, , , downlink, test device B",
  3544. ),
  3545. 'history_added' => 1,
  3546. 'history_removed' => 0,
  3547. 'history_modified' => 0,
  3548. ),
  3549. array(
  3550. 'description' => 'Create a second link from scratch, pointing to the same server and no port, to prepare for the next test case',
  3551. 'links' => array(
  3552. array(
  3553. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer",
  3554. 'networkdevice_id' => $iDev2,
  3555. 'connectableci_id' => $iServer,
  3556. 'network_port' => '',
  3557. 'device_port' => '',
  3558. ),
  3559. array(
  3560. 'networkdevice_id' => $iDev2,
  3561. 'connectableci_id' => $iServer,
  3562. 'network_port' => 'X',
  3563. 'device_port' => '',
  3564. ),
  3565. ),
  3566. 'expected-res' => array (
  3567. "$iDev2, test device B, unit test linkset, , , downlink, test device B",
  3568. "$iDev2, test device B, unit test linkset, X, , downlink, test device B",
  3569. ),
  3570. 'history_added' => 1,
  3571. 'history_removed' => 0,
  3572. 'history_modified' => 0,
  3573. ),
  3574. array(
  3575. 'description' => 'Create a second link from scratch, pointing to the same server and no port, to prepare for the next test case',
  3576. 'links' => array(
  3577. array(
  3578. 'id' => "SELECT lnkConnectableCIToNetworkDevice WHERE networkdevice_id = $iDev2 AND connectableci_id = $iServer",
  3579. 'networkdevice_id' => $iDev2,
  3580. 'connectableci_id' => $iServer,
  3581. 'network_port' => '',
  3582. 'device_port' => '',
  3583. ),
  3584. array(
  3585. 'networkdevice_id' => $iDev2,
  3586. 'connectableci_id' => $iServer,
  3587. 'network_port' => 'X',
  3588. 'device_port' => '',
  3589. ),
  3590. ),
  3591. 'expected-res' => array (
  3592. "$iDev2, test device B, unit test linkset, , , downlink, test device B",
  3593. "$iDev2, test device B, unit test linkset, X, , downlink, test device B",
  3594. ),
  3595. 'history_added' => 1,
  3596. 'history_removed' => 0,
  3597. 'history_modified' => 0,
  3598. ),
  3599. array(
  3600. 'description' => 'Device B twice (same characteristics) - known issue #1145',
  3601. 'links' => array(
  3602. array(
  3603. 'networkdevice_id' => $iDev2,
  3604. 'connectableci_id' => $iServer,
  3605. 'network_port' => 'portX',
  3606. 'device_port' => '',
  3607. ),
  3608. array(
  3609. 'networkdevice_id' => $iDev2,
  3610. 'connectableci_id' => $iServer,
  3611. 'network_port' => 'portX',
  3612. 'device_port' => '',
  3613. ),
  3614. ),
  3615. 'expected-res' => array (
  3616. "$iDev2, test device B, unit test linkset, portX, , downlink, test device B",
  3617. "$iDev2, test device B, unit test linkset, portX, , downlink, test device B",
  3618. ),
  3619. 'history_added' => 1,
  3620. 'history_removed' => 0,
  3621. 'history_modified' => 0,
  3622. ),
  3623. );
  3624. foreach ($aScenarii as $aScenario)
  3625. {
  3626. echo "<h4>".$aScenario['description']."</h4>\n";
  3627. $oChange = MetaModel::NewObject("CMDBChange");
  3628. $oChange->Set("date", time());
  3629. $oChange->Set("userinfo", CMDBChange::GetCurrentUserName());
  3630. $oChange->Set("origin", 'custom-extension');
  3631. $oChange->DBInsert();
  3632. CMDBObject::SetCurrentChange($oChange);
  3633. $iChange = $oChange->GetKey();
  3634. // Prepare set
  3635. $oLinkset = DBObjectSet::FromScratch('lnkConnectableCIToNetworkDevice');
  3636. foreach ($aScenario['links'] as $aLinkData)
  3637. {
  3638. if (array_key_exists('id', $aLinkData))
  3639. {
  3640. $sOQL = $aLinkData['id'];
  3641. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  3642. $oLink1 = $oSet->Fetch();
  3643. if (!is_object($oLink1)) throw new Exception('Failed to find the lnkConnectableCIToNetworkDevice: '.$sOQL);
  3644. }
  3645. else
  3646. {
  3647. $oLink1 = MetaModel::NewObject('lnkConnectableCIToNetworkDevice');
  3648. }
  3649. foreach ($aLinkData as $sAttCode => $value)
  3650. {
  3651. if ($sAttCode == 'id') continue;
  3652. $oLink1->Set($sAttCode, $value);
  3653. }
  3654. $oLinkset->AddObject($oLink1);
  3655. }
  3656. // Write
  3657. $oServer = MetaModel::GetObject('Server', $iServer);
  3658. $oServer->Set('networkdevice_list', $oLinkset);
  3659. $oServer->DBWrite();
  3660. // Check Results
  3661. $bFoundIssue = false;
  3662. $oServer = MetaModel::GetObject('Server', $iServer);
  3663. $oLinkset = $oServer->Get('networkdevice_list');
  3664. $aRes = $this->StandardizedDump($oLinkset, 'connectableci_id');
  3665. $sRes = var_export($aRes, true);
  3666. echo "Found: <pre>".$sRes."</pre>\n";
  3667. $sExpectedRes = var_export($aScenario['expected-res'], true);
  3668. if ($sRes != $sExpectedRes)
  3669. {
  3670. $bFoundIssue = true;
  3671. echo "NOT COMPLIANT!!! Expecting: <pre>".$sExpectedRes."</pre>\n";
  3672. }
  3673. // Check History
  3674. $aQueryParams = array('change' => $iChange, 'objclass' => get_class($oServer), 'objkey' => $oServer->GetKey());
  3675. $oAdded = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'added'"), array(), $aQueryParams);
  3676. echo "added: ".$oAdded->Count()."<br/>\n";
  3677. if ($aScenario['history_added'] != $oAdded->Count())
  3678. {
  3679. $bFoundIssue = true;
  3680. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_added']."<br/>\n";
  3681. }
  3682. $oRemoved = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'removed'"), array(), $aQueryParams);
  3683. echo "removed: ".$oRemoved->Count()."<br/>\n";
  3684. if ($aScenario['history_removed'] != $oRemoved->Count())
  3685. {
  3686. $bFoundIssue = true;
  3687. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_removed']."<br/>\n";
  3688. }
  3689. $oModified = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksTune WHERE objclass = :objclass AND objkey = :objkey AND change = :change"), array(), $aQueryParams);
  3690. echo "modified: ".$oModified->Count()."<br/>\n";
  3691. if ($aScenario['history_modified'] != $oModified->Count())
  3692. {
  3693. $bFoundIssue = true;
  3694. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_modified']."<br/>\n";
  3695. }
  3696. if ($bFoundIssue)
  3697. {
  3698. throw new Exception('Stopping on failed scenario');
  3699. }
  3700. }
  3701. }
  3702. protected function StandardizedDump($oSet, $sAttPrefixToIgnore)
  3703. {
  3704. if (!$oSet->m_bLoaded) $oSet->Load();
  3705. $oSet->Rewind();
  3706. $aRet = array();
  3707. while($oObject = $oSet->Fetch())
  3708. {
  3709. $aValues = array();
  3710. foreach(MetaModel::ListAttributeDefs(get_class($oObject)) as $sAttCode => $oAttDef)
  3711. {
  3712. if ($sAttCode == 'friendlyname') continue;
  3713. if (substr($sAttCode, 0, strlen($sAttPrefixToIgnore)) == $sAttPrefixToIgnore) continue;
  3714. if ($oAttDef->IsScalar())
  3715. {
  3716. $aValues[] = $oObject->Get($sAttCode);
  3717. }
  3718. }
  3719. $aRet[] = implode(', ', $aValues);
  3720. }
  3721. sort($aRet);
  3722. return $aRet;
  3723. }
  3724. }
  3725. class TestLinkSetRecording_NN_NoDuplicates extends TestBizModel
  3726. {
  3727. static public function GetName()
  3728. {
  3729. return 'Linksets N-N in general (99% of them)';
  3730. }
  3731. static public function GetDescription()
  3732. {
  3733. return 'Simulate CSV/data synchro type of recording. Check the values and the history.';
  3734. }
  3735. protected function DoExecute()
  3736. {
  3737. CMDBSource::Query('START TRANSACTION');
  3738. //CMDBSource::Query('ROLLBACK'); automatique !
  3739. ////////////////////////////////////////////////////////////////////////////////
  3740. // Set the stage
  3741. //
  3742. $oTeam = MetaModel::NewObject('Team');
  3743. $oTeam->Set('name', 'unit test linkset');
  3744. $oTeam->Set('org_id', 3);
  3745. $oTeam->DBInsert();
  3746. $iTeam = $oTeam->GetKey();
  3747. $oPerson = MetaModel::NewObject('Person');
  3748. $oPerson->Set('name', 'test person A');
  3749. $oPerson->Set('first_name', 'totoche');
  3750. $oPerson->Set('org_id', 3);
  3751. $oPerson->DBInsert();
  3752. $iPerson1 = $oPerson->GetKey();
  3753. $oPerson = MetaModel::NewObject('Person');
  3754. $oPerson->Set('name', 'test person B');
  3755. $oPerson->Set('first_name', 'totoche');
  3756. $oPerson->Set('org_id', 3);
  3757. $oPerson->DBInsert();
  3758. $iPerson2 = $oPerson->GetKey();
  3759. $oTypes = new DBObjectSet(DBSearch::FromOQL('SELECT ContactType WHERE name="Manager"'));
  3760. $iRole = $oTypes->Fetch()->GetKey();
  3761. ////////////////////////////////////////////////////////////////////////////////
  3762. // Scenarii
  3763. //
  3764. $aScenarii = array(
  3765. array(
  3766. 'description' => 'Add the first item',
  3767. 'links' => array(
  3768. array(
  3769. 'person_id' => $iPerson1,
  3770. 'team_id' => $iTeam,
  3771. 'role_id' => 0,
  3772. ),
  3773. ),
  3774. 'expected-res' => array (
  3775. "unit test linkset, $iPerson1, test person A, 0, , totoche test person A, ",
  3776. ),
  3777. 'history_added' => 1,
  3778. 'history_removed' => 0,
  3779. 'history_modified' => 0,
  3780. ),
  3781. array(
  3782. 'description' => 'Modify the unique item',
  3783. 'links' => array(
  3784. array(
  3785. 'person_id' => $iPerson1,
  3786. 'team_id' => $iTeam,
  3787. 'role_id' => $iRole,
  3788. ),
  3789. ),
  3790. 'expected-res' => array (
  3791. "unit test linkset, $iPerson1, test person A, $iRole, Manager, totoche test person A, Manager",
  3792. ),
  3793. 'history_added' => 0,
  3794. 'history_removed' => 0,
  3795. 'history_modified' => 1,
  3796. ),
  3797. array(
  3798. 'description' => 'Modify again the original item and add a second item',
  3799. 'links' => array(
  3800. array(
  3801. 'person_id' => $iPerson1,
  3802. 'team_id' => $iTeam,
  3803. 'role_id' => 0,
  3804. ),
  3805. array(
  3806. 'person_id' => $iPerson2,
  3807. 'team_id' => $iTeam,
  3808. 'role_id' => 0,
  3809. ),
  3810. ),
  3811. 'expected-res' => array (
  3812. "unit test linkset, $iPerson1, test person A, 0, , totoche test person A, ",
  3813. "unit test linkset, $iPerson2, test person B, 0, , totoche test person B, ",
  3814. ),
  3815. 'history_added' => 1,
  3816. 'history_removed' => 0,
  3817. 'history_modified' => 1,
  3818. ),
  3819. array(
  3820. 'description' => 'No change, the links are added in the reverse order',
  3821. 'links' => array(
  3822. array(
  3823. 'person_id' => $iPerson2,
  3824. 'team_id' => $iTeam,
  3825. 'role_id' => 0,
  3826. ),
  3827. array(
  3828. 'person_id' => $iPerson1,
  3829. 'team_id' => $iTeam,
  3830. 'role_id' => 0,
  3831. ),
  3832. ),
  3833. 'expected-res' => array (
  3834. "unit test linkset, $iPerson1, test person A, 0, , totoche test person A, ",
  3835. "unit test linkset, $iPerson2, test person B, 0, , totoche test person B, ",
  3836. ),
  3837. 'history_added' => 0,
  3838. 'history_removed' => 0,
  3839. 'history_modified' => 0,
  3840. ),
  3841. array(
  3842. 'description' => 'Removing A',
  3843. 'links' => array(
  3844. array(
  3845. 'person_id' => $iPerson2,
  3846. 'team_id' => $iTeam,
  3847. 'role_id' => 0,
  3848. ),
  3849. ),
  3850. 'expected-res' => array (
  3851. "unit test linkset, $iPerson2, test person B, 0, , totoche test person B, ",
  3852. ),
  3853. 'history_added' => 0,
  3854. 'history_removed' => 1,
  3855. 'history_modified' => 0,
  3856. ),
  3857. array(
  3858. 'description' => 'Adding B again (duplicate!)',
  3859. 'links' => array(
  3860. array(
  3861. 'person_id' => $iPerson2,
  3862. 'team_id' => $iTeam,
  3863. 'role_id' => 0,
  3864. ),
  3865. array(
  3866. 'person_id' => $iPerson2,
  3867. 'team_id' => $iTeam,
  3868. 'role_id' => 0,
  3869. ),
  3870. ),
  3871. 'expected-res' => array (
  3872. "unit test linkset, $iPerson2, test person B, 0, , totoche test person B, ",
  3873. ),
  3874. 'history_added' => 0,
  3875. 'history_removed' => 0,
  3876. 'history_modified' => 0,
  3877. ),
  3878. array(
  3879. 'description' => 'Remove all',
  3880. 'links' => array(
  3881. ),
  3882. 'expected-res' => array (
  3883. ),
  3884. 'history_added' => 0,
  3885. 'history_removed' => 1,
  3886. 'history_modified' => 0,
  3887. ),
  3888. array(
  3889. 'description' => 'Add the first item (again)',
  3890. 'links' => array(
  3891. array(
  3892. 'person_id' => $iPerson1,
  3893. 'team_id' => $iTeam,
  3894. 'role_id' => 0,
  3895. ),
  3896. ),
  3897. 'expected-res' => array (
  3898. "unit test linkset, $iPerson1, test person A, 0, , totoche test person A, ",
  3899. ),
  3900. 'history_added' => 1,
  3901. 'history_removed' => 0,
  3902. 'history_modified' => 0,
  3903. ),
  3904. array(
  3905. 'description' => 'Set the role (based on reloaded links, like in the UI)',
  3906. 'links' => array(
  3907. array(
  3908. 'id' => "SELECT lnkPersonToTeam WHERE person_id=$iPerson1 AND team_id=$iTeam",
  3909. 'person_id' => $iPerson1,
  3910. 'team_id' => $iTeam,
  3911. 'role_id' => $iRole,
  3912. ),
  3913. ),
  3914. 'expected-res' => array (
  3915. "unit test linkset, $iPerson1, test person A, 14, Manager, totoche test person A, Manager",
  3916. ),
  3917. 'history_added' => 0,
  3918. 'history_removed' => 0,
  3919. 'history_modified' => 1,
  3920. ),
  3921. array(
  3922. 'description' => 'Clear the role and add another person with a role (based on reloaded links, like in the UI)',
  3923. 'links' => array(
  3924. array(
  3925. 'id' => "SELECT lnkPersonToTeam WHERE person_id=$iPerson1 AND team_id=$iTeam",
  3926. 'person_id' => $iPerson1,
  3927. 'team_id' => $iTeam,
  3928. 'role_id' => 0,
  3929. ),
  3930. array(
  3931. 'person_id' => $iPerson2,
  3932. 'team_id' => $iTeam,
  3933. 'role_id' => $iRole,
  3934. ),
  3935. ),
  3936. 'expected-res' => array (
  3937. "unit test linkset, $iPerson1, test person A, 0, , totoche test person A, ",
  3938. "unit test linkset, $iPerson2, test person B, 14, Manager, totoche test person B, Manager",
  3939. ),
  3940. 'history_added' => 1,
  3941. 'history_removed' => 0,
  3942. 'history_modified' => 1,
  3943. ),
  3944. );
  3945. foreach ($aScenarii as $aScenario)
  3946. {
  3947. echo "<h4>".$aScenario['description']."</h4>\n";
  3948. $oChange = MetaModel::NewObject("CMDBChange");
  3949. $oChange->Set("date", time());
  3950. $oChange->Set("userinfo", CMDBChange::GetCurrentUserName());
  3951. $oChange->Set("origin", 'custom-extension');
  3952. $oChange->DBInsert();
  3953. CMDBObject::SetCurrentChange($oChange);
  3954. $iChange = $oChange->GetKey();
  3955. // Prepare set
  3956. $oLinkset = DBObjectSet::FromScratch('lnkPersonToTeam');
  3957. foreach ($aScenario['links'] as $aLinkData)
  3958. {
  3959. if (array_key_exists('id', $aLinkData))
  3960. {
  3961. $sOQL = $aLinkData['id'];
  3962. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  3963. $oLink1 = $oSet->Fetch();
  3964. if (!is_object($oLink1)) throw new Exception('Failed to find the lnkPersonToTeam: '.$sOQL);
  3965. }
  3966. else
  3967. {
  3968. $oLink1 = MetaModel::NewObject('lnkPersonToTeam');
  3969. }
  3970. foreach ($aLinkData as $sAttCode => $value)
  3971. {
  3972. if ($sAttCode == 'id') continue;
  3973. $oLink1->Set($sAttCode, $value);
  3974. }
  3975. $oLinkset->AddObject($oLink1);
  3976. }
  3977. // Write
  3978. $oTeam = MetaModel::GetObject('Team', $iTeam);
  3979. $oTeam->Set('persons_list', $oLinkset);
  3980. $oTeam->DBWrite();
  3981. // Check Results
  3982. $bFoundIssue = false;
  3983. $oTeam = MetaModel::GetObject('Team', $iTeam);
  3984. $oLinkset = $oTeam->Get('persons_list');
  3985. $aRes = $this->StandardizedDump($oLinkset, 'team_id');
  3986. $sRes = var_export($aRes, true);
  3987. echo "Found: <pre>".$sRes."</pre>\n";
  3988. $sExpectedRes = var_export($aScenario['expected-res'], true);
  3989. if ($sRes != $sExpectedRes)
  3990. {
  3991. $bFoundIssue = true;
  3992. echo "NOT COMPLIANT!!! Expecting: <pre>".$sExpectedRes."</pre>\n";
  3993. }
  3994. // Check History
  3995. $aQueryParams = array('change' => $iChange, 'objclass' => get_class($oTeam), 'objkey' => $oTeam->GetKey());
  3996. $oAdded = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'added'"), array(), $aQueryParams);
  3997. echo "added: ".$oAdded->Count()."<br/>\n";
  3998. if ($aScenario['history_added'] != $oAdded->Count())
  3999. {
  4000. $bFoundIssue = true;
  4001. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_added']."<br/>\n";
  4002. }
  4003. $oRemoved = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'removed'"), array(), $aQueryParams);
  4004. echo "removed: ".$oRemoved->Count()."<br/>\n";
  4005. if ($aScenario['history_removed'] != $oRemoved->Count())
  4006. {
  4007. $bFoundIssue = true;
  4008. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_removed']."<br/>\n";
  4009. }
  4010. $oModified = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksTune WHERE objclass = :objclass AND objkey = :objkey AND change = :change"), array(), $aQueryParams);
  4011. echo "modified: ".$oModified->Count()."<br/>\n";
  4012. if ($aScenario['history_modified'] != $oModified->Count())
  4013. {
  4014. $bFoundIssue = true;
  4015. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_modified']."<br/>\n";
  4016. }
  4017. if ($bFoundIssue)
  4018. {
  4019. throw new Exception('Stopping on failed scenario');
  4020. }
  4021. }
  4022. }
  4023. protected function StandardizedDump($oSet, $sAttPrefixToIgnore)
  4024. {
  4025. if (!$oSet->m_bLoaded) $oSet->Load();
  4026. $oSet->Rewind();
  4027. $aRet = array();
  4028. while($oObject = $oSet->Fetch())
  4029. {
  4030. $aValues = array();
  4031. foreach(MetaModel::ListAttributeDefs(get_class($oObject)) as $sAttCode => $oAttDef)
  4032. {
  4033. if ($sAttCode == 'friendlyname') continue;
  4034. if (substr($sAttCode, 0, strlen($sAttPrefixToIgnore)) == $sAttPrefixToIgnore) continue;
  4035. if ($oAttDef->IsScalar())
  4036. {
  4037. $aValues[] = $oObject->Get($sAttCode);
  4038. }
  4039. }
  4040. $aRet[] = implode(', ', $aValues);
  4041. }
  4042. sort($aRet);
  4043. return $aRet;
  4044. }
  4045. }
  4046. class TestLinkSetRecording_1N extends TestBizModel
  4047. {
  4048. static public function GetName()
  4049. {
  4050. return 'Linkset 1-N (Network Interface vs Server: Edit in-place)';
  4051. }
  4052. static public function GetDescription()
  4053. {
  4054. return 'Simulate CSV/data synchro type of recording. Check the values and the history.';
  4055. }
  4056. protected function DoExecute()
  4057. {
  4058. CMDBSource::Query('START TRANSACTION');
  4059. //CMDBSource::Query('ROLLBACK'); automatique !
  4060. ////////////////////////////////////////////////////////////////////////////////
  4061. // Set the stage
  4062. //
  4063. $oServer = MetaModel::NewObject('Server');
  4064. $oServer->Set('name', 'unit test linkset');
  4065. $oServer->Set('org_id', 3);
  4066. $oServer->DBInsert();
  4067. $iServer = $oServer->GetKey();
  4068. ////////////////////////////////////////////////////////////////////////////////
  4069. // Scenarii
  4070. //
  4071. $aScenarii = array(
  4072. array(
  4073. 'description' => 'Add the first interface',
  4074. 'interfaces' => array(
  4075. array(
  4076. 'connectableci_id' => $iServer,
  4077. 'name' => 'eth0',
  4078. 'speed' => '1000.00',
  4079. ),
  4080. ),
  4081. 'expected-res' => array (
  4082. "eth0, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4083. ),
  4084. 'history_added' => 1,
  4085. 'history_removed' => 0,
  4086. 'history_modified' => 0,
  4087. ),
  4088. array(
  4089. 'description' => 'Add a second interface',
  4090. 'interfaces' => array(
  4091. array(
  4092. 'connectableci_id' => $iServer,
  4093. 'name' => 'eth0',
  4094. 'speed' => '1000.00',
  4095. ),
  4096. array(
  4097. 'connectableci_id' => $iServer,
  4098. 'name' => 'eth1',
  4099. 'speed' => '1000.00',
  4100. ),
  4101. ),
  4102. 'expected-res' => array (
  4103. "eth0, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4104. "eth1, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4105. ),
  4106. 'history_added' => 1,
  4107. 'history_removed' => 0,
  4108. 'history_modified' => 0,
  4109. ),
  4110. array(
  4111. 'description' => 'Change the speed of an interface',
  4112. 'interfaces' => array(
  4113. array(
  4114. 'connectableci_id' => $iServer,
  4115. 'name' => 'eth0',
  4116. 'speed' => '100.00',
  4117. ),
  4118. array(
  4119. 'connectableci_id' => $iServer,
  4120. 'name' => 'eth1',
  4121. 'speed' => '1000.00',
  4122. ),
  4123. ),
  4124. 'expected-res' => array (
  4125. "eth0, , , , , , 100.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4126. "eth1, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4127. ),
  4128. 'history_added' => 1,
  4129. 'history_removed' => 1,
  4130. 'history_modified' => 0,
  4131. ),
  4132. array(
  4133. 'description' => 'Change the name of an interface',
  4134. 'interfaces' => array(
  4135. array(
  4136. 'connectableci_id' => $iServer,
  4137. 'name' => 'eth0-renamed',
  4138. 'speed' => '1000.00',
  4139. ),
  4140. array(
  4141. 'connectableci_id' => $iServer,
  4142. 'name' => 'eth1',
  4143. 'speed' => '1000.00',
  4144. ),
  4145. ),
  4146. 'expected-res' => array (
  4147. "eth0-renamed, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4148. "eth1, , , , , , 1000.00, $iServer, unit test linkset, PhysicalInterface, unit test linkset, Server",
  4149. ),
  4150. 'history_added' => 1,
  4151. 'history_removed' => 1,
  4152. 'history_modified' => 0,
  4153. ),
  4154. array(
  4155. 'description' => 'Remove all interfaces',
  4156. 'interfaces' => array(
  4157. ),
  4158. 'expected-res' => array (
  4159. ),
  4160. 'history_added' => 0,
  4161. 'history_removed' => 2,
  4162. 'history_modified' => 0,
  4163. ),
  4164. );
  4165. foreach ($aScenarii as $aScenario)
  4166. {
  4167. echo "<h4>".$aScenario['description']."</h4>\n";
  4168. $oChange = MetaModel::NewObject("CMDBChange");
  4169. $oChange->Set("date", time());
  4170. $oChange->Set("userinfo", CMDBChange::GetCurrentUserName());
  4171. $oChange->Set("origin", 'custom-extension');
  4172. $oChange->DBInsert();
  4173. CMDBObject::SetCurrentChange($oChange);
  4174. $iChange = $oChange->GetKey();
  4175. // Prepare set
  4176. $oLinkset = DBObjectSet::FromScratch('PhysicalInterface');
  4177. foreach ($aScenario['interfaces'] as $aIntfData)
  4178. {
  4179. $oInterface = MetaModel::NewObject('PhysicalInterface');
  4180. foreach ($aIntfData as $sAttCode => $value)
  4181. {
  4182. $oInterface->Set($sAttCode, $value);
  4183. }
  4184. $oLinkset->AddObject($oInterface);
  4185. }
  4186. // Write
  4187. $oServer = MetaModel::GetObject('Server', $iServer);
  4188. $oServer->Set('physicalinterface_list', $oLinkset);
  4189. $oServer->DBWrite();
  4190. // Check Results
  4191. $bFoundIssue = false;
  4192. $oServer = MetaModel::GetObject('Server', $iServer);
  4193. $oLinkset = $oServer->Get('physicalinterface_list');
  4194. $aRes = $this->StandardizedDump($oLinkset, 'zzz');
  4195. $sRes = var_export($aRes, true);
  4196. echo "Found: <pre>".$sRes."</pre>\n";
  4197. $sExpectedRes = var_export($aScenario['expected-res'], true);
  4198. if ($sRes != $sExpectedRes)
  4199. {
  4200. $bFoundIssue = true;
  4201. echo "NOT COMPLIANT!!! Expecting: <pre>".$sExpectedRes."</pre>\n";
  4202. }
  4203. // Check History
  4204. $aQueryParams = array('change' => $iChange, 'objclass' => get_class($oServer), 'objkey' => $oServer->GetKey());
  4205. $oAdded = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'added'"), array(), $aQueryParams);
  4206. echo "added: ".$oAdded->Count()."<br/>\n";
  4207. if ($aScenario['history_added'] != $oAdded->Count())
  4208. {
  4209. $bFoundIssue = true;
  4210. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_added']."<br/>\n";
  4211. }
  4212. $oRemoved = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'removed'"), array(), $aQueryParams);
  4213. echo "removed: ".$oRemoved->Count()."<br/>\n";
  4214. if ($aScenario['history_removed'] != $oRemoved->Count())
  4215. {
  4216. $bFoundIssue = true;
  4217. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_removed']."<br/>\n";
  4218. }
  4219. $oModified = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksTune WHERE objclass = :objclass AND objkey = :objkey AND change = :change"), array(), $aQueryParams);
  4220. echo "modified: ".$oModified->Count()."<br/>\n";
  4221. if ($aScenario['history_modified'] != $oModified->Count())
  4222. {
  4223. $bFoundIssue = true;
  4224. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_modified']."<br/>\n";
  4225. }
  4226. if ($bFoundIssue)
  4227. {
  4228. throw new Exception('Stopping on failed scenario');
  4229. }
  4230. }
  4231. }
  4232. protected function StandardizedDump($oSet, $sAttPrefixToIgnore)
  4233. {
  4234. if (!$oSet->m_bLoaded) $oSet->Load();
  4235. $oSet->Rewind();
  4236. $aRet = array();
  4237. while($oObject = $oSet->Fetch())
  4238. {
  4239. $aValues = array();
  4240. foreach(MetaModel::ListAttributeDefs(get_class($oObject)) as $sAttCode => $oAttDef)
  4241. {
  4242. if ($sAttCode == 'friendlyname') continue;
  4243. if (substr($sAttCode, 0, strlen($sAttPrefixToIgnore)) == $sAttPrefixToIgnore) continue;
  4244. if ($oAttDef->IsScalar())
  4245. {
  4246. $aValues[] = $oObject->Get($sAttCode);
  4247. }
  4248. }
  4249. $aRet[] = implode(', ', $aValues);
  4250. }
  4251. sort($aRet);
  4252. return $aRet;
  4253. }
  4254. }
  4255. class TestLinkSetRecording_1NAdd_Remove extends TestBizModel
  4256. {
  4257. static public function GetName()
  4258. {
  4259. return 'Linkset 1-N (Delivery Model vs Organization: Edit Add/Remove)';
  4260. }
  4261. static public function GetDescription()
  4262. {
  4263. return 'Simulate CSV/data synchro type of recording. Check the values and the history.';
  4264. }
  4265. protected function DoExecute()
  4266. {
  4267. CMDBSource::Query('START TRANSACTION');
  4268. //CMDBSource::Query('ROLLBACK'); automatique !
  4269. ////////////////////////////////////////////////////////////////////////////////
  4270. // Set the stage
  4271. //
  4272. $oProvider = new Organization();
  4273. $oProvider->Set('name', 'Test-Provider1');
  4274. $oProvider->DBInsert();
  4275. $iProvider = $oProvider->GetKey();
  4276. $oDM1 = new DeliveryModel();
  4277. $oDM1->Set('name', 'Test-DM-1');
  4278. $oDM1->Set('org_id', $iProvider);
  4279. $oDM1->DBInsert();
  4280. $iDM1 = $oDM1->GetKey();
  4281. $oDM2 = new DeliveryModel();
  4282. $oDM2->Set('name', 'Test-DM-2');
  4283. $oDM2->Set('org_id', $iProvider);
  4284. $oDM2->DBInsert();
  4285. $iDM2 = $oDM2->GetKey();
  4286. ////////////////////////////////////////////////////////////////////////////////
  4287. // Scenarii
  4288. //
  4289. $aScenarii = array(
  4290. array(
  4291. 'description' => 'Add the first customer',
  4292. 'organizations' => array(
  4293. array(
  4294. 'deliverymodel_id' => $iDM1,
  4295. 'name' => 'Test-Customer-1',
  4296. ),
  4297. ),
  4298. 'expected-res' => array (
  4299. "Test-Customer-1, , active, 0, , $iDM1, Test-DM-1, , Test-DM-1",
  4300. ),
  4301. 'history_added' => 0,
  4302. 'history_removed' => 0,
  4303. 'history_modified' => 0,
  4304. ),
  4305. array(
  4306. 'description' => 'Remove the customer by loading an empty set',
  4307. 'organizations' => array(
  4308. ),
  4309. 'expected-res' => array (
  4310. ),
  4311. 'history_added' => 0,
  4312. 'history_removed' => 0,
  4313. 'history_modified' => 0,
  4314. ),
  4315. array(
  4316. 'description' => 'Create two customers at once',
  4317. 'organizations' => array(
  4318. array(
  4319. 'deliverymodel_id' => $iDM1,
  4320. 'name' => 'Test-Customer-1',
  4321. ),
  4322. array(
  4323. 'deliverymodel_id' => $iDM1,
  4324. 'name' => 'Test-Customer-2',
  4325. ),
  4326. ),
  4327. 'expected-res' => array (
  4328. "Test-Customer-1, , active, 0, , $iDM1, Test-DM-1, , Test-DM-1",
  4329. "Test-Customer-2, , active, 0, , $iDM1, Test-DM-1, , Test-DM-1",
  4330. ),
  4331. 'history_added' => 0,
  4332. 'history_removed' => 0,
  4333. 'history_modified' => 0,
  4334. ),
  4335. array(
  4336. 'description' => 'Move Customer-1 to the second Delivery Model',
  4337. 'organizations' => array(
  4338. array(
  4339. 'id' => "SELECT Organization WHERE name='Test-Customer-1'",
  4340. 'deliverymodel_id' => $iDM2,
  4341. 'name' => 'Test-Customer-1',
  4342. ),
  4343. array(
  4344. 'deliverymodel_id' => $iDM1,
  4345. 'name' => 'Test-Customer-2',
  4346. ),
  4347. ),
  4348. 'expected-res' => array (
  4349. "Test-Customer-2, , active, 0, , $iDM1, Test-DM-1, , Test-DM-1",
  4350. ),
  4351. 'history_added' => 0,
  4352. 'history_removed' => 0,
  4353. 'history_modified' => 0,
  4354. ),
  4355. array(
  4356. 'description' => 'Move Customer-1 back to the first Delivery Model and reset Customer-2 (no Delivery Model)',
  4357. 'organizations' => array(
  4358. array(
  4359. 'id' => "SELECT Organization WHERE name='Test-Customer-1'",
  4360. 'deliverymodel_id' => $iDM1,
  4361. 'name' => 'Test-Customer-1',
  4362. ),
  4363. array(
  4364. 'id' => "SELECT Organization WHERE name='Test-Customer-2'",
  4365. 'deliverymodel_id' => 0,
  4366. 'name' => 'Test-Customer-2',
  4367. ),
  4368. ),
  4369. 'expected-res' => array (
  4370. "Test-Customer-1, , active, 0, , $iDM1, Test-DM-1, , Test-DM-1",
  4371. ),
  4372. 'history_added' => 0,
  4373. 'history_removed' => 0,
  4374. 'history_modified' => 0,
  4375. ),
  4376. );
  4377. foreach ($aScenarii as $aScenario)
  4378. {
  4379. echo "<h4>".$aScenario['description']."</h4>\n";
  4380. $oChange = MetaModel::NewObject("CMDBChange");
  4381. $oChange->Set("date", time());
  4382. $oChange->Set("userinfo", CMDBChange::GetCurrentUserName());
  4383. $oChange->Set("origin", 'custom-extension');
  4384. $oChange->DBInsert();
  4385. CMDBObject::SetCurrentChange($oChange);
  4386. $iChange = $oChange->GetKey();
  4387. // Prepare set
  4388. $oLinkset = DBObjectSet::FromScratch('Organization');
  4389. foreach ($aScenario['organizations'] as $aOrgData)
  4390. {
  4391. if (array_key_exists('id', $aOrgData))
  4392. {
  4393. $sOQL = $aOrgData['id'];
  4394. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  4395. $oOrg = $oSet->Fetch();
  4396. if (!is_object($oOrg)) throw new Exception('Failed to find the Organization: '.$sOQL);
  4397. }
  4398. else
  4399. {
  4400. $oOrg = MetaModel::NewObject('Organization');
  4401. }
  4402. foreach ($aOrgData as $sAttCode => $value)
  4403. {
  4404. if ($sAttCode == 'id') continue;
  4405. $oOrg->Set($sAttCode, $value);
  4406. }
  4407. $oLinkset->AddObject($oOrg);
  4408. }
  4409. // Write
  4410. $oDM = MetaModel::GetObject('DeliveryModel', $iDM1);
  4411. $oDM->Set('customers_list', $oLinkset);
  4412. $oDM->DBWrite();
  4413. // Check Results
  4414. $bFoundIssue = false;
  4415. $oDM = MetaModel::GetObject('DeliveryModel', $iDM1);
  4416. $oLinkset = $oDM->Get('customers_list');
  4417. $aRes = $this->StandardizedDump($oLinkset, 'zzz');
  4418. $sRes = var_export($aRes, true);
  4419. echo "Found: <pre>".$sRes."</pre>\n";
  4420. $sExpectedRes = var_export($aScenario['expected-res'], true);
  4421. if ($sRes != $sExpectedRes)
  4422. {
  4423. $bFoundIssue = true;
  4424. echo "NOT COMPLIANT!!! Expecting: <pre>".$sExpectedRes."</pre>\n";
  4425. }
  4426. // Check History
  4427. $aQueryParams = array('change' => $iChange, 'objclass' => get_class($oDM), 'objkey' => $oDM->GetKey());
  4428. $oAdded = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'added'"), array(), $aQueryParams);
  4429. echo "added: ".$oAdded->Count()."<br/>\n";
  4430. if ($aScenario['history_added'] != $oAdded->Count())
  4431. {
  4432. $bFoundIssue = true;
  4433. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_added']."<br/>\n";
  4434. }
  4435. $oRemoved = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksAddRemove WHERE objclass = :objclass AND objkey = :objkey AND change = :change AND type = 'removed'"), array(), $aQueryParams);
  4436. echo "removed: ".$oRemoved->Count()."<br/>\n";
  4437. if ($aScenario['history_removed'] != $oRemoved->Count())
  4438. {
  4439. $bFoundIssue = true;
  4440. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_removed']."<br/>\n";
  4441. }
  4442. $oModified = new DBObjectSet(DBSearch::FromOQL("SELECT CMDBChangeOpSetAttributeLinksTune WHERE objclass = :objclass AND objkey = :objkey AND change = :change"), array(), $aQueryParams);
  4443. echo "modified: ".$oModified->Count()."<br/>\n";
  4444. if ($aScenario['history_modified'] != $oModified->Count())
  4445. {
  4446. $bFoundIssue = true;
  4447. echo "NOT COMPLIANT!!! Expecting: ".$aScenario['history_modified']."<br/>\n";
  4448. }
  4449. if ($bFoundIssue)
  4450. {
  4451. throw new Exception('Stopping on failed scenario');
  4452. }
  4453. }
  4454. }
  4455. protected function StandardizedDump($oSet, $sAttPrefixToIgnore)
  4456. {
  4457. if (!$oSet->m_bLoaded) $oSet->Load();
  4458. $oSet->Rewind();
  4459. $aRet = array();
  4460. while($oObject = $oSet->Fetch())
  4461. {
  4462. $aValues = array();
  4463. foreach(MetaModel::ListAttributeDefs(get_class($oObject)) as $sAttCode => $oAttDef)
  4464. {
  4465. if ($sAttCode == 'friendlyname') continue;
  4466. if (substr($sAttCode, 0, strlen($sAttPrefixToIgnore)) == $sAttPrefixToIgnore) continue;
  4467. if ($oAttDef->IsScalar())
  4468. {
  4469. $aValues[] = $oObject->Get($sAttCode);
  4470. }
  4471. }
  4472. $aRet[] = implode(', ', $aValues);
  4473. }
  4474. sort($aRet);
  4475. return $aRet;
  4476. }
  4477. }