testlist.inc.php 186 KB

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